import * as path from 'path';
import path__default, { join, dirname } from 'path';
import * as fs from 'fs';
import fs__default, { existsSync as existsSync$1, readFileSync as readFileSync$1, mkdirSync, statSync as statSync$1, writeFileSync, promises } from 'fs';
import fsProm, { stat as stat$1, readdir, unlink as unlink$1 } from 'fs/promises';
import { ReadableStream as ReadableStream$1 } from 'node:stream/web';
import * as stream$3 from 'node:stream';
import stream__default, { Readable, PassThrough, pipeline } from 'node:stream';
import fs$1, { open, stat, writeFile, constants as constants$1, unlink, readdir as readdir$1 } from 'node:fs/promises';
import { createRequire } from 'module';
import https$1 from 'node:https';
import http from 'node:http';
import * as crypto$2 from 'crypto';
import crypto__default, { randomUUID, createHmac, createHash as createHash$1 } from 'crypto';
import path$1, { basename, resolve as resolve$1, dirname as dirname$1, join as join$1 } from 'node:path';
import os$1, { platform, arch, constants } from 'node:os';
import fs$2, { readFileSync, statSync, createReadStream, existsSync, unlink as unlink$2 } from 'node:fs';
import * as crypto$1 from 'node:crypto';
import crypto__default$1, { createHash, randomBytes, randomUUID as randomUUID$1 } from 'node:crypto';
import * as os from 'os';
import os__default from 'os';
import * as net from 'node:net';
import net__default, { isIP } from 'node:net';
import assert$1 from 'node:assert';
import * as zlib from 'node:zlib';
import zlib__default from 'node:zlib';
import { dlopen } from 'node:process';
import { execFile, fork } from 'child_process';
import require$$0$6, { promisify } from 'util';
import * as https from 'https';
import https__default, { createServer } from 'https';
import require$$1$1, { PassThrough as PassThrough$1, Writable } from 'stream';
import require$$1$2, { gunzipSync as gunzipSync$1 } from 'zlib';
import require$$0$5, { EventEmitter as EventEmitter$2 } from 'events';
import require$$0$4 from 'buffer';
import require$$0$7 from 'constants';
import require$$1$3 from 'string_decoder';
import require$$2$2 from 'assert';
import { pipeline as pipeline$1 } from 'stream/promises';
import { fileURLToPath, URL as URL$2 } from 'url';
import require$$0$8, { createServer as createServer$1 } from 'http';
import EventEmitter, { EventEmitter as EventEmitter$1 } from 'node:events';
import express, { Router } from 'express';
import { WebSocketServer, WebSocket } from 'ws';
import * as net$1 from 'net';
import { Socket } from 'net';
import { Worker as Worker$1 } from 'worker_threads';
import { C as ConoutWorkerMessage, g as getWorkerPipeName } from './conout-D9oph_Le.js';
import { fileURLToPath as fileURLToPath$1 } from 'node:url';
import * as tty from 'tty';
import { Buffer as Buffer$1 } from 'node:buffer';
import { decode, isSilk, isWav, getDuration, getWavFileInfo } from 'silk-wasm';
import * as process$1 from 'process';

/**
 * Get the type of a JSON value.
 * Distinguishes between array, null and object.
 */
function typeofJsonValue(value) {
    let t = typeof value;
    if (t == "object") {
        if (Array.isArray(value))
            return "array";
        if (value === null)
            return "null";
    }
    return t;
}
/**
 * Is this a JSON object (instead of an array or null)?
 */
function isJsonObject(value) {
    return value !== null && typeof value == "object" && !Array.isArray(value);
}

// lookup table from base64 character to byte
let encTable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
// lookup table from base64 character *code* to byte because lookup by number is fast
let decTable = [];
for (let i = 0; i < encTable.length; i++)
    decTable[encTable[i].charCodeAt(0)] = i;
// support base64url variants
decTable["-".charCodeAt(0)] = encTable.indexOf("+");
decTable["_".charCodeAt(0)] = encTable.indexOf("/");
/**
 * Decodes a base64 string to a byte array.
 *
 * - ignores white-space, including line breaks and tabs
 * - allows inner padding (can decode concatenated base64 strings)
 * - does not require padding
 * - understands base64url encoding:
 *   "-" instead of "+",
 *   "_" instead of "/",
 *   no padding
 */
function base64decode(base64Str) {
    // estimate byte size, not accounting for inner padding and whitespace
    let es = base64Str.length * 3 / 4;
    // if (es % 3 !== 0)
    // throw new Error('invalid base64 string');
    if (base64Str[base64Str.length - 2] == '=')
        es -= 2;
    else if (base64Str[base64Str.length - 1] == '=')
        es -= 1;
    let bytes = new Uint8Array(es), bytePos = 0, // position in byte array
    groupPos = 0, // position in base64 group
    b, // current byte
    p = 0 // previous byte
    ;
    for (let i = 0; i < base64Str.length; i++) {
        b = decTable[base64Str.charCodeAt(i)];
        if (b === undefined) {
            // noinspection FallThroughInSwitchStatementJS
            switch (base64Str[i]) {
                case '=':
                    groupPos = 0; // reset state when padding found
                case '\n':
                case '\r':
                case '\t':
                case ' ':
                    continue; // skip white-space, and padding
                default:
                    throw Error(`invalid base64 string.`);
            }
        }
        switch (groupPos) {
            case 0:
                p = b;
                groupPos = 1;
                break;
            case 1:
                bytes[bytePos++] = p << 2 | (b & 48) >> 4;
                p = b;
                groupPos = 2;
                break;
            case 2:
                bytes[bytePos++] = (p & 15) << 4 | (b & 60) >> 2;
                p = b;
                groupPos = 3;
                break;
            case 3:
                bytes[bytePos++] = (p & 3) << 6 | b;
                groupPos = 0;
                break;
        }
    }
    if (groupPos == 1)
        throw Error(`invalid base64 string.`);
    return bytes.subarray(0, bytePos);
}
/**
 * Encodes a byte array to a base64 string.
 * Adds padding at the end.
 * Does not insert newlines.
 */
function base64encode(bytes) {
    let base64 = '', groupPos = 0, // position in base64 group
    b, // current byte
    p = 0; // carry over from previous byte
    for (let i = 0; i < bytes.length; i++) {
        b = bytes[i];
        switch (groupPos) {
            case 0:
                base64 += encTable[b >> 2];
                p = (b & 3) << 4;
                groupPos = 1;
                break;
            case 1:
                base64 += encTable[p | b >> 4];
                p = (b & 15) << 2;
                groupPos = 2;
                break;
            case 2:
                base64 += encTable[p | b >> 6];
                base64 += encTable[b & 63];
                groupPos = 0;
                break;
        }
    }
    // padding required?
    if (groupPos) {
        base64 += encTable[p];
        base64 += '=';
        if (groupPos == 1)
            base64 += '=';
    }
    return base64;
}

/**
 * This handler implements the default behaviour for unknown fields.
 * When reading data, unknown fields are stored on the message, in a
 * symbol property.
 * When writing data, the symbol property is queried and unknown fields
 * are serialized into the output again.
 */
var UnknownFieldHandler;
(function (UnknownFieldHandler) {
    /**
     * The symbol used to store unknown fields for a message.
     * The property must conform to `UnknownFieldContainer`.
     */
    UnknownFieldHandler.symbol = Symbol.for("protobuf-ts/unknown");
    /**
     * Store an unknown field during binary read directly on the message.
     * This method is compatible with `BinaryReadOptions.readUnknownField`.
     */
    UnknownFieldHandler.onRead = (typeName, message, fieldNo, wireType, data) => {
        let container = is(message) ? message[UnknownFieldHandler.symbol] : message[UnknownFieldHandler.symbol] = [];
        container.push({ no: fieldNo, wireType, data });
    };
    /**
     * Write unknown fields stored for the message to the writer.
     * This method is compatible with `BinaryWriteOptions.writeUnknownFields`.
     */
    UnknownFieldHandler.onWrite = (typeName, message, writer) => {
        for (let { no, wireType, data } of UnknownFieldHandler.list(message))
            writer.tag(no, wireType).raw(data);
    };
    /**
     * List unknown fields stored for the message.
     * Note that there may be multiples fields with the same number.
     */
    UnknownFieldHandler.list = (message, fieldNo) => {
        if (is(message)) {
            let all = message[UnknownFieldHandler.symbol];
            return fieldNo ? all.filter(uf => uf.no == fieldNo) : all;
        }
        return [];
    };
    /**
     * Returns the last unknown field by field number.
     */
    UnknownFieldHandler.last = (message, fieldNo) => UnknownFieldHandler.list(message, fieldNo).slice(-1)[0];
    const is = (message) => message && Array.isArray(message[UnknownFieldHandler.symbol]);
})(UnknownFieldHandler || (UnknownFieldHandler = {}));
/**
 * Protobuf binary format wire types.
 *
 * A wire type provides just enough information to find the length of the
 * following value.
 *
 * See https://developers.google.com/protocol-buffers/docs/encoding#structure
 */
var WireType;
(function (WireType) {
    /**
     * Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum
     */
    WireType[WireType["Varint"] = 0] = "Varint";
    /**
     * Used for fixed64, sfixed64, double.
     * Always 8 bytes with little-endian byte order.
     */
    WireType[WireType["Bit64"] = 1] = "Bit64";
    /**
     * Used for string, bytes, embedded messages, packed repeated fields
     *
     * Only repeated numeric types (types which use the varint, 32-bit,
     * or 64-bit wire types) can be packed. In proto3, such fields are
     * packed by default.
     */
    WireType[WireType["LengthDelimited"] = 2] = "LengthDelimited";
    /**
     * Used for groups
     * @deprecated
     */
    WireType[WireType["StartGroup"] = 3] = "StartGroup";
    /**
     * Used for groups
     * @deprecated
     */
    WireType[WireType["EndGroup"] = 4] = "EndGroup";
    /**
     * Used for fixed32, sfixed32, float.
     * Always 4 bytes with little-endian byte order.
     */
    WireType[WireType["Bit32"] = 5] = "Bit32";
})(WireType || (WireType = {}));

// Copyright 2008 Google Inc.  All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Code generated by the Protocol Buffer compiler is owned by the owner
// of the input file used when generating it.  This code is not
// standalone and requires a support library to be linked with it.  This
// support library is itself covered by the above license.
/**
 * Read a 64 bit varint as two JS numbers.
 *
 * Returns tuple:
 * [0]: low bits
 * [0]: high bits
 *
 * Copyright 2008 Google Inc.  All rights reserved.
 *
 * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175
 */
function varint64read() {
    let lowBits = 0;
    let highBits = 0;
    for (let shift = 0; shift < 28; shift += 7) {
        let b = this.buf[this.pos++];
        lowBits |= (b & 0x7F) << shift;
        if ((b & 0x80) == 0) {
            this.assertBounds();
            return [lowBits, highBits];
        }
    }
    let middleByte = this.buf[this.pos++];
    // last four bits of the first 32 bit number
    lowBits |= (middleByte & 0x0F) << 28;
    // 3 upper bits are part of the next 32 bit number
    highBits = (middleByte & 0x70) >> 4;
    if ((middleByte & 0x80) == 0) {
        this.assertBounds();
        return [lowBits, highBits];
    }
    for (let shift = 3; shift <= 31; shift += 7) {
        let b = this.buf[this.pos++];
        highBits |= (b & 0x7F) << shift;
        if ((b & 0x80) == 0) {
            this.assertBounds();
            return [lowBits, highBits];
        }
    }
    throw new Error('invalid varint');
}
/**
 * Write a 64 bit varint, given as two JS numbers, to the given bytes array.
 *
 * Copyright 2008 Google Inc.  All rights reserved.
 *
 * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344
 */
function varint64write(lo, hi, bytes) {
    for (let i = 0; i < 28; i = i + 7) {
        const shift = lo >>> i;
        const hasNext = !((shift >>> 7) == 0 && hi == 0);
        const byte = (hasNext ? shift | 0x80 : shift) & 0xFF;
        bytes.push(byte);
        if (!hasNext) {
            return;
        }
    }
    const splitBits = ((lo >>> 28) & 0x0F) | ((hi & 0x07) << 4);
    const hasMoreBits = !((hi >> 3) == 0);
    bytes.push((hasMoreBits ? splitBits | 0x80 : splitBits) & 0xFF);
    if (!hasMoreBits) {
        return;
    }
    for (let i = 3; i < 31; i = i + 7) {
        const shift = hi >>> i;
        const hasNext = !((shift >>> 7) == 0);
        const byte = (hasNext ? shift | 0x80 : shift) & 0xFF;
        bytes.push(byte);
        if (!hasNext) {
            return;
        }
    }
    bytes.push((hi >>> 31) & 0x01);
}
// constants for binary math
const TWO_PWR_32_DBL$1 = (1 << 16) * (1 << 16);
/**
 * Parse decimal string of 64 bit integer value as two JS numbers.
 *
 * Returns tuple:
 * [0]: minus sign?
 * [1]: low bits
 * [2]: high bits
 *
 * Copyright 2008 Google Inc.
 */
function int64fromString(dec) {
    // Check for minus sign.
    let minus = dec[0] == '-';
    if (minus)
        dec = dec.slice(1);
    // Work 6 decimal digits at a time, acting like we're converting base 1e6
    // digits to binary. This is safe to do with floating point math because
    // Number.isSafeInteger(ALL_32_BITS * 1e6) == true.
    const base = 1e6;
    let lowBits = 0;
    let highBits = 0;
    function add1e6digit(begin, end) {
        // Note: Number('') is 0.
        const digit1e6 = Number(dec.slice(begin, end));
        highBits *= base;
        lowBits = lowBits * base + digit1e6;
        // Carry bits from lowBits to highBits
        if (lowBits >= TWO_PWR_32_DBL$1) {
            highBits = highBits + ((lowBits / TWO_PWR_32_DBL$1) | 0);
            lowBits = lowBits % TWO_PWR_32_DBL$1;
        }
    }
    add1e6digit(-24, -18);
    add1e6digit(-18, -12);
    add1e6digit(-12, -6);
    add1e6digit(-6);
    return [minus, lowBits, highBits];
}
/**
 * Format 64 bit integer value (as two JS numbers) to decimal string.
 *
 * Copyright 2008 Google Inc.
 */
function int64toString(bitsLow, bitsHigh) {
    // Skip the expensive conversion if the number is small enough to use the
    // built-in conversions.
    if ((bitsHigh >>> 0) <= 0x1FFFFF) {
        return '' + (TWO_PWR_32_DBL$1 * bitsHigh + (bitsLow >>> 0));
    }
    // What this code is doing is essentially converting the input number from
    // base-2 to base-1e7, which allows us to represent the 64-bit range with
    // only 3 (very large) digits. Those digits are then trivial to convert to
    // a base-10 string.
    // The magic numbers used here are -
    // 2^24 = 16777216 = (1,6777216) in base-1e7.
    // 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7.
    // Split 32:32 representation into 16:24:24 representation so our
    // intermediate digits don't overflow.
    let low = bitsLow & 0xFFFFFF;
    let mid = (((bitsLow >>> 24) | (bitsHigh << 8)) >>> 0) & 0xFFFFFF;
    let high = (bitsHigh >> 16) & 0xFFFF;
    // Assemble our three base-1e7 digits, ignoring carries. The maximum
    // value in a digit at this step is representable as a 48-bit integer, which
    // can be stored in a 64-bit floating point number.
    let digitA = low + (mid * 6777216) + (high * 6710656);
    let digitB = mid + (high * 8147497);
    let digitC = (high * 2);
    // Apply carries from A to B and from B to C.
    let base = 10000000;
    if (digitA >= base) {
        digitB += Math.floor(digitA / base);
        digitA %= base;
    }
    if (digitB >= base) {
        digitC += Math.floor(digitB / base);
        digitB %= base;
    }
    // Convert base-1e7 digits to base-10, with optional leading zeroes.
    function decimalFrom1e7(digit1e7, needLeadingZeros) {
        let partial = digit1e7 ? String(digit1e7) : '';
        if (needLeadingZeros) {
            return '0000000'.slice(partial.length) + partial;
        }
        return partial;
    }
    return decimalFrom1e7(digitC, /*needLeadingZeros=*/ 0) +
        decimalFrom1e7(digitB, /*needLeadingZeros=*/ digitC) +
        // If the final 1e7 digit didn't need leading zeros, we would have
        // returned via the trivial code path at the top.
        decimalFrom1e7(digitA, /*needLeadingZeros=*/ 1);
}
/**
 * Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)`
 *
 * Copyright 2008 Google Inc.  All rights reserved.
 *
 * See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144
 */
function varint32write(value, bytes) {
    if (value >= 0) {
        // write value as varint 32
        while (value > 0x7f) {
            bytes.push((value & 0x7f) | 0x80);
            value = value >>> 7;
        }
        bytes.push(value);
    }
    else {
        for (let i = 0; i < 9; i++) {
            bytes.push(value & 127 | 128);
            value = value >> 7;
        }
        bytes.push(1);
    }
}
/**
 * Read an unsigned 32 bit varint.
 *
 * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220
 */
function varint32read() {
    let b = this.buf[this.pos++];
    let result = b & 0x7F;
    if ((b & 0x80) == 0) {
        this.assertBounds();
        return result;
    }
    b = this.buf[this.pos++];
    result |= (b & 0x7F) << 7;
    if ((b & 0x80) == 0) {
        this.assertBounds();
        return result;
    }
    b = this.buf[this.pos++];
    result |= (b & 0x7F) << 14;
    if ((b & 0x80) == 0) {
        this.assertBounds();
        return result;
    }
    b = this.buf[this.pos++];
    result |= (b & 0x7F) << 21;
    if ((b & 0x80) == 0) {
        this.assertBounds();
        return result;
    }
    // Extract only last 4 bits
    b = this.buf[this.pos++];
    result |= (b & 0x0F) << 28;
    for (let readBytes = 5; ((b & 0x80) !== 0) && readBytes < 10; readBytes++)
        b = this.buf[this.pos++];
    if ((b & 0x80) != 0)
        throw new Error('invalid varint');
    this.assertBounds();
    // Result can have 32 bits, convert it to unsigned
    return result >>> 0;
}

let BI;
function detectBi() {
    const dv = new DataView(new ArrayBuffer(8));
    const ok = globalThis.BigInt !== undefined
        && typeof dv.getBigInt64 === "function"
        && typeof dv.getBigUint64 === "function"
        && typeof dv.setBigInt64 === "function"
        && typeof dv.setBigUint64 === "function";
    BI = ok ? {
        MIN: BigInt("-9223372036854775808"),
        MAX: BigInt("9223372036854775807"),
        UMIN: BigInt("0"),
        UMAX: BigInt("18446744073709551615"),
        C: BigInt,
        V: dv,
    } : undefined;
}
detectBi();
function assertBi(bi) {
    if (!bi)
        throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support");
}
// used to validate from(string) input (when bigint is unavailable)
const RE_DECIMAL_STR = /^-?[0-9]+$/;
// constants for binary math
const TWO_PWR_32_DBL = 0x100000000;
const HALF_2_PWR_32 = 0x080000000;
// base class for PbLong and PbULong provides shared code
class SharedPbLong {
    /**
     * Create a new instance with the given bits.
     */
    constructor(lo, hi) {
        this.lo = lo | 0;
        this.hi = hi | 0;
    }
    /**
     * Is this instance equal to 0?
     */
    isZero() {
        return this.lo == 0 && this.hi == 0;
    }
    /**
     * Convert to a native number.
     */
    toNumber() {
        let result = this.hi * TWO_PWR_32_DBL + (this.lo >>> 0);
        if (!Number.isSafeInteger(result))
            throw new Error("cannot convert to safe number");
        return result;
    }
}
/**
 * 64-bit unsigned integer as two 32-bit values.
 * Converts between `string`, `number` and `bigint` representations.
 */
class PbULong extends SharedPbLong {
    /**
     * Create instance from a `string`, `number` or `bigint`.
     */
    static from(value) {
        if (BI)
            // noinspection FallThroughInSwitchStatementJS
            switch (typeof value) {
                case "string":
                    if (value == "0")
                        return this.ZERO;
                    if (value == "")
                        throw new Error('string is no integer');
                    value = BI.C(value);
                case "number":
                    if (value === 0)
                        return this.ZERO;
                    value = BI.C(value);
                case "bigint":
                    if (!value)
                        return this.ZERO;
                    if (value < BI.UMIN)
                        throw new Error('signed value for ulong');
                    if (value > BI.UMAX)
                        throw new Error('ulong too large');
                    BI.V.setBigUint64(0, value, true);
                    return new PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true));
            }
        else
            switch (typeof value) {
                case "string":
                    if (value == "0")
                        return this.ZERO;
                    value = value.trim();
                    if (!RE_DECIMAL_STR.test(value))
                        throw new Error('string is no integer');
                    let [minus, lo, hi] = int64fromString(value);
                    if (minus)
                        throw new Error('signed value for ulong');
                    return new PbULong(lo, hi);
                case "number":
                    if (value == 0)
                        return this.ZERO;
                    if (!Number.isSafeInteger(value))
                        throw new Error('number is no integer');
                    if (value < 0)
                        throw new Error('signed value for ulong');
                    return new PbULong(value, value / TWO_PWR_32_DBL);
            }
        throw new Error('unknown value ' + typeof value);
    }
    /**
     * Convert to decimal string.
     */
    toString() {
        return BI ? this.toBigInt().toString() : int64toString(this.lo, this.hi);
    }
    /**
     * Convert to native bigint.
     */
    toBigInt() {
        assertBi(BI);
        BI.V.setInt32(0, this.lo, true);
        BI.V.setInt32(4, this.hi, true);
        return BI.V.getBigUint64(0, true);
    }
}
/**
 * ulong 0 singleton.
 */
PbULong.ZERO = new PbULong(0, 0);
/**
 * 64-bit signed integer as two 32-bit values.
 * Converts between `string`, `number` and `bigint` representations.
 */
class PbLong extends SharedPbLong {
    /**
     * Create instance from a `string`, `number` or `bigint`.
     */
    static from(value) {
        if (BI)
            // noinspection FallThroughInSwitchStatementJS
            switch (typeof value) {
                case "string":
                    if (value == "0")
                        return this.ZERO;
                    if (value == "")
                        throw new Error('string is no integer');
                    value = BI.C(value);
                case "number":
                    if (value === 0)
                        return this.ZERO;
                    value = BI.C(value);
                case "bigint":
                    if (!value)
                        return this.ZERO;
                    if (value < BI.MIN)
                        throw new Error('signed long too small');
                    if (value > BI.MAX)
                        throw new Error('signed long too large');
                    BI.V.setBigInt64(0, value, true);
                    return new PbLong(BI.V.getInt32(0, true), BI.V.getInt32(4, true));
            }
        else
            switch (typeof value) {
                case "string":
                    if (value == "0")
                        return this.ZERO;
                    value = value.trim();
                    if (!RE_DECIMAL_STR.test(value))
                        throw new Error('string is no integer');
                    let [minus, lo, hi] = int64fromString(value);
                    if (minus) {
                        if (hi > HALF_2_PWR_32 || (hi == HALF_2_PWR_32 && lo != 0))
                            throw new Error('signed long too small');
                    }
                    else if (hi >= HALF_2_PWR_32)
                        throw new Error('signed long too large');
                    let pbl = new PbLong(lo, hi);
                    return minus ? pbl.negate() : pbl;
                case "number":
                    if (value == 0)
                        return this.ZERO;
                    if (!Number.isSafeInteger(value))
                        throw new Error('number is no integer');
                    return value > 0
                        ? new PbLong(value, value / TWO_PWR_32_DBL)
                        : new PbLong(-value, -value / TWO_PWR_32_DBL).negate();
            }
        throw new Error('unknown value ' + typeof value);
    }
    /**
     * Do we have a minus sign?
     */
    isNegative() {
        return (this.hi & HALF_2_PWR_32) !== 0;
    }
    /**
     * Negate two's complement.
     * Invert all the bits and add one to the result.
     */
    negate() {
        let hi = ~this.hi, lo = this.lo;
        if (lo)
            lo = ~lo + 1;
        else
            hi += 1;
        return new PbLong(lo, hi);
    }
    /**
     * Convert to decimal string.
     */
    toString() {
        if (BI)
            return this.toBigInt().toString();
        if (this.isNegative()) {
            let n = this.negate();
            return '-' + int64toString(n.lo, n.hi);
        }
        return int64toString(this.lo, this.hi);
    }
    /**
     * Convert to native bigint.
     */
    toBigInt() {
        assertBi(BI);
        BI.V.setInt32(0, this.lo, true);
        BI.V.setInt32(4, this.hi, true);
        return BI.V.getBigInt64(0, true);
    }
}
/**
 * long 0 singleton.
 */
PbLong.ZERO = new PbLong(0, 0);

const defaultsRead$1 = {
    readUnknownField: true,
    readerFactory: bytes => new BinaryReader(bytes),
};
/**
 * Make options for reading binary data form partial options.
 */
function binaryReadOptions(options) {
    return options ? Object.assign(Object.assign({}, defaultsRead$1), options) : defaultsRead$1;
}
class BinaryReader {
    constructor(buf, textDecoder) {
        this.varint64 = varint64read; // dirty cast for `this`
        /**
         * Read a `uint32` field, an unsigned 32 bit varint.
         */
        this.uint32 = varint32read; // dirty cast for `this` and access to protected `buf`
        this.buf = buf;
        this.len = buf.length;
        this.pos = 0;
        this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
        this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder("utf-8", {
            fatal: true,
            ignoreBOM: true,
        });
    }
    /**
     * Reads a tag - field number and wire type.
     */
    tag() {
        let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7;
        if (fieldNo <= 0 || wireType < 0 || wireType > 5)
            throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType);
        return [fieldNo, wireType];
    }
    /**
     * Skip one element on the wire and return the skipped data.
     * Supports WireType.StartGroup since v2.0.0-alpha.23.
     */
    skip(wireType) {
        let start = this.pos;
        // noinspection FallThroughInSwitchStatementJS
        switch (wireType) {
            case WireType.Varint:
                while (this.buf[this.pos++] & 0x80) {
                    // ignore
                }
                break;
            case WireType.Bit64:
                this.pos += 4;
            case WireType.Bit32:
                this.pos += 4;
                break;
            case WireType.LengthDelimited:
                let len = this.uint32();
                this.pos += len;
                break;
            case WireType.StartGroup:
                // From descriptor.proto: Group type is deprecated, not supported in proto3.
                // But we must still be able to parse and treat as unknown.
                let t;
                while ((t = this.tag()[1]) !== WireType.EndGroup) {
                    this.skip(t);
                }
                break;
            default:
                throw new Error("cant skip wire type " + wireType);
        }
        this.assertBounds();
        return this.buf.subarray(start, this.pos);
    }
    /**
     * Throws error if position in byte array is out of range.
     */
    assertBounds() {
        if (this.pos > this.len)
            throw new RangeError("premature EOF");
    }
    /**
     * Read a `int32` field, a signed 32 bit varint.
     */
    int32() {
        return this.uint32() | 0;
    }
    /**
     * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint.
     */
    sint32() {
        let zze = this.uint32();
        // decode zigzag
        return (zze >>> 1) ^ -(zze & 1);
    }
    /**
     * Read a `int64` field, a signed 64-bit varint.
     */
    int64() {
        return new PbLong(...this.varint64());
    }
    /**
     * Read a `uint64` field, an unsigned 64-bit varint.
     */
    uint64() {
        return new PbULong(...this.varint64());
    }
    /**
     * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint.
     */
    sint64() {
        let [lo, hi] = this.varint64();
        // decode zig zag
        let s = -(lo & 1);
        lo = ((lo >>> 1 | (hi & 1) << 31) ^ s);
        hi = (hi >>> 1 ^ s);
        return new PbLong(lo, hi);
    }
    /**
     * Read a `bool` field, a variant.
     */
    bool() {
        let [lo, hi] = this.varint64();
        return lo !== 0 || hi !== 0;
    }
    /**
     * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer.
     */
    fixed32() {
        return this.view.getUint32((this.pos += 4) - 4, true);
    }
    /**
     * Read a `sfixed32` field, a signed, fixed-length 32-bit integer.
     */
    sfixed32() {
        return this.view.getInt32((this.pos += 4) - 4, true);
    }
    /**
     * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer.
     */
    fixed64() {
        return new PbULong(this.sfixed32(), this.sfixed32());
    }
    /**
     * Read a `fixed64` field, a signed, fixed-length 64-bit integer.
     */
    sfixed64() {
        return new PbLong(this.sfixed32(), this.sfixed32());
    }
    /**
     * Read a `float` field, 32-bit floating point number.
     */
    float() {
        return this.view.getFloat32((this.pos += 4) - 4, true);
    }
    /**
     * Read a `double` field, a 64-bit floating point number.
     */
    double() {
        return this.view.getFloat64((this.pos += 8) - 8, true);
    }
    /**
     * Read a `bytes` field, length-delimited arbitrary data.
     */
    bytes() {
        let len = this.uint32();
        let start = this.pos;
        this.pos += len;
        this.assertBounds();
        return this.buf.subarray(start, start + len);
    }
    /**
     * Read a `string` field, length-delimited data converted to UTF-8 text.
     */
    string() {
        return this.textDecoder.decode(this.bytes());
    }
}

/**
 * assert that condition is true or throw error (with message)
 */
function assert(condition, msg) {
    if (!condition) {
        throw new Error(msg);
    }
}
const FLOAT32_MAX = 3.4028234663852886e+38, FLOAT32_MIN = -34028234663852886e22, UINT32_MAX = 0xFFFFFFFF, INT32_MAX = 0X7FFFFFFF, INT32_MIN = -2147483648;
function assertInt32(arg) {
    if (typeof arg !== "number")
        throw new Error('invalid int 32: ' + typeof arg);
    if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN)
        throw new Error('invalid int 32: ' + arg);
}
function assertUInt32(arg) {
    if (typeof arg !== "number")
        throw new Error('invalid uint 32: ' + typeof arg);
    if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0)
        throw new Error('invalid uint 32: ' + arg);
}
function assertFloat32(arg) {
    if (typeof arg !== "number")
        throw new Error('invalid float 32: ' + typeof arg);
    if (!Number.isFinite(arg))
        return;
    if (arg > FLOAT32_MAX || arg < FLOAT32_MIN)
        throw new Error('invalid float 32: ' + arg);
}

const defaultsWrite$1 = {
    writeUnknownFields: true,
    writerFactory: () => new BinaryWriter(),
};
/**
 * Make options for writing binary data form partial options.
 */
function binaryWriteOptions(options) {
    return options ? Object.assign(Object.assign({}, defaultsWrite$1), options) : defaultsWrite$1;
}
class BinaryWriter {
    constructor(textEncoder) {
        /**
         * Previous fork states.
         */
        this.stack = [];
        this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder();
        this.chunks = [];
        this.buf = [];
    }
    /**
     * Return all bytes written and reset this writer.
     */
    finish() {
        this.chunks.push(new Uint8Array(this.buf)); // flush the buffer
        let len = 0;
        for (let i = 0; i < this.chunks.length; i++)
            len += this.chunks[i].length;
        let bytes = new Uint8Array(len);
        let offset = 0;
        for (let i = 0; i < this.chunks.length; i++) {
            bytes.set(this.chunks[i], offset);
            offset += this.chunks[i].length;
        }
        this.chunks = [];
        return bytes;
    }
    /**
     * Start a new fork for length-delimited data like a message
     * or a packed repeated field.
     *
     * Must be joined later with `join()`.
     */
    fork() {
        this.stack.push({ chunks: this.chunks, buf: this.buf });
        this.chunks = [];
        this.buf = [];
        return this;
    }
    /**
     * Join the last fork. Write its length and bytes, then
     * return to the previous state.
     */
    join() {
        // get chunk of fork
        let chunk = this.finish();
        // restore previous state
        let prev = this.stack.pop();
        if (!prev)
            throw new Error('invalid state, fork stack empty');
        this.chunks = prev.chunks;
        this.buf = prev.buf;
        // write length of chunk as varint
        this.uint32(chunk.byteLength);
        return this.raw(chunk);
    }
    /**
     * Writes a tag (field number and wire type).
     *
     * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`.
     *
     * Generated code should compute the tag ahead of time and call `uint32()`.
     */
    tag(fieldNo, type) {
        return this.uint32((fieldNo << 3 | type) >>> 0);
    }
    /**
     * Write a chunk of raw bytes.
     */
    raw(chunk) {
        if (this.buf.length) {
            this.chunks.push(new Uint8Array(this.buf));
            this.buf = [];
        }
        this.chunks.push(chunk);
        return this;
    }
    /**
     * Write a `uint32` value, an unsigned 32 bit varint.
     */
    uint32(value) {
        assertUInt32(value);
        // write value as varint 32, inlined for speed
        while (value > 0x7f) {
            this.buf.push((value & 0x7f) | 0x80);
            value = value >>> 7;
        }
        this.buf.push(value);
        return this;
    }
    /**
     * Write a `int32` value, a signed 32 bit varint.
     */
    int32(value) {
        assertInt32(value);
        varint32write(value, this.buf);
        return this;
    }
    /**
     * Write a `bool` value, a variant.
     */
    bool(value) {
        this.buf.push(value ? 1 : 0);
        return this;
    }
    /**
     * Write a `bytes` value, length-delimited arbitrary data.
     */
    bytes(value) {
        this.uint32(value.byteLength); // write length of chunk as varint
        return this.raw(value);
    }
    /**
     * Write a `string` value, length-delimited data converted to UTF-8 text.
     */
    string(value) {
        let chunk = this.textEncoder.encode(value);
        this.uint32(chunk.byteLength); // write length of chunk as varint
        return this.raw(chunk);
    }
    /**
     * Write a `float` value, 32-bit floating point number.
     */
    float(value) {
        assertFloat32(value);
        let chunk = new Uint8Array(4);
        new DataView(chunk.buffer).setFloat32(0, value, true);
        return this.raw(chunk);
    }
    /**
     * Write a `double` value, a 64-bit floating point number.
     */
    double(value) {
        let chunk = new Uint8Array(8);
        new DataView(chunk.buffer).setFloat64(0, value, true);
        return this.raw(chunk);
    }
    /**
     * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer.
     */
    fixed32(value) {
        assertUInt32(value);
        let chunk = new Uint8Array(4);
        new DataView(chunk.buffer).setUint32(0, value, true);
        return this.raw(chunk);
    }
    /**
     * Write a `sfixed32` value, a signed, fixed-length 32-bit integer.
     */
    sfixed32(value) {
        assertInt32(value);
        let chunk = new Uint8Array(4);
        new DataView(chunk.buffer).setInt32(0, value, true);
        return this.raw(chunk);
    }
    /**
     * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint.
     */
    sint32(value) {
        assertInt32(value);
        // zigzag encode
        value = ((value << 1) ^ (value >> 31)) >>> 0;
        varint32write(value, this.buf);
        return this;
    }
    /**
     * Write a `fixed64` value, a signed, fixed-length 64-bit integer.
     */
    sfixed64(value) {
        let chunk = new Uint8Array(8);
        let view = new DataView(chunk.buffer);
        let long = PbLong.from(value);
        view.setInt32(0, long.lo, true);
        view.setInt32(4, long.hi, true);
        return this.raw(chunk);
    }
    /**
     * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer.
     */
    fixed64(value) {
        let chunk = new Uint8Array(8);
        let view = new DataView(chunk.buffer);
        let long = PbULong.from(value);
        view.setInt32(0, long.lo, true);
        view.setInt32(4, long.hi, true);
        return this.raw(chunk);
    }
    /**
     * Write a `int64` value, a signed 64-bit varint.
     */
    int64(value) {
        let long = PbLong.from(value);
        varint64write(long.lo, long.hi, this.buf);
        return this;
    }
    /**
     * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint.
     */
    sint64(value) {
        let long = PbLong.from(value), 
        // zigzag encode
        sign = long.hi >> 31, lo = (long.lo << 1) ^ sign, hi = ((long.hi << 1) | (long.lo >>> 31)) ^ sign;
        varint64write(lo, hi, this.buf);
        return this;
    }
    /**
     * Write a `uint64` value, an unsigned 64-bit varint.
     */
    uint64(value) {
        let long = PbULong.from(value);
        varint64write(long.lo, long.hi, this.buf);
        return this;
    }
}

const defaultsWrite = {
    emitDefaultValues: false,
    enumAsInteger: false,
    useProtoFieldName: false,
    prettySpaces: 0,
}, defaultsRead = {
    ignoreUnknownFields: false,
};
/**
 * Make options for reading JSON data from partial options.
 */
function jsonReadOptions(options) {
    return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead;
}
/**
 * Make options for writing JSON data from partial options.
 */
function jsonWriteOptions(options) {
    return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite;
}

/**
 * The symbol used as a key on message objects to store the message type.
 *
 * Note that this is an experimental feature - it is here to stay, but
 * implementation details may change without notice.
 */
const MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type");

/**
 * Converts snake_case to lowerCamelCase.
 *
 * Should behave like protoc:
 * https://github.com/protocolbuffers/protobuf/blob/e8ae137c96444ea313485ed1118c5e43b2099cf1/src/google/protobuf/compiler/java/java_helpers.cc#L118
 */
function lowerCamelCase(snakeCase) {
    let capNext = false;
    const sb = [];
    for (let i = 0; i < snakeCase.length; i++) {
        let next = snakeCase.charAt(i);
        if (next == '_') {
            capNext = true;
        }
        else if (/\d/.test(next)) {
            sb.push(next);
            capNext = true;
        }
        else if (capNext) {
            sb.push(next.toUpperCase());
            capNext = false;
        }
        else if (i == 0) {
            sb.push(next.toLowerCase());
        }
        else {
            sb.push(next);
        }
    }
    return sb.join('');
}

/**
 * Scalar value types. This is a subset of field types declared by protobuf
 * enum google.protobuf.FieldDescriptorProto.Type The types GROUP and MESSAGE
 * are omitted, but the numerical values are identical.
 */
var ScalarType;
(function (ScalarType) {
    // 0 is reserved for errors.
    // Order is weird for historical reasons.
    ScalarType[ScalarType["DOUBLE"] = 1] = "DOUBLE";
    ScalarType[ScalarType["FLOAT"] = 2] = "FLOAT";
    // Not ZigZag encoded.  Negative numbers take 10 bytes.  Use TYPE_SINT64 if
    // negative values are likely.
    ScalarType[ScalarType["INT64"] = 3] = "INT64";
    ScalarType[ScalarType["UINT64"] = 4] = "UINT64";
    // Not ZigZag encoded.  Negative numbers take 10 bytes.  Use TYPE_SINT32 if
    // negative values are likely.
    ScalarType[ScalarType["INT32"] = 5] = "INT32";
    ScalarType[ScalarType["FIXED64"] = 6] = "FIXED64";
    ScalarType[ScalarType["FIXED32"] = 7] = "FIXED32";
    ScalarType[ScalarType["BOOL"] = 8] = "BOOL";
    ScalarType[ScalarType["STRING"] = 9] = "STRING";
    // Tag-delimited aggregate.
    // Group type is deprecated and not supported in proto3. However, Proto3
    // implementations should still be able to parse the group wire format and
    // treat group fields as unknown fields.
    // TYPE_GROUP = 10,
    // TYPE_MESSAGE = 11,  // Length-delimited aggregate.
    // New in version 2.
    ScalarType[ScalarType["BYTES"] = 12] = "BYTES";
    ScalarType[ScalarType["UINT32"] = 13] = "UINT32";
    // TYPE_ENUM = 14,
    ScalarType[ScalarType["SFIXED32"] = 15] = "SFIXED32";
    ScalarType[ScalarType["SFIXED64"] = 16] = "SFIXED64";
    ScalarType[ScalarType["SINT32"] = 17] = "SINT32";
    ScalarType[ScalarType["SINT64"] = 18] = "SINT64";
})(ScalarType || (ScalarType = {}));
/**
 * JavaScript representation of 64 bit integral types. Equivalent to the
 * field option "jstype".
 *
 * By default, protobuf-ts represents 64 bit types as `bigint`.
 *
 * You can change the default behaviour by enabling the plugin parameter
 * `long_type_string`, which will represent 64 bit types as `string`.
 *
 * Alternatively, you can change the behaviour for individual fields
 * with the field option "jstype":
 *
 * ```protobuf
 * uint64 my_field = 1 [jstype = JS_STRING];
 * uint64 other_field = 2 [jstype = JS_NUMBER];
 * ```
 */
var LongType;
(function (LongType) {
    /**
     * Use JavaScript `bigint`.
     *
     * Field option `[jstype = JS_NORMAL]`.
     */
    LongType[LongType["BIGINT"] = 0] = "BIGINT";
    /**
     * Use JavaScript `string`.
     *
     * Field option `[jstype = JS_STRING]`.
     */
    LongType[LongType["STRING"] = 1] = "STRING";
    /**
     * Use JavaScript `number`.
     *
     * Large values will loose precision.
     *
     * Field option `[jstype = JS_NUMBER]`.
     */
    LongType[LongType["NUMBER"] = 2] = "NUMBER";
})(LongType || (LongType = {}));
/**
 * Protobuf 2.1.0 introduced packed repeated fields.
 * Setting the field option `[packed = true]` enables packing.
 *
 * In proto3, all repeated fields are packed by default.
 * Setting the field option `[packed = false]` disables packing.
 *
 * Packed repeated fields are encoded with a single tag,
 * then a length-delimiter, then the element values.
 *
 * Unpacked repeated fields are encoded with a tag and
 * value for each element.
 *
 * `bytes` and `string` cannot be packed.
 */
var RepeatType;
(function (RepeatType) {
    /**
     * The field is not repeated.
     */
    RepeatType[RepeatType["NO"] = 0] = "NO";
    /**
     * The field is repeated and should be packed.
     * Invalid for `bytes` and `string`, they cannot be packed.
     */
    RepeatType[RepeatType["PACKED"] = 1] = "PACKED";
    /**
     * The field is repeated but should not be packed.
     * The only valid repeat type for repeated `bytes` and `string`.
     */
    RepeatType[RepeatType["UNPACKED"] = 2] = "UNPACKED";
})(RepeatType || (RepeatType = {}));
/**
 * Turns PartialFieldInfo into FieldInfo.
 */
function normalizeFieldInfo(field) {
    var _a, _b, _c, _d;
    field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lowerCamelCase(field.name);
    field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lowerCamelCase(field.name);
    field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO;
    field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : (field.repeat ? false : field.oneof ? false : field.kind == "message");
    return field;
}

/**
 * Is the given value a valid oneof group?
 *
 * We represent protobuf `oneof` as algebraic data types (ADT) in generated
 * code. But when working with messages of unknown type, the ADT does not
 * help us.
 *
 * This type guard checks if the given object adheres to the ADT rules, which
 * are as follows:
 *
 * 1) Must be an object.
 *
 * 2) Must have a "oneofKind" discriminator property.
 *
 * 3) If "oneofKind" is `undefined`, no member field is selected. The object
 * must not have any other properties.
 *
 * 4) If "oneofKind" is a `string`, the member field with this name is
 * selected.
 *
 * 5) If a member field is selected, the object must have a second property
 * with this name. The property must not be `undefined`.
 *
 * 6) No extra properties are allowed. The object has either one property
 * (no selection) or two properties (selection).
 *
 */
function isOneofGroup(any) {
    if (typeof any != 'object' || any === null || !any.hasOwnProperty('oneofKind')) {
        return false;
    }
    switch (typeof any.oneofKind) {
        case "string":
            if (any[any.oneofKind] === undefined)
                return false;
            return Object.keys(any).length == 2;
        case "undefined":
            return Object.keys(any).length == 1;
        default:
            return false;
    }
}

// noinspection JSMethodCanBeStatic
class ReflectionTypeCheck {
    constructor(info) {
        var _a;
        this.fields = (_a = info.fields) !== null && _a !== void 0 ? _a : [];
    }
    prepare() {
        if (this.data)
            return;
        const req = [], known = [], oneofs = [];
        for (let field of this.fields) {
            if (field.oneof) {
                if (!oneofs.includes(field.oneof)) {
                    oneofs.push(field.oneof);
                    req.push(field.oneof);
                    known.push(field.oneof);
                }
            }
            else {
                known.push(field.localName);
                switch (field.kind) {
                    case "scalar":
                    case "enum":
                        if (!field.opt || field.repeat)
                            req.push(field.localName);
                        break;
                    case "message":
                        if (field.repeat)
                            req.push(field.localName);
                        break;
                    case "map":
                        req.push(field.localName);
                        break;
                }
            }
        }
        this.data = { req, known, oneofs: Object.values(oneofs) };
    }
    /**
     * Is the argument a valid message as specified by the
     * reflection information?
     *
     * Checks all field types recursively. The `depth`
     * specifies how deep into the structure the check will be.
     *
     * With a depth of 0, only the presence of fields
     * is checked.
     *
     * With a depth of 1 or more, the field types are checked.
     *
     * With a depth of 2 or more, the members of map, repeated
     * and message fields are checked.
     *
     * Message fields will be checked recursively with depth - 1.
     *
     * The number of map entries / repeated values being checked
     * is < depth.
     */
    is(message, depth, allowExcessProperties = false) {
        if (depth < 0)
            return true;
        if (message === null || message === undefined || typeof message != 'object')
            return false;
        this.prepare();
        let keys = Object.keys(message), data = this.data;
        // if a required field is missing in arg, this cannot be a T
        if (keys.length < data.req.length || data.req.some(n => !keys.includes(n)))
            return false;
        if (!allowExcessProperties) {
            // if the arg contains a key we dont know, this is not a literal T
            if (keys.some(k => !data.known.includes(k)))
                return false;
        }
        // "With a depth of 0, only the presence and absence of fields is checked."
        // "With a depth of 1 or more, the field types are checked."
        if (depth < 1) {
            return true;
        }
        // check oneof group
        for (const name of data.oneofs) {
            const group = message[name];
            if (!isOneofGroup(group))
                return false;
            if (group.oneofKind === undefined)
                continue;
            const field = this.fields.find(f => f.localName === group.oneofKind);
            if (!field)
                return false; // we found no field, but have a kind, something is wrong
            if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth))
                return false;
        }
        // check types
        for (const field of this.fields) {
            if (field.oneof !== undefined)
                continue;
            if (!this.field(message[field.localName], field, allowExcessProperties, depth))
                return false;
        }
        return true;
    }
    field(arg, field, allowExcessProperties, depth) {
        let repeated = field.repeat;
        switch (field.kind) {
            case "scalar":
                if (arg === undefined)
                    return field.opt;
                if (repeated)
                    return this.scalars(arg, field.T, depth, field.L);
                return this.scalar(arg, field.T, field.L);
            case "enum":
                if (arg === undefined)
                    return field.opt;
                if (repeated)
                    return this.scalars(arg, ScalarType.INT32, depth);
                return this.scalar(arg, ScalarType.INT32);
            case "message":
                if (arg === undefined)
                    return true;
                if (repeated)
                    return this.messages(arg, field.T(), allowExcessProperties, depth);
                return this.message(arg, field.T(), allowExcessProperties, depth);
            case "map":
                if (typeof arg != 'object' || arg === null)
                    return false;
                if (depth < 2)
                    return true;
                if (!this.mapKeys(arg, field.K, depth))
                    return false;
                switch (field.V.kind) {
                    case "scalar":
                        return this.scalars(Object.values(arg), field.V.T, depth, field.V.L);
                    case "enum":
                        return this.scalars(Object.values(arg), ScalarType.INT32, depth);
                    case "message":
                        return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth);
                }
                break;
        }
        return true;
    }
    message(arg, type, allowExcessProperties, depth) {
        if (allowExcessProperties) {
            return type.isAssignable(arg, depth);
        }
        return type.is(arg, depth);
    }
    messages(arg, type, allowExcessProperties, depth) {
        if (!Array.isArray(arg))
            return false;
        if (depth < 2)
            return true;
        if (allowExcessProperties) {
            for (let i = 0; i < arg.length && i < depth; i++)
                if (!type.isAssignable(arg[i], depth - 1))
                    return false;
        }
        else {
            for (let i = 0; i < arg.length && i < depth; i++)
                if (!type.is(arg[i], depth - 1))
                    return false;
        }
        return true;
    }
    scalar(arg, type, longType) {
        let argType = typeof arg;
        switch (type) {
            case ScalarType.UINT64:
            case ScalarType.FIXED64:
            case ScalarType.INT64:
            case ScalarType.SFIXED64:
            case ScalarType.SINT64:
                switch (longType) {
                    case LongType.BIGINT:
                        return argType == "bigint";
                    case LongType.NUMBER:
                        return argType == "number" && !isNaN(arg);
                    default:
                        return argType == "string";
                }
            case ScalarType.BOOL:
                return argType == 'boolean';
            case ScalarType.STRING:
                return argType == 'string';
            case ScalarType.BYTES:
                return arg instanceof Uint8Array;
            case ScalarType.DOUBLE:
            case ScalarType.FLOAT:
                return argType == 'number' && !isNaN(arg);
            default:
                // case ScalarType.UINT32:
                // case ScalarType.FIXED32:
                // case ScalarType.INT32:
                // case ScalarType.SINT32:
                // case ScalarType.SFIXED32:
                return argType == 'number' && Number.isInteger(arg);
        }
    }
    scalars(arg, type, depth, longType) {
        if (!Array.isArray(arg))
            return false;
        if (depth < 2)
            return true;
        if (Array.isArray(arg))
            for (let i = 0; i < arg.length && i < depth; i++)
                if (!this.scalar(arg[i], type, longType))
                    return false;
        return true;
    }
    mapKeys(map, type, depth) {
        let keys = Object.keys(map);
        switch (type) {
            case ScalarType.INT32:
            case ScalarType.FIXED32:
            case ScalarType.SFIXED32:
            case ScalarType.SINT32:
            case ScalarType.UINT32:
                return this.scalars(keys.slice(0, depth).map(k => parseInt(k)), type, depth);
            case ScalarType.BOOL:
                return this.scalars(keys.slice(0, depth).map(k => k == 'true' ? true : k == 'false' ? false : k), type, depth);
            default:
                return this.scalars(keys, type, depth, LongType.STRING);
        }
    }
}

/**
 * Utility method to convert a PbLong or PbUlong to a JavaScript
 * representation during runtime.
 *
 * Works with generated field information, `undefined` is equivalent
 * to `STRING`.
 */
function reflectionLongConvert(long, type) {
    switch (type) {
        case LongType.BIGINT:
            return long.toBigInt();
        case LongType.NUMBER:
            return long.toNumber();
        default:
            // case undefined:
            // case LongType.STRING:
            return long.toString();
    }
}

/**
 * Reads proto3 messages in canonical JSON format using reflection information.
 *
 * https://developers.google.com/protocol-buffers/docs/proto3#json
 */
class ReflectionJsonReader {
    constructor(info) {
        this.info = info;
    }
    prepare() {
        var _a;
        if (this.fMap === undefined) {
            this.fMap = {};
            const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : [];
            for (const field of fieldsInput) {
                this.fMap[field.name] = field;
                this.fMap[field.jsonName] = field;
                this.fMap[field.localName] = field;
            }
        }
    }
    // Cannot parse JSON <type of jsonValue> for <type name>#<fieldName>.
    assert(condition, fieldName, jsonValue) {
        if (!condition) {
            let what = typeofJsonValue(jsonValue);
            if (what == "number" || what == "boolean")
                what = jsonValue.toString();
            throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`);
        }
    }
    /**
     * Reads a message from canonical JSON format into the target message.
     *
     * Repeated fields are appended. Map entries are added, overwriting
     * existing keys.
     *
     * If a message field is already present, it will be merged with the
     * new data.
     */
    read(input, message, options) {
        this.prepare();
        const oneofsHandled = [];
        for (const [jsonKey, jsonValue] of Object.entries(input)) {
            const field = this.fMap[jsonKey];
            if (!field) {
                if (!options.ignoreUnknownFields)
                    throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`);
                continue;
            }
            const localName = field.localName;
            // handle oneof ADT
            let target; // this will be the target for the field value, whether it is member of a oneof or not
            if (field.oneof) {
                if (jsonValue === null && (field.kind !== 'enum' || field.T()[0] !== 'google.protobuf.NullValue')) {
                    continue;
                }
                // since json objects are unordered by specification, it is not possible to take the last of multiple oneofs
                if (oneofsHandled.includes(field.oneof))
                    throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`);
                oneofsHandled.push(field.oneof);
                target = message[field.oneof] = {
                    oneofKind: localName
                };
            }
            else {
                target = message;
            }
            // we have handled oneof above. we just have read the value into `target`.
            if (field.kind == 'map') {
                if (jsonValue === null) {
                    continue;
                }
                // check input
                this.assert(isJsonObject(jsonValue), field.name, jsonValue);
                // our target to put map entries into
                const fieldObj = target[localName];
                // read entries
                for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) {
                    this.assert(jsonObjValue !== null, field.name + " map value", null);
                    // read value
                    let val;
                    switch (field.V.kind) {
                        case "message":
                            val = field.V.T().internalJsonRead(jsonObjValue, options);
                            break;
                        case "enum":
                            val = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields);
                            if (val === false)
                                continue;
                            break;
                        case "scalar":
                            val = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name);
                            break;
                    }
                    this.assert(val !== undefined, field.name + " map value", jsonObjValue);
                    // read key
                    let key = jsonObjKey;
                    if (field.K == ScalarType.BOOL)
                        key = key == "true" ? true : key == "false" ? false : key;
                    key = this.scalar(key, field.K, LongType.STRING, field.name).toString();
                    fieldObj[key] = val;
                }
            }
            else if (field.repeat) {
                if (jsonValue === null)
                    continue;
                // check input
                this.assert(Array.isArray(jsonValue), field.name, jsonValue);
                // our target to put array entries into
                const fieldArr = target[localName];
                // read array entries
                for (const jsonItem of jsonValue) {
                    this.assert(jsonItem !== null, field.name, null);
                    let val;
                    switch (field.kind) {
                        case "message":
                            val = field.T().internalJsonRead(jsonItem, options);
                            break;
                        case "enum":
                            val = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields);
                            if (val === false)
                                continue;
                            break;
                        case "scalar":
                            val = this.scalar(jsonItem, field.T, field.L, field.name);
                            break;
                    }
                    this.assert(val !== undefined, field.name, jsonValue);
                    fieldArr.push(val);
                }
            }
            else {
                switch (field.kind) {
                    case "message":
                        if (jsonValue === null && field.T().typeName != 'google.protobuf.Value') {
                            this.assert(field.oneof === undefined, field.name + " (oneof member)", null);
                            continue;
                        }
                        target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]);
                        break;
                    case "enum":
                        if (jsonValue === null)
                            continue;
                        let val = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields);
                        if (val === false)
                            continue;
                        target[localName] = val;
                        break;
                    case "scalar":
                        if (jsonValue === null)
                            continue;
                        target[localName] = this.scalar(jsonValue, field.T, field.L, field.name);
                        break;
                }
            }
        }
    }
    /**
     * Returns `false` for unrecognized string representations.
     *
     * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`).
     */
    enum(type, json, fieldName, ignoreUnknownFields) {
        if (type[0] == 'google.protobuf.NullValue')
            assert(json === null || json === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} only accepts null.`);
        if (json === null)
            // we require 0 to be default value for all enums
            return 0;
        switch (typeof json) {
            case "number":
                assert(Number.isInteger(json), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json}.`);
                return json;
            case "string":
                let localEnumName = json;
                if (type[2] && json.substring(0, type[2].length) === type[2])
                    // lookup without the shared prefix
                    localEnumName = json.substring(type[2].length);
                let enumNumber = type[1][localEnumName];
                if (typeof enumNumber === 'undefined' && ignoreUnknownFields) {
                    return false;
                }
                assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} has no value for "${json}".`);
                return enumNumber;
        }
        assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json}".`);
    }
    scalar(json, type, longType, fieldName) {
        let e;
        try {
            switch (type) {
                // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
                // Either numbers or strings are accepted. Exponent notation is also accepted.
                case ScalarType.DOUBLE:
                case ScalarType.FLOAT:
                    if (json === null)
                        return .0;
                    if (json === "NaN")
                        return Number.NaN;
                    if (json === "Infinity")
                        return Number.POSITIVE_INFINITY;
                    if (json === "-Infinity")
                        return Number.NEGATIVE_INFINITY;
                    if (json === "") {
                        e = "empty string";
                        break;
                    }
                    if (typeof json == "string" && json.trim().length !== json.length) {
                        e = "extra whitespace";
                        break;
                    }
                    if (typeof json != "string" && typeof json != "number") {
                        break;
                    }
                    let float = Number(json);
                    if (Number.isNaN(float)) {
                        e = "not a number";
                        break;
                    }
                    if (!Number.isFinite(float)) {
                        // infinity and -infinity are handled by string representation above, so this is an error
                        e = "too large or small";
                        break;
                    }
                    if (type == ScalarType.FLOAT)
                        assertFloat32(float);
                    return float;
                // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
                case ScalarType.INT32:
                case ScalarType.FIXED32:
                case ScalarType.SFIXED32:
                case ScalarType.SINT32:
                case ScalarType.UINT32:
                    if (json === null)
                        return 0;
                    let int32;
                    if (typeof json == "number")
                        int32 = json;
                    else if (json === "")
                        e = "empty string";
                    else if (typeof json == "string") {
                        if (json.trim().length !== json.length)
                            e = "extra whitespace";
                        else
                            int32 = Number(json);
                    }
                    if (int32 === undefined)
                        break;
                    if (type == ScalarType.UINT32)
                        assertUInt32(int32);
                    else
                        assertInt32(int32);
                    return int32;
                // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted.
                case ScalarType.INT64:
                case ScalarType.SFIXED64:
                case ScalarType.SINT64:
                    if (json === null)
                        return reflectionLongConvert(PbLong.ZERO, longType);
                    if (typeof json != "number" && typeof json != "string")
                        break;
                    return reflectionLongConvert(PbLong.from(json), longType);
                case ScalarType.FIXED64:
                case ScalarType.UINT64:
                    if (json === null)
                        return reflectionLongConvert(PbULong.ZERO, longType);
                    if (typeof json != "number" && typeof json != "string")
                        break;
                    return reflectionLongConvert(PbULong.from(json), longType);
                // bool:
                case ScalarType.BOOL:
                    if (json === null)
                        return false;
                    if (typeof json !== "boolean")
                        break;
                    return json;
                // string:
                case ScalarType.STRING:
                    if (json === null)
                        return "";
                    if (typeof json !== "string") {
                        e = "extra whitespace";
                        break;
                    }
                    try {
                        encodeURIComponent(json);
                    }
                    catch (e) {
                        e = "invalid UTF8";
                        break;
                    }
                    return json;
                // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
                // Either standard or URL-safe base64 encoding with/without paddings are accepted.
                case ScalarType.BYTES:
                    if (json === null || json === "")
                        return new Uint8Array(0);
                    if (typeof json !== 'string')
                        break;
                    return base64decode(json);
            }
        }
        catch (error) {
            e = error.message;
        }
        this.assert(false, fieldName + (e ? " - " + e : ""), json);
    }
}

/**
 * Writes proto3 messages in canonical JSON format using reflection
 * information.
 *
 * https://developers.google.com/protocol-buffers/docs/proto3#json
 */
class ReflectionJsonWriter {
    constructor(info) {
        var _a;
        this.fields = (_a = info.fields) !== null && _a !== void 0 ? _a : [];
    }
    /**
     * Converts the message to a JSON object, based on the field descriptors.
     */
    write(message, options) {
        const json = {}, source = message;
        for (const field of this.fields) {
            // field is not part of a oneof, simply write as is
            if (!field.oneof) {
                let jsonValue = this.field(field, source[field.localName], options);
                if (jsonValue !== undefined)
                    json[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue;
                continue;
            }
            // field is part of a oneof
            const group = source[field.oneof];
            if (group.oneofKind !== field.localName)
                continue; // not selected, skip
            const opt = field.kind == 'scalar' || field.kind == 'enum'
                ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options;
            let jsonValue = this.field(field, group[field.localName], opt);
            assert(jsonValue !== undefined);
            json[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue;
        }
        return json;
    }
    field(field, value, options) {
        let jsonValue = undefined;
        if (field.kind == 'map') {
            assert(typeof value == "object" && value !== null);
            const jsonObj = {};
            switch (field.V.kind) {
                case "scalar":
                    for (const [entryKey, entryValue] of Object.entries(value)) {
                        const val = this.scalar(field.V.T, entryValue, field.name, false, true);
                        assert(val !== undefined);
                        jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key
                    }
                    break;
                case "message":
                    const messageType = field.V.T();
                    for (const [entryKey, entryValue] of Object.entries(value)) {
                        const val = this.message(messageType, entryValue, field.name, options);
                        assert(val !== undefined);
                        jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key
                    }
                    break;
                case "enum":
                    const enumInfo = field.V.T();
                    for (const [entryKey, entryValue] of Object.entries(value)) {
                        assert(entryValue === undefined || typeof entryValue == 'number');
                        const val = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger);
                        assert(val !== undefined);
                        jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key
                    }
                    break;
            }
            if (options.emitDefaultValues || Object.keys(jsonObj).length > 0)
                jsonValue = jsonObj;
        }
        else if (field.repeat) {
            assert(Array.isArray(value));
            const jsonArr = [];
            switch (field.kind) {
                case "scalar":
                    for (let i = 0; i < value.length; i++) {
                        const val = this.scalar(field.T, value[i], field.name, field.opt, true);
                        assert(val !== undefined);
                        jsonArr.push(val);
                    }
                    break;
                case "enum":
                    const enumInfo = field.T();
                    for (let i = 0; i < value.length; i++) {
                        assert(value[i] === undefined || typeof value[i] == 'number');
                        const val = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger);
                        assert(val !== undefined);
                        jsonArr.push(val);
                    }
                    break;
                case "message":
                    const messageType = field.T();
                    for (let i = 0; i < value.length; i++) {
                        const val = this.message(messageType, value[i], field.name, options);
                        assert(val !== undefined);
                        jsonArr.push(val);
                    }
                    break;
            }
            // add converted array to json output
            if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues)
                jsonValue = jsonArr;
        }
        else {
            switch (field.kind) {
                case "scalar":
                    jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues);
                    break;
                case "enum":
                    jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger);
                    break;
                case "message":
                    jsonValue = this.message(field.T(), value, field.name, options);
                    break;
            }
        }
        return jsonValue;
    }
    /**
     * Returns `null` as the default for google.protobuf.NullValue.
     */
    enum(type, value, fieldName, optional, emitDefaultValues, enumAsInteger) {
        if (type[0] == 'google.protobuf.NullValue')
            return !emitDefaultValues && !optional ? undefined : null;
        if (value === undefined) {
            assert(optional);
            return undefined;
        }
        if (value === 0 && !emitDefaultValues && !optional)
            // we require 0 to be default value for all enums
            return undefined;
        assert(typeof value == 'number');
        assert(Number.isInteger(value));
        if (enumAsInteger || !type[1].hasOwnProperty(value))
            // if we don't now the enum value, just return the number
            return value;
        if (type[2])
            // restore the dropped prefix
            return type[2] + type[1][value];
        return type[1][value];
    }
    message(type, value, fieldName, options) {
        if (value === undefined)
            return options.emitDefaultValues ? null : undefined;
        return type.internalJsonWrite(value, options);
    }
    scalar(type, value, fieldName, optional, emitDefaultValues) {
        if (value === undefined) {
            assert(optional);
            return undefined;
        }
        const ed = emitDefaultValues || optional;
        // noinspection FallThroughInSwitchStatementJS
        switch (type) {
            // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
            case ScalarType.INT32:
            case ScalarType.SFIXED32:
            case ScalarType.SINT32:
                if (value === 0)
                    return ed ? 0 : undefined;
                assertInt32(value);
                return value;
            case ScalarType.FIXED32:
            case ScalarType.UINT32:
                if (value === 0)
                    return ed ? 0 : undefined;
                assertUInt32(value);
                return value;
            // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
            // Either numbers or strings are accepted. Exponent notation is also accepted.
            case ScalarType.FLOAT:
                assertFloat32(value);
            case ScalarType.DOUBLE:
                if (value === 0)
                    return ed ? 0 : undefined;
                assert(typeof value == 'number');
                if (Number.isNaN(value))
                    return 'NaN';
                if (value === Number.POSITIVE_INFINITY)
                    return 'Infinity';
                if (value === Number.NEGATIVE_INFINITY)
                    return '-Infinity';
                return value;
            // string:
            case ScalarType.STRING:
                if (value === "")
                    return ed ? '' : undefined;
                assert(typeof value == 'string');
                return value;
            // bool:
            case ScalarType.BOOL:
                if (value === false)
                    return ed ? false : undefined;
                assert(typeof value == 'boolean');
                return value;
            // JSON value will be a decimal string. Either numbers or strings are accepted.
            case ScalarType.UINT64:
            case ScalarType.FIXED64:
                assert(typeof value == 'number' || typeof value == 'string' || typeof value == 'bigint');
                let ulong = PbULong.from(value);
                if (ulong.isZero() && !ed)
                    return undefined;
                return ulong.toString();
            // JSON value will be a decimal string. Either numbers or strings are accepted.
            case ScalarType.INT64:
            case ScalarType.SFIXED64:
            case ScalarType.SINT64:
                assert(typeof value == 'number' || typeof value == 'string' || typeof value == 'bigint');
                let long = PbLong.from(value);
                if (long.isZero() && !ed)
                    return undefined;
                return long.toString();
            // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
            // Either standard or URL-safe base64 encoding with/without paddings are accepted.
            case ScalarType.BYTES:
                assert(value instanceof Uint8Array);
                if (!value.byteLength)
                    return ed ? "" : undefined;
                return base64encode(value);
        }
    }
}

/**
 * Creates the default value for a scalar type.
 */
function reflectionScalarDefault(type, longType = LongType.STRING) {
    switch (type) {
        case ScalarType.BOOL:
            return false;
        case ScalarType.UINT64:
        case ScalarType.FIXED64:
            return reflectionLongConvert(PbULong.ZERO, longType);
        case ScalarType.INT64:
        case ScalarType.SFIXED64:
        case ScalarType.SINT64:
            return reflectionLongConvert(PbLong.ZERO, longType);
        case ScalarType.DOUBLE:
        case ScalarType.FLOAT:
            return 0.0;
        case ScalarType.BYTES:
            return new Uint8Array(0);
        case ScalarType.STRING:
            return "";
        default:
            // case ScalarType.INT32:
            // case ScalarType.UINT32:
            // case ScalarType.SINT32:
            // case ScalarType.FIXED32:
            // case ScalarType.SFIXED32:
            return 0;
    }
}

/**
 * Reads proto3 messages in binary format using reflection information.
 *
 * https://developers.google.com/protocol-buffers/docs/encoding
 */
class ReflectionBinaryReader {
    constructor(info) {
        this.info = info;
    }
    prepare() {
        var _a;
        if (!this.fieldNoToField) {
            const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : [];
            this.fieldNoToField = new Map(fieldsInput.map(field => [field.no, field]));
        }
    }
    /**
     * Reads a message from binary format into the target message.
     *
     * Repeated fields are appended. Map entries are added, overwriting
     * existing keys.
     *
     * If a message field is already present, it will be merged with the
     * new data.
     */
    read(reader, message, options, length) {
        this.prepare();
        const end = length === undefined ? reader.len : reader.pos + length;
        while (reader.pos < end) {
            // read the tag and find the field
            const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo);
            if (!field) {
                let u = options.readUnknownField;
                if (u == "throw")
                    throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`);
                let d = reader.skip(wireType);
                if (u !== false)
                    (u === true ? UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d);
                continue;
            }
            // target object for the field we are reading
            let target = message, repeated = field.repeat, localName = field.localName;
            // if field is member of oneof ADT, use ADT as target
            if (field.oneof) {
                target = target[field.oneof];
                // if other oneof member selected, set new ADT
                if (target.oneofKind !== localName)
                    target = message[field.oneof] = {
                        oneofKind: localName
                    };
            }
            // we have handled oneof above, we just have read the value into `target[localName]`
            switch (field.kind) {
                case "scalar":
                case "enum":
                    let T = field.kind == "enum" ? ScalarType.INT32 : field.T;
                    let L = field.kind == "scalar" ? field.L : undefined;
                    if (repeated) {
                        let arr = target[localName]; // safe to assume presence of array, oneof cannot contain repeated values
                        if (wireType == WireType.LengthDelimited && T != ScalarType.STRING && T != ScalarType.BYTES) {
                            let e = reader.uint32() + reader.pos;
                            while (reader.pos < e)
                                arr.push(this.scalar(reader, T, L));
                        }
                        else
                            arr.push(this.scalar(reader, T, L));
                    }
                    else
                        target[localName] = this.scalar(reader, T, L);
                    break;
                case "message":
                    if (repeated) {
                        let arr = target[localName]; // safe to assume presence of array, oneof cannot contain repeated values
                        let msg = field.T().internalBinaryRead(reader, reader.uint32(), options);
                        arr.push(msg);
                    }
                    else
                        target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]);
                    break;
                case "map":
                    let [mapKey, mapVal] = this.mapEntry(field, reader, options);
                    // safe to assume presence of map object, oneof cannot contain repeated values
                    target[localName][mapKey] = mapVal;
                    break;
            }
        }
    }
    /**
     * Read a map field, expecting key field = 1, value field = 2
     */
    mapEntry(field, reader, options) {
        let length = reader.uint32();
        let end = reader.pos + length;
        let key = undefined; // javascript only allows number or string for object properties
        let val = undefined;
        while (reader.pos < end) {
            let [fieldNo, wireType] = reader.tag();
            switch (fieldNo) {
                case 1:
                    if (field.K == ScalarType.BOOL)
                        key = reader.bool().toString();
                    else
                        // long types are read as string, number types are okay as number
                        key = this.scalar(reader, field.K, LongType.STRING);
                    break;
                case 2:
                    switch (field.V.kind) {
                        case "scalar":
                            val = this.scalar(reader, field.V.T, field.V.L);
                            break;
                        case "enum":
                            val = reader.int32();
                            break;
                        case "message":
                            val = field.V.T().internalBinaryRead(reader, reader.uint32(), options);
                            break;
                    }
                    break;
                default:
                    throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`);
            }
        }
        if (key === undefined) {
            let keyRaw = reflectionScalarDefault(field.K);
            key = field.K == ScalarType.BOOL ? keyRaw.toString() : keyRaw;
        }
        if (val === undefined)
            switch (field.V.kind) {
                case "scalar":
                    val = reflectionScalarDefault(field.V.T, field.V.L);
                    break;
                case "enum":
                    val = 0;
                    break;
                case "message":
                    val = field.V.T().create();
                    break;
            }
        return [key, val];
    }
    scalar(reader, type, longType) {
        switch (type) {
            case ScalarType.INT32:
                return reader.int32();
            case ScalarType.STRING:
                return reader.string();
            case ScalarType.BOOL:
                return reader.bool();
            case ScalarType.DOUBLE:
                return reader.double();
            case ScalarType.FLOAT:
                return reader.float();
            case ScalarType.INT64:
                return reflectionLongConvert(reader.int64(), longType);
            case ScalarType.UINT64:
                return reflectionLongConvert(reader.uint64(), longType);
            case ScalarType.FIXED64:
                return reflectionLongConvert(reader.fixed64(), longType);
            case ScalarType.FIXED32:
                return reader.fixed32();
            case ScalarType.BYTES:
                return reader.bytes();
            case ScalarType.UINT32:
                return reader.uint32();
            case ScalarType.SFIXED32:
                return reader.sfixed32();
            case ScalarType.SFIXED64:
                return reflectionLongConvert(reader.sfixed64(), longType);
            case ScalarType.SINT32:
                return reader.sint32();
            case ScalarType.SINT64:
                return reflectionLongConvert(reader.sint64(), longType);
        }
    }
}

/**
 * Writes proto3 messages in binary format using reflection information.
 *
 * https://developers.google.com/protocol-buffers/docs/encoding
 */
class ReflectionBinaryWriter {
    constructor(info) {
        this.info = info;
    }
    prepare() {
        if (!this.fields) {
            const fieldsInput = this.info.fields ? this.info.fields.concat() : [];
            this.fields = fieldsInput.sort((a, b) => a.no - b.no);
        }
    }
    /**
     * Writes the message to binary format.
     */
    write(message, writer, options) {
        this.prepare();
        for (const field of this.fields) {
            let value, // this will be our field value, whether it is member of a oneof or not
            emitDefault, // whether we emit the default value (only true for oneof members)
            repeated = field.repeat, localName = field.localName;
            // handle oneof ADT
            if (field.oneof) {
                const group = message[field.oneof];
                if (group.oneofKind !== localName)
                    continue; // if field is not selected, skip
                value = group[localName];
                emitDefault = true;
            }
            else {
                value = message[localName];
                emitDefault = false;
            }
            // we have handled oneof above. we just have to honor `emitDefault`.
            switch (field.kind) {
                case "scalar":
                case "enum":
                    let T = field.kind == "enum" ? ScalarType.INT32 : field.T;
                    if (repeated) {
                        assert(Array.isArray(value));
                        if (repeated == RepeatType.PACKED)
                            this.packed(writer, T, field.no, value);
                        else
                            for (const item of value)
                                this.scalar(writer, T, field.no, item, true);
                    }
                    else if (value === undefined)
                        assert(field.opt);
                    else
                        this.scalar(writer, T, field.no, value, emitDefault || field.opt);
                    break;
                case "message":
                    if (repeated) {
                        assert(Array.isArray(value));
                        for (const item of value)
                            this.message(writer, options, field.T(), field.no, item);
                    }
                    else {
                        this.message(writer, options, field.T(), field.no, value);
                    }
                    break;
                case "map":
                    assert(typeof value == 'object' && value !== null);
                    for (const [key, val] of Object.entries(value))
                        this.mapEntry(writer, options, field, key, val);
                    break;
            }
        }
        let u = options.writeUnknownFields;
        if (u !== false)
            (u === true ? UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer);
    }
    mapEntry(writer, options, field, key, value) {
        writer.tag(field.no, WireType.LengthDelimited);
        writer.fork();
        // javascript only allows number or string for object properties
        // we convert from our representation to the protobuf type
        let keyValue = key;
        switch (field.K) {
            case ScalarType.INT32:
            case ScalarType.FIXED32:
            case ScalarType.UINT32:
            case ScalarType.SFIXED32:
            case ScalarType.SINT32:
                keyValue = Number.parseInt(key);
                break;
            case ScalarType.BOOL:
                assert(key == 'true' || key == 'false');
                keyValue = key == 'true';
                break;
        }
        // write key, expecting key field number = 1
        this.scalar(writer, field.K, 1, keyValue, true);
        // write value, expecting value field number = 2
        switch (field.V.kind) {
            case 'scalar':
                this.scalar(writer, field.V.T, 2, value, true);
                break;
            case 'enum':
                this.scalar(writer, ScalarType.INT32, 2, value, true);
                break;
            case 'message':
                this.message(writer, options, field.V.T(), 2, value);
                break;
        }
        writer.join();
    }
    message(writer, options, handler, fieldNo, value) {
        if (value === undefined)
            return;
        handler.internalBinaryWrite(value, writer.tag(fieldNo, WireType.LengthDelimited).fork(), options);
        writer.join();
    }
    /**
     * Write a single scalar value.
     */
    scalar(writer, type, fieldNo, value, emitDefault) {
        let [wireType, method, isDefault] = this.scalarInfo(type, value);
        if (!isDefault || emitDefault) {
            writer.tag(fieldNo, wireType);
            writer[method](value);
        }
    }
    /**
     * Write an array of scalar values in packed format.
     */
    packed(writer, type, fieldNo, value) {
        if (!value.length)
            return;
        assert(type !== ScalarType.BYTES && type !== ScalarType.STRING);
        // write tag
        writer.tag(fieldNo, WireType.LengthDelimited);
        // begin length-delimited
        writer.fork();
        // write values without tags
        let [, method,] = this.scalarInfo(type);
        for (let i = 0; i < value.length; i++)
            writer[method](value[i]);
        // end length delimited
        writer.join();
    }
    /**
     * Get information for writing a scalar value.
     *
     * Returns tuple:
     * [0]: appropriate WireType
     * [1]: name of the appropriate method of IBinaryWriter
     * [2]: whether the given value is a default value
     *
     * If argument `value` is omitted, [2] is always false.
     */
    scalarInfo(type, value) {
        let t = WireType.Varint;
        let m;
        let i = value === undefined;
        let d = value === 0;
        switch (type) {
            case ScalarType.INT32:
                m = "int32";
                break;
            case ScalarType.STRING:
                d = i || !value.length;
                t = WireType.LengthDelimited;
                m = "string";
                break;
            case ScalarType.BOOL:
                d = value === false;
                m = "bool";
                break;
            case ScalarType.UINT32:
                m = "uint32";
                break;
            case ScalarType.DOUBLE:
                t = WireType.Bit64;
                m = "double";
                break;
            case ScalarType.FLOAT:
                t = WireType.Bit32;
                m = "float";
                break;
            case ScalarType.INT64:
                d = i || PbLong.from(value).isZero();
                m = "int64";
                break;
            case ScalarType.UINT64:
                d = i || PbULong.from(value).isZero();
                m = "uint64";
                break;
            case ScalarType.FIXED64:
                d = i || PbULong.from(value).isZero();
                t = WireType.Bit64;
                m = "fixed64";
                break;
            case ScalarType.BYTES:
                d = i || !value.byteLength;
                t = WireType.LengthDelimited;
                m = "bytes";
                break;
            case ScalarType.FIXED32:
                t = WireType.Bit32;
                m = "fixed32";
                break;
            case ScalarType.SFIXED32:
                t = WireType.Bit32;
                m = "sfixed32";
                break;
            case ScalarType.SFIXED64:
                d = i || PbLong.from(value).isZero();
                t = WireType.Bit64;
                m = "sfixed64";
                break;
            case ScalarType.SINT32:
                m = "sint32";
                break;
            case ScalarType.SINT64:
                d = i || PbLong.from(value).isZero();
                m = "sint64";
                break;
        }
        return [t, m, i || d];
    }
}

/**
 * Creates an instance of the generic message, using the field
 * information.
 */
function reflectionCreate(type) {
    /**
     * This ternary can be removed in the next major version.
     * The `Object.create()` code path utilizes a new `messagePrototype`
     * property on the `IMessageType` which has this same `MESSAGE_TYPE`
     * non-enumerable property on it. Doing it this way means that we only
     * pay the cost of `Object.defineProperty()` once per `IMessageType`
     * class of once per "instance". The falsy code path is only provided
     * for backwards compatibility in cases where the runtime library is
     * updated without also updating the generated code.
     */
    const msg = type.messagePrototype
        ? Object.create(type.messagePrototype)
        : Object.defineProperty({}, MESSAGE_TYPE, { value: type });
    for (let field of type.fields) {
        let name = field.localName;
        if (field.opt)
            continue;
        if (field.oneof)
            msg[field.oneof] = { oneofKind: undefined };
        else if (field.repeat)
            msg[name] = [];
        else
            switch (field.kind) {
                case "scalar":
                    msg[name] = reflectionScalarDefault(field.T, field.L);
                    break;
                case "enum":
                    // we require 0 to be default value for all enums
                    msg[name] = 0;
                    break;
                case "map":
                    msg[name] = {};
                    break;
            }
    }
    return msg;
}

/**
 * Copy partial data into the target message.
 *
 * If a singular scalar or enum field is present in the source, it
 * replaces the field in the target.
 *
 * If a singular message field is present in the source, it is merged
 * with the target field by calling mergePartial() of the responsible
 * message type.
 *
 * If a repeated field is present in the source, its values replace
 * all values in the target array, removing extraneous values.
 * Repeated message fields are copied, not merged.
 *
 * If a map field is present in the source, entries are added to the
 * target map, replacing entries with the same key. Entries that only
 * exist in the target remain. Entries with message values are copied,
 * not merged.
 *
 * Note that this function differs from protobuf merge semantics,
 * which appends repeated fields.
 */
function reflectionMergePartial(info, target, source) {
    let fieldValue, // the field value we are working with
    input = source, output; // where we want our field value to go
    for (let field of info.fields) {
        let name = field.localName;
        if (field.oneof) {
            const group = input[field.oneof]; // this is the oneof`s group in the source
            if ((group === null || group === void 0 ? void 0 : group.oneofKind) == undefined) { // the user is free to omit
                continue; // we skip this field, and all other members too
            }
            fieldValue = group[name]; // our value comes from the the oneof group of the source
            output = target[field.oneof]; // and our output is the oneof group of the target
            output.oneofKind = group.oneofKind; // always update discriminator
            if (fieldValue == undefined) {
                delete output[name]; // remove any existing value
                continue; // skip further work on field
            }
        }
        else {
            fieldValue = input[name]; // we are using the source directly
            output = target; // we want our field value to go directly into the target
            if (fieldValue == undefined) {
                continue; // skip further work on field, existing value is used as is
            }
        }
        if (field.repeat)
            output[name].length = fieldValue.length; // resize target array to match source array
        // now we just work with `fieldValue` and `output` to merge the value
        switch (field.kind) {
            case "scalar":
            case "enum":
                if (field.repeat)
                    for (let i = 0; i < fieldValue.length; i++)
                        output[name][i] = fieldValue[i]; // not a reference type
                else
                    output[name] = fieldValue; // not a reference type
                break;
            case "message":
                let T = field.T();
                if (field.repeat)
                    for (let i = 0; i < fieldValue.length; i++)
                        output[name][i] = T.create(fieldValue[i]);
                else if (output[name] === undefined)
                    output[name] = T.create(fieldValue); // nothing to merge with
                else
                    T.mergePartial(output[name], fieldValue);
                break;
            case "map":
                // Map and repeated fields are simply overwritten, not appended or merged
                switch (field.V.kind) {
                    case "scalar":
                    case "enum":
                        Object.assign(output[name], fieldValue); // elements are not reference types
                        break;
                    case "message":
                        let T = field.V.T();
                        for (let k of Object.keys(fieldValue))
                            output[name][k] = T.create(fieldValue[k]);
                        break;
                }
                break;
        }
    }
}

/**
 * Determines whether two message of the same type have the same field values.
 * Checks for deep equality, traversing repeated fields, oneof groups, maps
 * and messages recursively.
 * Will also return true if both messages are `undefined`.
 */
function reflectionEquals(info, a, b) {
    if (a === b)
        return true;
    if (!a || !b)
        return false;
    for (let field of info.fields) {
        let localName = field.localName;
        let val_a = field.oneof ? a[field.oneof][localName] : a[localName];
        let val_b = field.oneof ? b[field.oneof][localName] : b[localName];
        switch (field.kind) {
            case "enum":
            case "scalar":
                let t = field.kind == "enum" ? ScalarType.INT32 : field.T;
                if (!(field.repeat
                    ? repeatedPrimitiveEq(t, val_a, val_b)
                    : primitiveEq(t, val_a, val_b)))
                    return false;
                break;
            case "map":
                if (!(field.V.kind == "message"
                    ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b))
                    : repeatedPrimitiveEq(field.V.kind == "enum" ? ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b))))
                    return false;
                break;
            case "message":
                let T = field.T();
                if (!(field.repeat
                    ? repeatedMsgEq(T, val_a, val_b)
                    : T.equals(val_a, val_b)))
                    return false;
                break;
        }
    }
    return true;
}
const objectValues = Object.values;
function primitiveEq(type, a, b) {
    if (a === b)
        return true;
    if (type !== ScalarType.BYTES)
        return false;
    let ba = a;
    let bb = b;
    if (ba.length !== bb.length)
        return false;
    for (let i = 0; i < ba.length; i++)
        if (ba[i] != bb[i])
            return false;
    return true;
}
function repeatedPrimitiveEq(type, a, b) {
    if (a.length !== b.length)
        return false;
    for (let i = 0; i < a.length; i++)
        if (!primitiveEq(type, a[i], b[i]))
            return false;
    return true;
}
function repeatedMsgEq(type, a, b) {
    if (a.length !== b.length)
        return false;
    for (let i = 0; i < a.length; i++)
        if (!type.equals(a[i], b[i]))
            return false;
    return true;
}

const baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));
const messageTypeDescriptor = baseDescriptors[MESSAGE_TYPE] = {};
/**
 * This standard message type provides reflection-based
 * operations to work with a message.
 */
class MessageType {
    constructor(name, fields, options) {
        this.defaultCheckDepth = 16;
        this.typeName = name;
        this.fields = fields.map(normalizeFieldInfo);
        this.options = options !== null && options !== void 0 ? options : {};
        messageTypeDescriptor.value = this;
        this.messagePrototype = Object.create(null, baseDescriptors);
        this.refTypeCheck = new ReflectionTypeCheck(this);
        this.refJsonReader = new ReflectionJsonReader(this);
        this.refJsonWriter = new ReflectionJsonWriter(this);
        this.refBinReader = new ReflectionBinaryReader(this);
        this.refBinWriter = new ReflectionBinaryWriter(this);
    }
    create(value) {
        let message = reflectionCreate(this);
        if (value !== undefined) {
            reflectionMergePartial(this, message, value);
        }
        return message;
    }
    /**
     * Clone the message.
     *
     * Unknown fields are discarded.
     */
    clone(message) {
        let copy = this.create();
        reflectionMergePartial(this, copy, message);
        return copy;
    }
    /**
     * Determines whether two message of the same type have the same field values.
     * Checks for deep equality, traversing repeated fields, oneof groups, maps
     * and messages recursively.
     * Will also return true if both messages are `undefined`.
     */
    equals(a, b) {
        return reflectionEquals(this, a, b);
    }
    /**
     * Is the given value assignable to our message type
     * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)?
     */
    is(arg, depth = this.defaultCheckDepth) {
        return this.refTypeCheck.is(arg, depth, false);
    }
    /**
     * Is the given value assignable to our message type,
     * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)?
     */
    isAssignable(arg, depth = this.defaultCheckDepth) {
        return this.refTypeCheck.is(arg, depth, true);
    }
    /**
     * Copy partial data into the target message.
     */
    mergePartial(target, source) {
        reflectionMergePartial(this, target, source);
    }
    /**
     * Create a new message from binary format.
     */
    fromBinary(data, options) {
        let opt = binaryReadOptions(options);
        return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt);
    }
    /**
     * Read a new message from a JSON value.
     */
    fromJson(json, options) {
        return this.internalJsonRead(json, jsonReadOptions(options));
    }
    /**
     * Read a new message from a JSON string.
     * This is equivalent to `T.fromJson(JSON.parse(json))`.
     */
    fromJsonString(json, options) {
        let value = JSON.parse(json);
        return this.fromJson(value, options);
    }
    /**
     * Write the message to canonical JSON value.
     */
    toJson(message, options) {
        return this.internalJsonWrite(message, jsonWriteOptions(options));
    }
    /**
     * Convert the message to canonical JSON string.
     * This is equivalent to `JSON.stringify(T.toJson(t))`
     */
    toJsonString(message, options) {
        var _a;
        let value = this.toJson(message, options);
        return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0);
    }
    /**
     * Write the message to binary format.
     */
    toBinary(message, options) {
        let opt = binaryWriteOptions(options);
        return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish();
    }
    /**
     * This is an internal method. If you just want to read a message from
     * JSON, use `fromJson()` or `fromJsonString()`.
     *
     * Reads JSON value and merges the fields into the target
     * according to protobuf rules. If the target is omitted,
     * a new instance is created first.
     */
    internalJsonRead(json, options, target) {
        if (json !== null && typeof json == "object" && !Array.isArray(json)) {
            let message = target !== null && target !== void 0 ? target : this.create();
            this.refJsonReader.read(json, message, options);
            return message;
        }
        throw new Error(`Unable to parse message ${this.typeName} from JSON ${typeofJsonValue(json)}.`);
    }
    /**
     * This is an internal method. If you just want to write a message
     * to JSON, use `toJson()` or `toJsonString().
     *
     * Writes JSON value and returns it.
     */
    internalJsonWrite(message, options) {
        return this.refJsonWriter.write(message, options);
    }
    /**
     * This is an internal method. If you just want to write a message
     * in binary format, use `toBinary()`.
     *
     * Serializes the message in binary format and appends it to the given
     * writer. Returns passed writer.
     */
    internalBinaryWrite(message, writer, options) {
        this.refBinWriter.write(message, writer, options);
        return writer;
    }
    /**
     * This is an internal method. If you just want to read a message from
     * binary data, use `fromBinary()`.
     *
     * Reads data from binary format and merges the fields into
     * the target according to protobuf rules. If the target is
     * omitted, a new instance is created first.
     */
    internalBinaryRead(reader, length, options, target) {
        let message = target !== null && target !== void 0 ? target : this.create();
        this.refBinReader.read(reader, message, options, length);
        return message;
    }
}

function ProtoField(no, type, optional, repeat) {
  if (typeof type === "function") {
    return { kind: "message", no, type, optional: optional ?? false, repeat: repeat ?? false };
  } else {
    return { kind: "scalar", no, type, optional: optional ?? false, repeat: repeat ?? false };
  }
}
class NapProtoRealMsg {
  _field;
  _proto_msg;
  static cache = /* @__PURE__ */ new WeakMap();
  constructor(fields) {
    this._field = Object.keys(fields).map((key) => {
      const field = fields[key];
      if (field.kind === "scalar") {
        const repeatType = field.repeat ? [ScalarType.STRING, ScalarType.BYTES].includes(field.type) ? RepeatType.UNPACKED : RepeatType.PACKED : RepeatType.NO;
        return {
          no: field.no,
          name: key,
          kind: "scalar",
          T: field.type,
          opt: field.optional,
          repeat: repeatType
        };
      } else if (field.kind === "message") {
        return {
          no: field.no,
          name: key,
          kind: "message",
          repeat: field.repeat ? RepeatType.PACKED : RepeatType.NO,
          T: () => NapProtoRealMsg.getInstance(field.type())._proto_msg
        };
      } else {
        throw new Error(`Unknown field kind: ${field.kind}`);
      }
    });
    this._proto_msg = new MessageType("nya", this._field);
  }
  static getInstance(fields) {
    let instance = this.cache.get(fields);
    if (!instance) {
      instance = new NapProtoRealMsg(fields);
      this.cache.set(fields, instance);
    }
    return instance;
  }
  encode(data) {
    return this._proto_msg.toBinary(this._proto_msg.create(data));
  }
  decode(data) {
    return this._proto_msg.fromBinary(data);
  }
}
class NapProtoMsg {
  realMsg;
  constructor(fields) {
    this.realMsg = NapProtoRealMsg.getInstance(fields);
  }
  encode(data) {
    return this.realMsg.encode(data);
  }
  decode(data) {
    return this.realMsg.decode(data);
  }
}

var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

function getDefaultExportFromCjs (x) {
	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}

function getAugmentedNamespace(n) {
  if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
  var f = n.default;
	if (typeof f == "function") {
		var a = function a () {
			if (this instanceof a) {
        return Reflect.construct(f, arguments, this.constructor);
			}
			return f.apply(this, arguments);
		};
		a.prototype = f.prototype;
  } else a = {};
  Object.defineProperty(a, '__esModule', {value: true});
	Object.keys(n).forEach(function (k) {
		var d = Object.getOwnPropertyDescriptor(n, k);
		Object.defineProperty(a, k, d.get ? d : {
			enumerable: true,
			get: function () {
				return n[k];
			}
		});
	});
	return a;
}

var _Reflect = {};

/*! *****************************************************************************
Copyright (C) Microsoft. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */

var hasRequired_Reflect;

function require_Reflect () {
	if (hasRequired_Reflect) return _Reflect;
	hasRequired_Reflect = 1;
	var Reflect;
	(function (Reflect) {
	    // Metadata Proposal
	    // https://rbuckton.github.io/reflect-metadata/
	    (function (factory) {
	        var root = typeof globalThis === "object" ? globalThis :
	            typeof commonjsGlobal === "object" ? commonjsGlobal :
	                typeof self === "object" ? self :
	                    typeof this === "object" ? this :
	                        sloppyModeThis();
	        var exporter = makeExporter(Reflect);
	        if (typeof root.Reflect !== "undefined") {
	            exporter = makeExporter(root.Reflect, exporter);
	        }
	        factory(exporter, root);
	        if (typeof root.Reflect === "undefined") {
	            root.Reflect = Reflect;
	        }
	        function makeExporter(target, previous) {
	            return function (key, value) {
	                Object.defineProperty(target, key, { configurable: true, writable: true, value: value });
	                if (previous)
	                    previous(key, value);
	            };
	        }
	        function functionThis() {
	            try {
	                return Function("return this;")();
	            }
	            catch (_) { }
	        }
	        function indirectEvalThis() {
	            try {
	                return (void 0, eval)("(function() { return this; })()");
	            }
	            catch (_) { }
	        }
	        function sloppyModeThis() {
	            return functionThis() || indirectEvalThis();
	        }
	    })(function (exporter, root) {
	        var hasOwn = Object.prototype.hasOwnProperty;
	        // feature test for Symbol support
	        var supportsSymbol = typeof Symbol === "function";
	        var toPrimitiveSymbol = supportsSymbol && typeof Symbol.toPrimitive !== "undefined" ? Symbol.toPrimitive : "@@toPrimitive";
	        var iteratorSymbol = supportsSymbol && typeof Symbol.iterator !== "undefined" ? Symbol.iterator : "@@iterator";
	        var supportsCreate = typeof Object.create === "function"; // feature test for Object.create support
	        var supportsProto = { __proto__: [] } instanceof Array; // feature test for __proto__ support
	        var downLevel = !supportsCreate && !supportsProto;
	        var HashMap = {
	            // create an object in dictionary mode (a.k.a. "slow" mode in v8)
	            create: supportsCreate
	                ? function () { return MakeDictionary(Object.create(null)); }
	                : supportsProto
	                    ? function () { return MakeDictionary({ __proto__: null }); }
	                    : function () { return MakeDictionary({}); },
	            has: downLevel
	                ? function (map, key) { return hasOwn.call(map, key); }
	                : function (map, key) { return key in map; },
	            get: downLevel
	                ? function (map, key) { return hasOwn.call(map, key) ? map[key] : undefined; }
	                : function (map, key) { return map[key]; },
	        };
	        // Load global or shim versions of Map, Set, and WeakMap
	        var functionPrototype = Object.getPrototypeOf(Function);
	        var _Map = typeof Map === "function" && typeof Map.prototype.entries === "function" ? Map : CreateMapPolyfill();
	        var _Set = typeof Set === "function" && typeof Set.prototype.entries === "function" ? Set : CreateSetPolyfill();
	        var _WeakMap = typeof WeakMap === "function" ? WeakMap : CreateWeakMapPolyfill();
	        var registrySymbol = supportsSymbol ? Symbol.for("@reflect-metadata:registry") : undefined;
	        var metadataRegistry = GetOrCreateMetadataRegistry();
	        var metadataProvider = CreateMetadataProvider(metadataRegistry);
	        /**
	         * Applies a set of decorators to a property of a target object.
	         * @param decorators An array of decorators.
	         * @param target The target object.
	         * @param propertyKey (Optional) The property key to decorate.
	         * @param attributes (Optional) The property descriptor for the target key.
	         * @remarks Decorators are applied in reverse order.
	         * @example
	         *
	         *     class Example {
	         *         // property declarations are not part of ES6, though they are valid in TypeScript:
	         *         // static staticProperty;
	         *         // property;
	         *
	         *         constructor(p) { }
	         *         static staticMethod(p) { }
	         *         method(p) { }
	         *     }
	         *
	         *     // constructor
	         *     Example = Reflect.decorate(decoratorsArray, Example);
	         *
	         *     // property (on constructor)
	         *     Reflect.decorate(decoratorsArray, Example, "staticProperty");
	         *
	         *     // property (on prototype)
	         *     Reflect.decorate(decoratorsArray, Example.prototype, "property");
	         *
	         *     // method (on constructor)
	         *     Object.defineProperty(Example, "staticMethod",
	         *         Reflect.decorate(decoratorsArray, Example, "staticMethod",
	         *             Object.getOwnPropertyDescriptor(Example, "staticMethod")));
	         *
	         *     // method (on prototype)
	         *     Object.defineProperty(Example.prototype, "method",
	         *         Reflect.decorate(decoratorsArray, Example.prototype, "method",
	         *             Object.getOwnPropertyDescriptor(Example.prototype, "method")));
	         *
	         */
	        function decorate(decorators, target, propertyKey, attributes) {
	            if (!IsUndefined(propertyKey)) {
	                if (!IsArray(decorators))
	                    throw new TypeError();
	                if (!IsObject(target))
	                    throw new TypeError();
	                if (!IsObject(attributes) && !IsUndefined(attributes) && !IsNull(attributes))
	                    throw new TypeError();
	                if (IsNull(attributes))
	                    attributes = undefined;
	                propertyKey = ToPropertyKey(propertyKey);
	                return DecorateProperty(decorators, target, propertyKey, attributes);
	            }
	            else {
	                if (!IsArray(decorators))
	                    throw new TypeError();
	                if (!IsConstructor(target))
	                    throw new TypeError();
	                return DecorateConstructor(decorators, target);
	            }
	        }
	        exporter("decorate", decorate);
	        // 4.1.2 Reflect.metadata(metadataKey, metadataValue)
	        // https://rbuckton.github.io/reflect-metadata/#reflect.metadata
	        /**
	         * A default metadata decorator factory that can be used on a class, class member, or parameter.
	         * @param metadataKey The key for the metadata entry.
	         * @param metadataValue The value for the metadata entry.
	         * @returns A decorator function.
	         * @remarks
	         * If `metadataKey` is already defined for the target and target key, the
	         * metadataValue for that key will be overwritten.
	         * @example
	         *
	         *     // constructor
	         *     @Reflect.metadata(key, value)
	         *     class Example {
	         *     }
	         *
	         *     // property (on constructor, TypeScript only)
	         *     class Example {
	         *         @Reflect.metadata(key, value)
	         *         static staticProperty;
	         *     }
	         *
	         *     // property (on prototype, TypeScript only)
	         *     class Example {
	         *         @Reflect.metadata(key, value)
	         *         property;
	         *     }
	         *
	         *     // method (on constructor)
	         *     class Example {
	         *         @Reflect.metadata(key, value)
	         *         static staticMethod() { }
	         *     }
	         *
	         *     // method (on prototype)
	         *     class Example {
	         *         @Reflect.metadata(key, value)
	         *         method() { }
	         *     }
	         *
	         */
	        function metadata(metadataKey, metadataValue) {
	            function decorator(target, propertyKey) {
	                if (!IsObject(target))
	                    throw new TypeError();
	                if (!IsUndefined(propertyKey) && !IsPropertyKey(propertyKey))
	                    throw new TypeError();
	                OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey);
	            }
	            return decorator;
	        }
	        exporter("metadata", metadata);
	        /**
	         * Define a unique metadata entry on the target.
	         * @param metadataKey A key used to store and retrieve metadata.
	         * @param metadataValue A value that contains attached metadata.
	         * @param target The target object on which to define metadata.
	         * @param propertyKey (Optional) The property key for the target.
	         * @example
	         *
	         *     class Example {
	         *         // property declarations are not part of ES6, though they are valid in TypeScript:
	         *         // static staticProperty;
	         *         // property;
	         *
	         *         constructor(p) { }
	         *         static staticMethod(p) { }
	         *         method(p) { }
	         *     }
	         *
	         *     // constructor
	         *     Reflect.defineMetadata("custom:annotation", options, Example);
	         *
	         *     // property (on constructor)
	         *     Reflect.defineMetadata("custom:annotation", options, Example, "staticProperty");
	         *
	         *     // property (on prototype)
	         *     Reflect.defineMetadata("custom:annotation", options, Example.prototype, "property");
	         *
	         *     // method (on constructor)
	         *     Reflect.defineMetadata("custom:annotation", options, Example, "staticMethod");
	         *
	         *     // method (on prototype)
	         *     Reflect.defineMetadata("custom:annotation", options, Example.prototype, "method");
	         *
	         *     // decorator factory as metadata-producing annotation.
	         *     function MyAnnotation(options): Decorator {
	         *         return (target, key?) => Reflect.defineMetadata("custom:annotation", options, target, key);
	         *     }
	         *
	         */
	        function defineMetadata(metadataKey, metadataValue, target, propertyKey) {
	            if (!IsObject(target))
	                throw new TypeError();
	            if (!IsUndefined(propertyKey))
	                propertyKey = ToPropertyKey(propertyKey);
	            return OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey);
	        }
	        exporter("defineMetadata", defineMetadata);
	        /**
	         * Gets a value indicating whether the target object or its prototype chain has the provided metadata key defined.
	         * @param metadataKey A key used to store and retrieve metadata.
	         * @param target The target object on which the metadata is defined.
	         * @param propertyKey (Optional) The property key for the target.
	         * @returns `true` if the metadata key was defined on the target object or its prototype chain; otherwise, `false`.
	         * @example
	         *
	         *     class Example {
	         *         // property declarations are not part of ES6, though they are valid in TypeScript:
	         *         // static staticProperty;
	         *         // property;
	         *
	         *         constructor(p) { }
	         *         static staticMethod(p) { }
	         *         method(p) { }
	         *     }
	         *
	         *     // constructor
	         *     result = Reflect.hasMetadata("custom:annotation", Example);
	         *
	         *     // property (on constructor)
	         *     result = Reflect.hasMetadata("custom:annotation", Example, "staticProperty");
	         *
	         *     // property (on prototype)
	         *     result = Reflect.hasMetadata("custom:annotation", Example.prototype, "property");
	         *
	         *     // method (on constructor)
	         *     result = Reflect.hasMetadata("custom:annotation", Example, "staticMethod");
	         *
	         *     // method (on prototype)
	         *     result = Reflect.hasMetadata("custom:annotation", Example.prototype, "method");
	         *
	         */
	        function hasMetadata(metadataKey, target, propertyKey) {
	            if (!IsObject(target))
	                throw new TypeError();
	            if (!IsUndefined(propertyKey))
	                propertyKey = ToPropertyKey(propertyKey);
	            return OrdinaryHasMetadata(metadataKey, target, propertyKey);
	        }
	        exporter("hasMetadata", hasMetadata);
	        /**
	         * Gets a value indicating whether the target object has the provided metadata key defined.
	         * @param metadataKey A key used to store and retrieve metadata.
	         * @param target The target object on which the metadata is defined.
	         * @param propertyKey (Optional) The property key for the target.
	         * @returns `true` if the metadata key was defined on the target object; otherwise, `false`.
	         * @example
	         *
	         *     class Example {
	         *         // property declarations are not part of ES6, though they are valid in TypeScript:
	         *         // static staticProperty;
	         *         // property;
	         *
	         *         constructor(p) { }
	         *         static staticMethod(p) { }
	         *         method(p) { }
	         *     }
	         *
	         *     // constructor
	         *     result = Reflect.hasOwnMetadata("custom:annotation", Example);
	         *
	         *     // property (on constructor)
	         *     result = Reflect.hasOwnMetadata("custom:annotation", Example, "staticProperty");
	         *
	         *     // property (on prototype)
	         *     result = Reflect.hasOwnMetadata("custom:annotation", Example.prototype, "property");
	         *
	         *     // method (on constructor)
	         *     result = Reflect.hasOwnMetadata("custom:annotation", Example, "staticMethod");
	         *
	         *     // method (on prototype)
	         *     result = Reflect.hasOwnMetadata("custom:annotation", Example.prototype, "method");
	         *
	         */
	        function hasOwnMetadata(metadataKey, target, propertyKey) {
	            if (!IsObject(target))
	                throw new TypeError();
	            if (!IsUndefined(propertyKey))
	                propertyKey = ToPropertyKey(propertyKey);
	            return OrdinaryHasOwnMetadata(metadataKey, target, propertyKey);
	        }
	        exporter("hasOwnMetadata", hasOwnMetadata);
	        /**
	         * Gets the metadata value for the provided metadata key on the target object or its prototype chain.
	         * @param metadataKey A key used to store and retrieve metadata.
	         * @param target The target object on which the metadata is defined.
	         * @param propertyKey (Optional) The property key for the target.
	         * @returns The metadata value for the metadata key if found; otherwise, `undefined`.
	         * @example
	         *
	         *     class Example {
	         *         // property declarations are not part of ES6, though they are valid in TypeScript:
	         *         // static staticProperty;
	         *         // property;
	         *
	         *         constructor(p) { }
	         *         static staticMethod(p) { }
	         *         method(p) { }
	         *     }
	         *
	         *     // constructor
	         *     result = Reflect.getMetadata("custom:annotation", Example);
	         *
	         *     // property (on constructor)
	         *     result = Reflect.getMetadata("custom:annotation", Example, "staticProperty");
	         *
	         *     // property (on prototype)
	         *     result = Reflect.getMetadata("custom:annotation", Example.prototype, "property");
	         *
	         *     // method (on constructor)
	         *     result = Reflect.getMetadata("custom:annotation", Example, "staticMethod");
	         *
	         *     // method (on prototype)
	         *     result = Reflect.getMetadata("custom:annotation", Example.prototype, "method");
	         *
	         */
	        function getMetadata(metadataKey, target, propertyKey) {
	            if (!IsObject(target))
	                throw new TypeError();
	            if (!IsUndefined(propertyKey))
	                propertyKey = ToPropertyKey(propertyKey);
	            return OrdinaryGetMetadata(metadataKey, target, propertyKey);
	        }
	        exporter("getMetadata", getMetadata);
	        /**
	         * Gets the metadata value for the provided metadata key on the target object.
	         * @param metadataKey A key used to store and retrieve metadata.
	         * @param target The target object on which the metadata is defined.
	         * @param propertyKey (Optional) The property key for the target.
	         * @returns The metadata value for the metadata key if found; otherwise, `undefined`.
	         * @example
	         *
	         *     class Example {
	         *         // property declarations are not part of ES6, though they are valid in TypeScript:
	         *         // static staticProperty;
	         *         // property;
	         *
	         *         constructor(p) { }
	         *         static staticMethod(p) { }
	         *         method(p) { }
	         *     }
	         *
	         *     // constructor
	         *     result = Reflect.getOwnMetadata("custom:annotation", Example);
	         *
	         *     // property (on constructor)
	         *     result = Reflect.getOwnMetadata("custom:annotation", Example, "staticProperty");
	         *
	         *     // property (on prototype)
	         *     result = Reflect.getOwnMetadata("custom:annotation", Example.prototype, "property");
	         *
	         *     // method (on constructor)
	         *     result = Reflect.getOwnMetadata("custom:annotation", Example, "staticMethod");
	         *
	         *     // method (on prototype)
	         *     result = Reflect.getOwnMetadata("custom:annotation", Example.prototype, "method");
	         *
	         */
	        function getOwnMetadata(metadataKey, target, propertyKey) {
	            if (!IsObject(target))
	                throw new TypeError();
	            if (!IsUndefined(propertyKey))
	                propertyKey = ToPropertyKey(propertyKey);
	            return OrdinaryGetOwnMetadata(metadataKey, target, propertyKey);
	        }
	        exporter("getOwnMetadata", getOwnMetadata);
	        /**
	         * Gets the metadata keys defined on the target object or its prototype chain.
	         * @param target The target object on which the metadata is defined.
	         * @param propertyKey (Optional) The property key for the target.
	         * @returns An array of unique metadata keys.
	         * @example
	         *
	         *     class Example {
	         *         // property declarations are not part of ES6, though they are valid in TypeScript:
	         *         // static staticProperty;
	         *         // property;
	         *
	         *         constructor(p) { }
	         *         static staticMethod(p) { }
	         *         method(p) { }
	         *     }
	         *
	         *     // constructor
	         *     result = Reflect.getMetadataKeys(Example);
	         *
	         *     // property (on constructor)
	         *     result = Reflect.getMetadataKeys(Example, "staticProperty");
	         *
	         *     // property (on prototype)
	         *     result = Reflect.getMetadataKeys(Example.prototype, "property");
	         *
	         *     // method (on constructor)
	         *     result = Reflect.getMetadataKeys(Example, "staticMethod");
	         *
	         *     // method (on prototype)
	         *     result = Reflect.getMetadataKeys(Example.prototype, "method");
	         *
	         */
	        function getMetadataKeys(target, propertyKey) {
	            if (!IsObject(target))
	                throw new TypeError();
	            if (!IsUndefined(propertyKey))
	                propertyKey = ToPropertyKey(propertyKey);
	            return OrdinaryMetadataKeys(target, propertyKey);
	        }
	        exporter("getMetadataKeys", getMetadataKeys);
	        /**
	         * Gets the unique metadata keys defined on the target object.
	         * @param target The target object on which the metadata is defined.
	         * @param propertyKey (Optional) The property key for the target.
	         * @returns An array of unique metadata keys.
	         * @example
	         *
	         *     class Example {
	         *         // property declarations are not part of ES6, though they are valid in TypeScript:
	         *         // static staticProperty;
	         *         // property;
	         *
	         *         constructor(p) { }
	         *         static staticMethod(p) { }
	         *         method(p) { }
	         *     }
	         *
	         *     // constructor
	         *     result = Reflect.getOwnMetadataKeys(Example);
	         *
	         *     // property (on constructor)
	         *     result = Reflect.getOwnMetadataKeys(Example, "staticProperty");
	         *
	         *     // property (on prototype)
	         *     result = Reflect.getOwnMetadataKeys(Example.prototype, "property");
	         *
	         *     // method (on constructor)
	         *     result = Reflect.getOwnMetadataKeys(Example, "staticMethod");
	         *
	         *     // method (on prototype)
	         *     result = Reflect.getOwnMetadataKeys(Example.prototype, "method");
	         *
	         */
	        function getOwnMetadataKeys(target, propertyKey) {
	            if (!IsObject(target))
	                throw new TypeError();
	            if (!IsUndefined(propertyKey))
	                propertyKey = ToPropertyKey(propertyKey);
	            return OrdinaryOwnMetadataKeys(target, propertyKey);
	        }
	        exporter("getOwnMetadataKeys", getOwnMetadataKeys);
	        /**
	         * Deletes the metadata entry from the target object with the provided key.
	         * @param metadataKey A key used to store and retrieve metadata.
	         * @param target The target object on which the metadata is defined.
	         * @param propertyKey (Optional) The property key for the target.
	         * @returns `true` if the metadata entry was found and deleted; otherwise, false.
	         * @example
	         *
	         *     class Example {
	         *         // property declarations are not part of ES6, though they are valid in TypeScript:
	         *         // static staticProperty;
	         *         // property;
	         *
	         *         constructor(p) { }
	         *         static staticMethod(p) { }
	         *         method(p) { }
	         *     }
	         *
	         *     // constructor
	         *     result = Reflect.deleteMetadata("custom:annotation", Example);
	         *
	         *     // property (on constructor)
	         *     result = Reflect.deleteMetadata("custom:annotation", Example, "staticProperty");
	         *
	         *     // property (on prototype)
	         *     result = Reflect.deleteMetadata("custom:annotation", Example.prototype, "property");
	         *
	         *     // method (on constructor)
	         *     result = Reflect.deleteMetadata("custom:annotation", Example, "staticMethod");
	         *
	         *     // method (on prototype)
	         *     result = Reflect.deleteMetadata("custom:annotation", Example.prototype, "method");
	         *
	         */
	        function deleteMetadata(metadataKey, target, propertyKey) {
	            if (!IsObject(target))
	                throw new TypeError();
	            if (!IsUndefined(propertyKey))
	                propertyKey = ToPropertyKey(propertyKey);
	            if (!IsObject(target))
	                throw new TypeError();
	            if (!IsUndefined(propertyKey))
	                propertyKey = ToPropertyKey(propertyKey);
	            var provider = GetMetadataProvider(target, propertyKey, /*Create*/ false);
	            if (IsUndefined(provider))
	                return false;
	            return provider.OrdinaryDeleteMetadata(metadataKey, target, propertyKey);
	        }
	        exporter("deleteMetadata", deleteMetadata);
	        function DecorateConstructor(decorators, target) {
	            for (var i = decorators.length - 1; i >= 0; --i) {
	                var decorator = decorators[i];
	                var decorated = decorator(target);
	                if (!IsUndefined(decorated) && !IsNull(decorated)) {
	                    if (!IsConstructor(decorated))
	                        throw new TypeError();
	                    target = decorated;
	                }
	            }
	            return target;
	        }
	        function DecorateProperty(decorators, target, propertyKey, descriptor) {
	            for (var i = decorators.length - 1; i >= 0; --i) {
	                var decorator = decorators[i];
	                var decorated = decorator(target, propertyKey, descriptor);
	                if (!IsUndefined(decorated) && !IsNull(decorated)) {
	                    if (!IsObject(decorated))
	                        throw new TypeError();
	                    descriptor = decorated;
	                }
	            }
	            return descriptor;
	        }
	        // 3.1.1.1 OrdinaryHasMetadata(MetadataKey, O, P)
	        // https://rbuckton.github.io/reflect-metadata/#ordinaryhasmetadata
	        function OrdinaryHasMetadata(MetadataKey, O, P) {
	            var hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P);
	            if (hasOwn)
	                return true;
	            var parent = OrdinaryGetPrototypeOf(O);
	            if (!IsNull(parent))
	                return OrdinaryHasMetadata(MetadataKey, parent, P);
	            return false;
	        }
	        // 3.1.2.1 OrdinaryHasOwnMetadata(MetadataKey, O, P)
	        // https://rbuckton.github.io/reflect-metadata/#ordinaryhasownmetadata
	        function OrdinaryHasOwnMetadata(MetadataKey, O, P) {
	            var provider = GetMetadataProvider(O, P, /*Create*/ false);
	            if (IsUndefined(provider))
	                return false;
	            return ToBoolean(provider.OrdinaryHasOwnMetadata(MetadataKey, O, P));
	        }
	        // 3.1.3.1 OrdinaryGetMetadata(MetadataKey, O, P)
	        // https://rbuckton.github.io/reflect-metadata/#ordinarygetmetadata
	        function OrdinaryGetMetadata(MetadataKey, O, P) {
	            var hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P);
	            if (hasOwn)
	                return OrdinaryGetOwnMetadata(MetadataKey, O, P);
	            var parent = OrdinaryGetPrototypeOf(O);
	            if (!IsNull(parent))
	                return OrdinaryGetMetadata(MetadataKey, parent, P);
	            return undefined;
	        }
	        // 3.1.4.1 OrdinaryGetOwnMetadata(MetadataKey, O, P)
	        // https://rbuckton.github.io/reflect-metadata/#ordinarygetownmetadata
	        function OrdinaryGetOwnMetadata(MetadataKey, O, P) {
	            var provider = GetMetadataProvider(O, P, /*Create*/ false);
	            if (IsUndefined(provider))
	                return;
	            return provider.OrdinaryGetOwnMetadata(MetadataKey, O, P);
	        }
	        // 3.1.5.1 OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P)
	        // https://rbuckton.github.io/reflect-metadata/#ordinarydefineownmetadata
	        function OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) {
	            var provider = GetMetadataProvider(O, P, /*Create*/ true);
	            provider.OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P);
	        }
	        // 3.1.6.1 OrdinaryMetadataKeys(O, P)
	        // https://rbuckton.github.io/reflect-metadata/#ordinarymetadatakeys
	        function OrdinaryMetadataKeys(O, P) {
	            var ownKeys = OrdinaryOwnMetadataKeys(O, P);
	            var parent = OrdinaryGetPrototypeOf(O);
	            if (parent === null)
	                return ownKeys;
	            var parentKeys = OrdinaryMetadataKeys(parent, P);
	            if (parentKeys.length <= 0)
	                return ownKeys;
	            if (ownKeys.length <= 0)
	                return parentKeys;
	            var set = new _Set();
	            var keys = [];
	            for (var _i = 0, ownKeys_1 = ownKeys; _i < ownKeys_1.length; _i++) {
	                var key = ownKeys_1[_i];
	                var hasKey = set.has(key);
	                if (!hasKey) {
	                    set.add(key);
	                    keys.push(key);
	                }
	            }
	            for (var _a = 0, parentKeys_1 = parentKeys; _a < parentKeys_1.length; _a++) {
	                var key = parentKeys_1[_a];
	                var hasKey = set.has(key);
	                if (!hasKey) {
	                    set.add(key);
	                    keys.push(key);
	                }
	            }
	            return keys;
	        }
	        // 3.1.7.1 OrdinaryOwnMetadataKeys(O, P)
	        // https://rbuckton.github.io/reflect-metadata/#ordinaryownmetadatakeys
	        function OrdinaryOwnMetadataKeys(O, P) {
	            var provider = GetMetadataProvider(O, P, /*create*/ false);
	            if (!provider) {
	                return [];
	            }
	            return provider.OrdinaryOwnMetadataKeys(O, P);
	        }
	        // 6 ECMAScript Data Types and Values
	        // https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values
	        function Type(x) {
	            if (x === null)
	                return 1 /* Null */;
	            switch (typeof x) {
	                case "undefined": return 0 /* Undefined */;
	                case "boolean": return 2 /* Boolean */;
	                case "string": return 3 /* String */;
	                case "symbol": return 4 /* Symbol */;
	                case "number": return 5 /* Number */;
	                case "object": return x === null ? 1 /* Null */ : 6 /* Object */;
	                default: return 6 /* Object */;
	            }
	        }
	        // 6.1.1 The Undefined Type
	        // https://tc39.github.io/ecma262/#sec-ecmascript-language-types-undefined-type
	        function IsUndefined(x) {
	            return x === undefined;
	        }
	        // 6.1.2 The Null Type
	        // https://tc39.github.io/ecma262/#sec-ecmascript-language-types-null-type
	        function IsNull(x) {
	            return x === null;
	        }
	        // 6.1.5 The Symbol Type
	        // https://tc39.github.io/ecma262/#sec-ecmascript-language-types-symbol-type
	        function IsSymbol(x) {
	            return typeof x === "symbol";
	        }
	        // 6.1.7 The Object Type
	        // https://tc39.github.io/ecma262/#sec-object-type
	        function IsObject(x) {
	            return typeof x === "object" ? x !== null : typeof x === "function";
	        }
	        // 7.1 Type Conversion
	        // https://tc39.github.io/ecma262/#sec-type-conversion
	        // 7.1.1 ToPrimitive(input [, PreferredType])
	        // https://tc39.github.io/ecma262/#sec-toprimitive
	        function ToPrimitive(input, PreferredType) {
	            switch (Type(input)) {
	                case 0 /* Undefined */: return input;
	                case 1 /* Null */: return input;
	                case 2 /* Boolean */: return input;
	                case 3 /* String */: return input;
	                case 4 /* Symbol */: return input;
	                case 5 /* Number */: return input;
	            }
	            var hint = "string" ;
	            var exoticToPrim = GetMethod(input, toPrimitiveSymbol);
	            if (exoticToPrim !== undefined) {
	                var result = exoticToPrim.call(input, hint);
	                if (IsObject(result))
	                    throw new TypeError();
	                return result;
	            }
	            return OrdinaryToPrimitive(input);
	        }
	        // 7.1.1.1 OrdinaryToPrimitive(O, hint)
	        // https://tc39.github.io/ecma262/#sec-ordinarytoprimitive
	        function OrdinaryToPrimitive(O, hint) {
	            var valueOf, result, toString_2; {
	                var toString_1 = O.toString;
	                if (IsCallable(toString_1)) {
	                    var result = toString_1.call(O);
	                    if (!IsObject(result))
	                        return result;
	                }
	                var valueOf = O.valueOf;
	                if (IsCallable(valueOf)) {
	                    var result = valueOf.call(O);
	                    if (!IsObject(result))
	                        return result;
	                }
	            }
	            throw new TypeError();
	        }
	        // 7.1.2 ToBoolean(argument)
	        // https://tc39.github.io/ecma262/2016/#sec-toboolean
	        function ToBoolean(argument) {
	            return !!argument;
	        }
	        // 7.1.12 ToString(argument)
	        // https://tc39.github.io/ecma262/#sec-tostring
	        function ToString(argument) {
	            return "" + argument;
	        }
	        // 7.1.14 ToPropertyKey(argument)
	        // https://tc39.github.io/ecma262/#sec-topropertykey
	        function ToPropertyKey(argument) {
	            var key = ToPrimitive(argument);
	            if (IsSymbol(key))
	                return key;
	            return ToString(key);
	        }
	        // 7.2 Testing and Comparison Operations
	        // https://tc39.github.io/ecma262/#sec-testing-and-comparison-operations
	        // 7.2.2 IsArray(argument)
	        // https://tc39.github.io/ecma262/#sec-isarray
	        function IsArray(argument) {
	            return Array.isArray
	                ? Array.isArray(argument)
	                : argument instanceof Object
	                    ? argument instanceof Array
	                    : Object.prototype.toString.call(argument) === "[object Array]";
	        }
	        // 7.2.3 IsCallable(argument)
	        // https://tc39.github.io/ecma262/#sec-iscallable
	        function IsCallable(argument) {
	            // NOTE: This is an approximation as we cannot check for [[Call]] internal method.
	            return typeof argument === "function";
	        }
	        // 7.2.4 IsConstructor(argument)
	        // https://tc39.github.io/ecma262/#sec-isconstructor
	        function IsConstructor(argument) {
	            // NOTE: This is an approximation as we cannot check for [[Construct]] internal method.
	            return typeof argument === "function";
	        }
	        // 7.2.7 IsPropertyKey(argument)
	        // https://tc39.github.io/ecma262/#sec-ispropertykey
	        function IsPropertyKey(argument) {
	            switch (Type(argument)) {
	                case 3 /* String */: return true;
	                case 4 /* Symbol */: return true;
	                default: return false;
	            }
	        }
	        function SameValueZero(x, y) {
	            return x === y || x !== x && y !== y;
	        }
	        // 7.3 Operations on Objects
	        // https://tc39.github.io/ecma262/#sec-operations-on-objects
	        // 7.3.9 GetMethod(V, P)
	        // https://tc39.github.io/ecma262/#sec-getmethod
	        function GetMethod(V, P) {
	            var func = V[P];
	            if (func === undefined || func === null)
	                return undefined;
	            if (!IsCallable(func))
	                throw new TypeError();
	            return func;
	        }
	        // 7.4 Operations on Iterator Objects
	        // https://tc39.github.io/ecma262/#sec-operations-on-iterator-objects
	        function GetIterator(obj) {
	            var method = GetMethod(obj, iteratorSymbol);
	            if (!IsCallable(method))
	                throw new TypeError(); // from Call
	            var iterator = method.call(obj);
	            if (!IsObject(iterator))
	                throw new TypeError();
	            return iterator;
	        }
	        // 7.4.4 IteratorValue(iterResult)
	        // https://tc39.github.io/ecma262/2016/#sec-iteratorvalue
	        function IteratorValue(iterResult) {
	            return iterResult.value;
	        }
	        // 7.4.5 IteratorStep(iterator)
	        // https://tc39.github.io/ecma262/#sec-iteratorstep
	        function IteratorStep(iterator) {
	            var result = iterator.next();
	            return result.done ? false : result;
	        }
	        // 7.4.6 IteratorClose(iterator, completion)
	        // https://tc39.github.io/ecma262/#sec-iteratorclose
	        function IteratorClose(iterator) {
	            var f = iterator["return"];
	            if (f)
	                f.call(iterator);
	        }
	        // 9.1 Ordinary Object Internal Methods and Internal Slots
	        // https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots
	        // 9.1.1.1 OrdinaryGetPrototypeOf(O)
	        // https://tc39.github.io/ecma262/#sec-ordinarygetprototypeof
	        function OrdinaryGetPrototypeOf(O) {
	            var proto = Object.getPrototypeOf(O);
	            if (typeof O !== "function" || O === functionPrototype)
	                return proto;
	            // TypeScript doesn't set __proto__ in ES5, as it's non-standard.
	            // Try to determine the superclass constructor. Compatible implementations
	            // must either set __proto__ on a subclass constructor to the superclass constructor,
	            // or ensure each class has a valid `constructor` property on its prototype that
	            // points back to the constructor.
	            // If this is not the same as Function.[[Prototype]], then this is definately inherited.
	            // This is the case when in ES6 or when using __proto__ in a compatible browser.
	            if (proto !== functionPrototype)
	                return proto;
	            // If the super prototype is Object.prototype, null, or undefined, then we cannot determine the heritage.
	            var prototype = O.prototype;
	            var prototypeProto = prototype && Object.getPrototypeOf(prototype);
	            if (prototypeProto == null || prototypeProto === Object.prototype)
	                return proto;
	            // If the constructor was not a function, then we cannot determine the heritage.
	            var constructor = prototypeProto.constructor;
	            if (typeof constructor !== "function")
	                return proto;
	            // If we have some kind of self-reference, then we cannot determine the heritage.
	            if (constructor === O)
	                return proto;
	            // we have a pretty good guess at the heritage.
	            return constructor;
	        }
	        // Global metadata registry
	        // - Allows `import "reflect-metadata"` and `import "reflect-metadata/no-conflict"` to interoperate.
	        // - Uses isolated metadata if `Reflect` is frozen before the registry can be installed.
	        /**
	         * Creates a registry used to allow multiple `reflect-metadata` providers.
	         */
	        function CreateMetadataRegistry() {
	            var fallback;
	            if (!IsUndefined(registrySymbol) &&
	                typeof root.Reflect !== "undefined" &&
	                !(registrySymbol in root.Reflect) &&
	                typeof root.Reflect.defineMetadata === "function") {
	                // interoperate with older version of `reflect-metadata` that did not support a registry.
	                fallback = CreateFallbackProvider(root.Reflect);
	            }
	            var first;
	            var second;
	            var rest;
	            var targetProviderMap = new _WeakMap();
	            var registry = {
	                registerProvider: registerProvider,
	                getProvider: getProvider,
	                setProvider: setProvider,
	            };
	            return registry;
	            function registerProvider(provider) {
	                if (!Object.isExtensible(registry)) {
	                    throw new Error("Cannot add provider to a frozen registry.");
	                }
	                switch (true) {
	                    case fallback === provider: break;
	                    case IsUndefined(first):
	                        first = provider;
	                        break;
	                    case first === provider: break;
	                    case IsUndefined(second):
	                        second = provider;
	                        break;
	                    case second === provider: break;
	                    default:
	                        if (rest === undefined)
	                            rest = new _Set();
	                        rest.add(provider);
	                        break;
	                }
	            }
	            function getProviderNoCache(O, P) {
	                if (!IsUndefined(first)) {
	                    if (first.isProviderFor(O, P))
	                        return first;
	                    if (!IsUndefined(second)) {
	                        if (second.isProviderFor(O, P))
	                            return first;
	                        if (!IsUndefined(rest)) {
	                            var iterator = GetIterator(rest);
	                            while (true) {
	                                var next = IteratorStep(iterator);
	                                if (!next) {
	                                    return undefined;
	                                }
	                                var provider = IteratorValue(next);
	                                if (provider.isProviderFor(O, P)) {
	                                    IteratorClose(iterator);
	                                    return provider;
	                                }
	                            }
	                        }
	                    }
	                }
	                if (!IsUndefined(fallback) && fallback.isProviderFor(O, P)) {
	                    return fallback;
	                }
	                return undefined;
	            }
	            function getProvider(O, P) {
	                var providerMap = targetProviderMap.get(O);
	                var provider;
	                if (!IsUndefined(providerMap)) {
	                    provider = providerMap.get(P);
	                }
	                if (!IsUndefined(provider)) {
	                    return provider;
	                }
	                provider = getProviderNoCache(O, P);
	                if (!IsUndefined(provider)) {
	                    if (IsUndefined(providerMap)) {
	                        providerMap = new _Map();
	                        targetProviderMap.set(O, providerMap);
	                    }
	                    providerMap.set(P, provider);
	                }
	                return provider;
	            }
	            function hasProvider(provider) {
	                if (IsUndefined(provider))
	                    throw new TypeError();
	                return first === provider || second === provider || !IsUndefined(rest) && rest.has(provider);
	            }
	            function setProvider(O, P, provider) {
	                if (!hasProvider(provider)) {
	                    throw new Error("Metadata provider not registered.");
	                }
	                var existingProvider = getProvider(O, P);
	                if (existingProvider !== provider) {
	                    if (!IsUndefined(existingProvider)) {
	                        return false;
	                    }
	                    var providerMap = targetProviderMap.get(O);
	                    if (IsUndefined(providerMap)) {
	                        providerMap = new _Map();
	                        targetProviderMap.set(O, providerMap);
	                    }
	                    providerMap.set(P, provider);
	                }
	                return true;
	            }
	        }
	        /**
	         * Gets or creates the shared registry of metadata providers.
	         */
	        function GetOrCreateMetadataRegistry() {
	            var metadataRegistry;
	            if (!IsUndefined(registrySymbol) && IsObject(root.Reflect) && Object.isExtensible(root.Reflect)) {
	                metadataRegistry = root.Reflect[registrySymbol];
	            }
	            if (IsUndefined(metadataRegistry)) {
	                metadataRegistry = CreateMetadataRegistry();
	            }
	            if (!IsUndefined(registrySymbol) && IsObject(root.Reflect) && Object.isExtensible(root.Reflect)) {
	                Object.defineProperty(root.Reflect, registrySymbol, {
	                    enumerable: false,
	                    configurable: false,
	                    writable: false,
	                    value: metadataRegistry
	                });
	            }
	            return metadataRegistry;
	        }
	        function CreateMetadataProvider(registry) {
	            // [[Metadata]] internal slot
	            // https://rbuckton.github.io/reflect-metadata/#ordinary-object-internal-methods-and-internal-slots
	            var metadata = new _WeakMap();
	            var provider = {
	                isProviderFor: function (O, P) {
	                    var targetMetadata = metadata.get(O);
	                    if (IsUndefined(targetMetadata))
	                        return false;
	                    return targetMetadata.has(P);
	                },
	                OrdinaryDefineOwnMetadata: OrdinaryDefineOwnMetadata,
	                OrdinaryHasOwnMetadata: OrdinaryHasOwnMetadata,
	                OrdinaryGetOwnMetadata: OrdinaryGetOwnMetadata,
	                OrdinaryOwnMetadataKeys: OrdinaryOwnMetadataKeys,
	                OrdinaryDeleteMetadata: OrdinaryDeleteMetadata,
	            };
	            metadataRegistry.registerProvider(provider);
	            return provider;
	            function GetOrCreateMetadataMap(O, P, Create) {
	                var targetMetadata = metadata.get(O);
	                var createdTargetMetadata = false;
	                if (IsUndefined(targetMetadata)) {
	                    if (!Create)
	                        return undefined;
	                    targetMetadata = new _Map();
	                    metadata.set(O, targetMetadata);
	                    createdTargetMetadata = true;
	                }
	                var metadataMap = targetMetadata.get(P);
	                if (IsUndefined(metadataMap)) {
	                    if (!Create)
	                        return undefined;
	                    metadataMap = new _Map();
	                    targetMetadata.set(P, metadataMap);
	                    if (!registry.setProvider(O, P, provider)) {
	                        targetMetadata.delete(P);
	                        if (createdTargetMetadata) {
	                            metadata.delete(O);
	                        }
	                        throw new Error("Wrong provider for target.");
	                    }
	                }
	                return metadataMap;
	            }
	            // 3.1.2.1 OrdinaryHasOwnMetadata(MetadataKey, O, P)
	            // https://rbuckton.github.io/reflect-metadata/#ordinaryhasownmetadata
	            function OrdinaryHasOwnMetadata(MetadataKey, O, P) {
	                var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false);
	                if (IsUndefined(metadataMap))
	                    return false;
	                return ToBoolean(metadataMap.has(MetadataKey));
	            }
	            // 3.1.4.1 OrdinaryGetOwnMetadata(MetadataKey, O, P)
	            // https://rbuckton.github.io/reflect-metadata/#ordinarygetownmetadata
	            function OrdinaryGetOwnMetadata(MetadataKey, O, P) {
	                var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false);
	                if (IsUndefined(metadataMap))
	                    return undefined;
	                return metadataMap.get(MetadataKey);
	            }
	            // 3.1.5.1 OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P)
	            // https://rbuckton.github.io/reflect-metadata/#ordinarydefineownmetadata
	            function OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) {
	                var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ true);
	                metadataMap.set(MetadataKey, MetadataValue);
	            }
	            // 3.1.7.1 OrdinaryOwnMetadataKeys(O, P)
	            // https://rbuckton.github.io/reflect-metadata/#ordinaryownmetadatakeys
	            function OrdinaryOwnMetadataKeys(O, P) {
	                var keys = [];
	                var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false);
	                if (IsUndefined(metadataMap))
	                    return keys;
	                var keysObj = metadataMap.keys();
	                var iterator = GetIterator(keysObj);
	                var k = 0;
	                while (true) {
	                    var next = IteratorStep(iterator);
	                    if (!next) {
	                        keys.length = k;
	                        return keys;
	                    }
	                    var nextValue = IteratorValue(next);
	                    try {
	                        keys[k] = nextValue;
	                    }
	                    catch (e) {
	                        try {
	                            IteratorClose(iterator);
	                        }
	                        finally {
	                            throw e;
	                        }
	                    }
	                    k++;
	                }
	            }
	            function OrdinaryDeleteMetadata(MetadataKey, O, P) {
	                var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false);
	                if (IsUndefined(metadataMap))
	                    return false;
	                if (!metadataMap.delete(MetadataKey))
	                    return false;
	                if (metadataMap.size === 0) {
	                    var targetMetadata = metadata.get(O);
	                    if (!IsUndefined(targetMetadata)) {
	                        targetMetadata.delete(P);
	                        if (targetMetadata.size === 0) {
	                            metadata.delete(targetMetadata);
	                        }
	                    }
	                }
	                return true;
	            }
	        }
	        function CreateFallbackProvider(reflect) {
	            var defineMetadata = reflect.defineMetadata, hasOwnMetadata = reflect.hasOwnMetadata, getOwnMetadata = reflect.getOwnMetadata, getOwnMetadataKeys = reflect.getOwnMetadataKeys, deleteMetadata = reflect.deleteMetadata;
	            var metadataOwner = new _WeakMap();
	            var provider = {
	                isProviderFor: function (O, P) {
	                    var metadataPropertySet = metadataOwner.get(O);
	                    if (!IsUndefined(metadataPropertySet) && metadataPropertySet.has(P)) {
	                        return true;
	                    }
	                    if (getOwnMetadataKeys(O, P).length) {
	                        if (IsUndefined(metadataPropertySet)) {
	                            metadataPropertySet = new _Set();
	                            metadataOwner.set(O, metadataPropertySet);
	                        }
	                        metadataPropertySet.add(P);
	                        return true;
	                    }
	                    return false;
	                },
	                OrdinaryDefineOwnMetadata: defineMetadata,
	                OrdinaryHasOwnMetadata: hasOwnMetadata,
	                OrdinaryGetOwnMetadata: getOwnMetadata,
	                OrdinaryOwnMetadataKeys: getOwnMetadataKeys,
	                OrdinaryDeleteMetadata: deleteMetadata,
	            };
	            return provider;
	        }
	        /**
	         * Gets the metadata provider for an object. If the object has no metadata provider and this is for a create operation,
	         * then this module's metadata provider is assigned to the object.
	         */
	        function GetMetadataProvider(O, P, Create) {
	            var registeredProvider = metadataRegistry.getProvider(O, P);
	            if (!IsUndefined(registeredProvider)) {
	                return registeredProvider;
	            }
	            if (Create) {
	                if (metadataRegistry.setProvider(O, P, metadataProvider)) {
	                    return metadataProvider;
	                }
	                throw new Error("Illegal state.");
	            }
	            return undefined;
	        }
	        // naive Map shim
	        function CreateMapPolyfill() {
	            var cacheSentinel = {};
	            var arraySentinel = [];
	            var MapIterator = /** @class */ (function () {
	                function MapIterator(keys, values, selector) {
	                    this._index = 0;
	                    this._keys = keys;
	                    this._values = values;
	                    this._selector = selector;
	                }
	                MapIterator.prototype["@@iterator"] = function () { return this; };
	                MapIterator.prototype[iteratorSymbol] = function () { return this; };
	                MapIterator.prototype.next = function () {
	                    var index = this._index;
	                    if (index >= 0 && index < this._keys.length) {
	                        var result = this._selector(this._keys[index], this._values[index]);
	                        if (index + 1 >= this._keys.length) {
	                            this._index = -1;
	                            this._keys = arraySentinel;
	                            this._values = arraySentinel;
	                        }
	                        else {
	                            this._index++;
	                        }
	                        return { value: result, done: false };
	                    }
	                    return { value: undefined, done: true };
	                };
	                MapIterator.prototype.throw = function (error) {
	                    if (this._index >= 0) {
	                        this._index = -1;
	                        this._keys = arraySentinel;
	                        this._values = arraySentinel;
	                    }
	                    throw error;
	                };
	                MapIterator.prototype.return = function (value) {
	                    if (this._index >= 0) {
	                        this._index = -1;
	                        this._keys = arraySentinel;
	                        this._values = arraySentinel;
	                    }
	                    return { value: value, done: true };
	                };
	                return MapIterator;
	            }());
	            var Map = /** @class */ (function () {
	                function Map() {
	                    this._keys = [];
	                    this._values = [];
	                    this._cacheKey = cacheSentinel;
	                    this._cacheIndex = -2;
	                }
	                Object.defineProperty(Map.prototype, "size", {
	                    get: function () { return this._keys.length; },
	                    enumerable: true,
	                    configurable: true
	                });
	                Map.prototype.has = function (key) { return this._find(key, /*insert*/ false) >= 0; };
	                Map.prototype.get = function (key) {
	                    var index = this._find(key, /*insert*/ false);
	                    return index >= 0 ? this._values[index] : undefined;
	                };
	                Map.prototype.set = function (key, value) {
	                    var index = this._find(key, /*insert*/ true);
	                    this._values[index] = value;
	                    return this;
	                };
	                Map.prototype.delete = function (key) {
	                    var index = this._find(key, /*insert*/ false);
	                    if (index >= 0) {
	                        var size = this._keys.length;
	                        for (var i = index + 1; i < size; i++) {
	                            this._keys[i - 1] = this._keys[i];
	                            this._values[i - 1] = this._values[i];
	                        }
	                        this._keys.length--;
	                        this._values.length--;
	                        if (SameValueZero(key, this._cacheKey)) {
	                            this._cacheKey = cacheSentinel;
	                            this._cacheIndex = -2;
	                        }
	                        return true;
	                    }
	                    return false;
	                };
	                Map.prototype.clear = function () {
	                    this._keys.length = 0;
	                    this._values.length = 0;
	                    this._cacheKey = cacheSentinel;
	                    this._cacheIndex = -2;
	                };
	                Map.prototype.keys = function () { return new MapIterator(this._keys, this._values, getKey); };
	                Map.prototype.values = function () { return new MapIterator(this._keys, this._values, getValue); };
	                Map.prototype.entries = function () { return new MapIterator(this._keys, this._values, getEntry); };
	                Map.prototype["@@iterator"] = function () { return this.entries(); };
	                Map.prototype[iteratorSymbol] = function () { return this.entries(); };
	                Map.prototype._find = function (key, insert) {
	                    if (!SameValueZero(this._cacheKey, key)) {
	                        this._cacheIndex = -1;
	                        for (var i = 0; i < this._keys.length; i++) {
	                            if (SameValueZero(this._keys[i], key)) {
	                                this._cacheIndex = i;
	                                break;
	                            }
	                        }
	                    }
	                    if (this._cacheIndex < 0 && insert) {
	                        this._cacheIndex = this._keys.length;
	                        this._keys.push(key);
	                        this._values.push(undefined);
	                    }
	                    return this._cacheIndex;
	                };
	                return Map;
	            }());
	            return Map;
	            function getKey(key, _) {
	                return key;
	            }
	            function getValue(_, value) {
	                return value;
	            }
	            function getEntry(key, value) {
	                return [key, value];
	            }
	        }
	        // naive Set shim
	        function CreateSetPolyfill() {
	            var Set = /** @class */ (function () {
	                function Set() {
	                    this._map = new _Map();
	                }
	                Object.defineProperty(Set.prototype, "size", {
	                    get: function () { return this._map.size; },
	                    enumerable: true,
	                    configurable: true
	                });
	                Set.prototype.has = function (value) { return this._map.has(value); };
	                Set.prototype.add = function (value) { return this._map.set(value, value), this; };
	                Set.prototype.delete = function (value) { return this._map.delete(value); };
	                Set.prototype.clear = function () { this._map.clear(); };
	                Set.prototype.keys = function () { return this._map.keys(); };
	                Set.prototype.values = function () { return this._map.keys(); };
	                Set.prototype.entries = function () { return this._map.entries(); };
	                Set.prototype["@@iterator"] = function () { return this.keys(); };
	                Set.prototype[iteratorSymbol] = function () { return this.keys(); };
	                return Set;
	            }());
	            return Set;
	        }
	        // naive WeakMap shim
	        function CreateWeakMapPolyfill() {
	            var UUID_SIZE = 16;
	            var keys = HashMap.create();
	            var rootKey = CreateUniqueKey();
	            return /** @class */ (function () {
	                function WeakMap() {
	                    this._key = CreateUniqueKey();
	                }
	                WeakMap.prototype.has = function (target) {
	                    var table = GetOrCreateWeakMapTable(target, /*create*/ false);
	                    return table !== undefined ? HashMap.has(table, this._key) : false;
	                };
	                WeakMap.prototype.get = function (target) {
	                    var table = GetOrCreateWeakMapTable(target, /*create*/ false);
	                    return table !== undefined ? HashMap.get(table, this._key) : undefined;
	                };
	                WeakMap.prototype.set = function (target, value) {
	                    var table = GetOrCreateWeakMapTable(target, /*create*/ true);
	                    table[this._key] = value;
	                    return this;
	                };
	                WeakMap.prototype.delete = function (target) {
	                    var table = GetOrCreateWeakMapTable(target, /*create*/ false);
	                    return table !== undefined ? delete table[this._key] : false;
	                };
	                WeakMap.prototype.clear = function () {
	                    // NOTE: not a real clear, just makes the previous data unreachable
	                    this._key = CreateUniqueKey();
	                };
	                return WeakMap;
	            }());
	            function CreateUniqueKey() {
	                var key;
	                do
	                    key = "@@WeakMap@@" + CreateUUID();
	                while (HashMap.has(keys, key));
	                keys[key] = true;
	                return key;
	            }
	            function GetOrCreateWeakMapTable(target, create) {
	                if (!hasOwn.call(target, rootKey)) {
	                    if (!create)
	                        return undefined;
	                    Object.defineProperty(target, rootKey, { value: HashMap.create() });
	                }
	                return target[rootKey];
	            }
	            function FillRandomBytes(buffer, size) {
	                for (var i = 0; i < size; ++i)
	                    buffer[i] = Math.random() * 0xff | 0;
	                return buffer;
	            }
	            function GenRandomBytes(size) {
	                if (typeof Uint8Array === "function") {
	                    var array = new Uint8Array(size);
	                    if (typeof crypto !== "undefined") {
	                        crypto.getRandomValues(array);
	                    }
	                    else if (typeof msCrypto !== "undefined") {
	                        msCrypto.getRandomValues(array);
	                    }
	                    else {
	                        FillRandomBytes(array, size);
	                    }
	                    return array;
	                }
	                return FillRandomBytes(new Array(size), size);
	            }
	            function CreateUUID() {
	                var data = GenRandomBytes(UUID_SIZE);
	                // mark as random - RFC 4122 § 4.4
	                data[6] = data[6] & 0x4f | 0x40;
	                data[8] = data[8] & 0xbf | 0x80;
	                var result = "";
	                for (var offset = 0; offset < UUID_SIZE; ++offset) {
	                    var byte = data[offset];
	                    if (offset === 4 || offset === 6 || offset === 8)
	                        result += "-";
	                    if (byte < 16)
	                        result += "0";
	                    result += byte.toString(16).toLowerCase();
	                }
	                return result;
	            }
	        }
	        // uses a heuristic used by v8 and chakra to force an object into dictionary mode.
	        function MakeDictionary(obj) {
	            obj.__ = undefined;
	            delete obj.__;
	            return obj;
	        }
	    });
	})(Reflect || (Reflect = {}));
	return _Reflect;
}

require_Reflect();

function e(e){return ("object"==typeof e&&null!==e||"function"==typeof e)&&"function"==typeof e.then}function t$1(e){switch(typeof e){case "string":case "symbol":return e.toString();case "function":return e.name;default:throw new Error(`Unexpected ${typeof e} service id type`)}}const n$1=Symbol.for("@inversifyjs/common/islazyServiceIdentifier");class r{[n$1];#e;constructor(e){this.#e=e,this[n$1]=true;}static is(e){return "object"==typeof e&&null!==e&&true===e[n$1]}unwrap(){return this.#e()}}

function c$2(t,n,e){return Reflect.getOwnMetadata(n,t,e)}function a$1(t,n,e,u){Reflect.defineMetadata(n,e,t,u);}function i$1(t,n,e,u,f){const r=u(c$2(t,n,f)??e());Reflect.defineMetadata(n,r,t,f);}

const a="@inversifyjs/container/bindingId";function c$1(){const i=c$2(Object,a)??0;return i===Number.MAX_SAFE_INTEGER?a$1(Object,a,Number.MIN_SAFE_INTEGER):i$1(Object,a,()=>i,e=>e+1),i}const d={Request:"Request",Singleton:"Singleton",Transient:"Transient"},u={ConstantValue:"ConstantValue",DynamicValue:"DynamicValue",Factory:"Factory",Instance:"Instance",Provider:"Provider",ResolvedValue:"ResolvedValue",ServiceRedirection:"ServiceRedirection"};function*l$1(...e){for(const t of e)yield*t;}class p{#e;#t;#n;constructor(e){this.#e=new Map,this.#t={};for(const t of Reflect.ownKeys(e))this.#t[t]=new Map;this.#n=e;}add(e,t){this.#i(e).push(t);for(const n of Reflect.ownKeys(t))this.#o(n,t[n]).push(e);}clone(){const e=this.#r(),t=this.#s(),n=Reflect.ownKeys(this.#n),i=this._buildNewInstance(this.#n);this.#a(this.#e,i.#e,e,t);for(const t of n)this.#c(this.#t[t],i.#t[t],e);return i}get(e,t){return this.#t[e].get(t)}getAllKeys(e){return this.#t[e].keys()}removeByRelation(e,t){const n=this.get(e,t);if(void 0===n)return;const i=new Set(n);for(const n of i){const i=this.#e.get(n);if(void 0===i)throw new Error("Expecting model relation, none found");for(const o of i)o[e]===t&&this.#d(n,o);this.#e.delete(n);}}_buildNewInstance(e){return new p(e)}_cloneModel(e){return e}_cloneRelation(e){return e}#r(){const e=new Map;for(const t of this.#e.keys()){const n=this._cloneModel(t);e.set(t,n);}return e}#s(){const e=new Map;for(const t of this.#e.values())for(const n of t){const t=this._cloneRelation(n);e.set(n,t);}return e}#i(e){let t=this.#e.get(e);return void 0===t&&(t=[],this.#e.set(e,t)),t}#o(e,t){let n=this.#t[e].get(t);return void 0===n&&(n=[],this.#t[e].set(t,n)),n}#u(e,t){const n=t.get(e);if(void 0===n)throw new Error("Expecting model to be cloned, none found");return n}#l(e,t){const n=t.get(e);if(void 0===n)throw new Error("Expecting relation to be cloned, none found");return n}#c(e,t,n){for(const[i,o]of e){const e=new Array;for(const t of o)e.push(this.#u(t,n));t.set(i,e);}}#a(e,t,n,i){for(const[o,r]of e){const e=new Array;for(const t of r)e.push(this.#l(t,i));t.set(this.#u(o,n),e);}}#d(e,t){for(const n of Reflect.ownKeys(t))this.#p(e,n,t[n]);}#p(e,t,n){const i=this.#t[t].get(n);if(void 0!==i){const o=i.indexOf(e);-1!==o&&i.splice(o,1),0===i.length&&this.#t[t].delete(n);}}}var f;!function(e){e.moduleId="moduleId",e.serviceId="serviceId";}(f||(f={}));class v{#f;#v;constructor(e,t){this.#f=t??new p({moduleId:{isOptional:true},serviceId:{isOptional:false}}),this.#v=e;}static build(e){return new v(e)}add(e,t){this.#f.add(e,t);}clone(){return new v(this.#v,this.#f.clone())}get(e){const t=[],n=this.#f.get(f.serviceId,e);void 0!==n&&t.push(n);const i=this.#v()?.get(e);if(void 0!==i&&t.push(i),0!==t.length)return l$1(...t)}removeAllByModuleId(e){this.#f.removeByRelation(f.moduleId,e);}removeAllByServiceId(e){this.#f.removeByRelation(f.serviceId,e);}}const h="@inversifyjs/core/classMetadataReflectKey";function g$1(){return {constructorArguments:[],lifecycle:{postConstructMethodNames:new Set,preDestroyMethodNames:new Set},properties:new Map,scope:void 0}}const m="@inversifyjs/core/pendingClassMetadataCountReflectKey";const y=Symbol.for("@inversifyjs/core/InversifyCoreError");let M$1 = class M extends Error{[y];kind;constructor(e,t,n){super(t,n),this[y]=true,this.kind=e;}static is(e){return "object"==typeof e&&null!==e&&true===e[y]}static isErrorOfKind(e,t){return M.is(e)&&e.kind===t}};var I$1,b,w,C$1,S$1;function N$1(t){const n=c$2(t,h)??g$1();if(!function(t){const n=c$2(t,m);return void 0!==n&&0!==n}(t))return function(e,t){const n=[];if(t.length<e.length)throw new M$1(I$1.missingInjectionDecorator,`Found unexpected missing metadata on type "${e.name}". "${e.name}" constructor requires at least ${e.length.toString()} arguments, found ${t.length.toString()} instead.\nAre you using @inject, @multiInject or @unmanaged decorators in every non optional constructor argument?\n\nIf you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`);for(let e=0;e<t.length;++e) void 0===t[e]&&n.push(e);if(n.length>0)throw new M$1(I$1.missingInjectionDecorator,`Found unexpected missing metadata on type "${e.name}" at constructor indexes "${n.join('", "')}".\n\nAre you using @inject, @multiInject or @unmanaged decorators at those indexes?\n\nIf you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`)}(t,n.constructorArguments),n;!function(e,t){const n=[];for(let i=0;i<t.constructorArguments.length;++i){const o=t.constructorArguments[i];void 0!==o&&o.kind!==b.unknown||n.push(`  - Missing or incomplete metadata for type "${e.name}" at constructor argument with index ${i.toString()}.\nEvery constructor parameter must be decorated either with @inject, @multiInject or @unmanaged decorator.`);}for(const[i,o]of t.properties)o.kind===b.unknown&&n.push(`  - Missing or incomplete metadata for type "${e.name}" at property "${i.toString()}".\nThis property must be decorated either with @inject or @multiInject decorator.`);if(0===n.length)throw new M$1(I$1.unknown,`Unexpected class metadata for type "${e.name}" with uncompletion traces.\nThis might be caused by one of the following reasons:\n\n1. A third party library is targeting inversify reflection metadata.\n2. A bug is causing the issue. Consider submiting an issue to fix it.`);throw new M$1(I$1.missingInjectionDecorator,`Invalid class metadata at type ${e.name}:\n\n${n.join("\n\n")}`)}(t,n);}function P$1(e,t){const n=N$1(t).scope??e.scope;return {cache:{isRight:false,value:void 0},id:c$1(),implementationType:t,isSatisfiedBy:()=>true,moduleId:void 0,onActivation:void 0,onDeactivation:void 0,scope:n,serviceIdentifier:t,type:u.Instance}}function A$2(e){return e.isRight?{isRight:true,value:e.value}:e}function R(e){switch(e.type){case u.ConstantValue:case u.DynamicValue:return function(e){return {cache:A$2(e.cache),id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type,value:e.value}}(e);case u.Factory:return function(e){return {cache:A$2(e.cache),factory:e.factory,id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case u.Instance:return function(e){return {cache:A$2(e.cache),id:e.id,implementationType:e.implementationType,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case u.Provider:return function(e){return {cache:A$2(e.cache),id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,provider:e.provider,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case u.ResolvedValue:return function(e){return {cache:A$2(e.cache),factory:e.factory,id:e.id,isSatisfiedBy:e.isSatisfiedBy,metadata:e.metadata,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case u.ServiceRedirection:return function(e){return {id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,serviceIdentifier:e.serviceIdentifier,targetServiceIdentifier:e.targetServiceIdentifier,type:e.type}}(e)}}!function(e){e[e.injectionDecoratorConflict=0]="injectionDecoratorConflict",e[e.missingInjectionDecorator=1]="missingInjectionDecorator",e[e.planning=2]="planning",e[e.resolution=3]="resolution",e[e.unknown=4]="unknown";}(I$1||(I$1={})),function(e){e[e.unknown=32]="unknown";}(b||(b={})),function(e){e.id="id",e.moduleId="moduleId",e.serviceId="serviceId";}(w||(w={}));let x$3 = class x extends p{_buildNewInstance(e){return new x(e)}_cloneModel(e){return R(e)}};let T$2 = class T{#h;#g;#v;constructor(e,t,n){this.#g=n??new x$3({id:{isOptional:false},moduleId:{isOptional:true},serviceId:{isOptional:false}}),this.#v=e,this.#h=t;}static build(e,t){return new T(e,t)}clone(){return new T(this.#v,this.#h,this.#g.clone())}get(e){const t=this.getNonParentBindings(e)??this.#v()?.get(e);if(void 0!==t)return t;const n=this.#m(e);return void 0===n?n:[n]}*getChained(e){const t=this.getNonParentBindings(e);void 0!==t&&(yield*t);const n=this.#v();if(void 0===n){if(void 0===t){const t=this.#m(e);void 0!==t&&(yield t);}}else yield*n.getChained(e);}getBoundServices(){const e=new Set(this.#g.getAllKeys(w.serviceId)),t=this.#v();if(void 0!==t)for(const n of t.getBoundServices())e.add(n);return e}getById(e){return this.#g.get(w.id,e)??this.#v()?.getById(e)}getByModuleId(e){return this.#g.get(w.moduleId,e)??this.#v()?.getByModuleId(e)}getNonParentBindings(e){return this.#g.get(w.serviceId,e)}getNonParentBoundServices(){return this.#g.getAllKeys(w.serviceId)}removeById(e){this.#g.removeByRelation(w.id,e);}removeAllByModuleId(e){this.#g.removeByRelation(w.moduleId,e);}removeAllByServiceId(e){this.#g.removeByRelation(w.serviceId,e);}set(e){const t={[w.id]:e.id,[w.serviceId]:e.serviceIdentifier};void 0!==e.moduleId&&(t[w.moduleId]=e.moduleId),this.#g.add(e,t);}#m(e){if(void 0===this.#h||"function"!=typeof e)return;const t=P$1(this.#h,e);return this.set(t),t}};!function(e){e.moduleId="moduleId",e.serviceId="serviceId";}(C$1||(C$1={}));let j$2 = class j{#y;#v;constructor(e,t){this.#y=t??new p({moduleId:{isOptional:true},serviceId:{isOptional:false}}),this.#v=e;}static build(e){return new j(e)}add(e,t){this.#y.add(e,t);}clone(){return new j(this.#v,this.#y.clone())}get(e){const t=[],n=this.#y.get(C$1.serviceId,e);void 0!==n&&t.push(n);const i=this.#v()?.get(e);if(void 0!==i&&t.push(i),0!==t.length)return l$1(...t)}removeAllByModuleId(e){this.#y.removeByRelation(C$1.moduleId,e);}removeAllByServiceId(e){this.#y.removeByRelation(C$1.serviceId,e);}};!function(e){e[e.multipleInjection=0]="multipleInjection",e[e.singleInjection=1]="singleInjection",e[e.unmanaged=2]="unmanaged";}(S$1||(S$1={}));var E$1;!function(e){e[e.method=0]="method",e[e.parameter=1]="parameter",e[e.property=2]="property";}(E$1||(E$1={}));const K$1="@inversifyjs/core/classIsInjectableFlagReflectKey";const q$1=[Array,BigInt,Boolean,Function,Number,Object,String];function G$1(t){const i=c$2(t,"design:paramtypes");void 0!==i&&i$1(t,h,g$1,function(e){return t=>(e.forEach((e,n)=>{var i;void 0!==t.constructorArguments[n]||(i=e,q$1.includes(i))||(t.constructorArguments[n]=function(e){return {isFromTypescriptParamType:true,kind:S$1.singleInjection,name:void 0,optional:false,tags:new Map,value:e}}(e));}),t)}(i));}function W$2(i){return o=>{!function(n){if(void 0!==c$2(n,K$1))throw new M$1(I$1.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${n.name}"`);a$1(n,K$1,true);}(o),G$1(o);}}var fe;function ve(e){if(!(e instanceof Error))return  false;return e instanceof RangeError&&/stack space|call stack|too much recursion/i.test(e.message)||"InternalError"===e.name&&/too much recursion/.test(e.message)}function he(e,t){if(ve(t)){const n=function(e){const t=[...e];if(0===t.length)return "(No dependency trace)";return t.map(t$1).join(" -> ")}(function(e){const t=new Set;for(const n of e.servicesBranch){if(t.has(n))return [...t,n];t.add(n);}return [...t]}(e));throw new M$1(I$1.planning,`Circular dependency found: ${n}`,{cause:t})}throw t}!function(e){e[e.multipleInjection=0]="multipleInjection",e[e.singleInjection=1]="singleInjection";}(fe||(fe={}));const ge=Symbol.for("@inversifyjs/core/LazyPlanServiceNode");class me{[ge];_serviceIdentifier;_serviceNode;constructor(e,t){this[ge]=true,this._serviceNode=e,this._serviceIdentifier=t;}get bindings(){return this._getNode().bindings}get isContextFree(){return this._getNode().isContextFree}get serviceIdentifier(){return this._serviceIdentifier}set bindings(e){this._getNode().bindings=e;}set isContextFree(e){this._getNode().isContextFree=e;}static is(e){return "object"==typeof e&&null!==e&&true===e[ge]}invalidate(){this._serviceNode=void 0;}isExpanded(){return void 0!==this._serviceNode}_getNode(){return void 0===this._serviceNode&&(this._serviceNode=this._buildPlanServiceNode()),this._serviceNode}}class ye{#M;constructor(e){this.#M=e;}get name(){return this.#M.elem.name}get serviceIdentifier(){return this.#M.elem.serviceIdentifier}get tags(){return this.#M.elem.tags}getAncestor(){if(this.#M.elem.getAncestorsCalled=true,void 0!==this.#M.previous)return new ye(this.#M.previous)}}function Me(e,t,n){const i=n?.customServiceIdentifier??t.serviceIdentifier,o=(true===n?.chained?[...e.operations.getBindingsChained(i)]:[...e.operations.getBindings(i)??[]]).filter(e=>e.isSatisfiedBy(t));if(0===o.length&&void 0!==e.autobindOptions&&"function"==typeof i){const n=P$1(e.autobindOptions,i);e.operations.setBinding(n),n.isSatisfiedBy(t)&&o.push(n);}return o}class Ie{last;constructor(e){this.last=e;}concat(e){return new Ie({elem:e,previous:this.last})}[Symbol.iterator](){let e=this.last;return {next:()=>{if(void 0===e)return {done:true,value:void 0};const t=e.elem;return e=e.previous,{done:false,value:t}}}}}function be(e){const t=new Map;return void 0!==e.rootConstraints.tag&&t.set(e.rootConstraints.tag.key,e.rootConstraints.tag.value),new Ie({elem:{getAncestorsCalled:false,name:e.rootConstraints.name,serviceIdentifier:e.rootConstraints.serviceIdentifier,tags:t},previous:void 0})}function we(e){return void 0!==e.redirections}function Ce(e,t,n,i){const r=n.elem.serviceIdentifier,s=n.previous?.elem.serviceIdentifier;Array.isArray(e)?function(e,t,n,i,r,s){if(0!==e.length){const t=s[s.length-1]??n,a=`Ambiguous bindings found for service: "${t$1(t)}".${Ae(s)}\n\nRegistered bindings:\n\n${e.map(e=>function(e){switch(e.type){case u.Instance:return `[ type: "${e.type}", serviceIdentifier: "${t$1(e.serviceIdentifier)}", scope: "${e.scope}", implementationType: "${e.implementationType.name}" ]`;case u.ServiceRedirection:return `[ type: "${e.type}", serviceIdentifier: "${t$1(e.serviceIdentifier)}", redirection: "${t$1(e.targetServiceIdentifier)}" ]`;default:return `[ type: "${e.type}", serviceIdentifier: "${t$1(e.serviceIdentifier)}", scope: "${e.scope}" ]`}}(e.binding)).join("\n")}\n\nTrying to resolve bindings for "${Ne(n,i)}".${Pe(r)}`;throw new M$1(I$1.planning,a)}t||Se(n,i,r,s);}(e,t,r,s,n.elem,i):function(e,t,n,i,o,r){ void 0!==e||t||Se(n,i,o,r);}(e,t,r,s,n.elem,i);}function Se(e,t,n,i){const r=i[i.length-1]??e,s=`No bindings found for service: "${t$1(r)}".\n\nTrying to resolve bindings for "${Ne(e,t)}".${Ae(i)}${Pe(n)}`;throw new M$1(I$1.planning,s)}function Ne(e,t){return void 0===t?`${t$1(e)} (Root service)`:t$1(t)}function Pe(e){const t=0===e.tags.size?"":`\n- tags:\n  - ${[...e.tags.keys()].map(e=>e.toString()).join("\n  - ")}`;return `\n\nBinding constraints:\n- service identifier: ${t$1(e.serviceIdentifier)}\n- name: ${e.name?.toString()??"-"}${t}`}function Ae(e){return 0===e.length?"":`\n\n- service redirections:\n  - ${e.map(e=>t$1(e)).join("\n  - ")}`}function Re(e,t,n,i){if(1===e.redirections.length){const[o]=e.redirections;return void(we(o)&&Re(o,t,n,[...i,o.binding.targetServiceIdentifier]))}Ce(e.redirections,t,n,i);}function xe(e,t,n){if(Array.isArray(e.bindings)&&1===e.bindings.length){const[i]=e.bindings;return void(we(i)&&Re(i,t,n,[i.binding.targetServiceIdentifier]))}Ce(e.bindings,t,n,[]);}function Te(e){return r.is(e)?e.unwrap():e}function je(e){return (t,n,i)=>{const o=Te(i.value),r=n.concat({getAncestorsCalled:false,name:i.name,serviceIdentifier:o,tags:i.tags}),s=new ye(r.last),a=i.kind===S$1.multipleInjection&&i.chained,c=Me(t,s,{chained:a}),d=[],u={bindings:d,isContextFree:true,serviceIdentifier:o};if(d.push(...e(t,r,c,u,a)),u.isContextFree=!r.last.elem.getAncestorsCalled,i.kind===S$1.singleInjection){xe(u,i.optional,r.last);const[e]=d;u.bindings=e;}return u}}function Be(e){return (t,n,i)=>{const o=Te(i.value),r=n.concat({getAncestorsCalled:false,name:i.name,serviceIdentifier:o,tags:i.tags}),s=new ye(r.last),a=i.kind===fe.multipleInjection&&i.chained,c=Me(t,s,{chained:a}),d=[],u={bindings:d,isContextFree:true,serviceIdentifier:o};if(d.push(...e(t,r,c,u,a)),u.isContextFree=!r.last.elem.getAncestorsCalled,i.kind===fe.singleInjection){xe(u,i.optional,r.last);const[e]=d;u.bindings=e;}return u}}function Fe(e){const t=function(e){return (t,n,i)=>{const o={binding:n,classMetadata:t.operations.getClassMetadata(n.implementationType),constructorParams:[],propertyParams:new Map},r={autobindOptions:t.autobindOptions,node:o,operations:t.operations,servicesBranch:t.servicesBranch};return e(r,i)}}(e),n=function(e){return (t,n,i)=>{const o={binding:n,params:[]},r={autobindOptions:t.autobindOptions,node:o,operations:t.operations,servicesBranch:t.servicesBranch};return e(r,i)}}(e),i=(e,i,r,s,a)=>{const c=we(s)?s.binding.targetServiceIdentifier:s.serviceIdentifier;e.servicesBranch.push(c);const d=[];for(const s of r)switch(s.type){case u.Instance:d.push(t(e,s,i));break;case u.ResolvedValue:d.push(n(e,s,i));break;case u.ServiceRedirection:{const t=o(e,i,s,a);d.push(t);break}default:d.push({binding:s});}return e.servicesBranch.pop(),d},o=function(e){return (t,n,i,o)=>{const r={binding:i,redirections:[]},s=Me(t,new ye(n.last),{chained:o,customServiceIdentifier:i.targetServiceIdentifier});return r.redirections.push(...e(t,n,s,r,o)),r}}(i);return i}function ke(e,t,n,i){if(void 0!==e&&(me.is(n)&&!n.isExpanded()||n.isContextFree)){const i={tree:{root:n}};t.setPlan(e,i);}else t.setNonCachedServiceNode(n,i);}class $e extends me{#I;#b;#w;#C;constructor(e,t,n,i,o){super(o,Te(i.value)),this.#b=t,this.#I=e,this.#w=n,this.#C=i;}_buildPlanServiceNode(){return this.#b(this.#I,this.#w,this.#C)}}class De extends me{#I;#S;#w;#N;constructor(e,t,n,i,o){super(o,Te(i.value)),this.#I=e,this.#S=t,this.#w=n,this.#N=i;}_buildPlanServiceNode(){return this.#S(this.#I,this.#w,this.#N)}}function Ve(e,t,n,i){const o=function(e,t){const n=function(e,t){return (n,i,o)=>{if(o.kind===S$1.unmanaged)return;const s=function(e){let t;if(0===e.tags.size)t=void 0;else {if(1!==e.tags.size)return;{const[n,i]=e.tags.entries().next().value;t={key:n,value:i};}}const n=r.is(e.value)?e.value.unwrap():e.value;return e.kind===S$1.multipleInjection?{chained:e.chained,isMultiple:true,name:e.name,optional:e.optional,serviceIdentifier:n,tag:t}:{isMultiple:false,name:e.name,optional:e.optional,serviceIdentifier:n,tag:t}}(o);if(void 0!==s){const e=n.operations.getPlan(s);if(void 0!==e&&e.tree.root.isContextFree)return e.tree.root}const a=t(n,i,o),c=new $e(n,e,i,o,a);return ke(s,n.operations,c,{bindingConstraintsList:i,chainedBindings:o.kind===S$1.multipleInjection&&o.chained,optionalBindings:o.optional}),c}}(e,t);return (e,t,i)=>{const o=t.classMetadata;for(const[r,s]of o.constructorArguments.entries())t.constructorParams[r]=n(e,i,s);for(const[r,s]of o.properties){const o=n(e,i,s);void 0!==o&&t.propertyParams.set(r,o);}return e.node}}(e,n),s=function(e,t){const n=function(e,t){return (n,i,o)=>{const s=function(e){let t;if(0===e.tags.size)t=void 0;else {if(1!==e.tags.size)return;{const[n,i]=e.tags.entries().next().value;t={key:n,value:i};}}const n=r.is(e.value)?e.value.unwrap():e.value;return e.kind===fe.multipleInjection?{chained:e.chained,isMultiple:true,name:e.name,optional:e.optional,serviceIdentifier:n,tag:t}:{isMultiple:false,name:e.name,optional:e.optional,serviceIdentifier:n,tag:t}}(o);if(void 0!==s){const e=n.operations.getPlan(s);if(void 0!==e&&e.tree.root.isContextFree)return e.tree.root}const a=t(n,i,o),c=new De(n,e,i,o,a);return ke(s,n.operations,c,{bindingConstraintsList:i,chainedBindings:o.kind===fe.multipleInjection&&o.chained,optionalBindings:o.optional}),c}}(e,t);return (e,t,i)=>{const o=t.binding.metadata;for(const[r,s]of o.arguments.entries())t.params[r]=n(e,i,s);return e.node}}(t,i);return (e,t)=>e.node.binding.type===u.Instance?o(e,e.node,t):s(e,e.node,t)}class Oe extends me{#I;constructor(e,t){super(t,t.serviceIdentifier),this.#I=e;}_buildPlanServiceNode(){return Ue(this.#I)}}const Ee=je(Le),_e=Be(Le),ze=Fe(Ve(Ee,_e,Ee,_e));function Le(e,t,n,i,o){return ze(e,t,n,i,o)}const Ue=function(e){return t=>{const n=be(t),i=new ye(n.last),o=t.rootConstraints.isMultiple&&t.rootConstraints.chained,r=Me(t,i,{chained:o}),s=[],a={bindings:s,isContextFree:true,serviceIdentifier:t.rootConstraints.serviceIdentifier};if(s.push(...e(t,n,r,a,o)),a.isContextFree=!n.last.elem.getAncestorsCalled,!t.rootConstraints.isMultiple){xe(a,t.rootConstraints.isOptional??false,n.last);const[e]=s;a.bindings=e;}return a}}(ze);function Ke(e){try{const t=function(e){return e.rootConstraints.isMultiple?{chained:e.rootConstraints.chained,isMultiple:!0,name:e.rootConstraints.name,optional:e.rootConstraints.isOptional??!1,serviceIdentifier:e.rootConstraints.serviceIdentifier,tag:e.rootConstraints.tag}:{isMultiple:!1,name:e.rootConstraints.name,optional:e.rootConstraints.isOptional??!1,serviceIdentifier:e.rootConstraints.serviceIdentifier,tag:e.rootConstraints.tag}}(e),n=e.operations.getPlan(t);if(void 0!==n)return n;const i=Ue(e),o={tree:{root:new Oe(e,i)}};return e.operations.setPlan(t,o),o}catch(t){he(e,t);}}var qe;!function(e){e.bindingAdded="bindingAdded",e.bindingRemoved="bindingRemoved";}(qe||(qe={}));class Ge{#P;#A;#R;constructor(){this.#P=[],this.#A=8,this.#R=1024;}*[Symbol.iterator](){let e=0;for(const t of this.#P){const n=t.deref();void 0===n?++e:yield n;}this.#P.length>=this.#A&&this.#x(e)&&this.#T(e);}push(e){const t=new WeakRef(e);if(this.#P.push(t),this.#P.length>=this.#A&&this.#P.length%this.#R===0){let e=0;for(const t of this.#P) void 0===t.deref()&&++e;this.#x(e)&&this.#T(e);}}#T(e){const t=new Array(this.#P.length-e);let n=0;for(const e of this.#P)e.deref()&&(t[n++]=e);this.#P=t;}#x(e){return e>=.5*this.#P.length}}const We=Fe(Ve(Ee,_e,function(e,t,n){return Xe(e,t,n)},function(e,t,n){return He(e,t,n)})),Xe=function(e){const t=je(e);return (e,n,i)=>{try{return t(e,n,i)}catch(e){if(M$1.isErrorOfKind(e,I$1.planning))return;throw e}}}(We),He=function(e){const t=Be(e);return (e,n,i)=>{try{return t(e,n,i)}catch(e){if(M$1.isErrorOfKind(e,I$1.planning))return;throw e}}}(We);function Je(e,t,n,i,o){if(me.is(t)&&!t.isExpanded())return {isContextFreeBinding:true,shouldInvalidateServiceNode:false};const r=new ye(i.last);return !n.isSatisfiedBy(r)||i.last.elem.getAncestorsCalled?{isContextFreeBinding:!i.last.elem.getAncestorsCalled,shouldInvalidateServiceNode:false}:function(e,t,n,i,o){let r;try{[r]=We(e,i,[n],t,o);}catch(e){if(ve(e))return {isContextFreeBinding:false,shouldInvalidateServiceNode:true};throw e}return function(e,t){if(Array.isArray(e.bindings))e.bindings.push(t);else {if(void 0!==e.bindings){if(!me.is(e))throw new M$1(I$1.planning,"Unexpected non-lazy plan service node. This is likely a bug in the planning logic. Please, report this issue");return {isContextFreeBinding:true,shouldInvalidateServiceNode:true}}e.bindings=t;}return {isContextFreeBinding:true,shouldInvalidateServiceNode:false}}(t,r)}(e,t,n,i,o)}function Qe(e,t,n,i){if(me.is(e)&&!e.isExpanded())return {bindingNodeRemoved:void 0,isContextFreeBinding:true};const o=new ye(n.last);if(!t.isSatisfiedBy(o)||n.last.elem.getAncestorsCalled)return {bindingNodeRemoved:void 0,isContextFreeBinding:!n.last.elem.getAncestorsCalled};let r;if(Array.isArray(e.bindings))e.bindings=e.bindings.filter(e=>e.binding!==t||(r=e,false));else if(e.bindings?.binding===t)if(r=e.bindings,i)e.bindings=void 0;else {if(!me.is(e))throw new M$1(I$1.planning,"Unexpected non-lazy plan service node. This is likely a bug in the planning logic. Please, report this issue");e.invalidate();}return {bindingNodeRemoved:r,isContextFreeBinding:true}}class Ye{#j;#B;#F;#k;#$;#D;constructor(){this.#j=new Map,this.#B=this.#V(),this.#F=this.#V(),this.#k=this.#V(),this.#$=this.#V(),this.#D=new Ge;}clearCache(){for(const e of this.#O())e.clear();for(const e of this.#D)e.clearCache();}get(e){return void 0===e.name?void 0===e.tag?this.#E(this.#B,e).get(e.serviceIdentifier):this.#E(this.#$,e).get(e.serviceIdentifier)?.get(e.tag.key)?.get(e.tag.value):void 0===e.tag?this.#E(this.#F,e).get(e.serviceIdentifier)?.get(e.name):this.#E(this.#k,e).get(e.serviceIdentifier)?.get(e.name)?.get(e.tag.key)?.get(e.tag.value)}invalidateServiceBinding(e){this.#_(e),this.#z(e),this.#L(e),this.#U(e),this.#K(e);for(const t of this.#D)t.invalidateServiceBinding(e);}set(e,t){ void 0===e.name?void 0===e.tag?this.#E(this.#B,e).set(e.serviceIdentifier,t):this.#q(this.#q(this.#E(this.#$,e),e.serviceIdentifier),e.tag.key).set(e.tag.value,t):void 0===e.tag?this.#q(this.#E(this.#F,e),e.serviceIdentifier).set(e.name,t):this.#q(this.#q(this.#q(this.#E(this.#k,e),e.serviceIdentifier),e.name),e.tag.key).set(e.tag.value,t);}setNonCachedServiceNode(e,t){let n=this.#j.get(e.serviceIdentifier);void 0===n&&(n=new Map,this.#j.set(e.serviceIdentifier,n)),n.set(e,t);}subscribe(e){this.#D.push(e);}#V(){const e=new Array(8);for(let t=0;t<e.length;++t)e[t]=new Map;return e}#G(e,t,n,i){const o=!!(2&t);let r;if(o){r={chained:!!(0&t),isMultiple:o,serviceIdentifier:e.binding.serviceIdentifier};}else r={isMultiple:o,serviceIdentifier:e.binding.serviceIdentifier};return !!(1&t)&&(r.isOptional=true),void 0!==n&&(r.name=n),void 0!==i&&(r.tag=i),{autobindOptions:void 0,operations:e.operations,rootConstraints:r,servicesBranch:[]}}#q(e,t){let n=e.get(t);return void 0===n&&(n=new Map,e.set(t,n)),n}#E(e,t){return e[this.#W(t)]}#O(){return [this.#j,...this.#B,...this.#F,...this.#k,...this.#$]}#W(e){return e.isMultiple?(e.chained?4:0)|(e.optional?1:0)|2:e.optional?1:0}#z(e){for(const[t,n]of this.#F.entries()){const i=n.get(e.binding.serviceIdentifier);if(void 0!==i)for(const[n,o]of i.entries())this.#X(e,o,t,n,void 0);}}#L(e){for(const[t,n]of this.#k.entries()){const i=n.get(e.binding.serviceIdentifier);if(void 0!==i)for(const[n,o]of i.entries())for(const[i,r]of o.entries())for(const[o,s]of r.entries())this.#X(e,s,t,n,{key:i,value:o});}}#H(e){switch(e.binding.type){case u.ServiceRedirection:for(const t of e.redirections)this.#H(t);break;case u.Instance:for(const t of e.constructorParams) void 0!==t&&this.#J(t);for(const t of e.propertyParams.values())this.#J(t);break;case u.ResolvedValue:for(const t of e.params)this.#J(t);}}#J(e){const t=this.#j.get(e.serviceIdentifier);void 0!==t&&t.has(e)&&(t.delete(e),this.#Q(e));}#Q(e){if((!me.is(e)||e.isExpanded())&&void 0!==e.bindings)if(Array.isArray(e.bindings))for(const t of e.bindings)this.#H(t);else this.#H(e.bindings);}#K(e){const t=this.#j.get(e.binding.serviceIdentifier);if(void 0!==t)switch(e.kind){case qe.bindingAdded:for(const[n,i]of t){const t=Je({autobindOptions:void 0,operations:e.operations,servicesBranch:[]},n,e.binding,i.bindingConstraintsList,i.chainedBindings);t.isContextFreeBinding?t.shouldInvalidateServiceNode&&me.is(n)&&(this.#Q(n),n.invalidate()):this.clearCache();}break;case qe.bindingRemoved:for(const[n,i]of t){const t=Qe(n,e.binding,i.bindingConstraintsList,i.optionalBindings);t.isContextFreeBinding?void 0!==t.bindingNodeRemoved&&this.#H(t.bindingNodeRemoved):this.clearCache();}}}#_(e){for(const[t,n]of this.#B.entries()){const i=n.get(e.binding.serviceIdentifier);this.#X(e,i,t,void 0,void 0);}}#U(e){for(const[t,n]of this.#$.entries()){const i=n.get(e.binding.serviceIdentifier);if(void 0!==i)for(const[n,o]of i.entries())for(const[i,r]of o.entries())this.#X(e,r,t,void 0,{key:n,value:i});}}#X(e,t,n,i,o){if(void 0!==t&&me.is(t.tree.root)){const c=this.#G(e,n,i,o);switch(e.kind){case qe.bindingAdded:{const n=(r=c,s=t.tree.root,a=e.binding,me.is(s)&&!s.isExpanded()?{isContextFreeBinding:true,shouldInvalidateServiceNode:false}:Je(r,s,a,be(r),r.rootConstraints.isMultiple&&r.rootConstraints.chained));n.isContextFreeBinding?n.shouldInvalidateServiceNode&&(this.#Q(t.tree.root),t.tree.root.invalidate()):this.clearCache();}break;case qe.bindingRemoved:{const n=function(e,t,n){return me.is(t)&&!t.isExpanded()?{bindingNodeRemoved:void 0,isContextFreeBinding:true}:Qe(t,n,be(e),e.rootConstraints.isOptional??false)}(c,t.tree.root,e.binding);n.isContextFreeBinding?void 0!==n.bindingNodeRemoved&&this.#H(n.bindingNodeRemoved):this.clearCache();}}}var r,s,a;}}function Ze(e,t){if(ve(t)){const n=function(e){const t=[...e];if(0===t.length)return "(No dependency trace)";return t.map(t$1).join(" -> ")}(function(e){const t=e.planResult.tree.root,n=[];function i(e){const t=n.indexOf(e);if(-1!==t){return [...n.slice(t),e].map(e=>e.serviceIdentifier)}n.push(e);try{for(const t of function(e){const t=[],n=e.bindings;if(void 0===n)return t;const i=e=>{if(we(e))for(const t of e.redirections)i(t);else switch(e.binding.type){case u.Instance:{const n=e;for(const e of n.constructorParams)void 0!==e&&t.push(e);for(const e of n.propertyParams.values())t.push(e);break}case u.ResolvedValue:{const n=e;for(const e of n.params)t.push(e);break}}};if(Array.isArray(n))for(const e of n)i(e);else i(n);return t}(e)){const e=i(t);if(void 0!==e)return e}}finally{n.pop();}}return i(t)??[]}(e));throw new M$1(I$1.planning,`Circular dependency found: ${n}`,{cause:t})}throw t}function et$1(e$1,t){return e(t)?(e$1.cache={isRight:true,value:t},t.then(t=>tt(e$1,t))):tt(e$1,t)}function tt(e,t){return e.cache={isRight:true,value:t},t}function nt(e$1,t,n){const i=e$1.getActivations(t);return void 0===i?n:e(n)?it(e$1,n,i[Symbol.iterator]()):function(e$1,t,n){let i=t,o=n.next();for(;true!==o.done;){const t=o.value(e$1.context,i);if(e(t))return it(e$1,t,n);i=t,o=n.next();}return i}(e$1,n,i[Symbol.iterator]())}async function it(e,t,n){let i=await t,o=n.next();for(;true!==o.done;)i=await o.value(e.context,i),o=n.next();return i}function ot(e$1,t,n){let i=n;if(void 0!==t.onActivation){const n=t.onActivation;i=e(i)?i.then(t=>n(e$1.context,t)):n(e$1.context,i);}return nt(e$1,t.serviceIdentifier,i)}function rt(e){return (t,n)=>{if(n.cache.isRight)return n.cache.value;return et$1(n,ot(t,n,e(t,n)))}}const st=rt(function(e,t){return t.value});function at(e){return e}function ct(e,t){return (n,i)=>{const o=e(i);switch(o.scope){case d.Singleton:if(o.cache.isRight)return o.cache.value;return et$1(o,ot(n,o,t(n,i)));case d.Request:{if(n.requestScopeCache.has(o.id))return n.requestScopeCache.get(o.id);const e=ot(n,o,t(n,i));return n.requestScopeCache.set(o.id,e),e}case d.Transient:return ot(n,o,t(n,i))}}}const dt=(e=>ct(at,e))(function(e,t){return t.value(e.context)});const ut=rt(function(e,t){return t.factory(e.context)});function lt(e$1,t,n){const i=function(e$1,t,n){if(!(n in e$1))throw new M$1(I$1.resolution,`Expecting a "${n.toString()}" property when resolving "${t.implementationType.name}" class @postConstruct decorated method, none found.`);if("function"!=typeof e$1[n])throw new M$1(I$1.resolution,`Expecting a "${n.toString()}" method when resolving "${t.implementationType.name}" class @postConstruct decorated method, a non function property was found instead.`);{let i;try{i=e$1[n]();}catch(e){throw new M$1(I$1.resolution,`Unexpected error found when calling "${n.toString()}" @postConstruct decorated method on class "${t.implementationType.name}"`,{cause:e})}if(e(i))return async function(e,t,n){try{await n;}catch(n){throw new M$1(I$1.resolution,`Unexpected error found when calling "${t.toString()}" @postConstruct decorated method on class "${e.implementationType.name}"`,{cause:n})}}(t,n,i)}}(e$1,t,n);return e(i)?i.then(()=>e$1):e$1}function pt(e$1,t,n){if(0===n.size)return e$1;let i=e$1;for(const e$1 of n)i=e(i)?i.then(n=>lt(n,t,e$1)):lt(i,t,e$1);return i}function ft(e$1){return (t,n,i)=>{const o=new i.binding.implementationType(...t),r=e$1(n,o,i);return e(r)?r.then(()=>pt(o,i.binding,i.classMetadata.lifecycle.postConstructMethodNames)):pt(o,i.binding,i.classMetadata.lifecycle.postConstructMethodNames)}}const vt=rt(function(e,t){return t.provider(e.context)});function ht(e){return e.binding}function gt(e){return e.binding}const mt=function(e$1){return (t,n,i)=>{const o=[];for(const[r,a]of i.propertyParams){const c=i.classMetadata.properties.get(r);if(void 0===c)throw new M$1(I$1.resolution,`Expecting metadata at property "${r.toString()}", none found`);c.kind!==S$1.unmanaged&&void 0!==a.bindings&&(n[r]=e$1(t,a),e(n[r])&&o.push((async()=>{n[r]=await n[r];})()));}if(o.length>0)return Promise.all(o).then(()=>{})}}(Nt),yt=function(e){return function t(n,i){const o=[];for(const r of i.redirections)we(r)?o.push(...t(n,r)):o.push(e(n,r));return o}}(St),Mt=function(e$1,t,n){return (i,o)=>{const r=e$1(i,o);return e(r)?t(r,i,o):n(r,i,o)}}(function(e$1){return (t,n)=>{const i=[];for(const o of n.constructorParams) void 0===o?i.push(void 0):i.push(e$1(t,o));return i.some(e)?Promise.all(i):i}}(Nt),function(e){return async(t,n,i)=>{const o=await t;return e(o,n,i)}}(ft(mt)),ft(mt)),It=function(e$1){return (t,n)=>{const i=e$1(t,n);return e(i)?i.then(e=>n.binding.factory(...e)):n.binding.factory(...i)}}(function(e$1){return (t,n)=>{const i=[];for(const o of n.params)i.push(e$1(t,o));return i.some(e)?Promise.all(i):i}}(Nt)),bt=(e=>ct(ht,e))(Mt),wt=(e=>ct(gt,e))(It);function Ct(e){try{return Nt(e,e.planResult.tree.root)}catch(t){Ze(e,t);}}function St(e,t){switch(t.binding.type){case u.ConstantValue:return st(e,t.binding);case u.DynamicValue:return dt(e,t.binding);case u.Factory:return ut(e,t.binding);case u.Instance:return bt(e,t);case u.Provider:return vt(e,t.binding);case u.ResolvedValue:return wt(e,t)}}function Nt(e$1,t){if(void 0!==t.bindings)return Array.isArray(t.bindings)?function(e$1,t){const n=[];for(const i of t)we(i)?n.push(...yt(e$1,i)):n.push(St(e$1,i));if(n.some(e))return Promise.all(n);return n}(e$1,t.bindings):function(e,t){if(we(t)){const n=yt(e,t);if(1===n.length)return n[0];throw new M$1(I$1.resolution,"Unexpected multiple resolved values on single injection")}return St(e,t)}(e$1,t.bindings)}function Pt(e){return void 0!==e.scope}function At(e,t){if("function"==typeof e[t]){return e[t]()}}function Rt(e,t){const n=e.lifecycle.preDestroyMethodNames;if(0===n.size)return;let i;for(const e of n)i=void 0===i?At(t,e):i.then(()=>At(t,e));return i}function xt(e$1,t,n){const i=e$1.getDeactivations(t);if(void 0!==i)return e(n)?Tt(n,i[Symbol.iterator]()):function(e$1,t){let n=t.next();for(;true!==n.done;){const i=n.value(e$1);if(e(i))return Tt(e$1,t);n=t.next();}}(n,i[Symbol.iterator]())}async function Tt(e,t){const n=await e;let i=t.next();for(;true!==i.done;)await i.value(n),i=t.next();}function jt(e$1,t){const n=function(e$1,t){if(t.type===u.Instance){const n=e$1.getClassMetadata(t.implementationType),i=t.cache.value;return e(i)?i.then(e=>Rt(n,e)):Rt(n,i)}}(e$1,t);return void 0===n?Bt(e$1,t):n.then(()=>Bt(e$1,t))}function Bt(e$1,t){const n=t.cache;return e(n.value)?n.value.then(n=>Ft(e$1,t,n)):Ft(e$1,t,n.value)}function Ft(e,t,n){let i;if(void 0!==t.onDeactivation){i=(0, t.onDeactivation)(n);}return void 0===i?xt(e,t.serviceIdentifier,n):i.then(()=>xt(e,t.serviceIdentifier,n))}function kt(e,t){if(void 0===t)return;const n=function(e){const t=[];for(const n of e)Pt(n)&&n.scope===d.Singleton&&n.cache.isRight&&t.push(n);return t}(t),i=[];for(const t of n){const n=jt(e,t);void 0!==n&&i.push(n);}return i.length>0?Promise.all(i).then(()=>{}):void 0}function $t(e,t){const n=e.getBindingsFromModule(t);return kt(e,n)}function Dt(e,t){const n=e.getBindings(t);return kt(e,n)}

const t=Symbol.for("@inversifyjs/plugin/isPlugin");

const I=Symbol.for("@inversifyjs/container/bindingIdentifier");function A$1(e){return "object"==typeof e&&null!==e&&true===e[I]}class P{static always=e=>true}const C=Symbol.for("@inversifyjs/container/InversifyContainerError");class B extends Error{[C];kind;constructor(e,n,i){super(n,i),this[C]=true,this.kind=e;}static is(e){return "object"==typeof e&&null!==e&&true===e[C]}static isErrorOfKind(e,n){return B.is(e)&&e.kind===n}}var O;function x$2(e){return {[I]:true,id:e.id}}function k(e){return n=>{for(let i=n.getAncestor();void 0!==i;i=i.getAncestor())if(e(i))return  true;return  false}}function N(e){return n=>n.name===e}function F(e){return n=>n.serviceIdentifier===e}function U(e,n){return i=>i.tags.has(e)&&i.tags.get(e)===n}function D(e){return void 0===e.name&&0===e.tags.size}function j$1(e){const n=k(e);return e=>!n(e)}function T$1(e){return n=>{const i=n.getAncestor();return void 0===i||!e(i)}}function V(e){return n=>{const i=n.getAncestor();return void 0!==i&&e(i)}}!function(e){e[e.invalidOperation=0]="invalidOperation";}(O||(O={}));class E{#i;constructor(e){this.#i=e;}getIdentifier(){return x$2(this.#i)}inRequestScope(){return this.#i.scope=d.Request,new G(this.#i)}inSingletonScope(){return this.#i.scope=d.Singleton,new G(this.#i)}inTransientScope(){return this.#i.scope=d.Transient,new G(this.#i)}}let L$1 = class L{#t;#r;#a;#s;constructor(e,n,i,t){this.#t=e,this.#r=n,this.#a=i,this.#s=t;}to(e){const n=N$1(e),i={cache:{isRight:false,value:void 0},id:c$1(),implementationType:e,isSatisfiedBy:P.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:n.scope??this.#a,serviceIdentifier:this.#s,type:u.Instance};return this.#t(i),new H(i)}toSelf(){if("function"!=typeof this.#s)throw new Error('"toSelf" function can only be applied when a newable function is used as service identifier');return this.to(this.#s)}toConstantValue(e){const n={cache:{isRight:false,value:void 0},id:c$1(),isSatisfiedBy:P.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:d.Singleton,serviceIdentifier:this.#s,type:u.ConstantValue,value:e};return this.#t(n),new G(n)}toDynamicValue(e){const n={cache:{isRight:false,value:void 0},id:c$1(),isSatisfiedBy:P.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:this.#a,serviceIdentifier:this.#s,type:u.DynamicValue,value:e};return this.#t(n),new H(n)}toResolvedValue(e,n){const i={cache:{isRight:false,value:void 0},factory:e,id:c$1(),isSatisfiedBy:P.always,metadata:this.#o(n),moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:this.#a,serviceIdentifier:this.#s,type:u.ResolvedValue};return this.#t(i),new H(i)}toFactory(e){const n={cache:{isRight:false,value:void 0},factory:e,id:c$1(),isSatisfiedBy:P.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,scope:d.Singleton,serviceIdentifier:this.#s,type:u.Factory};return this.#t(n),new G(n)}toProvider(e){const n={cache:{isRight:false,value:void 0},id:c$1(),isSatisfiedBy:P.always,moduleId:this.#r,onActivation:void 0,onDeactivation:void 0,provider:e,scope:d.Singleton,serviceIdentifier:this.#s,type:u.Provider};return this.#t(n),new G(n)}toService(e){const n={id:c$1(),isSatisfiedBy:P.always,moduleId:this.#r,serviceIdentifier:this.#s,targetServiceIdentifier:e,type:u.ServiceRedirection};this.#t(n);}#o(e){return {arguments:(e??[]).map(e=>function(e){return "object"==typeof e&&!r.is(e)}(e)?function(e){return  true===e.isMultiple}(e)?{chained:e.chained??false,kind:fe.multipleInjection,name:e.name,optional:e.optional??false,tags:new Map((e.tags??[]).map(e=>[e.key,e.value])),value:e.serviceIdentifier}:{kind:fe.singleInjection,name:e.name,optional:e.optional??false,tags:new Map((e.tags??[]).map(e=>[e.key,e.value])),value:e.serviceIdentifier}:{kind:fe.singleInjection,name:void 0,optional:false,tags:new Map,value:e})}}};class ${#i;constructor(e){this.#i=e;}getIdentifier(){return x$2(this.#i)}onActivation(e){return this.#i.onActivation=e,new q(this.#i)}onDeactivation(e){if(this.#i.onDeactivation=e,this.#i.scope!==d.Singleton)throw new B(O.invalidOperation,`Binding for service "${t$1(this.#i.serviceIdentifier)}" has a deactivation function, but its scope is not singleton. Deactivation functions can only be used with singleton bindings.`);return new q(this.#i)}}class q{#i;constructor(e){this.#i=e;}getIdentifier(){return x$2(this.#i)}when(e){return this.#i.isSatisfiedBy=e,new $(this.#i)}whenAnyAncestor(e){return this.when(k(e))}whenAnyAncestorIs(e){return this.when(k(F(e)))}whenAnyAncestorNamed(e){return this.when(function(e){return k(N(e))}(e))}whenAnyAncestorTagged(e,n){return this.when(function(e,n){return k(U(e,n))}(e,n))}whenDefault(){return this.when(D)}whenNamed(e){return this.when(N(e))}whenNoParent(e){return this.when(T$1(e))}whenNoParentIs(e){return this.when(T$1(F(e)))}whenNoParentNamed(e){return this.when(function(e){return T$1(N(e))}(e))}whenNoParentTagged(e,n){return this.when(function(e,n){return T$1(U(e,n))}(e,n))}whenParent(e){return this.when(V(e))}whenParentIs(e){return this.when(V(F(e)))}whenParentNamed(e){return this.when(function(e){return V(N(e))}(e))}whenParentTagged(e,n){return this.when(function(e,n){return V(U(e,n))}(e,n))}whenTagged(e,n){return this.when(U(e,n))}whenNoAncestor(e){return this.when(j$1(e))}whenNoAncestorIs(e){return this.when(j$1(F(e)))}whenNoAncestorNamed(e){return this.when(function(e){return j$1(N(e))}(e))}whenNoAncestorTagged(e,n){return this.when(function(e,n){return j$1(U(e,n))}(e,n))}}class G extends q{#c;constructor(e){super(e),this.#c=new $(e);}onActivation(e){return this.#c.onActivation(e)}onDeactivation(e){return this.#c.onDeactivation(e)}}class H extends G{#d;constructor(e){super(e),this.#d=new E(e);}inRequestScope(){return this.#d.inRequestScope()}inSingletonScope(){return this.#d.inSingletonScope()}inTransientScope(){return this.#d.inTransientScope()}}class _{#l;#a;#u;#h;constructor(e,n,i,t){this.#l=e,this.#a=n,this.#u=i,this.#h=t;}bind(e){return new L$1(e=>{this.#v(e);},void 0,this.#a,e)}isBound(e,n){const i=this.#h.bindingService.get(e);return this.#g(e,i,n)}isCurrentBound(e,n){const i=this.#h.bindingService.getNonParentBindings(e);return this.#g(e,i,n)}async rebind(e){return await this.unbind(e),this.bind(e)}rebindSync(e){return this.unbindSync(e),this.bind(e)}async unbind(e){await this.#f(e);}async unbindAll(){const e=[...this.#h.bindingService.getNonParentBoundServices()];await Promise.all(e.map(async e=>Dt(this.#l,e)));for(const n of e)this.#h.activationService.removeAllByServiceId(n),this.#h.bindingService.removeAllByServiceId(n),this.#h.deactivationService.removeAllByServiceId(n);this.#h.planResultCacheService.clearCache();}unbindSync(e){ void 0!==this.#f(e)&&this.#b(e);}#v(e){this.#h.bindingService.set(e),this.#u.invalidateService({binding:e,kind:qe.bindingAdded});}#b(e){let n;if(A$1(e)){const t=this.#h.bindingService.getById(e.id),r=(i=t,function(e){if(void 0===e)return;const n=e.next();return  true!==n.done?n.value:void 0}(i?.[Symbol.iterator]()))?.serviceIdentifier;n=void 0===r?"Unexpected asynchronous deactivation when unbinding binding identifier. Consider using Container.unbind() instead.":`Unexpected asynchronous deactivation when unbinding "${t$1(r)}" binding. Consider using Container.unbind() instead.`;}else n=`Unexpected asynchronous deactivation when unbinding "${t$1(e)}" service. Consider using Container.unbind() instead.`;var i;throw new B(O.invalidOperation,n)}#f(e){return A$1(e)?this.#p(e):this.#S(e)}#p(e){const n=this.#h.bindingService.getById(e.id),i=void 0===n?void 0:[...n],t=kt(this.#l,n);if(void 0!==t)return t.then(()=>{this.#M(i,e);});this.#M(i,e);}#M(e,n){if(this.#h.bindingService.removeById(n.id),void 0!==e)for(const n of e)this.#u.invalidateService({binding:n,kind:qe.bindingRemoved});}#S(e){const n=this.#h.bindingService.get(e),i=void 0===n?void 0:[...n],t=kt(this.#l,n);if(void 0!==t)return t.then(()=>{this.#R(e,i);});this.#R(e,i);}#R(e,n){if(this.#h.activationService.removeAllByServiceId(e),this.#h.bindingService.removeAllByServiceId(e),this.#h.deactivationService.removeAllByServiceId(e),void 0!==n)for(const e of n)this.#u.invalidateService({binding:e,kind:qe.bindingRemoved});}#g(e,n,i){if(void 0===n)return  false;const t={getAncestor:()=>{},name:i?.name,serviceIdentifier:e,tags:new Map};void 0!==i?.tag&&t.tags.set(i.tag.key,i.tag.value);for(const e of n)if(e.isSatisfiedBy(t))return  true;return  false}}class z{#y;#l;#a;#u;#h;constructor(e,n,i,t,r){this.#y=e,this.#l=n,this.#a=i,this.#u=t,this.#h=r;}async load(...e){await Promise.all(this.#n(...e));}loadSync(...e){const n=this.#n(...e);for(const e of n)if(void 0!==e)throw new B(O.invalidOperation,"Unexpected asynchronous module load. Consider using Container.load() instead.")}async unload(...e){await Promise.all(this.#m(...e)),this.#w(e);}unloadSync(...e){const n=this.#m(...e);for(const e of n)if(void 0!==e)throw new B(O.invalidOperation,"Unexpected asynchronous module unload. Consider using Container.unload() instead.");this.#w(e);}#I(e){return {bind:n=>new L$1(e=>{this.#v(e);},e,this.#a,n),isBound:this.#y.isBound.bind(this.#y),onActivation:(n,i)=>{this.#h.activationService.add(i,{moduleId:e,serviceId:n});},onDeactivation:(n,i)=>{this.#h.deactivationService.add(i,{moduleId:e,serviceId:n});},rebind:this.#y.rebind.bind(this.#y),rebindSync:this.#y.rebindSync.bind(this.#y),unbind:this.#y.unbind.bind(this.#y),unbindSync:this.#y.unbindSync.bind(this.#y)}}#w(e){for(const n of e)this.#h.activationService.removeAllByModuleId(n.id),this.#h.bindingService.removeAllByModuleId(n.id),this.#h.deactivationService.removeAllByModuleId(n.id);this.#h.planResultCacheService.clearCache();}#n(...e){return e.map(e=>e.load(this.#I(e.id)))}#v(e){this.#h.bindingService.set(e),this.#u.invalidateService({binding:e,kind:qe.bindingAdded});}#m(...e){return e.map(e=>$t(this.#l,e.id))}}class K{deactivationParams;constructor(e){this.deactivationParams=function(e){return {getBindings:e.bindingService.get.bind(e.bindingService),getBindingsFromModule:e.bindingService.getByModuleId.bind(e.bindingService),getClassMetadata:N$1,getDeactivations:e.deactivationService.get.bind(e.deactivationService)}}(e),e.onReset(()=>{!function(e,n){n.getBindings=e.bindingService.get.bind(e.bindingService),n.getBindingsFromModule=e.bindingService.getByModuleId.bind(e.bindingService),n.getDeactivations=e.deactivationService.get.bind(e.deactivationService);}(e,this.deactivationParams);});}}let X$1 = class X{planParamsOperations;#h;constructor(e){this.#h=e,this.planParamsOperations={getBindings:this.#h.bindingService.get.bind(this.#h.bindingService),getBindingsChained:this.#h.bindingService.getChained.bind(this.#h.bindingService),getClassMetadata:N$1,getPlan:this.#h.planResultCacheService.get.bind(this.#h.planResultCacheService),setBinding:this.#v.bind(this),setNonCachedServiceNode:this.#h.planResultCacheService.setNonCachedServiceNode.bind(this.#h.planResultCacheService),setPlan:this.#h.planResultCacheService.set.bind(this.#h.planResultCacheService)},this.#h.onReset(()=>{this.#A();});}#A(){this.planParamsOperations.getBindings=this.#h.bindingService.get.bind(this.#h.bindingService),this.planParamsOperations.getBindingsChained=this.#h.bindingService.getChained.bind(this.#h.bindingService),this.planParamsOperations.setBinding=this.#v.bind(this);}#v(e){this.#h.bindingService.set(e),this.#h.planResultCacheService.invalidateServiceBinding({binding:e,kind:qe.bindingAdded,operations:this.planParamsOperations});}};class J{#P;#h;constructor(e,n){this.#P=e,this.#h=n;}invalidateService(e){this.#h.planResultCacheService.invalidateServiceBinding({...e,operations:this.#P.planParamsOperations});}}class Q{#C;#B;#O;#h;constructor(e,n,i){this.#h=n,this.#O=i,this.#C=this.#x(e),this.#B=this.#k();}register(e,n){const i=new n(e,this.#B);if(true!==i[t])throw new B(O.invalidOperation,"Invalid plugin. The plugin must extend the Plugin class");i.load(this.#C);}#x(e){return {define:(n,i)=>{if(Object.prototype.hasOwnProperty.call(e,n))throw new B(O.invalidOperation,`Container already has a method named "${String(n)}"`);e[n]=i;},onPlan:this.#O.onPlan.bind(this.#O)}}#k(){const e=this.#h;return {get activationService(){return e.activationService},get bindingService(){return e.bindingService},get deactivationService(){return e.deactivationService},get planResultCacheService(){return e.planResultCacheService}}}}let W$1 = class W{activationService;bindingService;deactivationService;planResultCacheService;#N;constructor(e,n,i,t){this.activationService=e,this.bindingService=n,this.deactivationService=i,this.planResultCacheService=t,this.#N=[];}reset(e,n,i){this.activationService=e,this.bindingService=n,this.deactivationService=i,this.planResultCacheService.clearCache();for(const e of this.#N)e();}onReset(e){this.#N.push(e);}};class Y{#F;#a;#U;#D;#j;#P;#h;constructor(e,n,i,t){this.#P=e,this.#h=n,this.#D=this.#T(),this.#F=i,this.#a=t,this.#U=e=>this.#h.activationService.get(e),this.#j=[],this.#h.onReset(()=>{this.#A();});}get(e$1,n){const i=this.#V(false,e$1,n),t=this.#E(i);if(e(t))throw new B(O.invalidOperation,`Unexpected asynchronous service when resolving service "${t$1(e$1)}"`);return t}getAll(e$1,n){const i=this.#V(true,e$1,n),t=this.#E(i);if(e(t))throw new B(O.invalidOperation,`Unexpected asynchronous service when resolving service "${t$1(e$1)}"`);return t}async getAllAsync(e,n){const i=this.#V(true,e,n);return this.#E(i)}async getAsync(e,n){const i=this.#V(false,e,n);return this.#E(i)}onPlan(e){this.#j.push(e);}#A(){this.#D=this.#T();}#L(e,n,i){const t=i?.name,r=i?.optional??false,a=i?.tag;return e?{chained:i?.chained??false,isMultiple:e,name:t,optional:r,serviceIdentifier:n,tag:a}:{isMultiple:e,name:t,optional:r,serviceIdentifier:n,tag:a}}#$(e,n,i){const t={autobindOptions:i?.autobind??this.#F?{scope:this.#a}:void 0,operations:this.#P.planParamsOperations,rootConstraints:this.#q(e,n,i),servicesBranch:[]};return this.#G(t,i),t}#q(e,n,i){return n?{chained:i?.chained??false,isMultiple:n,serviceIdentifier:e}:{isMultiple:n,serviceIdentifier:e}}#V(e,n,i){const t=this.#L(e,n,i),r=this.#h.planResultCacheService.get(t);if(void 0!==r)return r;const a=Ke(this.#$(n,e,i));for(const e of this.#j)e(t,a);return a}#T(){return {get:this.get.bind(this),getAll:this.getAll.bind(this),getAllAsync:this.getAllAsync.bind(this),getAsync:this.getAsync.bind(this)}}#E(e){return Ct({context:this.#D,getActivations:this.#U,planResult:e,requestScopeCache:new Map})}#G(e,n){ void 0!==n&&(void 0!==n.name&&(e.rootConstraints.name=n.name),true===n.optional&&(e.rootConstraints.isOptional=true),void 0!==n.tag&&(e.rootConstraints.tag={key:n.tag.key,value:n.tag.value}),e.rootConstraints.isMultiple&&(e.rootConstraints.chained=n?.chained??false));}}let Z$1 = class Z{#h;#H;constructor(e){this.#h=e,this.#H=[];}restore(){const e=this.#H.pop();if(void 0===e)throw new B(O.invalidOperation,"No snapshot available to restore");this.#h.reset(e.activationService,e.bindingService,e.deactivationService);}snapshot(){this.#H.push({activationService:this.#h.activationService.clone(),bindingService:this.#h.bindingService.clone(),deactivationService:this.#h.deactivationService.clone()});}};const ee$1=d.Transient;class ne{#y;#_;#z;#h;#O;#K;constructor(e){const n=e?.autobind??false,i=e?.defaultScope??ee$1;this.#h=this.#X(e,n,i);const t=new X$1(this.#h),r=new J(t,this.#h),a=new K(this.#h);this.#y=new _(a.deactivationParams,i,r,this.#h),this.#_=new z(this.#y,a.deactivationParams,i,r,this.#h),this.#O=new Y(t,this.#h,n,i),this.#z=new Q(this,this.#h,this.#O),this.#K=new Z$1(this.#h);}bind(e){return this.#y.bind(e)}get(e,n){return this.#O.get(e,n)}getAll(e,n){return this.#O.getAll(e,n)}async getAllAsync(e,n){return this.#O.getAllAsync(e,n)}async getAsync(e,n){return this.#O.getAsync(e,n)}isBound(e,n){return this.#y.isBound(e,n)}isCurrentBound(e,n){return this.#y.isCurrentBound(e,n)}async load(...e){return this.#_.load(...e)}loadSync(...e){this.#_.loadSync(...e);}onActivation(e,n){this.#h.activationService.add(n,{serviceId:e});}onDeactivation(e,n){this.#h.deactivationService.add(n,{serviceId:e});}register(e){this.#z.register(this,e);}restore(){this.#K.restore();}async rebind(e){return this.#y.rebind(e)}rebindSync(e){return this.#y.rebindSync(e)}snapshot(){this.#K.snapshot();}async unbind(e){await this.#y.unbind(e);}async unbindAll(){return this.#y.unbindAll()}unbindSync(e){this.#y.unbindSync(e);}async unload(...e){return this.#_.unload(...e)}unloadSync(...e){this.#_.unloadSync(...e);}#J(e,n){if(e)return {scope:n}}#X(e,n,i){const t=this.#J(n,i);if(void 0===e?.parent)return new W$1(v.build(()=>{}),T$2.build(()=>{},t),j$2.build(()=>{}),new Ye);const r=new Ye,a=e.parent;return a.#h.planResultCacheService.subscribe(r),new W$1(v.build(()=>a.#h.activationService),T$2.build(()=>a.#h.bindingService,t),j$2.build(()=>a.#h.deactivationService),r)}}

var NTSex = /* @__PURE__ */ ((NTSex2) => {
  NTSex2[NTSex2["GENDER_UNKOWN"] = 0] = "GENDER_UNKOWN";
  NTSex2[NTSex2["GENDER_MALE"] = 1] = "GENDER_MALE";
  NTSex2[NTSex2["GENDER_FEMALE"] = 2] = "GENDER_FEMALE";
  NTSex2[NTSex2["GENDER_PRIVACY"] = 255] = "GENDER_PRIVACY";
  return NTSex2;
})(NTSex || {});
var BuddyListReqType = /* @__PURE__ */ ((BuddyListReqType2) => {
  BuddyListReqType2[BuddyListReqType2["KNOMAL"] = 0] = "KNOMAL";
  BuddyListReqType2[BuddyListReqType2["KLETTER"] = 1] = "KLETTER";
  return BuddyListReqType2;
})(BuddyListReqType || {});
var UserDetailSource = /* @__PURE__ */ ((UserDetailSource2) => {
  UserDetailSource2[UserDetailSource2["KDB"] = 0] = "KDB";
  UserDetailSource2[UserDetailSource2["KSERVER"] = 1] = "KSERVER";
  return UserDetailSource2;
})(UserDetailSource || {});
var ProfileBizType = /* @__PURE__ */ ((ProfileBizType2) => {
  ProfileBizType2[ProfileBizType2["KALL"] = 0] = "KALL";
  ProfileBizType2[ProfileBizType2["KBASEEXTEND"] = 1] = "KBASEEXTEND";
  ProfileBizType2[ProfileBizType2["KVAS"] = 2] = "KVAS";
  ProfileBizType2[ProfileBizType2["KQZONE"] = 3] = "KQZONE";
  ProfileBizType2[ProfileBizType2["KOTHER"] = 4] = "KOTHER";
  return ProfileBizType2;
})(ProfileBizType || {});

var GroupInfoSource = /* @__PURE__ */ ((GroupInfoSource2) => {
  GroupInfoSource2[GroupInfoSource2["KUNSPECIFIED"] = 0] = "KUNSPECIFIED";
  GroupInfoSource2[GroupInfoSource2["KBIGDATACARD"] = 1] = "KBIGDATACARD";
  GroupInfoSource2[GroupInfoSource2["KDATACARD"] = 2] = "KDATACARD";
  GroupInfoSource2[GroupInfoSource2["KNOTICE"] = 3] = "KNOTICE";
  GroupInfoSource2[GroupInfoSource2["KAIO"] = 4] = "KAIO";
  GroupInfoSource2[GroupInfoSource2["KRECENTCONTACT"] = 5] = "KRECENTCONTACT";
  GroupInfoSource2[GroupInfoSource2["KMOREPANEL"] = 6] = "KMOREPANEL";
  return GroupInfoSource2;
})(GroupInfoSource || {});
var NTGroupMemberRole = /* @__PURE__ */ ((NTGroupMemberRole2) => {
  NTGroupMemberRole2[NTGroupMemberRole2["KUNSPECIFIED"] = 0] = "KUNSPECIFIED";
  NTGroupMemberRole2[NTGroupMemberRole2["KSTRANGER"] = 1] = "KSTRANGER";
  NTGroupMemberRole2[NTGroupMemberRole2["KMEMBER"] = 2] = "KMEMBER";
  NTGroupMemberRole2[NTGroupMemberRole2["KADMIN"] = 3] = "KADMIN";
  NTGroupMemberRole2[NTGroupMemberRole2["KOWNER"] = 4] = "KOWNER";
  return NTGroupMemberRole2;
})(NTGroupMemberRole || {});

var ElementType = /* @__PURE__ */ ((ElementType2) => {
  ElementType2[ElementType2["UNKNOWN"] = 0] = "UNKNOWN";
  ElementType2[ElementType2["TEXT"] = 1] = "TEXT";
  ElementType2[ElementType2["PIC"] = 2] = "PIC";
  ElementType2[ElementType2["FILE"] = 3] = "FILE";
  ElementType2[ElementType2["PTT"] = 4] = "PTT";
  ElementType2[ElementType2["VIDEO"] = 5] = "VIDEO";
  ElementType2[ElementType2["FACE"] = 6] = "FACE";
  ElementType2[ElementType2["REPLY"] = 7] = "REPLY";
  ElementType2[ElementType2["GreyTip"] = 8] = "GreyTip";
  ElementType2[ElementType2["WALLET"] = 9] = "WALLET";
  ElementType2[ElementType2["ARK"] = 10] = "ARK";
  ElementType2[ElementType2["MFACE"] = 11] = "MFACE";
  ElementType2[ElementType2["LIVEGIFT"] = 12] = "LIVEGIFT";
  ElementType2[ElementType2["STRUCTLONGMSG"] = 13] = "STRUCTLONGMSG";
  ElementType2[ElementType2["MARKDOWN"] = 14] = "MARKDOWN";
  ElementType2[ElementType2["GIPHY"] = 15] = "GIPHY";
  ElementType2[ElementType2["MULTIFORWARD"] = 16] = "MULTIFORWARD";
  ElementType2[ElementType2["INLINEKEYBOARD"] = 17] = "INLINEKEYBOARD";
  ElementType2[ElementType2["INTEXTGIFT"] = 18] = "INTEXTGIFT";
  ElementType2[ElementType2["CALENDAR"] = 19] = "CALENDAR";
  ElementType2[ElementType2["YOLOGAMERESULT"] = 20] = "YOLOGAMERESULT";
  ElementType2[ElementType2["AVRECORD"] = 21] = "AVRECORD";
  ElementType2[ElementType2["FEED"] = 22] = "FEED";
  ElementType2[ElementType2["TOFURECORD"] = 23] = "TOFURECORD";
  ElementType2[ElementType2["ACEBUBBLE"] = 24] = "ACEBUBBLE";
  ElementType2[ElementType2["ACTIVITY"] = 25] = "ACTIVITY";
  ElementType2[ElementType2["TOFU"] = 26] = "TOFU";
  ElementType2[ElementType2["FACEBUBBLE"] = 27] = "FACEBUBBLE";
  ElementType2[ElementType2["SHARELOCATION"] = 28] = "SHARELOCATION";
  ElementType2[ElementType2["TASKTOPMSG"] = 29] = "TASKTOPMSG";
  ElementType2[ElementType2["RECOMMENDEDMSG"] = 43] = "RECOMMENDEDMSG";
  ElementType2[ElementType2["ACTIONBAR"] = 44] = "ACTIONBAR";
  return ElementType2;
})(ElementType || {});
var NTMsgType = /* @__PURE__ */ ((NTMsgType2) => {
  NTMsgType2[NTMsgType2["KMSGTYPEARKSTRUCT"] = 11] = "KMSGTYPEARKSTRUCT";
  NTMsgType2[NTMsgType2["KMSGTYPEFACEBUBBLE"] = 24] = "KMSGTYPEFACEBUBBLE";
  NTMsgType2[NTMsgType2["KMSGTYPEFILE"] = 3] = "KMSGTYPEFILE";
  NTMsgType2[NTMsgType2["KMSGTYPEGIFT"] = 14] = "KMSGTYPEGIFT";
  NTMsgType2[NTMsgType2["KMSGTYPEGIPHY"] = 13] = "KMSGTYPEGIPHY";
  NTMsgType2[NTMsgType2["KMSGTYPEGRAYTIPS"] = 5] = "KMSGTYPEGRAYTIPS";
  NTMsgType2[NTMsgType2["KMSGTYPEMIX"] = 2] = "KMSGTYPEMIX";
  NTMsgType2[NTMsgType2["KMSGTYPEMULTIMSGFORWARD"] = 8] = "KMSGTYPEMULTIMSGFORWARD";
  NTMsgType2[NTMsgType2["KMSGTYPENULL"] = 1] = "KMSGTYPENULL";
  NTMsgType2[NTMsgType2["KMSGTYPEONLINEFILE"] = 21] = "KMSGTYPEONLINEFILE";
  NTMsgType2[NTMsgType2["KMSGTYPEONLINEFOLDER"] = 27] = "KMSGTYPEONLINEFOLDER";
  NTMsgType2[NTMsgType2["KMSGTYPEPROLOGUE"] = 29] = "KMSGTYPEPROLOGUE";
  NTMsgType2[NTMsgType2["KMSGTYPEPTT"] = 6] = "KMSGTYPEPTT";
  NTMsgType2[NTMsgType2["KMSGTYPEREPLY"] = 9] = "KMSGTYPEREPLY";
  NTMsgType2[NTMsgType2["KMSGTYPESHARELOCATION"] = 25] = "KMSGTYPESHARELOCATION";
  NTMsgType2[NTMsgType2["KMSGTYPESTRUCT"] = 4] = "KMSGTYPESTRUCT";
  NTMsgType2[NTMsgType2["KMSGTYPESTRUCTLONGMSG"] = 12] = "KMSGTYPESTRUCTLONGMSG";
  NTMsgType2[NTMsgType2["KMSGTYPETEXTGIFT"] = 15] = "KMSGTYPETEXTGIFT";
  NTMsgType2[NTMsgType2["KMSGTYPEUNKNOWN"] = 0] = "KMSGTYPEUNKNOWN";
  NTMsgType2[NTMsgType2["KMSGTYPEVIDEO"] = 7] = "KMSGTYPEVIDEO";
  NTMsgType2[NTMsgType2["KMSGTYPEWALLET"] = 10] = "KMSGTYPEWALLET";
  return NTMsgType2;
})(NTMsgType || {});
var PicType = /* @__PURE__ */ ((PicType2) => {
  PicType2[PicType2["NEWPIC_APNG"] = 2001] = "NEWPIC_APNG";
  PicType2[PicType2["NEWPIC_BMP"] = 1005] = "NEWPIC_BMP";
  PicType2[PicType2["NEWPIC_GIF"] = 2e3] = "NEWPIC_GIF";
  PicType2[PicType2["NEWPIC_JPEG"] = 1e3] = "NEWPIC_JPEG";
  PicType2[PicType2["NEWPIC_PNG"] = 1001] = "NEWPIC_PNG";
  PicType2[PicType2["NEWPIC_PROGERSSIV_JPEG"] = 1003] = "NEWPIC_PROGERSSIV_JPEG";
  PicType2[PicType2["NEWPIC_SHARPP"] = 1004] = "NEWPIC_SHARPP";
  PicType2[PicType2["NEWPIC_WEBP"] = 1002] = "NEWPIC_WEBP";
  return PicType2;
})(PicType || {});
var NTMsgAtType = /* @__PURE__ */ ((NTMsgAtType2) => {
  NTMsgAtType2[NTMsgAtType2["ATTYPEALL"] = 1] = "ATTYPEALL";
  NTMsgAtType2[NTMsgAtType2["ATTYPECATEGORY"] = 512] = "ATTYPECATEGORY";
  NTMsgAtType2[NTMsgAtType2["ATTYPECHANNEL"] = 16] = "ATTYPECHANNEL";
  NTMsgAtType2[NTMsgAtType2["ATTYPEME"] = 4] = "ATTYPEME";
  NTMsgAtType2[NTMsgAtType2["ATTYPEONE"] = 2] = "ATTYPEONE";
  NTMsgAtType2[NTMsgAtType2["ATTYPEONLINE"] = 64] = "ATTYPEONLINE";
  NTMsgAtType2[NTMsgAtType2["ATTYPEROLE"] = 8] = "ATTYPEROLE";
  NTMsgAtType2[NTMsgAtType2["ATTYPESUMMON"] = 32] = "ATTYPESUMMON";
  NTMsgAtType2[NTMsgAtType2["ATTYPESUMMONONLINE"] = 128] = "ATTYPESUMMONONLINE";
  NTMsgAtType2[NTMsgAtType2["ATTYPESUMMONROLE"] = 256] = "ATTYPESUMMONROLE";
  NTMsgAtType2[NTMsgAtType2["ATTYPEUNKNOWN"] = 0] = "ATTYPEUNKNOWN";
  return NTMsgAtType2;
})(NTMsgAtType || {});
var MsgSourceType = /* @__PURE__ */ ((MsgSourceType2) => {
  MsgSourceType2[MsgSourceType2["K_DOWN_SOURCETYPE_AIOINNER"] = 1] = "K_DOWN_SOURCETYPE_AIOINNER";
  MsgSourceType2[MsgSourceType2["K_DOWN_SOURCETYPE_BIGSCREEN"] = 2] = "K_DOWN_SOURCETYPE_BIGSCREEN";
  MsgSourceType2[MsgSourceType2["K_DOWN_SOURCETYPE_HISTORY"] = 3] = "K_DOWN_SOURCETYPE_HISTORY";
  MsgSourceType2[MsgSourceType2["K_DOWN_SOURCETYPE_UNKNOWN"] = 0] = "K_DOWN_SOURCETYPE_UNKNOWN";
  return MsgSourceType2;
})(MsgSourceType || {});
var ChatType = /* @__PURE__ */ ((ChatType2) => {
  ChatType2[ChatType2["KCHATTYPEADELIE"] = 42] = "KCHATTYPEADELIE";
  ChatType2[ChatType2["KCHATTYPEBUDDYNOTIFY"] = 5] = "KCHATTYPEBUDDYNOTIFY";
  ChatType2[ChatType2["KCHATTYPEC2C"] = 1] = "KCHATTYPEC2C";
  ChatType2[ChatType2["KCHATTYPECIRCLE"] = 113] = "KCHATTYPECIRCLE";
  ChatType2[ChatType2["KCHATTYPEDATALINE"] = 8] = "KCHATTYPEDATALINE";
  ChatType2[ChatType2["KCHATTYPEDATALINEMQQ"] = 134] = "KCHATTYPEDATALINEMQQ";
  ChatType2[ChatType2["KCHATTYPEDISC"] = 3] = "KCHATTYPEDISC";
  ChatType2[ChatType2["KCHATTYPEFAV"] = 41] = "KCHATTYPEFAV";
  ChatType2[ChatType2["KCHATTYPEGAMEMESSAGE"] = 105] = "KCHATTYPEGAMEMESSAGE";
  ChatType2[ChatType2["KCHATTYPEGAMEMESSAGEFOLDER"] = 116] = "KCHATTYPEGAMEMESSAGEFOLDER";
  ChatType2[ChatType2["KCHATTYPEGROUP"] = 2] = "KCHATTYPEGROUP";
  ChatType2[ChatType2["KCHATTYPEGROUPBLESS"] = 133] = "KCHATTYPEGROUPBLESS";
  ChatType2[ChatType2["KCHATTYPEGROUPGUILD"] = 9] = "KCHATTYPEGROUPGUILD";
  ChatType2[ChatType2["KCHATTYPEGROUPHELPER"] = 7] = "KCHATTYPEGROUPHELPER";
  ChatType2[ChatType2["KCHATTYPEGROUPNOTIFY"] = 6] = "KCHATTYPEGROUPNOTIFY";
  ChatType2[ChatType2["KCHATTYPEGUILD"] = 4] = "KCHATTYPEGUILD";
  ChatType2[ChatType2["KCHATTYPEGUILDMETA"] = 16] = "KCHATTYPEGUILDMETA";
  ChatType2[ChatType2["KCHATTYPEMATCHFRIEND"] = 104] = "KCHATTYPEMATCHFRIEND";
  ChatType2[ChatType2["KCHATTYPEMATCHFRIENDFOLDER"] = 109] = "KCHATTYPEMATCHFRIENDFOLDER";
  ChatType2[ChatType2["KCHATTYPENEARBY"] = 106] = "KCHATTYPENEARBY";
  ChatType2[ChatType2["KCHATTYPENEARBYASSISTANT"] = 107] = "KCHATTYPENEARBYASSISTANT";
  ChatType2[ChatType2["KCHATTYPENEARBYFOLDER"] = 110] = "KCHATTYPENEARBYFOLDER";
  ChatType2[ChatType2["KCHATTYPENEARBYHELLOFOLDER"] = 112] = "KCHATTYPENEARBYHELLOFOLDER";
  ChatType2[ChatType2["KCHATTYPENEARBYINTERACT"] = 108] = "KCHATTYPENEARBYINTERACT";
  ChatType2[ChatType2["KCHATTYPEQQNOTIFY"] = 132] = "KCHATTYPEQQNOTIFY";
  ChatType2[ChatType2["KCHATTYPERELATEACCOUNT"] = 131] = "KCHATTYPERELATEACCOUNT";
  ChatType2[ChatType2["KCHATTYPESERVICEASSISTANT"] = 118] = "KCHATTYPESERVICEASSISTANT";
  ChatType2[ChatType2["KCHATTYPESERVICEASSISTANTSUB"] = 201] = "KCHATTYPESERVICEASSISTANTSUB";
  ChatType2[ChatType2["KCHATTYPESQUAREPUBLIC"] = 115] = "KCHATTYPESQUAREPUBLIC";
  ChatType2[ChatType2["KCHATTYPESUBSCRIBEFOLDER"] = 30] = "KCHATTYPESUBSCRIBEFOLDER";
  ChatType2[ChatType2["KCHATTYPETEMPADDRESSBOOK"] = 111] = "KCHATTYPETEMPADDRESSBOOK";
  ChatType2[ChatType2["KCHATTYPETEMPBUSSINESSCRM"] = 102] = "KCHATTYPETEMPBUSSINESSCRM";
  ChatType2[ChatType2["KCHATTYPETEMPC2CFROMGROUP"] = 100] = "KCHATTYPETEMPC2CFROMGROUP";
  ChatType2[ChatType2["KCHATTYPETEMPC2CFROMUNKNOWN"] = 99] = "KCHATTYPETEMPC2CFROMUNKNOWN";
  ChatType2[ChatType2["KCHATTYPETEMPFRIENDVERIFY"] = 101] = "KCHATTYPETEMPFRIENDVERIFY";
  ChatType2[ChatType2["KCHATTYPETEMPNEARBYPRO"] = 119] = "KCHATTYPETEMPNEARBYPRO";
  ChatType2[ChatType2["KCHATTYPETEMPPUBLICACCOUNT"] = 103] = "KCHATTYPETEMPPUBLICACCOUNT";
  ChatType2[ChatType2["KCHATTYPETEMPWPA"] = 117] = "KCHATTYPETEMPWPA";
  ChatType2[ChatType2["KCHATTYPEUNKNOWN"] = 0] = "KCHATTYPEUNKNOWN";
  ChatType2[ChatType2["KCHATTYPEWEIYUN"] = 40] = "KCHATTYPEWEIYUN";
  return ChatType2;
})(ChatType || {});
var NTGrayTipElementSubTypeV2 = /* @__PURE__ */ ((NTGrayTipElementSubTypeV22) => {
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_AIOOP"] = 15] = "GRAYTIP_ELEMENT_SUBTYPE_AIOOP";
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_BLOCK"] = 14] = "GRAYTIP_ELEMENT_SUBTYPE_BLOCK";
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_BUDDY"] = 5] = "GRAYTIP_ELEMENT_SUBTYPE_BUDDY";
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_BUDDYNOTIFY"] = 9] = "GRAYTIP_ELEMENT_SUBTYPE_BUDDYNOTIFY";
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_EMOJIREPLY"] = 3] = "GRAYTIP_ELEMENT_SUBTYPE_EMOJIREPLY";
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_ESSENCE"] = 7] = "GRAYTIP_ELEMENT_SUBTYPE_ESSENCE";
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_FEED"] = 6] = "GRAYTIP_ELEMENT_SUBTYPE_FEED";
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_FEEDCHANNELMSG"] = 11] = "GRAYTIP_ELEMENT_SUBTYPE_FEEDCHANNELMSG";
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_FILE"] = 10] = "GRAYTIP_ELEMENT_SUBTYPE_FILE";
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_GROUP"] = 4] = "GRAYTIP_ELEMENT_SUBTYPE_GROUP";
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_GROUPNOTIFY"] = 8] = "GRAYTIP_ELEMENT_SUBTYPE_GROUPNOTIFY";
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_JSON"] = 17] = "GRAYTIP_ELEMENT_SUBTYPE_JSON";
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_LOCALMSG"] = 13] = "GRAYTIP_ELEMENT_SUBTYPE_LOCALMSG";
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_PROCLAMATION"] = 2] = "GRAYTIP_ELEMENT_SUBTYPE_PROCLAMATION";
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_REVOKE"] = 1] = "GRAYTIP_ELEMENT_SUBTYPE_REVOKE";
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_UNKNOWN"] = 0] = "GRAYTIP_ELEMENT_SUBTYPE_UNKNOWN";
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_WALLET"] = 16] = "GRAYTIP_ELEMENT_SUBTYPE_WALLET";
  NTGrayTipElementSubTypeV22[NTGrayTipElementSubTypeV22["GRAYTIP_ELEMENT_SUBTYPE_XMLMSG"] = 12] = "GRAYTIP_ELEMENT_SUBTYPE_XMLMSG";
  return NTGrayTipElementSubTypeV22;
})(NTGrayTipElementSubTypeV2 || {});
var FaceIndex = /* @__PURE__ */ ((FaceIndex2) => {
  FaceIndex2[FaceIndex2["DICE"] = 358] = "DICE";
  FaceIndex2[FaceIndex2["RPS"] = 359] = "RPS";
  return FaceIndex2;
})(FaceIndex || {});
var TipGroupElementType = /* @__PURE__ */ ((TipGroupElementType2) => {
  TipGroupElementType2[TipGroupElementType2["KUNKNOWN"] = 0] = "KUNKNOWN";
  TipGroupElementType2[TipGroupElementType2["KMEMBERADD"] = 1] = "KMEMBERADD";
  TipGroupElementType2[TipGroupElementType2["KDISBANDED"] = 2] = "KDISBANDED";
  TipGroupElementType2[TipGroupElementType2["KQUITTE"] = 3] = "KQUITTE";
  TipGroupElementType2[TipGroupElementType2["KCREATED"] = 4] = "KCREATED";
  TipGroupElementType2[TipGroupElementType2["KGROUPNAMEMODIFIED"] = 5] = "KGROUPNAMEMODIFIED";
  TipGroupElementType2[TipGroupElementType2["KBLOCK"] = 6] = "KBLOCK";
  TipGroupElementType2[TipGroupElementType2["KUNBLOCK"] = 7] = "KUNBLOCK";
  TipGroupElementType2[TipGroupElementType2["KSHUTUP"] = 8] = "KSHUTUP";
  TipGroupElementType2[TipGroupElementType2["KBERECYCLED"] = 9] = "KBERECYCLED";
  TipGroupElementType2[TipGroupElementType2["KDISBANDORBERECYCLED"] = 10] = "KDISBANDORBERECYCLED";
  return TipGroupElementType2;
})(TipGroupElementType || {});
var SendStatusType = /* @__PURE__ */ ((SendStatusType2) => {
  SendStatusType2[SendStatusType2["KSEND_STATUS_FAILED"] = 0] = "KSEND_STATUS_FAILED";
  SendStatusType2[SendStatusType2["KSEND_STATUS_SENDING"] = 1] = "KSEND_STATUS_SENDING";
  SendStatusType2[SendStatusType2["KSEND_STATUS_SUCCESS"] = 2] = "KSEND_STATUS_SUCCESS";
  SendStatusType2[SendStatusType2["KSEND_STATUS_SUCCESS_NOSEQ"] = 3] = "KSEND_STATUS_SUCCESS_NOSEQ";
  return SendStatusType2;
})(SendStatusType || {});
var FaceType = /* @__PURE__ */ ((FaceType2) => {
  FaceType2[FaceType2["Unknown"] = 0] = "Unknown";
  FaceType2[FaceType2["OldFace"] = 1] = "OldFace";
  FaceType2[FaceType2["Normal"] = 2] = "Normal";
  FaceType2[FaceType2["AniSticke"] = 3] = "AniSticke";
  FaceType2[FaceType2["Lottie"] = 4] = "Lottie";
  FaceType2[FaceType2["Poke"] = 5] = "Poke";
  return FaceType2;
})(FaceType || {});

var GroupNotifyMsgType = /* @__PURE__ */ ((GroupNotifyMsgType2) => {
  GroupNotifyMsgType2[GroupNotifyMsgType2["UN_SPECIFIED"] = 0] = "UN_SPECIFIED";
  GroupNotifyMsgType2[GroupNotifyMsgType2["INVITED_BY_MEMBER"] = 1] = "INVITED_BY_MEMBER";
  GroupNotifyMsgType2[GroupNotifyMsgType2["REFUSE_INVITED"] = 2] = "REFUSE_INVITED";
  GroupNotifyMsgType2[GroupNotifyMsgType2["REFUSED_BY_ADMINI_STRATOR"] = 3] = "REFUSED_BY_ADMINI_STRATOR";
  GroupNotifyMsgType2[GroupNotifyMsgType2["AGREED_TOJOIN_DIRECT"] = 4] = "AGREED_TOJOIN_DIRECT";
  GroupNotifyMsgType2[GroupNotifyMsgType2["INVITED_NEED_ADMINI_STRATOR_PASS"] = 5] = "INVITED_NEED_ADMINI_STRATOR_PASS";
  GroupNotifyMsgType2[GroupNotifyMsgType2["AGREED_TO_JOIN_BY_ADMINI_STRATOR"] = 6] = "AGREED_TO_JOIN_BY_ADMINI_STRATOR";
  GroupNotifyMsgType2[GroupNotifyMsgType2["REQUEST_JOIN_NEED_ADMINI_STRATOR_PASS"] = 7] = "REQUEST_JOIN_NEED_ADMINI_STRATOR_PASS";
  GroupNotifyMsgType2[GroupNotifyMsgType2["SET_ADMIN"] = 8] = "SET_ADMIN";
  GroupNotifyMsgType2[GroupNotifyMsgType2["KICK_MEMBER_NOTIFY_ADMIN"] = 9] = "KICK_MEMBER_NOTIFY_ADMIN";
  GroupNotifyMsgType2[GroupNotifyMsgType2["KICK_MEMBER_NOTIFY_KICKED"] = 10] = "KICK_MEMBER_NOTIFY_KICKED";
  GroupNotifyMsgType2[GroupNotifyMsgType2["MEMBER_LEAVE_NOTIFY_ADMIN"] = 11] = "MEMBER_LEAVE_NOTIFY_ADMIN";
  GroupNotifyMsgType2[GroupNotifyMsgType2["CANCEL_ADMIN_NOTIFY_CANCELED"] = 12] = "CANCEL_ADMIN_NOTIFY_CANCELED";
  GroupNotifyMsgType2[GroupNotifyMsgType2["CANCEL_ADMIN_NOTIFY_ADMIN"] = 13] = "CANCEL_ADMIN_NOTIFY_ADMIN";
  GroupNotifyMsgType2[GroupNotifyMsgType2["TRANSFER_GROUP_NOTIFY_OLDOWNER"] = 14] = "TRANSFER_GROUP_NOTIFY_OLDOWNER";
  GroupNotifyMsgType2[GroupNotifyMsgType2["TRANSFER_GROUP_NOTIFY_ADMIN"] = 15] = "TRANSFER_GROUP_NOTIFY_ADMIN";
  return GroupNotifyMsgType2;
})(GroupNotifyMsgType || {});
var GroupNotifyMsgStatus = /* @__PURE__ */ ((GroupNotifyMsgStatus2) => {
  GroupNotifyMsgStatus2[GroupNotifyMsgStatus2["KINIT"] = 0] = "KINIT";
  GroupNotifyMsgStatus2[GroupNotifyMsgStatus2["KUNHANDLE"] = 1] = "KUNHANDLE";
  GroupNotifyMsgStatus2[GroupNotifyMsgStatus2["KAGREED"] = 2] = "KAGREED";
  GroupNotifyMsgStatus2[GroupNotifyMsgStatus2["KREFUSED"] = 3] = "KREFUSED";
  GroupNotifyMsgStatus2[GroupNotifyMsgStatus2["KIGNORED"] = 4] = "KIGNORED";
  return GroupNotifyMsgStatus2;
})(GroupNotifyMsgStatus || {});
var NTGroupRequestOperateTypes = /* @__PURE__ */ ((NTGroupRequestOperateTypes2) => {
  NTGroupRequestOperateTypes2[NTGroupRequestOperateTypes2["KUNSPECIFIED"] = 0] = "KUNSPECIFIED";
  NTGroupRequestOperateTypes2[NTGroupRequestOperateTypes2["KAGREE"] = 1] = "KAGREE";
  NTGroupRequestOperateTypes2[NTGroupRequestOperateTypes2["KREFUSE"] = 2] = "KREFUSE";
  NTGroupRequestOperateTypes2[NTGroupRequestOperateTypes2["KIGNORE"] = 3] = "KIGNORE";
  NTGroupRequestOperateTypes2[NTGroupRequestOperateTypes2["KDELETE"] = 4] = "KDELETE";
  return NTGroupRequestOperateTypes2;
})(NTGroupRequestOperateTypes || {});
var BuddyReqType = /* @__PURE__ */ ((BuddyReqType2) => {
  BuddyReqType2[BuddyReqType2["KMEINITIATOR"] = 0] = "KMEINITIATOR";
  BuddyReqType2[BuddyReqType2["KPEERINITIATOR"] = 1] = "KPEERINITIATOR";
  BuddyReqType2[BuddyReqType2["KMEAGREED"] = 2] = "KMEAGREED";
  BuddyReqType2[BuddyReqType2["KMEAGREEDANDADDED"] = 3] = "KMEAGREEDANDADDED";
  BuddyReqType2[BuddyReqType2["KPEERAGREED"] = 4] = "KPEERAGREED";
  BuddyReqType2[BuddyReqType2["KPEERAGREEDANDADDED"] = 5] = "KPEERAGREEDANDADDED";
  BuddyReqType2[BuddyReqType2["KPEERREFUSED"] = 6] = "KPEERREFUSED";
  BuddyReqType2[BuddyReqType2["KMEREFUSED"] = 7] = "KMEREFUSED";
  BuddyReqType2[BuddyReqType2["KMEIGNORED"] = 8] = "KMEIGNORED";
  BuddyReqType2[BuddyReqType2["KMEAGREEANYONE"] = 9] = "KMEAGREEANYONE";
  BuddyReqType2[BuddyReqType2["KMESETQUESTION"] = 10] = "KMESETQUESTION";
  BuddyReqType2[BuddyReqType2["KMEAGREEANDADDFAILED"] = 11] = "KMEAGREEANDADDFAILED";
  BuddyReqType2[BuddyReqType2["KMSGINFO"] = 12] = "KMSGINFO";
  BuddyReqType2[BuddyReqType2["KMEINITIATORWAITPEERCONFIRM"] = 13] = "KMEINITIATORWAITPEERCONFIRM";
  return BuddyReqType2;
})(BuddyReqType || {});
var MemberExtSourceType = /* @__PURE__ */ ((MemberExtSourceType2) => {
  MemberExtSourceType2[MemberExtSourceType2["DEFAULTTYPE"] = 0] = "DEFAULTTYPE";
  MemberExtSourceType2[MemberExtSourceType2["TITLETYPE"] = 1] = "TITLETYPE";
  MemberExtSourceType2[MemberExtSourceType2["NEWGROUPTYPE"] = 2] = "NEWGROUPTYPE";
  return MemberExtSourceType2;
})(MemberExtSourceType || {});

var WebHonorType = /* @__PURE__ */ ((WebHonorType2) => {
  WebHonorType2["ALL"] = "all";
  WebHonorType2["TALKATIVE"] = "talkative";
  WebHonorType2["PERFORMER"] = "performer";
  WebHonorType2["LEGEND"] = "legend";
  WebHonorType2["STRONG_NEWBIE"] = "strong_newbie";
  WebHonorType2["EMOTION"] = "emotion";
  return WebHonorType2;
})(WebHonorType || {});

const IMAGE_HTTP_HOST = "https://gchat.qpic.cn";
const IMAGE_HTTP_HOST_NT = "https://multimedia.nt.qq.com.cn";

var JsonGrayBusiId = /* @__PURE__ */ ((JsonGrayBusiId2) => {
  JsonGrayBusiId2[JsonGrayBusiId2["AIO_AV_C2C_NOTICE"] = 2021] = "AIO_AV_C2C_NOTICE";
  JsonGrayBusiId2[JsonGrayBusiId2["AIO_AV_GROUP_NOTICE"] = 2022] = "AIO_AV_GROUP_NOTICE";
  JsonGrayBusiId2[JsonGrayBusiId2["AIO_C2C_DONT_DISTURB"] = 2100] = "AIO_C2C_DONT_DISTURB";
  JsonGrayBusiId2[JsonGrayBusiId2["AIO_CRM_FLAGS_TIPS"] = 2050] = "AIO_CRM_FLAGS_TIPS";
  JsonGrayBusiId2[JsonGrayBusiId2["AIO_GROUP_ESSENCE_MSG_TIP"] = 2401] = "AIO_GROUP_ESSENCE_MSG_TIP";
  JsonGrayBusiId2[JsonGrayBusiId2["AIO_NUDGE_CUSTOM_GUIDE"] = 2041] = "AIO_NUDGE_CUSTOM_GUIDE";
  JsonGrayBusiId2[JsonGrayBusiId2["AIO_PUSH_GUIDE_GRAY_TIPS"] = 2701] = "AIO_PUSH_GUIDE_GRAY_TIPS";
  JsonGrayBusiId2[JsonGrayBusiId2["AIO_RECALL_MSGCUSTOM_WORDINGGUIDE"] = 2e3] = "AIO_RECALL_MSGCUSTOM_WORDINGGUIDE";
  JsonGrayBusiId2[JsonGrayBusiId2["AIO_ROBOT_SAFETY_TIP"] = 2201] = "AIO_ROBOT_SAFETY_TIP";
  JsonGrayBusiId2[JsonGrayBusiId2["AIO_ZPLAN_EMOTICON_GUIDE"] = 2301] = "AIO_ZPLAN_EMOTICON_GUIDE";
  JsonGrayBusiId2[JsonGrayBusiId2["AIO_ZPLAN_SCENE_LINKAGE"] = 2302] = "AIO_ZPLAN_SCENE_LINKAGE";
  JsonGrayBusiId2[JsonGrayBusiId2["AIO_ZPLAN_SEND_MEME"] = 2300] = "AIO_ZPLAN_SEND_MEME";
  JsonGrayBusiId2[JsonGrayBusiId2["DISBAND_DISCUSSION_GRAY_TIP_ID"] = 2603] = "DISBAND_DISCUSSION_GRAY_TIP_ID";
  JsonGrayBusiId2[JsonGrayBusiId2["FILE_SENDING_SIZE_4GB_LIMIT"] = 3003] = "FILE_SENDING_SIZE_4GB_LIMIT";
  JsonGrayBusiId2[JsonGrayBusiId2["GROUP_AIO_CONFIGURABLE_GRAY_TIPS"] = 2407] = "GROUP_AIO_CONFIGURABLE_GRAY_TIPS";
  JsonGrayBusiId2[JsonGrayBusiId2["GROUP_AIO_HOME_SCHOOL_WELCOME_GRAY_TIP_ID"] = 2404] = "GROUP_AIO_HOME_SCHOOL_WELCOME_GRAY_TIP_ID";
  JsonGrayBusiId2[JsonGrayBusiId2["GROUP_AIO_MSG_FREQUENCY_GRAY_TIP_ID"] = 2406] = "GROUP_AIO_MSG_FREQUENCY_GRAY_TIP_ID";
  JsonGrayBusiId2[JsonGrayBusiId2["GROUP_AIO_SHUTUP_GRAY_TIP_ID"] = 2402] = "GROUP_AIO_SHUTUP_GRAY_TIP_ID";
  JsonGrayBusiId2[JsonGrayBusiId2["GROUP_AIO_TEMPORARY_GRAY_TIP_ID"] = 2405] = "GROUP_AIO_TEMPORARY_GRAY_TIP_ID";
  JsonGrayBusiId2[JsonGrayBusiId2["GROUP_AIO_UNREAD_MSG_AI_SUMMARY"] = 2408] = "GROUP_AIO_UNREAD_MSG_AI_SUMMARY";
  JsonGrayBusiId2[JsonGrayBusiId2["GROUP_AIO_UPLOAD_PERMISSIONS_GRAY_TIP_ID"] = 2403] = "GROUP_AIO_UPLOAD_PERMISSIONS_GRAY_TIP_ID";
  JsonGrayBusiId2[JsonGrayBusiId2["LITE_ACTION"] = 86] = "LITE_ACTION";
  JsonGrayBusiId2[JsonGrayBusiId2["ONLINE_FILE_CANCEL_RECV_ON_RECVING"] = 4] = "ONLINE_FILE_CANCEL_RECV_ON_RECVING";
  JsonGrayBusiId2[JsonGrayBusiId2["ONLINE_FILE_GO_OFFLINE"] = 11] = "ONLINE_FILE_GO_OFFLINE";
  JsonGrayBusiId2[JsonGrayBusiId2["ONLINE_FILE_GO_OFFLINE_ALL"] = 12] = "ONLINE_FILE_GO_OFFLINE_ALL";
  JsonGrayBusiId2[JsonGrayBusiId2["ONLINE_FILE_RECV_BY_MOBILE"] = 13] = "ONLINE_FILE_RECV_BY_MOBILE";
  JsonGrayBusiId2[JsonGrayBusiId2["ONLINE_FILE_RECV_ERROR"] = 10] = "ONLINE_FILE_RECV_ERROR";
  JsonGrayBusiId2[JsonGrayBusiId2["ONLINE_FILE_REFUSE_ALL_RECV"] = 7] = "ONLINE_FILE_REFUSE_ALL_RECV";
  JsonGrayBusiId2[JsonGrayBusiId2["ONLINE_FILE_REFUSE_ALL_RECV_ON_RECVING"] = 8] = "ONLINE_FILE_REFUSE_ALL_RECV_ON_RECVING";
  JsonGrayBusiId2[JsonGrayBusiId2["ONLINE_FILE_REFUSE_RECV"] = 3] = "ONLINE_FILE_REFUSE_RECV";
  JsonGrayBusiId2[JsonGrayBusiId2["ONLINE_FILE_SEND_ERROR"] = 9] = "ONLINE_FILE_SEND_ERROR";
  JsonGrayBusiId2[JsonGrayBusiId2["ONLINE_FILE_STOP_ALL_SEND"] = 5] = "ONLINE_FILE_STOP_ALL_SEND";
  JsonGrayBusiId2[JsonGrayBusiId2["ONLINE_FILE_STOP_ALL_SEND_ON_SENDING"] = 6] = "ONLINE_FILE_STOP_ALL_SEND_ON_SENDING";
  JsonGrayBusiId2[JsonGrayBusiId2["ONLINE_FILE_STOP_SEND"] = 1] = "ONLINE_FILE_STOP_SEND";
  JsonGrayBusiId2[JsonGrayBusiId2["ONLINE_FILE_STOP_SEND_ON_SENDING"] = 2] = "ONLINE_FILE_STOP_SEND_ON_SENDING";
  JsonGrayBusiId2[JsonGrayBusiId2["ONLINE_GROUP_HOME_WORK"] = 51] = "ONLINE_GROUP_HOME_WORK";
  JsonGrayBusiId2[JsonGrayBusiId2["PTT_AUTO_CHANGE_GUIDE"] = 2060] = "PTT_AUTO_CHANGE_GUIDE";
  JsonGrayBusiId2[JsonGrayBusiId2["QCIRCLE_SHOW_FULE_TIPS"] = 2601] = "QCIRCLE_SHOW_FULE_TIPS";
  JsonGrayBusiId2[JsonGrayBusiId2["QWALLET_GRAY_TIP_ID"] = 2602] = "QWALLET_GRAY_TIP_ID";
  JsonGrayBusiId2[JsonGrayBusiId2["RED_BAG"] = 81] = "RED_BAG";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_C2C_GROUP_AIO_SETUP_GROUP_AND_REMARK"] = 1005] = "RELATION_C2C_GROUP_AIO_SETUP_GROUP_AND_REMARK";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_C2C_LOVER_BONUS"] = 1003] = "RELATION_C2C_LOVER_BONUS";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_C2C_MEMBER_ADD"] = 1017] = "RELATION_C2C_MEMBER_ADD";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_C2C_REACTIVE_DEGRADE_MSG"] = 1019] = "RELATION_C2C_REACTIVE_DEGRADE_MSG";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_C2C_REACTIVE_UPGRADE_MSG"] = 1018] = "RELATION_C2C_REACTIVE_UPGRADE_MSG";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_C2C_SAY_HELLO"] = 1004] = "RELATION_C2C_SAY_HELLO";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_CHAIN_BLACKED"] = 1e3] = "RELATION_CHAIN_BLACKED";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_CHAIN_MATCH_FRIEND"] = 1007] = "RELATION_CHAIN_MATCH_FRIEND";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_CREATE_GROUP_GRAY_TIP_ID"] = 1009] = "RELATION_CREATE_GROUP_GRAY_TIP_ID";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_EMOJIEGG_SHOW"] = 1001] = "RELATION_EMOJIEGG_SHOW";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_EMOJIEGG_WILL_DEGRADE"] = 1002] = "RELATION_EMOJIEGG_WILL_DEGRADE";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_FRIEND_CLONE_INFO"] = 1006] = "RELATION_FRIEND_CLONE_INFO";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_GROUP_BATCH_ADD_FRIEND"] = 1020] = "RELATION_GROUP_BATCH_ADD_FRIEND";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_GROUP_MEMBER_ADD"] = 1022] = "RELATION_GROUP_MEMBER_ADD";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_GROUP_MEMBER_ADD_WITH_MODIFY_NAME"] = 1015] = "RELATION_GROUP_MEMBER_ADD_WITH_MODIFY_NAME";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_GROUP_MEMBER_ADD_WITH_WELCOME"] = 1016] = "RELATION_GROUP_MEMBER_ADD_WITH_WELCOME";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_GROUP_MEMBER_RECOMMEND"] = 1021] = "RELATION_GROUP_MEMBER_RECOMMEND";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_GROUP_SHUT_UP"] = 1014] = "RELATION_GROUP_SHUT_UP";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_LIMIT_TMP_CONVERSATION_SET"] = 1011] = "RELATION_LIMIT_TMP_CONVERSATION_SET";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_NEARBY_GOTO_VERIFY"] = 1008] = "RELATION_NEARBY_GOTO_VERIFY";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_ONEWAY_FRIEND_GRAY_TIP_ID"] = 1012] = "RELATION_ONEWAY_FRIEND_GRAY_TIP_ID";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_ONEWAY_FRIEND_NEW_GRAY_TIP_ID"] = 1013] = "RELATION_ONEWAY_FRIEND_NEW_GRAY_TIP_ID";
  JsonGrayBusiId2[JsonGrayBusiId2["RELATION_YQT"] = 1010] = "RELATION_YQT";
  JsonGrayBusiId2[JsonGrayBusiId2["TROOP_ADD_FRIEND_ACTIVE"] = 19264] = "TROOP_ADD_FRIEND_ACTIVE";
  JsonGrayBusiId2[JsonGrayBusiId2["TROOP_ADD_FRIEND_HOT_CHAT"] = 19265] = "TROOP_ADD_FRIEND_HOT_CHAT";
  JsonGrayBusiId2[JsonGrayBusiId2["TROOP_ADD_FRIEND_NEW_MEMBER"] = 19267] = "TROOP_ADD_FRIEND_NEW_MEMBER";
  JsonGrayBusiId2[JsonGrayBusiId2["TROOP_ADD_FRIEND_REPLY_OR_AT"] = 19266] = "TROOP_ADD_FRIEND_REPLY_OR_AT";
  JsonGrayBusiId2[JsonGrayBusiId2["TROOP_BREAK_ICE"] = 10405] = "TROOP_BREAK_ICE";
  JsonGrayBusiId2[JsonGrayBusiId2["TROOP_FLAME_IGNITED"] = 19273] = "TROOP_FLAME_IGNITED";
  JsonGrayBusiId2[JsonGrayBusiId2["UI_RESERVE_100000_110000"] = 1e5] = "UI_RESERVE_100000_110000";
  JsonGrayBusiId2[JsonGrayBusiId2["VAS_FILE_UPLOAD_OVER_1G"] = 3002] = "VAS_FILE_UPLOAD_OVER_1G";
  JsonGrayBusiId2[JsonGrayBusiId2["VAS_FILE_UPLOAD_OVER_LIMIT"] = 3001] = "VAS_FILE_UPLOAD_OVER_LIMIT";
  return JsonGrayBusiId2;
})(JsonGrayBusiId || {});

const defaultMessages = 'End-Of-Stream';
/**
 * Thrown on read operation of the end of file or stream has been reached
 */
class EndOfStreamError extends Error {
    constructor() {
        super(defaultMessages);
        this.name = "EndOfStreamError";
    }
}
class AbortError extends Error {
    constructor(message = "The operation was aborted") {
        super(message);
        this.name = "AbortError";
    }
}

class Deferred {
    constructor() {
        this.resolve = () => null;
        this.reject = () => null;
        this.promise = new Promise((resolve, reject) => {
            this.reject = reject;
            this.resolve = resolve;
        });
    }
}

class AbstractStreamReader {
    constructor() {
        this.endOfStream = false;
        this.interrupted = false;
        /**
         * Store peeked data
         * @type {Array}
         */
        this.peekQueue = [];
    }
    async peek(uint8Array, mayBeLess = false) {
        const bytesRead = await this.read(uint8Array, mayBeLess);
        this.peekQueue.push(uint8Array.subarray(0, bytesRead)); // Put read data back to peek buffer
        return bytesRead;
    }
    async read(buffer, mayBeLess = false) {
        if (buffer.length === 0) {
            return 0;
        }
        let bytesRead = this.readFromPeekBuffer(buffer);
        if (!this.endOfStream) {
            bytesRead += await this.readRemainderFromStream(buffer.subarray(bytesRead), mayBeLess);
        }
        if (bytesRead === 0 && !mayBeLess) {
            throw new EndOfStreamError();
        }
        return bytesRead;
    }
    /**
     * Read chunk from stream
     * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in
     * @returns Number of bytes read
     */
    readFromPeekBuffer(buffer) {
        let remaining = buffer.length;
        let bytesRead = 0;
        // consume peeked data first
        while (this.peekQueue.length > 0 && remaining > 0) {
            const peekData = this.peekQueue.pop(); // Front of queue
            if (!peekData)
                throw new Error('peekData should be defined');
            const lenCopy = Math.min(peekData.length, remaining);
            buffer.set(peekData.subarray(0, lenCopy), bytesRead);
            bytesRead += lenCopy;
            remaining -= lenCopy;
            if (lenCopy < peekData.length) {
                // remainder back to queue
                this.peekQueue.push(peekData.subarray(lenCopy));
            }
        }
        return bytesRead;
    }
    async readRemainderFromStream(buffer, mayBeLess) {
        let bytesRead = 0;
        // Continue reading from stream if required
        while (bytesRead < buffer.length && !this.endOfStream) {
            if (this.interrupted) {
                throw new AbortError();
            }
            const chunkLen = await this.readFromStream(buffer.subarray(bytesRead), mayBeLess);
            if (chunkLen === 0)
                break;
            bytesRead += chunkLen;
        }
        if (!mayBeLess && bytesRead < buffer.length) {
            throw new EndOfStreamError();
        }
        return bytesRead;
    }
}

/**
 * Node.js Readable Stream Reader
 * Ref: https://nodejs.org/api/stream.html#readable-streams
 */
class StreamReader extends AbstractStreamReader {
    constructor(s) {
        super();
        this.s = s;
        /**
         * Deferred used for postponed read request (as not data is yet available to read)
         */
        this.deferred = null;
        if (!s.read || !s.once) {
            throw new Error('Expected an instance of stream.Readable');
        }
        this.s.once('end', () => {
            this.endOfStream = true;
            if (this.deferred) {
                this.deferred.resolve(0);
            }
        });
        this.s.once('error', err => this.reject(err));
        this.s.once('close', () => this.abort());
    }
    /**
     * Read chunk from stream
     * @param buffer Target Uint8Array (or Buffer) to store data read from stream in
     * @param mayBeLess - If true, may fill the buffer partially
     * @returns Number of bytes read
     */
    async readFromStream(buffer, mayBeLess) {
        if (buffer.length === 0)
            return 0;
        const readBuffer = this.s.read(buffer.length);
        if (readBuffer) {
            buffer.set(readBuffer);
            return readBuffer.length;
        }
        const request = {
            buffer,
            mayBeLess,
            deferred: new Deferred()
        };
        this.deferred = request.deferred;
        this.s.once('readable', () => {
            this.readDeferred(request);
        });
        return request.deferred.promise;
    }
    /**
     * Process deferred read request
     * @param request Deferred read request
     */
    readDeferred(request) {
        const readBuffer = this.s.read(request.buffer.length);
        if (readBuffer) {
            request.buffer.set(readBuffer);
            request.deferred.resolve(readBuffer.length);
            this.deferred = null;
        }
        else {
            this.s.once('readable', () => {
                this.readDeferred(request);
            });
        }
    }
    reject(err) {
        this.interrupted = true;
        if (this.deferred) {
            this.deferred.reject(err);
            this.deferred = null;
        }
    }
    async abort() {
        this.reject(new AbortError());
    }
    async close() {
        return this.abort();
    }
}

class WebStreamReader extends AbstractStreamReader {
    constructor(reader) {
        super();
        this.reader = reader;
    }
    async abort() {
        return this.close();
    }
    async close() {
        this.reader.releaseLock();
    }
}

/**
 * Read from a WebStream using a BYOB reader
 * Reference: https://nodejs.org/api/webstreams.html#class-readablestreambyobreader
 */
class WebStreamByobReader extends WebStreamReader {
    /**
     * Read from stream
     * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in
     * @param mayBeLess - If true, may fill the buffer partially
     * @protected Bytes read
     */
    async readFromStream(buffer, mayBeLess) {
        if (buffer.length === 0)
            return 0;
        // @ts-ignore
        const result = await this.reader.read(new Uint8Array(buffer.length), { min: mayBeLess ? undefined : buffer.length });
        if (result.done) {
            this.endOfStream = result.done;
        }
        if (result.value) {
            buffer.set(result.value);
            return result.value.length;
        }
        return 0;
    }
}

class WebStreamDefaultReader extends AbstractStreamReader {
    constructor(reader) {
        super();
        this.reader = reader;
        this.buffer = null; // Internal buffer to store excess data
    }
    /**
     * Copy chunk to target, and store the remainder in this.buffer
     */
    writeChunk(target, chunk) {
        const written = Math.min(chunk.length, target.length);
        target.set(chunk.subarray(0, written));
        // Adjust the remainder of the buffer
        if (written < chunk.length) {
            this.buffer = chunk.subarray(written);
        }
        else {
            this.buffer = null;
        }
        return written;
    }
    /**
     * Read from stream
     * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in
     * @param mayBeLess - If true, may fill the buffer partially
     * @protected Bytes read
     */
    async readFromStream(buffer, mayBeLess) {
        if (buffer.length === 0)
            return 0;
        let totalBytesRead = 0;
        // Serve from the internal buffer first
        if (this.buffer) {
            totalBytesRead += this.writeChunk(buffer, this.buffer);
        }
        // Continue reading from the stream if more data is needed
        while (totalBytesRead < buffer.length && !this.endOfStream) {
            const result = await this.reader.read();
            if (result.done) {
                this.endOfStream = true;
                break;
            }
            if (result.value) {
                totalBytesRead += this.writeChunk(buffer.subarray(totalBytesRead), result.value);
            }
        }
        if (!mayBeLess && totalBytesRead === 0 && this.endOfStream) {
            throw new EndOfStreamError();
        }
        return totalBytesRead;
    }
    abort() {
        this.interrupted = true;
        return this.reader.cancel();
    }
    async close() {
        await this.abort();
        this.reader.releaseLock();
    }
}

function makeWebStreamReader(stream) {
    try {
        const reader = stream.getReader({ mode: "byob" });
        if (reader instanceof ReadableStreamDefaultReader) {
            // Fallback to default reader in case `mode: byob` is ignored
            return new WebStreamDefaultReader(reader);
        }
        return new WebStreamByobReader(reader);
    }
    catch (error) {
        if (error instanceof TypeError) {
            // Fallback to default reader in case `mode: byob` rejected by a `TypeError`
            return new WebStreamDefaultReader(stream.getReader());
        }
        throw error;
    }
}

/**
 * Core tokenizer
 */
class AbstractTokenizer {
    /**
     * Constructor
     * @param options Tokenizer options
     * @protected
     */
    constructor(options) {
        this.numBuffer = new Uint8Array(8);
        /**
         * Tokenizer-stream position
         */
        this.position = 0;
        this.onClose = options?.onClose;
        if (options?.abortSignal) {
            options.abortSignal.addEventListener('abort', () => {
                this.abort();
            });
        }
    }
    /**
     * Read a token from the tokenizer-stream
     * @param token - The token to read
     * @param position - If provided, the desired position in the tokenizer-stream
     * @returns Promise with token data
     */
    async readToken(token, position = this.position) {
        const uint8Array = new Uint8Array(token.len);
        const len = await this.readBuffer(uint8Array, { position });
        if (len < token.len)
            throw new EndOfStreamError();
        return token.get(uint8Array, 0);
    }
    /**
     * Peek a token from the tokenizer-stream.
     * @param token - Token to peek from the tokenizer-stream.
     * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position.
     * @returns Promise with token data
     */
    async peekToken(token, position = this.position) {
        const uint8Array = new Uint8Array(token.len);
        const len = await this.peekBuffer(uint8Array, { position });
        if (len < token.len)
            throw new EndOfStreamError();
        return token.get(uint8Array, 0);
    }
    /**
     * Read a numeric token from the stream
     * @param token - Numeric token
     * @returns Promise with number
     */
    async readNumber(token) {
        const len = await this.readBuffer(this.numBuffer, { length: token.len });
        if (len < token.len)
            throw new EndOfStreamError();
        return token.get(this.numBuffer, 0);
    }
    /**
     * Read a numeric token from the stream
     * @param token - Numeric token
     * @returns Promise with number
     */
    async peekNumber(token) {
        const len = await this.peekBuffer(this.numBuffer, { length: token.len });
        if (len < token.len)
            throw new EndOfStreamError();
        return token.get(this.numBuffer, 0);
    }
    /**
     * Ignore number of bytes, advances the pointer in under tokenizer-stream.
     * @param length - Number of bytes to ignore
     * @return resolves the number of bytes ignored, equals length if this available, otherwise the number of bytes available
     */
    async ignore(length) {
        if (this.fileInfo.size !== undefined) {
            const bytesLeft = this.fileInfo.size - this.position;
            if (length > bytesLeft) {
                this.position += bytesLeft;
                return bytesLeft;
            }
        }
        this.position += length;
        return length;
    }
    async close() {
        await this.abort();
        await this.onClose?.();
    }
    normalizeOptions(uint8Array, options) {
        if (!this.supportsRandomAccess() && options && options.position !== undefined && options.position < this.position) {
            throw new Error('`options.position` must be equal or greater than `tokenizer.position`');
        }
        return {
            ...{
                mayBeLess: false,
                offset: 0,
                length: uint8Array.length,
                position: this.position
            }, ...options
        };
    }
    abort() {
        return Promise.resolve(); // Ignore abort signal
    }
}

const maxBufferSize = 256000;
class ReadStreamTokenizer extends AbstractTokenizer {
    /**
     * Constructor
     * @param streamReader stream-reader to read from
     * @param options Tokenizer options
     */
    constructor(streamReader, options) {
        super(options);
        this.streamReader = streamReader;
        this.fileInfo = options?.fileInfo ?? {};
    }
    /**
     * Read buffer from tokenizer
     * @param uint8Array - Target Uint8Array to fill with data read from the tokenizer-stream
     * @param options - Read behaviour options
     * @returns Promise with number of bytes read
     */
    async readBuffer(uint8Array, options) {
        const normOptions = this.normalizeOptions(uint8Array, options);
        const skipBytes = normOptions.position - this.position;
        if (skipBytes > 0) {
            await this.ignore(skipBytes);
            return this.readBuffer(uint8Array, options);
        }
        if (skipBytes < 0) {
            throw new Error('`options.position` must be equal or greater than `tokenizer.position`');
        }
        if (normOptions.length === 0) {
            return 0;
        }
        const bytesRead = await this.streamReader.read(uint8Array.subarray(0, normOptions.length), normOptions.mayBeLess);
        this.position += bytesRead;
        if ((!options || !options.mayBeLess) && bytesRead < normOptions.length) {
            throw new EndOfStreamError();
        }
        return bytesRead;
    }
    /**
     * Peek (read ahead) buffer from tokenizer
     * @param uint8Array - Uint8Array (or Buffer) to write data to
     * @param options - Read behaviour options
     * @returns Promise with number of bytes peeked
     */
    async peekBuffer(uint8Array, options) {
        const normOptions = this.normalizeOptions(uint8Array, options);
        let bytesRead = 0;
        if (normOptions.position) {
            const skipBytes = normOptions.position - this.position;
            if (skipBytes > 0) {
                const skipBuffer = new Uint8Array(normOptions.length + skipBytes);
                bytesRead = await this.peekBuffer(skipBuffer, { mayBeLess: normOptions.mayBeLess });
                uint8Array.set(skipBuffer.subarray(skipBytes));
                return bytesRead - skipBytes;
            }
            if (skipBytes < 0) {
                throw new Error('Cannot peek from a negative offset in a stream');
            }
        }
        if (normOptions.length > 0) {
            try {
                bytesRead = await this.streamReader.peek(uint8Array.subarray(0, normOptions.length), normOptions.mayBeLess);
            }
            catch (err) {
                if (options?.mayBeLess && err instanceof EndOfStreamError) {
                    return 0;
                }
                throw err;
            }
            if ((!normOptions.mayBeLess) && bytesRead < normOptions.length) {
                throw new EndOfStreamError();
            }
        }
        return bytesRead;
    }
    async ignore(length) {
        // debug(`ignore ${this.position}...${this.position + length - 1}`);
        const bufSize = Math.min(maxBufferSize, length);
        const buf = new Uint8Array(bufSize);
        let totBytesRead = 0;
        while (totBytesRead < length) {
            const remaining = length - totBytesRead;
            const bytesRead = await this.readBuffer(buf, { length: Math.min(bufSize, remaining) });
            if (bytesRead < 0) {
                return bytesRead;
            }
            totBytesRead += bytesRead;
        }
        return totBytesRead;
    }
    abort() {
        return this.streamReader.abort();
    }
    async close() {
        return this.streamReader.close();
    }
    supportsRandomAccess() {
        return false;
    }
}

class BufferTokenizer extends AbstractTokenizer {
    /**
     * Construct BufferTokenizer
     * @param uint8Array - Uint8Array to tokenize
     * @param options Tokenizer options
     */
    constructor(uint8Array, options) {
        super(options);
        this.uint8Array = uint8Array;
        this.fileInfo = { ...options?.fileInfo ?? {}, ...{ size: uint8Array.length } };
    }
    /**
     * Read buffer from tokenizer
     * @param uint8Array - Uint8Array to tokenize
     * @param options - Read behaviour options
     * @returns {Promise<number>}
     */
    async readBuffer(uint8Array, options) {
        if (options?.position) {
            this.position = options.position;
        }
        const bytesRead = await this.peekBuffer(uint8Array, options);
        this.position += bytesRead;
        return bytesRead;
    }
    /**
     * Peek (read ahead) buffer from tokenizer
     * @param uint8Array
     * @param options - Read behaviour options
     * @returns {Promise<number>}
     */
    async peekBuffer(uint8Array, options) {
        const normOptions = this.normalizeOptions(uint8Array, options);
        const bytes2read = Math.min(this.uint8Array.length - normOptions.position, normOptions.length);
        if ((!normOptions.mayBeLess) && bytes2read < normOptions.length) {
            throw new EndOfStreamError();
        }
        uint8Array.set(this.uint8Array.subarray(normOptions.position, normOptions.position + bytes2read));
        return bytes2read;
    }
    close() {
        return super.close();
    }
    supportsRandomAccess() {
        return true;
    }
    setPosition(position) {
        this.position = position;
    }
}

class BlobTokenizer extends AbstractTokenizer {
    /**
     * Construct BufferTokenizer
     * @param blob - Uint8Array to tokenize
     * @param options Tokenizer options
     */
    constructor(blob, options) {
        super(options);
        this.blob = blob;
        this.fileInfo = { ...options?.fileInfo ?? {}, ...{ size: blob.size, mimeType: blob.type } };
    }
    /**
     * Read buffer from tokenizer
     * @param uint8Array - Uint8Array to tokenize
     * @param options - Read behaviour options
     * @returns {Promise<number>}
     */
    async readBuffer(uint8Array, options) {
        if (options?.position) {
            this.position = options.position;
        }
        const bytesRead = await this.peekBuffer(uint8Array, options);
        this.position += bytesRead;
        return bytesRead;
    }
    /**
     * Peek (read ahead) buffer from tokenizer
     * @param buffer
     * @param options - Read behaviour options
     * @returns {Promise<number>}
     */
    async peekBuffer(buffer, options) {
        const normOptions = this.normalizeOptions(buffer, options);
        const bytes2read = Math.min(this.blob.size - normOptions.position, normOptions.length);
        if ((!normOptions.mayBeLess) && bytes2read < normOptions.length) {
            throw new EndOfStreamError();
        }
        const arrayBuffer = await this.blob.slice(normOptions.position, normOptions.position + bytes2read).arrayBuffer();
        buffer.set(new Uint8Array(arrayBuffer));
        return bytes2read;
    }
    close() {
        return super.close();
    }
    supportsRandomAccess() {
        return true;
    }
    setPosition(position) {
        this.position = position;
    }
}

/**
 * Construct ReadStreamTokenizer from given Stream.
 * Will set fileSize, if provided given Stream has set the .path property/
 * @param stream - Read from Node.js Stream.Readable
 * @param options - Tokenizer options
 * @returns ReadStreamTokenizer
 */
function fromStream$1(stream, options) {
    const streamReader = new StreamReader(stream);
    const _options = options ?? {};
    const chainedClose = _options.onClose;
    _options.onClose = async () => {
        await streamReader.close();
        if (chainedClose) {
            return chainedClose();
        }
    };
    return new ReadStreamTokenizer(streamReader, _options);
}
/**
 * Construct ReadStreamTokenizer from given ReadableStream (WebStream API).
 * Will set fileSize, if provided given Stream has set the .path property/
 * @param webStream - Read from Node.js Stream.Readable (must be a byte stream)
 * @param options - Tokenizer options
 * @returns ReadStreamTokenizer
 */
function fromWebStream(webStream, options) {
    const webStreamReader = makeWebStreamReader(webStream);
    const _options = options ?? {};
    const chainedClose = _options.onClose;
    _options.onClose = async () => {
        await webStreamReader.close();
        if (chainedClose) {
            return chainedClose();
        }
    };
    return new ReadStreamTokenizer(webStreamReader, _options);
}
/**
 * Construct ReadStreamTokenizer from given Buffer.
 * @param uint8Array - Uint8Array to tokenize
 * @param options - Tokenizer options
 * @returns BufferTokenizer
 */
function fromBuffer$1(uint8Array, options) {
    return new BufferTokenizer(uint8Array, options);
}
/**
 * Construct ReadStreamTokenizer from given Blob.
 * @param blob - Uint8Array to tokenize
 * @param options - Tokenizer options
 * @returns BufferTokenizer
 */
function fromBlob(blob, options) {
    return new BlobTokenizer(blob, options);
}

class FileTokenizer extends AbstractTokenizer {
    /**
     * Create tokenizer from provided file path
     * @param sourceFilePath File path
     */
    static async fromFile(sourceFilePath) {
        const fileHandle = await open(sourceFilePath, 'r');
        const stat = await fileHandle.stat();
        return new FileTokenizer(fileHandle, { fileInfo: { path: sourceFilePath, size: stat.size } });
    }
    constructor(fileHandle, options) {
        super(options);
        this.fileHandle = fileHandle;
        this.fileInfo = options.fileInfo;
    }
    /**
     * Read buffer from file
     * @param uint8Array - Uint8Array to write result to
     * @param options - Read behaviour options
     * @returns Promise number of bytes read
     */
    async readBuffer(uint8Array, options) {
        const normOptions = this.normalizeOptions(uint8Array, options);
        this.position = normOptions.position;
        if (normOptions.length === 0)
            return 0;
        const res = await this.fileHandle.read(uint8Array, 0, normOptions.length, normOptions.position);
        this.position += res.bytesRead;
        if (res.bytesRead < normOptions.length && (!options || !options.mayBeLess)) {
            throw new EndOfStreamError();
        }
        return res.bytesRead;
    }
    /**
     * Peek buffer from file
     * @param uint8Array - Uint8Array (or Buffer) to write data to
     * @param options - Read behaviour options
     * @returns Promise number of bytes read
     */
    async peekBuffer(uint8Array, options) {
        const normOptions = this.normalizeOptions(uint8Array, options);
        const res = await this.fileHandle.read(uint8Array, 0, normOptions.length, normOptions.position);
        if ((!normOptions.mayBeLess) && res.bytesRead < normOptions.length) {
            throw new EndOfStreamError();
        }
        return res.bytesRead;
    }
    async close() {
        await this.fileHandle.close();
        return super.close();
    }
    setPosition(position) {
        this.position = position;
    }
    supportsRandomAccess() {
        return true;
    }
}

/**
 * Construct ReadStreamTokenizer from given Stream.
 * Will set fileSize, if provided given Stream has set the .path property.
 * @param stream - Node.js Stream.Readable
 * @param options - Pass additional file information to the tokenizer
 * @returns Tokenizer
 */
async function fromStream(stream, options) {
    const rst = fromStream$1(stream, options);
    if (stream.path) {
        const stat$1 = await stat(stream.path);
        rst.fileInfo.path = stream.path;
        rst.fileInfo.size = stat$1.size;
    }
    return rst;
}
const fromFile = FileTokenizer.fromFile;

var ieee754 = {};

/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */

var hasRequiredIeee754;

function requireIeee754 () {
	if (hasRequiredIeee754) return ieee754;
	hasRequiredIeee754 = 1;
	ieee754.read = function (buffer, offset, isLE, mLen, nBytes) {
	  var e, m;
	  var eLen = (nBytes * 8) - mLen - 1;
	  var eMax = (1 << eLen) - 1;
	  var eBias = eMax >> 1;
	  var nBits = -7;
	  var i = isLE ? (nBytes - 1) : 0;
	  var d = isLE ? -1 : 1;
	  var s = buffer[offset + i];

	  i += d;

	  e = s & ((1 << (-nBits)) - 1);
	  s >>= (-nBits);
	  nBits += eLen;
	  for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}

	  m = e & ((1 << (-nBits)) - 1);
	  e >>= (-nBits);
	  nBits += mLen;
	  for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}

	  if (e === 0) {
	    e = 1 - eBias;
	  } else if (e === eMax) {
	    return m ? NaN : ((s ? -1 : 1) * Infinity)
	  } else {
	    m = m + Math.pow(2, mLen);
	    e = e - eBias;
	  }
	  return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
	};

	ieee754.write = function (buffer, value, offset, isLE, mLen, nBytes) {
	  var e, m, c;
	  var eLen = (nBytes * 8) - mLen - 1;
	  var eMax = (1 << eLen) - 1;
	  var eBias = eMax >> 1;
	  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
	  var i = isLE ? 0 : (nBytes - 1);
	  var d = isLE ? 1 : -1;
	  var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;

	  value = Math.abs(value);

	  if (isNaN(value) || value === Infinity) {
	    m = isNaN(value) ? 1 : 0;
	    e = eMax;
	  } else {
	    e = Math.floor(Math.log(value) / Math.LN2);
	    if (value * (c = Math.pow(2, -e)) < 1) {
	      e--;
	      c *= 2;
	    }
	    if (e + eBias >= 1) {
	      value += rt / c;
	    } else {
	      value += rt * Math.pow(2, 1 - eBias);
	    }
	    if (value * c >= 2) {
	      e++;
	      c /= 2;
	    }

	    if (e + eBias >= eMax) {
	      m = 0;
	      e = eMax;
	    } else if (e + eBias >= 1) {
	      m = ((value * c) - 1) * Math.pow(2, mLen);
	      e = e + eBias;
	    } else {
	      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
	      e = 0;
	    }
	  }

	  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}

	  e = (e << mLen) | m;
	  eLen += mLen;
	  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}

	  buffer[offset + i - d] |= s * 128;
	};
	return ieee754;
}

requireIeee754();

// text-polyfill.ts
// Minimal encode/decode for utf-8, utf-16le, ascii, latin1, windows-1252
const WINDOWS_1252_EXTRA = {
    0x80: "€", 0x82: "‚", 0x83: "ƒ", 0x84: "„", 0x85: "…", 0x86: "†",
    0x87: "‡", 0x88: "ˆ", 0x89: "‰", 0x8a: "Š", 0x8b: "‹", 0x8c: "Œ",
    0x8e: "Ž", 0x91: "‘", 0x92: "’", 0x93: "“", 0x94: "”", 0x95: "•",
    0x96: "–", 0x97: "—", 0x98: "˜", 0x99: "™", 0x9a: "š", 0x9b: "›",
    0x9c: "œ", 0x9e: "ž", 0x9f: "Ÿ",
};
for (const [code, char] of Object.entries(WINDOWS_1252_EXTRA)) {
}
/**
 * Decode text from binary data
 * @param bytes Binary data
 * @param encoding Encoding
 */
function textDecode(bytes, encoding = "utf-8") {
    switch (encoding.toLowerCase()) {
        case "utf-8":
        case "utf8":
            if (typeof globalThis.TextDecoder !== "undefined") {
                return new globalThis.TextDecoder("utf-8").decode(bytes);
            }
            return decodeUTF8(bytes);
        case "utf-16le":
            return decodeUTF16LE(bytes);
        case "ascii":
            return decodeASCII(bytes);
        case "latin1":
        case "iso-8859-1":
            return decodeLatin1(bytes);
        case "windows-1252":
            return decodeWindows1252(bytes);
        default:
            throw new RangeError(`Encoding '${encoding}' not supported`);
    }
}
// --- Internal helpers ---
function decodeUTF8(bytes) {
    let out = "";
    let i = 0;
    while (i < bytes.length) {
        const b1 = bytes[i++];
        if (b1 < 0x80) {
            out += String.fromCharCode(b1);
        }
        else if (b1 < 0xe0) {
            const b2 = bytes[i++] & 0x3f;
            out += String.fromCharCode(((b1 & 0x1f) << 6) | b2);
        }
        else if (b1 < 0xf0) {
            const b2 = bytes[i++] & 0x3f;
            const b3 = bytes[i++] & 0x3f;
            out += String.fromCharCode(((b1 & 0x0f) << 12) | (b2 << 6) | b3);
        }
        else {
            const b2 = bytes[i++] & 0x3f;
            const b3 = bytes[i++] & 0x3f;
            const b4 = bytes[i++] & 0x3f;
            let cp = ((b1 & 0x07) << 18) |
                (b2 << 12) |
                (b3 << 6) |
                b4;
            cp -= 0x10000;
            out += String.fromCharCode(0xd800 + ((cp >> 10) & 0x3ff), 0xdc00 + (cp & 0x3ff));
        }
    }
    return out;
}
function decodeUTF16LE(bytes) {
    let out = "";
    for (let i = 0; i < bytes.length; i += 2) {
        out += String.fromCharCode(bytes[i] | (bytes[i + 1] << 8));
    }
    return out;
}
function decodeASCII(bytes) {
    return String.fromCharCode(...bytes.map((b) => b & 0x7f));
}
function decodeLatin1(bytes) {
    return String.fromCharCode(...bytes);
}
function decodeWindows1252(bytes) {
    let out = "";
    for (const b of bytes) {
        if (b >= 0x80 && b <= 0x9f && WINDOWS_1252_EXTRA[b]) {
            out += WINDOWS_1252_EXTRA[b];
        }
        else {
            out += String.fromCharCode(b);
        }
    }
    return out;
}

// Primitive types
function dv(array) {
    return new DataView(array.buffer, array.byteOffset);
}
/*
 * 8-bit unsigned integer
 */
const UINT8 = {
    len: 1,
    get(array, offset) {
        return dv(array).getUint8(offset);
    },
    put(array, offset, value) {
        dv(array).setUint8(offset, value);
        return offset + 1;
    }
};
/**
 * 16-bit unsigned integer, Little Endian byte order
 */
const UINT16_LE = {
    len: 2,
    get(array, offset) {
        return dv(array).getUint16(offset, true);
    },
    put(array, offset, value) {
        dv(array).setUint16(offset, value, true);
        return offset + 2;
    }
};
/**
 * 16-bit unsigned integer, Big Endian byte order
 */
const UINT16_BE = {
    len: 2,
    get(array, offset) {
        return dv(array).getUint16(offset);
    },
    put(array, offset, value) {
        dv(array).setUint16(offset, value);
        return offset + 2;
    }
};
/**
 * 32-bit unsigned integer, Little Endian byte order
 */
const UINT32_LE = {
    len: 4,
    get(array, offset) {
        return dv(array).getUint32(offset, true);
    },
    put(array, offset, value) {
        dv(array).setUint32(offset, value, true);
        return offset + 4;
    }
};
/**
 * 32-bit unsigned integer, Big Endian byte order
 */
const UINT32_BE = {
    len: 4,
    get(array, offset) {
        return dv(array).getUint32(offset);
    },
    put(array, offset, value) {
        dv(array).setUint32(offset, value);
        return offset + 4;
    }
};
/**
 * 32-bit signed integer, Big Endian byte order
 */
const INT32_BE = {
    len: 4,
    get(array, offset) {
        return dv(array).getInt32(offset);
    },
    put(array, offset, value) {
        dv(array).setInt32(offset, value);
        return offset + 4;
    }
};
/**
 * 64-bit unsigned integer, Little Endian byte order
 */
const UINT64_LE = {
    len: 8,
    get(array, offset) {
        return dv(array).getBigUint64(offset, true);
    },
    put(array, offset, value) {
        dv(array).setBigUint64(offset, value, true);
        return offset + 8;
    }
};
/**
 * Consume a fixed number of bytes from the stream and return a string with a specified encoding.
 * Supports all encodings supported by TextDecoder, plus 'windows-1252'.
 */
class StringType {
    constructor(len, encoding) {
        this.len = len;
        this.encoding = encoding;
    }
    get(data, offset = 0) {
        const bytes = data.subarray(offset, offset + this.len);
        return textDecode(bytes, this.encoding);
    }
}

var require$1 = createRequire('/');
// DEFLATE is a complex format; to read this code, you should probably check the RFC first:
// https://tools.ietf.org/html/rfc1951
// You may also wish to take a look at the guide I made about this program:
// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad
// Some of the following code is similar to that of UZIP.js:
// https://github.com/photopea/UZIP.js
// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.
// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint
// is better for memory in most engines (I *think*).
// Mediocre shim
var Worker;
var workerAdd = ";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global";
try {
    Worker = require$1('worker_threads').Worker;
}
catch (e) {
}
var wk = Worker ? function (c, _, msg, transfer, cb) {
    var done = false;
    var w = new Worker(c + workerAdd, { eval: true })
        .on('error', function (e) { return cb(e, null); })
        .on('message', function (m) { return cb(null, m); })
        .on('exit', function (c) {
        if (c && !done)
            cb(new Error('exited with code ' + c), null);
    });
    w.postMessage(msg, transfer);
    w.terminate = function () {
        done = true;
        return Worker.prototype.terminate.call(w);
    };
    return w;
} : function (_, __, ___, ____, cb) {
    setImmediate(function () { return cb(new Error('async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)'), null); });
    var NOP = function () { };
    return {
        terminate: NOP,
        postMessage: NOP
    };
};

// aliases for shorter compressed code (most minifers don't do this)
var u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array;
// fixed length extra bits
var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);
// fixed distance extra bits
var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);
// code length index map
var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
// get base, reverse index map from extra bits
var freb = function (eb, start) {
    var b = new u16(31);
    for (var i = 0; i < 31; ++i) {
        b[i] = start += 1 << eb[i - 1];
    }
    // numbers here are at max 18 bits
    var r = new i32(b[30]);
    for (var i = 1; i < 30; ++i) {
        for (var j = b[i]; j < b[i + 1]; ++j) {
            r[j] = ((j - b[i]) << 5) | i;
        }
    }
    return { b: b, r: r };
};
var _a$y = freb(fleb, 2), fl = _a$y.b, revfl = _a$y.r;
// we can ignore the fact that the other numbers are wrong; they never happen anyway
fl[28] = 258, revfl[258] = 28;
var _b = freb(fdeb, 0), fd = _b.b;
// map of value to reverse (assuming 16 bits)
var rev = new u16(32768);
for (var i = 0; i < 32768; ++i) {
    // reverse table algorithm from SO
    var x$1 = ((i & 0xAAAA) >> 1) | ((i & 0x5555) << 1);
    x$1 = ((x$1 & 0xCCCC) >> 2) | ((x$1 & 0x3333) << 2);
    x$1 = ((x$1 & 0xF0F0) >> 4) | ((x$1 & 0x0F0F) << 4);
    rev[i] = (((x$1 & 0xFF00) >> 8) | ((x$1 & 0x00FF) << 8)) >> 1;
}
// create huffman tree from u8 "map": index -> code length for code index
// mb (max bits) must be at most 15
// TODO: optimize/split up?
var hMap = (function (cd, mb, r) {
    var s = cd.length;
    // index
    var i = 0;
    // u16 "map": index -> # of codes with bit length = index
    var l = new u16(mb);
    // length of cd must be 288 (total # of codes)
    for (; i < s; ++i) {
        if (cd[i])
            ++l[cd[i] - 1];
    }
    // u16 "map": index -> minimum code for bit length = index
    var le = new u16(mb);
    for (i = 1; i < mb; ++i) {
        le[i] = (le[i - 1] + l[i - 1]) << 1;
    }
    var co;
    if (r) {
        // u16 "map": index -> number of actual bits, symbol for code
        co = new u16(1 << mb);
        // bits to remove for reverser
        var rvb = 15 - mb;
        for (i = 0; i < s; ++i) {
            // ignore 0 lengths
            if (cd[i]) {
                // num encoding both symbol and bits read
                var sv = (i << 4) | cd[i];
                // free bits
                var r_1 = mb - cd[i];
                // start value
                var v = le[cd[i] - 1]++ << r_1;
                // m is end value
                for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {
                    // every 16 bit value starting with the code yields the same result
                    co[rev[v] >> rvb] = sv;
                }
            }
        }
    }
    else {
        co = new u16(s);
        for (i = 0; i < s; ++i) {
            if (cd[i]) {
                co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]);
            }
        }
    }
    return co;
});
// fixed length tree
var flt = new u8(288);
for (var i = 0; i < 144; ++i)
    flt[i] = 8;
for (var i = 144; i < 256; ++i)
    flt[i] = 9;
for (var i = 256; i < 280; ++i)
    flt[i] = 7;
for (var i = 280; i < 288; ++i)
    flt[i] = 8;
// fixed distance tree
var fdt = new u8(32);
for (var i = 0; i < 32; ++i)
    fdt[i] = 5;
// fixed length map
var flrm = /*#__PURE__*/ hMap(flt, 9, 1);
// fixed distance map
var fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);
// find max of array
var max$1 = function (a) {
    var m = a[0];
    for (var i = 1; i < a.length; ++i) {
        if (a[i] > m)
            m = a[i];
    }
    return m;
};
// read d, starting at bit p and mask with m
var bits = function (d, p, m) {
    var o = (p / 8) | 0;
    return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;
};
// read d, starting at bit p continuing for at least 16 bits
var bits16 = function (d, p) {
    var o = (p / 8) | 0;
    return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));
};
// get end of byte
var shft = function (p) { return ((p + 7) / 8) | 0; };
// typed array slice - allows garbage collector to free original reference,
// while being more compatible than .slice
var slc = function (v, s, e) {
    if (s == null || s < 0)
        s = 0;
    if (e == null || e > v.length)
        e = v.length;
    // can't use .constructor in case user-supplied
    return new u8(v.subarray(s, e));
};
// error codes
var ec = [
    'unexpected EOF',
    'invalid block type',
    'invalid length/literal',
    'invalid distance',
    'stream finished',
    'no stream handler',
    ,
    'no callback',
    'invalid UTF-8 data',
    'extra field too long',
    'date not in range 1980-2099',
    'filename too long',
    'stream finishing',
    'invalid zip data'
    // determined by unknown compression method
];
var err = function (ind, msg, nt) {
    var e = new Error(msg || ec[ind]);
    e.code = ind;
    if (Error.captureStackTrace)
        Error.captureStackTrace(e, err);
    if (!nt)
        throw e;
    return e;
};
// expands raw DEFLATE data
var inflt = function (dat, st, buf, dict) {
    // source length       dict length
    var sl = dat.length, dl = dict ? dict.length : 0;
    if (!sl || st.f && !st.l)
        return buf || new u8(0);
    var noBuf = !buf;
    // have to estimate size
    var resize = noBuf || st.i != 2;
    // no state
    var noSt = st.i;
    // Assumes roughly 33% compression ratio average
    if (noBuf)
        buf = new u8(sl * 3);
    // ensure buffer can fit at least l elements
    var cbuf = function (l) {
        var bl = buf.length;
        // need to increase size to fit
        if (l > bl) {
            // Double or set to necessary, whichever is greater
            var nbuf = new u8(Math.max(bl * 2, l));
            nbuf.set(buf);
            buf = nbuf;
        }
    };
    //  last chunk         bitpos           bytes
    var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
    // total bits
    var tbts = sl * 8;
    do {
        if (!lm) {
            // BFINAL - this is only 1 when last chunk is next
            final = bits(dat, pos, 1);
            // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman
            var type = bits(dat, pos + 1, 3);
            pos += 3;
            if (!type) {
                // go to end of byte boundary
                var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;
                if (t > sl) {
                    if (noSt)
                        err(0);
                    break;
                }
                // ensure size
                if (resize)
                    cbuf(bt + l);
                // Copy over uncompressed data
                buf.set(dat.subarray(s, t), bt);
                // Get new bitpos, update byte count
                st.b = bt += l, st.p = pos = t * 8, st.f = final;
                continue;
            }
            else if (type == 1)
                lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
            else if (type == 2) {
                //  literal                            lengths
                var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
                var tl = hLit + bits(dat, pos + 5, 31) + 1;
                pos += 14;
                // length+distance tree
                var ldt = new u8(tl);
                // code length tree
                var clt = new u8(19);
                for (var i = 0; i < hcLen; ++i) {
                    // use index map to get real code
                    clt[clim[i]] = bits(dat, pos + i * 3, 7);
                }
                pos += hcLen * 3;
                // code lengths bits
                var clb = max$1(clt), clbmsk = (1 << clb) - 1;
                // code lengths map
                var clm = hMap(clt, clb, 1);
                for (var i = 0; i < tl;) {
                    var r = clm[bits(dat, pos, clbmsk)];
                    // bits read
                    pos += r & 15;
                    // symbol
                    var s = r >> 4;
                    // code length to copy
                    if (s < 16) {
                        ldt[i++] = s;
                    }
                    else {
                        //  copy   count
                        var c = 0, n = 0;
                        if (s == 16)
                            n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
                        else if (s == 17)
                            n = 3 + bits(dat, pos, 7), pos += 3;
                        else if (s == 18)
                            n = 11 + bits(dat, pos, 127), pos += 7;
                        while (n--)
                            ldt[i++] = c;
                    }
                }
                //    length tree                 distance tree
                var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
                // max length bits
                lbt = max$1(lt);
                // max dist bits
                dbt = max$1(dt);
                lm = hMap(lt, lbt, 1);
                dm = hMap(dt, dbt, 1);
            }
            else
                err(1);
            if (pos > tbts) {
                if (noSt)
                    err(0);
                break;
            }
        }
        // Make sure the buffer can hold this + the largest possible addition
        // Maximum chunk size (practically, theoretically infinite) is 2^17
        if (resize)
            cbuf(bt + 131072);
        var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
        var lpos = pos;
        for (;; lpos = pos) {
            // bits read, code
            var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
            pos += c & 15;
            if (pos > tbts) {
                if (noSt)
                    err(0);
                break;
            }
            if (!c)
                err(2);
            if (sym < 256)
                buf[bt++] = sym;
            else if (sym == 256) {
                lpos = pos, lm = null;
                break;
            }
            else {
                var add = sym - 254;
                // no extra bits needed if less
                if (sym > 264) {
                    // index
                    var i = sym - 257, b = fleb[i];
                    add = bits(dat, pos, (1 << b) - 1) + fl[i];
                    pos += b;
                }
                // dist
                var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
                if (!d)
                    err(3);
                pos += d & 15;
                var dt = fd[dsym];
                if (dsym > 3) {
                    var b = fdeb[dsym];
                    dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
                }
                if (pos > tbts) {
                    if (noSt)
                        err(0);
                    break;
                }
                if (resize)
                    cbuf(bt + 131072);
                var end = bt + add;
                if (bt < dt) {
                    var shift = dl - dt, dend = Math.min(dt, end);
                    if (shift + bt < 0)
                        err(3);
                    for (; bt < dend; ++bt)
                        buf[bt] = dict[shift + bt];
                }
                for (; bt < end; ++bt)
                    buf[bt] = buf[bt - dt];
            }
        }
        st.l = lm, st.p = lpos, st.b = bt, st.f = final;
        if (lm)
            final = 1, st.m = lbt, st.d = dm, st.n = dbt;
    } while (!final);
    // don't reallocate for streams or user buffers
    return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
};
// empty
var et = /*#__PURE__*/ new u8(0);
// Walmart object spread
var mrg = function (a, b) {
    var o = {};
    for (var k in a)
        o[k] = a[k];
    for (var k in b)
        o[k] = b[k];
    return o;
};
// worker clone
// This is possibly the craziest part of the entire codebase, despite how simple it may seem.
// The only parameter to this function is a closure that returns an array of variables outside of the function scope.
// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.
// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).
// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.
// This took me three weeks to figure out how to do.
var wcln = function (fn, fnStr, td) {
    var dt = fn();
    var st = fn.toString();
    var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\s+/g, '').split(',');
    for (var i = 0; i < dt.length; ++i) {
        var v = dt[i], k = ks[i];
        if (typeof v == 'function') {
            fnStr += ';' + k + '=';
            var st_1 = v.toString();
            if (v.prototype) {
                // for global objects
                if (st_1.indexOf('[native code]') != -1) {
                    var spInd = st_1.indexOf(' ', 8) + 1;
                    fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));
                }
                else {
                    fnStr += st_1;
                    for (var t in v.prototype)
                        fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();
                }
            }
            else
                fnStr += st_1;
        }
        else
            td[k] = v;
    }
    return fnStr;
};
var ch = [];
// clone bufs
var cbfs = function (v) {
    var tl = [];
    for (var k in v) {
        if (v[k].buffer) {
            tl.push((v[k] = new v[k].constructor(v[k])).buffer);
        }
    }
    return tl;
};
// use a worker to execute code
var wrkr = function (fns, init, id, cb) {
    if (!ch[id]) {
        var fnStr = '', td_1 = {}, m = fns.length - 1;
        for (var i = 0; i < m; ++i)
            fnStr = wcln(fns[i], fnStr, td_1);
        ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 };
    }
    var td = mrg({}, ch[id].e);
    return wk(ch[id].c + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);
};
// base async inflate fn
var bInflt = function () { return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max$1, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt]; };
// gunzip extra
var guze = function () { return [gzs, gzl]; };
// post buf
var pbf = function (msg) { return postMessage(msg, [msg.buffer]); };
// get opts
var gopt = function (o) { return o && {
    out: o.size && new u8(o.size),
    dictionary: o.dictionary
}; };
// auto stream
var astrm = function (strm) {
    strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };
    return function (ev) {
        if (ev.data.length) {
            strm.push(ev.data[0], ev.data[1]);
            postMessage([ev.data[0].length]);
        }
        else
            strm.flush();
    };
};
// async stream attach
var astrmify = function (fns, strm, opts, init, id, flush, ext) {
    var t;
    var w = wrkr(fns, init, id, function (err, dat) {
        if (err)
            w.terminate(), strm.ondata.call(strm, err);
        else if (!Array.isArray(dat))
            ext(dat);
        else if (dat.length == 1) {
            strm.queuedSize -= dat[0];
            if (strm.ondrain)
                strm.ondrain(dat[0]);
        }
        else {
            if (dat[1])
                w.terminate();
            strm.ondata.call(strm, err, dat[0], dat[1]);
        }
    });
    w.postMessage(opts);
    strm.queuedSize = 0;
    strm.push = function (d, f) {
        if (!strm.ondata)
            err(5);
        if (t)
            strm.ondata(err(4, 0, 1), null, !!f);
        strm.queuedSize += d.length;
        w.postMessage([d, t = f], [d.buffer]);
    };
    strm.terminate = function () { w.terminate(); };
};
// gzip footer: -8 to -4 = CRC, -4 to -0 is length
// gzip start
var gzs = function (d) {
    if (d[0] != 31 || d[1] != 139 || d[2] != 8)
        err(6, 'invalid gzip data');
    var flg = d[3];
    var st = 10;
    if (flg & 4)
        st += (d[10] | d[11] << 8) + 2;
    for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])
        ;
    return st + (flg & 2);
};
// gzip length
var gzl = function (d) {
    var l = d.length;
    return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0;
};
// zlib start
var zls = function (d, dict) {
    if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31))
        err(6, 'invalid zlib data');
    if ((d[1] >> 5 & 1) == 1)
        err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary');
    return (d[1] >> 3 & 4) + 2;
};
function StrmOpt(opts, cb) {
    if (typeof opts == 'function')
        cb = opts, opts = {};
    this.ondata = cb;
    return opts;
}
/**
 * Streaming DEFLATE decompression
 */
var Inflate = /*#__PURE__*/ (function () {
    function Inflate(opts, cb) {
        // no StrmOpt here to avoid adding to workerizer
        if (typeof opts == 'function')
            cb = opts, opts = {};
        this.ondata = cb;
        var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768);
        this.s = { i: 0, b: dict ? dict.length : 0 };
        this.o = new u8(32768);
        this.p = new u8(0);
        if (dict)
            this.o.set(dict);
    }
    Inflate.prototype.e = function (c) {
        if (!this.ondata)
            err(5);
        if (this.d)
            err(4);
        if (!this.p.length)
            this.p = c;
        else if (c.length) {
            var n = new u8(this.p.length + c.length);
            n.set(this.p), n.set(c, this.p.length), this.p = n;
        }
    };
    Inflate.prototype.c = function (final) {
        this.s.i = +(this.d = final || false);
        var bts = this.s.b;
        var dt = inflt(this.p, this.s, this.o);
        this.ondata(slc(dt, bts, this.s.b), this.d);
        this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;
        this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;
    };
    /**
     * Pushes a chunk to be inflated
     * @param chunk The chunk to push
     * @param final Whether this is the final chunk
     */
    Inflate.prototype.push = function (chunk, final) {
        this.e(chunk), this.c(final);
    };
    return Inflate;
}());
/**
 * Expands DEFLATE data with no wrapper
 * @param data The data to decompress
 * @param opts The decompression options
 * @returns The decompressed version of the data
 */
function inflateSync(data, opts) {
    return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
}
/**
 * Streaming single or multi-member GZIP decompression
 */
var Gunzip = /*#__PURE__*/ (function () {
    function Gunzip(opts, cb) {
        this.v = 1;
        this.r = 0;
        Inflate.call(this, opts, cb);
    }
    /**
     * Pushes a chunk to be GUNZIPped
     * @param chunk The chunk to push
     * @param final Whether this is the last chunk
     */
    Gunzip.prototype.push = function (chunk, final) {
        Inflate.prototype.e.call(this, chunk);
        this.r += chunk.length;
        if (this.v) {
            var p = this.p.subarray(this.v - 1);
            var s = p.length > 3 ? gzs(p) : 4;
            if (s > p.length) {
                if (!final)
                    return;
            }
            else if (this.v > 1 && this.onmember) {
                this.onmember(this.r - p.length);
            }
            this.p = p.subarray(s), this.v = 0;
        }
        // necessary to prevent TS from using the closure value
        // This allows for workerization to function correctly
        Inflate.prototype.c.call(this, final);
        // process concatenated GZIP
        if (this.s.f && !this.s.l && !final) {
            this.v = shft(this.s.p) + 9;
            this.s = { i: 0 };
            this.o = new u8(0);
            this.push(new u8(0), final);
        }
    };
    return Gunzip;
}());
/**
 * Asynchronous streaming single or multi-member GZIP decompression
 */
var AsyncGunzip = /*#__PURE__*/ (function () {
    function AsyncGunzip(opts, cb) {
        var _this = this;
        astrmify([
            bInflt,
            guze,
            function () { return [astrm, Inflate, Gunzip]; }
        ], this, StrmOpt.call(this, opts, cb), function (ev) {
            var strm = new Gunzip(ev.data);
            strm.onmember = function (offset) { return postMessage(offset); };
            onmessage = astrm(strm);
        }, 9, 0, function (offset) { return _this.onmember && _this.onmember(offset); });
    }
    return AsyncGunzip;
}());
/**
 * Expands GZIP data
 * @param data The data to decompress
 * @param opts The decompression options
 * @returns The decompressed version of the data
 */
function gunzipSync(data, opts) {
    var st = gzs(data);
    if (st + 8 > data.length)
        err(6, 'invalid gzip data');
    return inflt(data.subarray(st, -8), { i: 2 }, new u8(gzl(data)), opts);
}
/**
 * Expands Zlib data
 * @param data The data to decompress
 * @param opts The decompression options
 * @returns The decompressed version of the data
 */
function unzlibSync(data, opts) {
    return inflt(data.subarray(zls(data), -4), { i: 2 }, opts, opts);
}
/**
 * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format
 * @param data The data to decompress
 * @param opts The decompression options
 * @returns The decompressed version of the data
 */
function decompressSync(data, opts) {
    return (data[0] == 31 && data[1] == 139 && data[2] == 8)
        ? gunzipSync(data, opts)
        : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))
            ? inflateSync(data, opts)
            : unzlibSync(data, opts);
}
// text decoder
var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();
// text decoder stream
var tds = 0;
try {
    td.decode(et, { stream: true });
    tds = 1;
}
catch (e) { }

var browser$5 = {exports: {}};

/**
 * Helpers.
 */

var ms$1;
var hasRequiredMs$2;

function requireMs$2 () {
	if (hasRequiredMs$2) return ms$1;
	hasRequiredMs$2 = 1;
	var s = 1000;
	var m = s * 60;
	var h = m * 60;
	var d = h * 24;
	var w = d * 7;
	var y = d * 365.25;

	/**
	 * Parse or format the given `val`.
	 *
	 * Options:
	 *
	 *  - `long` verbose formatting [false]
	 *
	 * @param {String|Number} val
	 * @param {Object} [options]
	 * @throws {Error} throw an error if val is not a non-empty string or a number
	 * @return {String|Number}
	 * @api public
	 */

	ms$1 = function (val, options) {
	  options = options || {};
	  var type = typeof val;
	  if (type === 'string' && val.length > 0) {
	    return parse(val);
	  } else if (type === 'number' && isFinite(val)) {
	    return options.long ? fmtLong(val) : fmtShort(val);
	  }
	  throw new Error(
	    'val is not a non-empty string or a valid number. val=' +
	      JSON.stringify(val)
	  );
	};

	/**
	 * Parse the given `str` and return milliseconds.
	 *
	 * @param {String} str
	 * @return {Number}
	 * @api private
	 */

	function parse(str) {
	  str = String(str);
	  if (str.length > 100) {
	    return;
	  }
	  var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
	    str
	  );
	  if (!match) {
	    return;
	  }
	  var n = parseFloat(match[1]);
	  var type = (match[2] || 'ms').toLowerCase();
	  switch (type) {
	    case 'years':
	    case 'year':
	    case 'yrs':
	    case 'yr':
	    case 'y':
	      return n * y;
	    case 'weeks':
	    case 'week':
	    case 'w':
	      return n * w;
	    case 'days':
	    case 'day':
	    case 'd':
	      return n * d;
	    case 'hours':
	    case 'hour':
	    case 'hrs':
	    case 'hr':
	    case 'h':
	      return n * h;
	    case 'minutes':
	    case 'minute':
	    case 'mins':
	    case 'min':
	    case 'm':
	      return n * m;
	    case 'seconds':
	    case 'second':
	    case 'secs':
	    case 'sec':
	    case 's':
	      return n * s;
	    case 'milliseconds':
	    case 'millisecond':
	    case 'msecs':
	    case 'msec':
	    case 'ms':
	      return n;
	    default:
	      return undefined;
	  }
	}

	/**
	 * Short format for `ms`.
	 *
	 * @param {Number} ms
	 * @return {String}
	 * @api private
	 */

	function fmtShort(ms) {
	  var msAbs = Math.abs(ms);
	  if (msAbs >= d) {
	    return Math.round(ms / d) + 'd';
	  }
	  if (msAbs >= h) {
	    return Math.round(ms / h) + 'h';
	  }
	  if (msAbs >= m) {
	    return Math.round(ms / m) + 'm';
	  }
	  if (msAbs >= s) {
	    return Math.round(ms / s) + 's';
	  }
	  return ms + 'ms';
	}

	/**
	 * Long format for `ms`.
	 *
	 * @param {Number} ms
	 * @return {String}
	 * @api private
	 */

	function fmtLong(ms) {
	  var msAbs = Math.abs(ms);
	  if (msAbs >= d) {
	    return plural(ms, msAbs, d, 'day');
	  }
	  if (msAbs >= h) {
	    return plural(ms, msAbs, h, 'hour');
	  }
	  if (msAbs >= m) {
	    return plural(ms, msAbs, m, 'minute');
	  }
	  if (msAbs >= s) {
	    return plural(ms, msAbs, s, 'second');
	  }
	  return ms + ' ms';
	}

	/**
	 * Pluralization helper.
	 */

	function plural(ms, msAbs, n, name) {
	  var isPlural = msAbs >= n * 1.5;
	  return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
	}
	return ms$1;
}

var common$1;
var hasRequiredCommon$1;

function requireCommon$1 () {
	if (hasRequiredCommon$1) return common$1;
	hasRequiredCommon$1 = 1;
	/**
	 * This is the common logic for both the Node.js and web browser
	 * implementations of `debug()`.
	 */

	function setup(env) {
		createDebug.debug = createDebug;
		createDebug.default = createDebug;
		createDebug.coerce = coerce;
		createDebug.disable = disable;
		createDebug.enable = enable;
		createDebug.enabled = enabled;
		createDebug.humanize = requireMs$2();
		createDebug.destroy = destroy;

		Object.keys(env).forEach(key => {
			createDebug[key] = env[key];
		});

		/**
		* The currently active debug mode names, and names to skip.
		*/

		createDebug.names = [];
		createDebug.skips = [];

		/**
		* Map of special "%n" handling functions, for the debug "format" argument.
		*
		* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
		*/
		createDebug.formatters = {};

		/**
		* Selects a color for a debug namespace
		* @param {String} namespace The namespace string for the debug instance to be colored
		* @return {Number|String} An ANSI color code for the given namespace
		* @api private
		*/
		function selectColor(namespace) {
			let hash = 0;

			for (let i = 0; i < namespace.length; i++) {
				hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
				hash |= 0; // Convert to 32bit integer
			}

			return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
		}
		createDebug.selectColor = selectColor;

		/**
		* Create a debugger with the given `namespace`.
		*
		* @param {String} namespace
		* @return {Function}
		* @api public
		*/
		function createDebug(namespace) {
			let prevTime;
			let enableOverride = null;
			let namespacesCache;
			let enabledCache;

			function debug(...args) {
				// Disabled?
				if (!debug.enabled) {
					return;
				}

				const self = debug;

				// Set `diff` timestamp
				const curr = Number(new Date());
				const ms = curr - (prevTime || curr);
				self.diff = ms;
				self.prev = prevTime;
				self.curr = curr;
				prevTime = curr;

				args[0] = createDebug.coerce(args[0]);

				if (typeof args[0] !== 'string') {
					// Anything else let's inspect with %O
					args.unshift('%O');
				}

				// Apply any `formatters` transformations
				let index = 0;
				args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
					// If we encounter an escaped % then don't increase the array index
					if (match === '%%') {
						return '%';
					}
					index++;
					const formatter = createDebug.formatters[format];
					if (typeof formatter === 'function') {
						const val = args[index];
						match = formatter.call(self, val);

						// Now we need to remove `args[index]` since it's inlined in the `format`
						args.splice(index, 1);
						index--;
					}
					return match;
				});

				// Apply env-specific formatting (colors, etc.)
				createDebug.formatArgs.call(self, args);

				const logFn = self.log || createDebug.log;
				logFn.apply(self, args);
			}

			debug.namespace = namespace;
			debug.useColors = createDebug.useColors();
			debug.color = createDebug.selectColor(namespace);
			debug.extend = extend;
			debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.

			Object.defineProperty(debug, 'enabled', {
				enumerable: true,
				configurable: false,
				get: () => {
					if (enableOverride !== null) {
						return enableOverride;
					}
					if (namespacesCache !== createDebug.namespaces) {
						namespacesCache = createDebug.namespaces;
						enabledCache = createDebug.enabled(namespace);
					}

					return enabledCache;
				},
				set: v => {
					enableOverride = v;
				}
			});

			// Env-specific initialization logic for debug instances
			if (typeof createDebug.init === 'function') {
				createDebug.init(debug);
			}

			return debug;
		}

		function extend(namespace, delimiter) {
			const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
			newDebug.log = this.log;
			return newDebug;
		}

		/**
		* Enables a debug mode by namespaces. This can include modes
		* separated by a colon and wildcards.
		*
		* @param {String} namespaces
		* @api public
		*/
		function enable(namespaces) {
			createDebug.save(namespaces);
			createDebug.namespaces = namespaces;

			createDebug.names = [];
			createDebug.skips = [];

			const split = (typeof namespaces === 'string' ? namespaces : '')
				.trim()
				.replace(/\s+/g, ',')
				.split(',')
				.filter(Boolean);

			for (const ns of split) {
				if (ns[0] === '-') {
					createDebug.skips.push(ns.slice(1));
				} else {
					createDebug.names.push(ns);
				}
			}
		}

		/**
		 * Checks if the given string matches a namespace template, honoring
		 * asterisks as wildcards.
		 *
		 * @param {String} search
		 * @param {String} template
		 * @return {Boolean}
		 */
		function matchesTemplate(search, template) {
			let searchIndex = 0;
			let templateIndex = 0;
			let starIndex = -1;
			let matchIndex = 0;

			while (searchIndex < search.length) {
				if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {
					// Match character or proceed with wildcard
					if (template[templateIndex] === '*') {
						starIndex = templateIndex;
						matchIndex = searchIndex;
						templateIndex++; // Skip the '*'
					} else {
						searchIndex++;
						templateIndex++;
					}
				} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition
					// Backtrack to the last '*' and try to match more characters
					templateIndex = starIndex + 1;
					matchIndex++;
					searchIndex = matchIndex;
				} else {
					return false; // No match
				}
			}

			// Handle trailing '*' in template
			while (templateIndex < template.length && template[templateIndex] === '*') {
				templateIndex++;
			}

			return templateIndex === template.length;
		}

		/**
		* Disable debug output.
		*
		* @return {String} namespaces
		* @api public
		*/
		function disable() {
			const namespaces = [
				...createDebug.names,
				...createDebug.skips.map(namespace => '-' + namespace)
			].join(',');
			createDebug.enable('');
			return namespaces;
		}

		/**
		* Returns true if the given mode name is enabled, false otherwise.
		*
		* @param {String} name
		* @return {Boolean}
		* @api public
		*/
		function enabled(name) {
			for (const skip of createDebug.skips) {
				if (matchesTemplate(name, skip)) {
					return false;
				}
			}

			for (const ns of createDebug.names) {
				if (matchesTemplate(name, ns)) {
					return true;
				}
			}

			return false;
		}

		/**
		* Coerce `val`.
		*
		* @param {Mixed} val
		* @return {Mixed}
		* @api private
		*/
		function coerce(val) {
			if (val instanceof Error) {
				return val.stack || val.message;
			}
			return val;
		}

		/**
		* XXX DO NOT USE. This is a temporary stub function.
		* XXX It WILL be removed in the next major release.
		*/
		function destroy() {
			console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
		}

		createDebug.enable(createDebug.load());

		return createDebug;
	}

	common$1 = setup;
	return common$1;
}

/* eslint-env browser */

var hasRequiredBrowser$5;

function requireBrowser$5 () {
	if (hasRequiredBrowser$5) return browser$5.exports;
	hasRequiredBrowser$5 = 1;
	(function (module, exports$1) {
		/**
		 * This is the web browser implementation of `debug()`.
		 */

		exports$1.formatArgs = formatArgs;
		exports$1.save = save;
		exports$1.load = load;
		exports$1.useColors = useColors;
		exports$1.storage = localstorage();
		exports$1.destroy = (() => {
			let warned = false;

			return () => {
				if (!warned) {
					warned = true;
					console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
				}
			};
		})();

		/**
		 * Colors.
		 */

		exports$1.colors = [
			'#0000CC',
			'#0000FF',
			'#0033CC',
			'#0033FF',
			'#0066CC',
			'#0066FF',
			'#0099CC',
			'#0099FF',
			'#00CC00',
			'#00CC33',
			'#00CC66',
			'#00CC99',
			'#00CCCC',
			'#00CCFF',
			'#3300CC',
			'#3300FF',
			'#3333CC',
			'#3333FF',
			'#3366CC',
			'#3366FF',
			'#3399CC',
			'#3399FF',
			'#33CC00',
			'#33CC33',
			'#33CC66',
			'#33CC99',
			'#33CCCC',
			'#33CCFF',
			'#6600CC',
			'#6600FF',
			'#6633CC',
			'#6633FF',
			'#66CC00',
			'#66CC33',
			'#9900CC',
			'#9900FF',
			'#9933CC',
			'#9933FF',
			'#99CC00',
			'#99CC33',
			'#CC0000',
			'#CC0033',
			'#CC0066',
			'#CC0099',
			'#CC00CC',
			'#CC00FF',
			'#CC3300',
			'#CC3333',
			'#CC3366',
			'#CC3399',
			'#CC33CC',
			'#CC33FF',
			'#CC6600',
			'#CC6633',
			'#CC9900',
			'#CC9933',
			'#CCCC00',
			'#CCCC33',
			'#FF0000',
			'#FF0033',
			'#FF0066',
			'#FF0099',
			'#FF00CC',
			'#FF00FF',
			'#FF3300',
			'#FF3333',
			'#FF3366',
			'#FF3399',
			'#FF33CC',
			'#FF33FF',
			'#FF6600',
			'#FF6633',
			'#FF9900',
			'#FF9933',
			'#FFCC00',
			'#FFCC33'
		];

		/**
		 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
		 * and the Firebug extension (any Firefox version) are known
		 * to support "%c" CSS customizations.
		 *
		 * TODO: add a `localStorage` variable to explicitly enable/disable colors
		 */

		// eslint-disable-next-line complexity
		function useColors() {
			// NB: In an Electron preload script, document will be defined but not fully
			// initialized. Since we know we're in Chrome, we'll just detect this case
			// explicitly
			if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
				return true;
			}

			// Internet Explorer and Edge do not support colors.
			if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
				return false;
			}

			let m;

			// Is webkit? http://stackoverflow.com/a/16459606/376773
			// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
			// eslint-disable-next-line no-return-assign
			return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
				// Is firebug? http://stackoverflow.com/a/398120/376773
				(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
				// Is firefox >= v31?
				// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
				(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) ||
				// Double check webkit in userAgent just in case we are in a worker
				(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
		}

		/**
		 * Colorize log arguments if enabled.
		 *
		 * @api public
		 */

		function formatArgs(args) {
			args[0] = (this.useColors ? '%c' : '') +
				this.namespace +
				(this.useColors ? ' %c' : ' ') +
				args[0] +
				(this.useColors ? '%c ' : ' ') +
				'+' + module.exports.humanize(this.diff);

			if (!this.useColors) {
				return;
			}

			const c = 'color: ' + this.color;
			args.splice(1, 0, c, 'color: inherit');

			// The final "%c" is somewhat tricky, because there could be other
			// arguments passed either before or after the %c, so we need to
			// figure out the correct index to insert the CSS into
			let index = 0;
			let lastC = 0;
			args[0].replace(/%[a-zA-Z%]/g, match => {
				if (match === '%%') {
					return;
				}
				index++;
				if (match === '%c') {
					// We only are interested in the *last* %c
					// (the user may have provided their own)
					lastC = index;
				}
			});

			args.splice(lastC, 0, c);
		}

		/**
		 * Invokes `console.debug()` when available.
		 * No-op when `console.debug` is not a "function".
		 * If `console.debug` is not available, falls back
		 * to `console.log`.
		 *
		 * @api public
		 */
		exports$1.log = console.debug || console.log || (() => {});

		/**
		 * Save `namespaces`.
		 *
		 * @param {String} namespaces
		 * @api private
		 */
		function save(namespaces) {
			try {
				if (namespaces) {
					exports$1.storage.setItem('debug', namespaces);
				} else {
					exports$1.storage.removeItem('debug');
				}
			} catch (error) {
				// Swallow
				// XXX (@Qix-) should we be logging these?
			}
		}

		/**
		 * Load `namespaces`.
		 *
		 * @return {String} returns the previously persisted debug modes
		 * @api private
		 */
		function load() {
			let r;
			try {
				r = exports$1.storage.getItem('debug') || exports$1.storage.getItem('DEBUG') ;
			} catch (error) {
				// Swallow
				// XXX (@Qix-) should we be logging these?
			}

			// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
			if (!r && typeof process !== 'undefined' && 'env' in process) {
				r = process.env.DEBUG;
			}

			return r;
		}

		/**
		 * Localstorage attempts to return the localstorage.
		 *
		 * This is necessary because safari throws
		 * when a user disables cookies/localstorage
		 * and you attempt to access it.
		 *
		 * @return {LocalStorage}
		 * @api private
		 */

		function localstorage() {
			try {
				// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
				// The Browser also has localStorage in the global context.
				return localStorage;
			} catch (error) {
				// Swallow
				// XXX (@Qix-) should we be logging these?
			}
		}

		module.exports = requireCommon$1()(exports$1);

		const {formatters} = module.exports;

		/**
		 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
		 */

		formatters.j = function (v) {
			try {
				return JSON.stringify(v);
			} catch (error) {
				return '[UnexpectedJSONParseError]: ' + error.message;
			}
		}; 
	} (browser$5, browser$5.exports));
	return browser$5.exports;
}

var browserExports = requireBrowser$5();
const initDebug = /*@__PURE__*/getDefaultExportFromCjs(browserExports);

/**
 * Ref https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
 */
const Signature = {
    LocalFileHeader: 0x04034b50,
    DataDescriptor: 0x08074b50,
    CentralFileHeader: 0x02014b50,
    EndOfCentralDirectory: 0x06054b50
};
const DataDescriptor = {
    get(array) {
        return {
            signature: UINT32_LE.get(array, 0),
            compressedSize: UINT32_LE.get(array, 8),
            uncompressedSize: UINT32_LE.get(array, 12),
        };
    }, len: 16
};
/**
 * First part of the ZIP Local File Header
 * Offset | Bytes| Description
 * -------|------+-------------------------------------------------------------------
 *      0 |    4 | Signature (0x04034b50)
 *      4 |    2 | Minimum version needed to extract
 *      6 |    2 | Bit flag
 *      8 |    2 | Compression method
 *     10 |    2 | File last modification time (MS-DOS format)
 *     12 |    2 | File last modification date (MS-DOS format)
 *     14 |    4 | CRC-32 of uncompressed data
 *     18 |    4 | Compressed size
 *     22 |    4 | Uncompressed size
 *     26 |    2 | File name length (n)
 *     28 |    2 | Extra field length (m)
 *     30 |    n | File name
 * 30 + n |    m | Extra field
 */
const LocalFileHeaderToken = {
    get(array) {
        const flags = UINT16_LE.get(array, 6);
        return {
            signature: UINT32_LE.get(array, 0),
            minVersion: UINT16_LE.get(array, 4),
            dataDescriptor: !!(flags & 0x0008),
            compressedMethod: UINT16_LE.get(array, 8),
            compressedSize: UINT32_LE.get(array, 18),
            uncompressedSize: UINT32_LE.get(array, 22),
            filenameLength: UINT16_LE.get(array, 26),
            extraFieldLength: UINT16_LE.get(array, 28),
            filename: null
        };
    }, len: 30
};
/**
 * 4.3.16  End of central directory record:
 *  end of central dir signature (0x06064b50)                                      4 bytes
 *  number of this disk                                                            2 bytes
 *  number of the disk with the start of the central directory                     2 bytes
 *  total number of entries in the central directory on this disk                  2 bytes
 *  total number of entries in the size of the central directory                   2 bytes
 *  sizeOfTheCentralDirectory                                                      4 bytes
 *  offset of start of central directory with respect to the starting disk number  4 bytes
 *  .ZIP file comment length                                                       2 bytes
 *  .ZIP file comment       (variable size)
 */
const EndOfCentralDirectoryRecordToken = {
    get(array) {
        return {
            signature: UINT32_LE.get(array, 0),
            nrOfThisDisk: UINT16_LE.get(array, 4),
            nrOfThisDiskWithTheStart: UINT16_LE.get(array, 6),
            nrOfEntriesOnThisDisk: UINT16_LE.get(array, 8),
            nrOfEntriesOfSize: UINT16_LE.get(array, 10),
            sizeOfCd: UINT32_LE.get(array, 12),
            offsetOfStartOfCd: UINT32_LE.get(array, 16),
            zipFileCommentLength: UINT16_LE.get(array, 20),
        };
    }, len: 22
};
/**
 * File header:
 *    central file header signature   4 bytes   0 (0x02014b50)
 *    version made by                 2 bytes   4
 *    version needed to extract       2 bytes   6
 *    general purpose bit flag        2 bytes   8
 *    compression method              2 bytes  10
 *    last mod file time              2 bytes  12
 *    last mod file date              2 bytes  14
 *    crc-32                          4 bytes  16
 *    compressed size                 4 bytes  20
 *    uncompressed size               4 bytes  24
 *    file name length                2 bytes  28
 *    extra field length              2 bytes  30
 *    file comment length             2 bytes  32
 *    disk number start               2 bytes  34
 *    internal file attributes        2 bytes  36
 *    external file attributes        4 bytes  38
 *    relative offset of local header 4 bytes  42
 */
const FileHeader = {
    get(array) {
        const flags = UINT16_LE.get(array, 8);
        return {
            signature: UINT32_LE.get(array, 0),
            minVersion: UINT16_LE.get(array, 6),
            dataDescriptor: !!(flags & 0x0008),
            compressedMethod: UINT16_LE.get(array, 10),
            compressedSize: UINT32_LE.get(array, 20),
            uncompressedSize: UINT32_LE.get(array, 24),
            filenameLength: UINT16_LE.get(array, 28),
            extraFieldLength: UINT16_LE.get(array, 30),
            fileCommentLength: UINT16_LE.get(array, 32),
            relativeOffsetOfLocalHeader: UINT32_LE.get(array, 42),
            filename: null
        };
    }, len: 46
};

function signatureToArray(signature) {
    const signatureBytes = new Uint8Array(UINT32_LE.len);
    UINT32_LE.put(signatureBytes, 0, signature);
    return signatureBytes;
}
const debug$1 = initDebug('tokenizer:inflate');
const syncBufferSize = 256 * 1024;
const ddSignatureArray = signatureToArray(Signature.DataDescriptor);
const eocdSignatureBytes = signatureToArray(Signature.EndOfCentralDirectory);
class ZipHandler {
    constructor(tokenizer) {
        this.tokenizer = tokenizer;
        this.syncBuffer = new Uint8Array(syncBufferSize);
    }
    async isZip() {
        return await this.peekSignature() === Signature.LocalFileHeader;
    }
    peekSignature() {
        return this.tokenizer.peekToken(UINT32_LE);
    }
    async findEndOfCentralDirectoryLocator() {
        const randomReadTokenizer = this.tokenizer;
        const chunkLength = Math.min(16 * 1024, randomReadTokenizer.fileInfo.size);
        const buffer = this.syncBuffer.subarray(0, chunkLength);
        await this.tokenizer.readBuffer(buffer, { position: randomReadTokenizer.fileInfo.size - chunkLength });
        // Search the buffer from end to beginning for EOCD signature
        // const signature = 0x06054b50;
        for (let i = buffer.length - 4; i >= 0; i--) {
            // Compare 4 bytes directly without calling readUInt32LE
            if (buffer[i] === eocdSignatureBytes[0] &&
                buffer[i + 1] === eocdSignatureBytes[1] &&
                buffer[i + 2] === eocdSignatureBytes[2] &&
                buffer[i + 3] === eocdSignatureBytes[3]) {
                return randomReadTokenizer.fileInfo.size - chunkLength + i;
            }
        }
        return -1;
    }
    async readCentralDirectory() {
        if (!this.tokenizer.supportsRandomAccess()) {
            debug$1('Cannot reading central-directory without random-read support');
            return;
        }
        debug$1('Reading central-directory...');
        const pos = this.tokenizer.position;
        const offset = await this.findEndOfCentralDirectoryLocator();
        if (offset > 0) {
            debug$1('Central-directory 32-bit signature found');
            const eocdHeader = await this.tokenizer.readToken(EndOfCentralDirectoryRecordToken, offset);
            const files = [];
            this.tokenizer.setPosition(eocdHeader.offsetOfStartOfCd);
            for (let n = 0; n < eocdHeader.nrOfEntriesOfSize; ++n) {
                const entry = await this.tokenizer.readToken(FileHeader);
                if (entry.signature !== Signature.CentralFileHeader) {
                    throw new Error('Expected Central-File-Header signature');
                }
                entry.filename = await this.tokenizer.readToken(new StringType(entry.filenameLength, 'utf-8'));
                await this.tokenizer.ignore(entry.extraFieldLength);
                await this.tokenizer.ignore(entry.fileCommentLength);
                files.push(entry);
                debug$1(`Add central-directory file-entry: n=${n + 1}/${files.length}: filename=${files[n].filename}`);
            }
            this.tokenizer.setPosition(pos);
            return files;
        }
        this.tokenizer.setPosition(pos);
    }
    async unzip(fileCb) {
        const entries = await this.readCentralDirectory();
        if (entries) {
            // Use Central Directory to iterate over files
            return this.iterateOverCentralDirectory(entries, fileCb);
        }
        // Scan Zip files for local-file-header
        let stop = false;
        do {
            const zipHeader = await this.readLocalFileHeader();
            if (!zipHeader)
                break;
            const next = fileCb(zipHeader);
            stop = !!next.stop;
            let fileData = undefined;
            await this.tokenizer.ignore(zipHeader.extraFieldLength);
            if (zipHeader.dataDescriptor && zipHeader.compressedSize === 0) {
                const chunks = [];
                let len = syncBufferSize;
                debug$1('Compressed-file-size unknown, scanning for next data-descriptor-signature....');
                let nextHeaderIndex = -1;
                while (nextHeaderIndex < 0 && len === syncBufferSize) {
                    len = await this.tokenizer.peekBuffer(this.syncBuffer, { mayBeLess: true });
                    nextHeaderIndex = indexOf(this.syncBuffer.subarray(0, len), ddSignatureArray);
                    const size = nextHeaderIndex >= 0 ? nextHeaderIndex : len;
                    if (next.handler) {
                        const data = new Uint8Array(size);
                        await this.tokenizer.readBuffer(data);
                        chunks.push(data);
                    }
                    else {
                        // Move position to the next header if found, skip the whole buffer otherwise
                        await this.tokenizer.ignore(size);
                    }
                }
                debug$1(`Found data-descriptor-signature at pos=${this.tokenizer.position}`);
                if (next.handler) {
                    await this.inflate(zipHeader, mergeArrays(chunks), next.handler);
                }
            }
            else {
                if (next.handler) {
                    debug$1(`Reading compressed-file-data: ${zipHeader.compressedSize} bytes`);
                    fileData = new Uint8Array(zipHeader.compressedSize);
                    await this.tokenizer.readBuffer(fileData);
                    await this.inflate(zipHeader, fileData, next.handler);
                }
                else {
                    debug$1(`Ignoring compressed-file-data: ${zipHeader.compressedSize} bytes`);
                    await this.tokenizer.ignore(zipHeader.compressedSize);
                }
            }
            debug$1(`Reading data-descriptor at pos=${this.tokenizer.position}`);
            if (zipHeader.dataDescriptor) {
                // await this.tokenizer.ignore(DataDescriptor.len);
                const dataDescriptor = await this.tokenizer.readToken(DataDescriptor);
                if (dataDescriptor.signature !== 0x08074b50) {
                    throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position - DataDescriptor.len}`);
                }
            }
        } while (!stop);
    }
    async iterateOverCentralDirectory(entries, fileCb) {
        for (const fileHeader of entries) {
            const next = fileCb(fileHeader);
            if (next.handler) {
                this.tokenizer.setPosition(fileHeader.relativeOffsetOfLocalHeader);
                const zipHeader = await this.readLocalFileHeader();
                if (zipHeader) {
                    await this.tokenizer.ignore(zipHeader.extraFieldLength);
                    const fileData = new Uint8Array(fileHeader.compressedSize);
                    await this.tokenizer.readBuffer(fileData);
                    await this.inflate(zipHeader, fileData, next.handler);
                }
            }
            if (next.stop)
                break;
        }
    }
    inflate(zipHeader, fileData, cb) {
        if (zipHeader.compressedMethod === 0) {
            return cb(fileData);
        }
        debug$1(`Decompress filename=${zipHeader.filename}, compressed-size=${fileData.length}`);
        const uncompressedData = decompressSync(fileData);
        return cb(uncompressedData);
    }
    async readLocalFileHeader() {
        const signature = await this.tokenizer.peekToken(UINT32_LE);
        if (signature === Signature.LocalFileHeader) {
            const header = await this.tokenizer.readToken(LocalFileHeaderToken);
            header.filename = await this.tokenizer.readToken(new StringType(header.filenameLength, 'utf-8'));
            return header;
        }
        if (signature === Signature.CentralFileHeader) {
            return false;
        }
        if (signature === 0xE011CFD0) {
            throw new Error('Encrypted ZIP');
        }
        throw new Error('Unexpected signature');
    }
}
function indexOf(buffer, portion) {
    const bufferLength = buffer.length;
    const portionLength = portion.length;
    // Return -1 if the portion is longer than the buffer
    if (portionLength > bufferLength)
        return -1;
    // Search for the portion in the buffer
    for (let i = 0; i <= bufferLength - portionLength; i++) {
        let found = true;
        for (let j = 0; j < portionLength; j++) {
            if (buffer[i + j] !== portion[j]) {
                found = false;
                break;
            }
        }
        if (found) {
            return i; // Return the starting offset
        }
    }
    return -1; // Not found
}
function mergeArrays(chunks) {
    // Concatenate chunks into a single Uint8Array
    const totalLength = chunks.reduce((acc, curr) => acc + curr.length, 0);
    const mergedArray = new Uint8Array(totalLength);
    let offset = 0;
    for (const chunk of chunks) {
        mergedArray.set(chunk, offset);
        offset += chunk.length;
    }
    return mergedArray;
}

class GzipHandler {
    constructor(tokenizer) {
        this.gunzip = undefined;
        this.tokenizer = tokenizer;
    }
    inflate() {
        let done = false;
        let cancelled = false;
        const parent = this;
        return new ReadableStream({
            start: controller => {
                parent.gunzip = new AsyncGunzip((err, chunk, final) => {
                    if (err) {
                        controller.error(err);
                        return;
                    }
                    if (chunk && !cancelled) {
                        controller.enqueue(chunk);
                    }
                    if (final && !cancelled) {
                        controller.close();
                        parent.gunzip.terminate();
                    }
                });
            },
            async pull(controller) {
                const chunkSize = 1024;
                try {
                    const buffer = new Uint8Array(chunkSize);
                    const size = await parent.tokenizer.readBuffer(buffer, { mayBeLess: true });
                    if (size === 0) {
                        if (!done) {
                            done = true;
                            if (!cancelled) {
                                parent.gunzip.push(new Uint8Array(0), true);
                            }
                        }
                        return;
                    }
                    parent.gunzip.push(buffer.subarray(0, size), false);
                }
                catch (err) {
                    controller.error(err);
                }
            },
            cancel: () => {
                parent.gunzip.terminate();
                cancelled = true;
            }
        });
    }
}

({
	utf8: new globalThis.TextDecoder('utf8'),
});

new globalThis.TextEncoder();

Array.from({length: 256}, (_, index) => index.toString(16).padStart(2, '0'));

/**
@param {DataView} view
@returns {number}
*/
function getUintBE(view) {
	const {byteLength} = view;

	if (byteLength === 6) {
		return (view.getUint16(0) * (2 ** 32)) + view.getUint32(2);
	}

	if (byteLength === 5) {
		return (view.getUint8(0) * (2 ** 32)) + view.getUint32(1);
	}

	if (byteLength === 4) {
		return view.getUint32(0);
	}

	if (byteLength === 3) {
		return (view.getUint8(0) * (2 ** 16)) + view.getUint16(1);
	}

	if (byteLength === 2) {
		return view.getUint16(0);
	}

	if (byteLength === 1) {
		return view.getUint8(0);
	}
}

function stringToBytes(string, encoding) {
	if (encoding === 'utf-16le') {
		const bytes = [];
		for (let index = 0; index < string.length; index++) {
			const code = string.charCodeAt(index); // eslint-disable-line unicorn/prefer-code-point
			bytes.push(code & 0xFF, (code >> 8) & 0xFF); // High byte
		}

		return bytes;
	}

	if (encoding === 'utf-16be') {
		const bytes = [];
		for (let index = 0; index < string.length; index++) {
			const code = string.charCodeAt(index); // eslint-disable-line unicorn/prefer-code-point
			bytes.push((code >> 8) & 0xFF, code & 0xFF); // Low byte
		}

		return bytes;
	}

	return [...string].map(character => character.charCodeAt(0)); // eslint-disable-line unicorn/prefer-code-point
}

/**
Checks whether the TAR checksum is valid.

@param {Uint8Array} arrayBuffer - The TAR header `[offset ... offset + 512]`.
@param {number} offset - TAR header offset.
@returns {boolean} `true` if the TAR checksum is valid, otherwise `false`.
*/
function tarHeaderChecksumMatches(arrayBuffer, offset = 0) {
	const readSum = Number.parseInt(new StringType(6).get(arrayBuffer, 148).replace(/\0.*$/, '').trim(), 8); // Read sum in header
	if (Number.isNaN(readSum)) {
		return false;
	}

	let sum = 8 * 0x20; // Initialize signed bit sum

	for (let index = offset; index < offset + 148; index++) {
		sum += arrayBuffer[index];
	}

	for (let index = offset + 156; index < offset + 512; index++) {
		sum += arrayBuffer[index];
	}

	return readSum === sum;
}

/**
ID3 UINT32 sync-safe tokenizer token.
28 bits (representing up to 256MB) integer, the msb is 0 to avoid "false syncsignals".
*/
const uint32SyncSafeToken = {
	get: (buffer, offset) => (buffer[offset + 3] & 0x7F) | ((buffer[offset + 2]) << 7) | ((buffer[offset + 1]) << 14) | ((buffer[offset]) << 21),
	len: 4,
};

const extensions = [
	'jpg',
	'png',
	'apng',
	'gif',
	'webp',
	'flif',
	'xcf',
	'cr2',
	'cr3',
	'orf',
	'arw',
	'dng',
	'nef',
	'rw2',
	'raf',
	'tif',
	'bmp',
	'icns',
	'jxr',
	'psd',
	'indd',
	'zip',
	'tar',
	'rar',
	'gz',
	'bz2',
	'7z',
	'dmg',
	'mp4',
	'mid',
	'mkv',
	'webm',
	'mov',
	'avi',
	'mpg',
	'mp2',
	'mp3',
	'm4a',
	'oga',
	'ogg',
	'ogv',
	'opus',
	'flac',
	'wav',
	'spx',
	'amr',
	'pdf',
	'epub',
	'elf',
	'macho',
	'exe',
	'swf',
	'rtf',
	'wasm',
	'woff',
	'woff2',
	'eot',
	'ttf',
	'otf',
	'ttc',
	'ico',
	'flv',
	'ps',
	'xz',
	'sqlite',
	'nes',
	'crx',
	'xpi',
	'cab',
	'deb',
	'ar',
	'rpm',
	'Z',
	'lz',
	'cfb',
	'mxf',
	'mts',
	'blend',
	'bpg',
	'docx',
	'pptx',
	'xlsx',
	'3gp',
	'3g2',
	'j2c',
	'jp2',
	'jpm',
	'jpx',
	'mj2',
	'aif',
	'qcp',
	'odt',
	'ods',
	'odp',
	'xml',
	'mobi',
	'heic',
	'cur',
	'ktx',
	'ape',
	'wv',
	'dcm',
	'ics',
	'glb',
	'pcap',
	'dsf',
	'lnk',
	'alias',
	'voc',
	'ac3',
	'm4v',
	'm4p',
	'm4b',
	'f4v',
	'f4p',
	'f4b',
	'f4a',
	'mie',
	'asf',
	'ogm',
	'ogx',
	'mpc',
	'arrow',
	'shp',
	'aac',
	'mp1',
	'it',
	's3m',
	'xm',
	'skp',
	'avif',
	'eps',
	'lzh',
	'pgp',
	'asar',
	'stl',
	'chm',
	'3mf',
	'zst',
	'jxl',
	'vcf',
	'jls',
	'pst',
	'dwg',
	'parquet',
	'class',
	'arj',
	'cpio',
	'ace',
	'avro',
	'icc',
	'fbx',
	'vsdx',
	'vtt',
	'apk',
	'drc',
	'lz4',
	'potx',
	'xltx',
	'dotx',
	'xltm',
	'ott',
	'ots',
	'otp',
	'odg',
	'otg',
	'xlsm',
	'docm',
	'dotm',
	'potm',
	'pptm',
	'jar',
	'rm',
	'ppsm',
	'ppsx',
	'tar.gz',
	'reg',
	'dat',
];

const mimeTypes$1 = [
	'image/jpeg',
	'image/png',
	'image/gif',
	'image/webp',
	'image/flif',
	'image/x-xcf',
	'image/x-canon-cr2',
	'image/x-canon-cr3',
	'image/tiff',
	'image/bmp',
	'image/vnd.ms-photo',
	'image/vnd.adobe.photoshop',
	'application/x-indesign',
	'application/epub+zip',
	'application/x-xpinstall',
	'application/vnd.ms-powerpoint.slideshow.macroenabled.12',
	'application/vnd.oasis.opendocument.text',
	'application/vnd.oasis.opendocument.spreadsheet',
	'application/vnd.oasis.opendocument.presentation',
	'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
	'application/vnd.openxmlformats-officedocument.presentationml.presentation',
	'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
	'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
	'application/zip',
	'application/x-tar',
	'application/x-rar-compressed',
	'application/gzip',
	'application/x-bzip2',
	'application/x-7z-compressed',
	'application/x-apple-diskimage',
	'application/vnd.apache.arrow.file',
	'video/mp4',
	'audio/midi',
	'video/matroska',
	'video/webm',
	'video/quicktime',
	'video/vnd.avi',
	'audio/wav',
	'audio/qcelp',
	'audio/x-ms-asf',
	'video/x-ms-asf',
	'application/vnd.ms-asf',
	'video/mpeg',
	'video/3gpp',
	'audio/mpeg',
	'audio/mp4', // RFC 4337
	'video/ogg',
	'audio/ogg',
	'audio/ogg; codecs=opus',
	'application/ogg',
	'audio/flac',
	'audio/ape',
	'audio/wavpack',
	'audio/amr',
	'application/pdf',
	'application/x-elf',
	'application/x-mach-binary',
	'application/x-msdownload',
	'application/x-shockwave-flash',
	'application/rtf',
	'application/wasm',
	'font/woff',
	'font/woff2',
	'application/vnd.ms-fontobject',
	'font/ttf',
	'font/otf',
	'font/collection',
	'image/x-icon',
	'video/x-flv',
	'application/postscript',
	'application/eps',
	'application/x-xz',
	'application/x-sqlite3',
	'application/x-nintendo-nes-rom',
	'application/x-google-chrome-extension',
	'application/vnd.ms-cab-compressed',
	'application/x-deb',
	'application/x-unix-archive',
	'application/x-rpm',
	'application/x-compress',
	'application/x-lzip',
	'application/x-cfb',
	'application/x-mie',
	'application/mxf',
	'video/mp2t',
	'application/x-blender',
	'image/bpg',
	'image/j2c',
	'image/jp2',
	'image/jpx',
	'image/jpm',
	'image/mj2',
	'audio/aiff',
	'application/xml',
	'application/x-mobipocket-ebook',
	'image/heif',
	'image/heif-sequence',
	'image/heic',
	'image/heic-sequence',
	'image/icns',
	'image/ktx',
	'application/dicom',
	'audio/x-musepack',
	'text/calendar',
	'text/vcard',
	'text/vtt',
	'model/gltf-binary',
	'application/vnd.tcpdump.pcap',
	'audio/x-dsf', // Non-standard
	'application/x.ms.shortcut', // Invented by us
	'application/x.apple.alias', // Invented by us
	'audio/x-voc',
	'audio/vnd.dolby.dd-raw',
	'audio/x-m4a',
	'image/apng',
	'image/x-olympus-orf',
	'image/x-sony-arw',
	'image/x-adobe-dng',
	'image/x-nikon-nef',
	'image/x-panasonic-rw2',
	'image/x-fujifilm-raf',
	'video/x-m4v',
	'video/3gpp2',
	'application/x-esri-shape',
	'audio/aac',
	'audio/x-it',
	'audio/x-s3m',
	'audio/x-xm',
	'video/MP1S',
	'video/MP2P',
	'application/vnd.sketchup.skp',
	'image/avif',
	'application/x-lzh-compressed',
	'application/pgp-encrypted',
	'application/x-asar',
	'model/stl',
	'application/vnd.ms-htmlhelp',
	'model/3mf',
	'image/jxl',
	'application/zstd',
	'image/jls',
	'application/vnd.ms-outlook',
	'image/vnd.dwg',
	'application/vnd.apache.parquet',
	'application/java-vm',
	'application/x-arj',
	'application/x-cpio',
	'application/x-ace-compressed',
	'application/avro',
	'application/vnd.iccprofile',
	'application/x.autodesk.fbx', // Invented by us
	'application/vnd.visio',
	'application/vnd.android.package-archive',
	'application/vnd.google.draco', // Invented by us
	'application/x-lz4', // Invented by us
	'application/vnd.openxmlformats-officedocument.presentationml.template',
	'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
	'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
	'application/vnd.ms-excel.template.macroenabled.12',
	'application/vnd.oasis.opendocument.text-template',
	'application/vnd.oasis.opendocument.spreadsheet-template',
	'application/vnd.oasis.opendocument.presentation-template',
	'application/vnd.oasis.opendocument.graphics',
	'application/vnd.oasis.opendocument.graphics-template',
	'application/vnd.ms-excel.sheet.macroenabled.12',
	'application/vnd.ms-word.document.macroenabled.12',
	'application/vnd.ms-word.template.macroenabled.12',
	'application/vnd.ms-powerpoint.template.macroenabled.12',
	'application/vnd.ms-powerpoint.presentation.macroenabled.12',
	'application/java-archive',
	'application/vnd.rn-realmedia',
	'application/x-ms-regedit',
	'application/x-ft-windows-registry-hive',
];

/**
Primary entry point, Node.js specific entry point is index.js
*/


const reasonableDetectionSizeInBytes = 4100; // A fair amount of file-types are detectable within this range.

function getFileTypeFromMimeType(mimeType) {
	mimeType = mimeType.toLowerCase();
	switch (mimeType) {
		case 'application/epub+zip':
			return {
				ext: 'epub',
				mime: mimeType,
			};
		case 'application/vnd.oasis.opendocument.text':
			return {
				ext: 'odt',
				mime: mimeType,
			};
		case 'application/vnd.oasis.opendocument.text-template':
			return {
				ext: 'ott',
				mime: mimeType,
			};
		case 'application/vnd.oasis.opendocument.spreadsheet':
			return {
				ext: 'ods',
				mime: mimeType,
			};
		case 'application/vnd.oasis.opendocument.spreadsheet-template':
			return {
				ext: 'ots',
				mime: mimeType,
			};
		case 'application/vnd.oasis.opendocument.presentation':
			return {
				ext: 'odp',
				mime: mimeType,
			};
		case 'application/vnd.oasis.opendocument.presentation-template':
			return {
				ext: 'otp',
				mime: mimeType,
			};
		case 'application/vnd.oasis.opendocument.graphics':
			return {
				ext: 'odg',
				mime: mimeType,
			};
		case 'application/vnd.oasis.opendocument.graphics-template':
			return {
				ext: 'otg',
				mime: mimeType,
			};
		case 'application/vnd.openxmlformats-officedocument.presentationml.slideshow':
			return {
				ext: 'ppsx',
				mime: mimeType,
			};
		case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
			return {
				ext: 'xlsx',
				mime: mimeType,
			};
		case 'application/vnd.ms-excel.sheet.macroenabled':
			return {
				ext: 'xlsm',
				mime: 'application/vnd.ms-excel.sheet.macroenabled.12',
			};
		case 'application/vnd.openxmlformats-officedocument.spreadsheetml.template':
			return {
				ext: 'xltx',
				mime: mimeType,
			};
		case 'application/vnd.ms-excel.template.macroenabled':
			return {
				ext: 'xltm',
				mime: 'application/vnd.ms-excel.template.macroenabled.12',
			};
		case 'application/vnd.ms-powerpoint.slideshow.macroenabled':
			return {
				ext: 'ppsm',
				mime: 'application/vnd.ms-powerpoint.slideshow.macroenabled.12',
			};
		case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
			return {
				ext: 'docx',
				mime: mimeType,
			};
		case 'application/vnd.ms-word.document.macroenabled':
			return {
				ext: 'docm',
				mime: 'application/vnd.ms-word.document.macroenabled.12',
			};
		case 'application/vnd.openxmlformats-officedocument.wordprocessingml.template':
			return {
				ext: 'dotx',
				mime: mimeType,
			};
		case 'application/vnd.ms-word.template.macroenabledtemplate':
			return {
				ext: 'dotm',
				mime: 'application/vnd.ms-word.template.macroenabled.12',
			};
		case 'application/vnd.openxmlformats-officedocument.presentationml.template':
			return {
				ext: 'potx',
				mime: mimeType,
			};
		case 'application/vnd.ms-powerpoint.template.macroenabled':
			return {
				ext: 'potm',
				mime: 'application/vnd.ms-powerpoint.template.macroenabled.12',
			};
		case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
			return {
				ext: 'pptx',
				mime: mimeType,
			};
		case 'application/vnd.ms-powerpoint.presentation.macroenabled':
			return {
				ext: 'pptm',
				mime: 'application/vnd.ms-powerpoint.presentation.macroenabled.12',
			};
		case 'application/vnd.ms-visio.drawing':
			return {
				ext: 'vsdx',
				mime: 'application/vnd.visio',
			};
		case 'application/vnd.ms-package.3dmanufacturing-3dmodel+xml':
			return {
				ext: '3mf',
				mime: 'model/3mf',
			};
	}
}

function _check(buffer, headers, options) {
	options = {
		offset: 0,
		...options,
	};

	for (const [index, header] of headers.entries()) {
		// If a bitmask is set
		if (options.mask) {
			// If header doesn't equal `buf` with bits masked off
			if (header !== (options.mask[index] & buffer[index + options.offset])) {
				return false;
			}
		} else if (header !== buffer[index + options.offset]) {
			return false;
		}
	}

	return true;
}

let FileTypeParser$1 = class FileTypeParser {
	constructor(options) {
		this.options = {
			mpegOffsetTolerance: 0,
			...options,
		};

		this.detectors = [...(options?.customDetectors ?? []),
			{id: 'core', detect: this.detectConfident},
			{id: 'core.imprecise', detect: this.detectImprecise}];
		this.tokenizerOptions = {
			abortSignal: options?.signal,
		};
	}

	async fromTokenizer(tokenizer) {
		const initialPosition = tokenizer.position;

		// Iterate through all file-type detectors
		for (const detector of this.detectors) {
			const fileType = await detector.detect(tokenizer);
			if (fileType) {
				return fileType;
			}

			if (initialPosition !== tokenizer.position) {
				return undefined; // Cannot proceed scanning of the tokenizer is at an arbitrary position
			}
		}
	}

	async fromBuffer(input) {
		if (!(input instanceof Uint8Array || input instanceof ArrayBuffer)) {
			throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof input}\``);
		}

		const buffer = input instanceof Uint8Array ? input : new Uint8Array(input);

		if (!(buffer?.length > 1)) {
			return;
		}

		return this.fromTokenizer(fromBuffer$1(buffer, this.tokenizerOptions));
	}

	async fromBlob(blob) {
		const tokenizer = fromBlob(blob, this.tokenizerOptions);
		try {
			return await this.fromTokenizer(tokenizer);
		} finally {
			await tokenizer.close();
		}
	}

	async fromStream(stream) {
		const tokenizer = fromWebStream(stream, this.tokenizerOptions);
		try {
			return await this.fromTokenizer(tokenizer);
		} finally {
			await tokenizer.close();
		}
	}

	async toDetectionStream(stream, options) {
		const {sampleSize = reasonableDetectionSizeInBytes} = options;
		let detectedFileType;
		let firstChunk;

		const reader = stream.getReader({mode: 'byob'});
		try {
			// Read the first chunk from the stream
			const {value: chunk, done} = await reader.read(new Uint8Array(sampleSize));
			firstChunk = chunk;
			if (!done && chunk) {
				try {
					// Attempt to detect the file type from the chunk
					detectedFileType = await this.fromBuffer(chunk.subarray(0, sampleSize));
				} catch (error) {
					if (!(error instanceof EndOfStreamError)) {
						throw error; // Re-throw non-EndOfStreamError
					}

					detectedFileType = undefined;
				}
			}

			firstChunk = chunk;
		} finally {
			reader.releaseLock(); // Ensure the reader is released
		}

		// Create a new ReadableStream to manage locking issues
		const transformStream = new TransformStream({
			async start(controller) {
				controller.enqueue(firstChunk); // Enqueue the initial chunk
			},
			transform(chunk, controller) {
				// Pass through the chunks without modification
				controller.enqueue(chunk);
			},
		});

		const newStream = stream.pipeThrough(transformStream);
		newStream.fileType = detectedFileType;

		return newStream;
	}

	check(header, options) {
		return _check(this.buffer, header, options);
	}

	checkString(header, options) {
		return this.check(stringToBytes(header, options?.encoding), options);
	}

	// Detections with a high degree of certainty in identifying the correct file type
	detectConfident = async tokenizer => {
		this.buffer = new Uint8Array(reasonableDetectionSizeInBytes);

		// Keep reading until EOF if the file size is unknown.
		if (tokenizer.fileInfo.size === undefined) {
			tokenizer.fileInfo.size = Number.MAX_SAFE_INTEGER;
		}

		this.tokenizer = tokenizer;

		await tokenizer.peekBuffer(this.buffer, {length: 32, mayBeLess: true});

		// -- 2-byte signatures --

		if (this.check([0x42, 0x4D])) {
			return {
				ext: 'bmp',
				mime: 'image/bmp',
			};
		}

		if (this.check([0x0B, 0x77])) {
			return {
				ext: 'ac3',
				mime: 'audio/vnd.dolby.dd-raw',
			};
		}

		if (this.check([0x78, 0x01])) {
			return {
				ext: 'dmg',
				mime: 'application/x-apple-diskimage',
			};
		}

		if (this.check([0x4D, 0x5A])) {
			return {
				ext: 'exe',
				mime: 'application/x-msdownload',
			};
		}

		if (this.check([0x25, 0x21])) {
			await tokenizer.peekBuffer(this.buffer, {length: 24, mayBeLess: true});

			if (
				this.checkString('PS-Adobe-', {offset: 2})
				&& this.checkString(' EPSF-', {offset: 14})
			) {
				return {
					ext: 'eps',
					mime: 'application/eps',
				};
			}

			return {
				ext: 'ps',
				mime: 'application/postscript',
			};
		}

		if (
			this.check([0x1F, 0xA0])
			|| this.check([0x1F, 0x9D])
		) {
			return {
				ext: 'Z',
				mime: 'application/x-compress',
			};
		}

		if (this.check([0xC7, 0x71])) {
			return {
				ext: 'cpio',
				mime: 'application/x-cpio',
			};
		}

		if (this.check([0x60, 0xEA])) {
			return {
				ext: 'arj',
				mime: 'application/x-arj',
			};
		}

		// -- 3-byte signatures --

		if (this.check([0xEF, 0xBB, 0xBF])) { // UTF-8-BOM
			// Strip off UTF-8-BOM
			this.tokenizer.ignore(3);
			return this.detectConfident(tokenizer);
		}

		if (this.check([0x47, 0x49, 0x46])) {
			return {
				ext: 'gif',
				mime: 'image/gif',
			};
		}

		if (this.check([0x49, 0x49, 0xBC])) {
			return {
				ext: 'jxr',
				mime: 'image/vnd.ms-photo',
			};
		}

		if (this.check([0x1F, 0x8B, 0x8])) {
			const gzipHandler = new GzipHandler(tokenizer);

			const stream = gzipHandler.inflate();
			try {
				const compressedFileType = await this.fromStream(stream);
				if (compressedFileType && compressedFileType.ext === 'tar') {
					return {
						ext: 'tar.gz',
						mime: 'application/gzip',
					};
				}
			} finally {
				await stream.cancel();
			}

			return {
				ext: 'gz',
				mime: 'application/gzip',
			};
		}

		if (this.check([0x42, 0x5A, 0x68])) {
			return {
				ext: 'bz2',
				mime: 'application/x-bzip2',
			};
		}

		if (this.checkString('ID3')) {
			await tokenizer.ignore(6); // Skip ID3 header until the header size
			const id3HeaderLength = await tokenizer.readToken(uint32SyncSafeToken);
			if (tokenizer.position + id3HeaderLength > tokenizer.fileInfo.size) {
				// Guess file type based on ID3 header for backward compatibility
				return {
					ext: 'mp3',
					mime: 'audio/mpeg',
				};
			}

			await tokenizer.ignore(id3HeaderLength);
			return this.fromTokenizer(tokenizer); // Skip ID3 header, recursion
		}

		// Musepack, SV7
		if (this.checkString('MP+')) {
			return {
				ext: 'mpc',
				mime: 'audio/x-musepack',
			};
		}

		if (
			(this.buffer[0] === 0x43 || this.buffer[0] === 0x46)
			&& this.check([0x57, 0x53], {offset: 1})
		) {
			return {
				ext: 'swf',
				mime: 'application/x-shockwave-flash',
			};
		}

		// -- 4-byte signatures --

		// Requires a sample size of 4 bytes
		if (this.check([0xFF, 0xD8, 0xFF])) {
			if (this.check([0xF7], {offset: 3})) { // JPG7/SOF55, indicating a ISO/IEC 14495 / JPEG-LS file
				return {
					ext: 'jls',
					mime: 'image/jls',
				};
			}

			return {
				ext: 'jpg',
				mime: 'image/jpeg',
			};
		}

		if (this.check([0x4F, 0x62, 0x6A, 0x01])) {
			return {
				ext: 'avro',
				mime: 'application/avro',
			};
		}

		if (this.checkString('FLIF')) {
			return {
				ext: 'flif',
				mime: 'image/flif',
			};
		}

		if (this.checkString('8BPS')) {
			return {
				ext: 'psd',
				mime: 'image/vnd.adobe.photoshop',
			};
		}

		// Musepack, SV8
		if (this.checkString('MPCK')) {
			return {
				ext: 'mpc',
				mime: 'audio/x-musepack',
			};
		}

		if (this.checkString('FORM')) {
			return {
				ext: 'aif',
				mime: 'audio/aiff',
			};
		}

		if (this.checkString('icns', {offset: 0})) {
			return {
				ext: 'icns',
				mime: 'image/icns',
			};
		}

		// Zip-based file formats
		// Need to be before the `zip` check
		if (this.check([0x50, 0x4B, 0x3, 0x4])) { // Local file header signature
			let fileType;
			await new ZipHandler(tokenizer).unzip(zipHeader => {
				switch (zipHeader.filename) {
					case 'META-INF/mozilla.rsa':
						fileType = {
							ext: 'xpi',
							mime: 'application/x-xpinstall',
						};
						return {
							stop: true,
						};
					case 'META-INF/MANIFEST.MF':
						fileType = {
							ext: 'jar',
							mime: 'application/java-archive',
						};
						return {
							stop: true,
						};
					case 'mimetype':
						return {
							async handler(fileData) {
								// Use TextDecoder to decode the UTF-8 encoded data
								const mimeType = new TextDecoder('utf-8').decode(fileData).trim();
								fileType = getFileTypeFromMimeType(mimeType);
							},
							stop: true,
						};

					case '[Content_Types].xml':
						return {
							async handler(fileData) {
								// Use TextDecoder to decode the UTF-8 encoded data
								let xmlContent = new TextDecoder('utf-8').decode(fileData);
								const endPos = xmlContent.indexOf('.main+xml"');
								if (endPos === -1) {
									const mimeType = 'application/vnd.ms-package.3dmanufacturing-3dmodel+xml';
									if (xmlContent.includes(`ContentType="${mimeType}"`)) {
										fileType = getFileTypeFromMimeType(mimeType);
									}
								} else {
									xmlContent = xmlContent.slice(0, Math.max(0, endPos));
									const firstPos = xmlContent.lastIndexOf('"');
									const mimeType = xmlContent.slice(Math.max(0, firstPos + 1));
									fileType = getFileTypeFromMimeType(mimeType);
								}
							},
							stop: true,
						};
					default:
						if (/classes\d*\.dex/.test(zipHeader.filename)) {
							fileType = {
								ext: 'apk',
								mime: 'application/vnd.android.package-archive',
							};
							return {stop: true};
						}

						return {};
				}
			}).catch(error => {
				if (!(error instanceof EndOfStreamError)) {
					throw error; // Re-throw non-EndOfStreamError
				}
			});

			return fileType ?? {
				ext: 'zip',
				mime: 'application/zip',
			};
		}

		if (this.checkString('OggS')) {
			// This is an OGG container
			await tokenizer.ignore(28);
			const type = new Uint8Array(8);
			await tokenizer.readBuffer(type);

			// Needs to be before `ogg` check
			if (_check(type, [0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64])) {
				return {
					ext: 'opus',
					mime: 'audio/ogg; codecs=opus',
				};
			}

			// If ' theora' in header.
			if (_check(type, [0x80, 0x74, 0x68, 0x65, 0x6F, 0x72, 0x61])) {
				return {
					ext: 'ogv',
					mime: 'video/ogg',
				};
			}

			// If '\x01video' in header.
			if (_check(type, [0x01, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x00])) {
				return {
					ext: 'ogm',
					mime: 'video/ogg',
				};
			}

			// If ' FLAC' in header  https://xiph.org/flac/faq.html
			if (_check(type, [0x7F, 0x46, 0x4C, 0x41, 0x43])) {
				return {
					ext: 'oga',
					mime: 'audio/ogg',
				};
			}

			// 'Speex  ' in header https://en.wikipedia.org/wiki/Speex
			if (_check(type, [0x53, 0x70, 0x65, 0x65, 0x78, 0x20, 0x20])) {
				return {
					ext: 'spx',
					mime: 'audio/ogg',
				};
			}

			// If '\x01vorbis' in header
			if (_check(type, [0x01, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73])) {
				return {
					ext: 'ogg',
					mime: 'audio/ogg',
				};
			}

			// Default OGG container https://www.iana.org/assignments/media-types/application/ogg
			return {
				ext: 'ogx',
				mime: 'application/ogg',
			};
		}

		if (
			this.check([0x50, 0x4B])
			&& (this.buffer[2] === 0x3 || this.buffer[2] === 0x5 || this.buffer[2] === 0x7)
			&& (this.buffer[3] === 0x4 || this.buffer[3] === 0x6 || this.buffer[3] === 0x8)
		) {
			return {
				ext: 'zip',
				mime: 'application/zip',
			};
		}

		if (this.checkString('MThd')) {
			return {
				ext: 'mid',
				mime: 'audio/midi',
			};
		}

		if (
			this.checkString('wOFF')
			&& (
				this.check([0x00, 0x01, 0x00, 0x00], {offset: 4})
				|| this.checkString('OTTO', {offset: 4})
			)
		) {
			return {
				ext: 'woff',
				mime: 'font/woff',
			};
		}

		if (
			this.checkString('wOF2')
			&& (
				this.check([0x00, 0x01, 0x00, 0x00], {offset: 4})
				|| this.checkString('OTTO', {offset: 4})
			)
		) {
			return {
				ext: 'woff2',
				mime: 'font/woff2',
			};
		}

		if (this.check([0xD4, 0xC3, 0xB2, 0xA1]) || this.check([0xA1, 0xB2, 0xC3, 0xD4])) {
			return {
				ext: 'pcap',
				mime: 'application/vnd.tcpdump.pcap',
			};
		}

		// Sony DSD Stream File (DSF)
		if (this.checkString('DSD ')) {
			return {
				ext: 'dsf',
				mime: 'audio/x-dsf', // Non-standard
			};
		}

		if (this.checkString('LZIP')) {
			return {
				ext: 'lz',
				mime: 'application/x-lzip',
			};
		}

		if (this.checkString('fLaC')) {
			return {
				ext: 'flac',
				mime: 'audio/flac',
			};
		}

		if (this.check([0x42, 0x50, 0x47, 0xFB])) {
			return {
				ext: 'bpg',
				mime: 'image/bpg',
			};
		}

		if (this.checkString('wvpk')) {
			return {
				ext: 'wv',
				mime: 'audio/wavpack',
			};
		}

		if (this.checkString('%PDF')) {
			// Assume this is just a normal PDF
			return {
				ext: 'pdf',
				mime: 'application/pdf',
			};
		}

		if (this.check([0x00, 0x61, 0x73, 0x6D])) {
			return {
				ext: 'wasm',
				mime: 'application/wasm',
			};
		}

		// TIFF, little-endian type
		if (this.check([0x49, 0x49])) {
			const fileType = await this.readTiffHeader(false);
			if (fileType) {
				return fileType;
			}
		}

		// TIFF, big-endian type
		if (this.check([0x4D, 0x4D])) {
			const fileType = await this.readTiffHeader(true);
			if (fileType) {
				return fileType;
			}
		}

		if (this.checkString('MAC ')) {
			return {
				ext: 'ape',
				mime: 'audio/ape',
			};
		}

		// https://github.com/file/file/blob/master/magic/Magdir/matroska
		if (this.check([0x1A, 0x45, 0xDF, 0xA3])) { // Root element: EBML
			async function readField() {
				const msb = await tokenizer.peekNumber(UINT8);
				let mask = 0x80;
				let ic = 0; // 0 = A, 1 = B, 2 = C, 3 = D

				while ((msb & mask) === 0 && mask !== 0) {
					++ic;
					mask >>= 1;
				}

				const id = new Uint8Array(ic + 1);
				await tokenizer.readBuffer(id);
				return id;
			}

			async function readElement() {
				const idField = await readField();
				const lengthField = await readField();

				lengthField[0] ^= 0x80 >> (lengthField.length - 1);
				const nrLength = Math.min(6, lengthField.length); // JavaScript can max read 6 bytes integer

				const idView = new DataView(idField.buffer);
				const lengthView = new DataView(lengthField.buffer, lengthField.length - nrLength, nrLength);

				return {
					id: getUintBE(idView),
					len: getUintBE(lengthView),
				};
			}

			async function readChildren(children) {
				while (children > 0) {
					const element = await readElement();
					if (element.id === 0x42_82) {
						const rawValue = await tokenizer.readToken(new StringType(element.len));
						return rawValue.replaceAll(/\00.*$/g, ''); // Return DocType
					}

					await tokenizer.ignore(element.len); // ignore payload
					--children;
				}
			}

			const re = await readElement();
			const documentType = await readChildren(re.len);

			switch (documentType) {
				case 'webm':
					return {
						ext: 'webm',
						mime: 'video/webm',
					};

				case 'matroska':
					return {
						ext: 'mkv',
						mime: 'video/matroska',
					};

				default:
					return;
			}
		}

		if (this.checkString('SQLi')) {
			return {
				ext: 'sqlite',
				mime: 'application/x-sqlite3',
			};
		}

		if (this.check([0x4E, 0x45, 0x53, 0x1A])) {
			return {
				ext: 'nes',
				mime: 'application/x-nintendo-nes-rom',
			};
		}

		if (this.checkString('Cr24')) {
			return {
				ext: 'crx',
				mime: 'application/x-google-chrome-extension',
			};
		}

		if (
			this.checkString('MSCF')
			|| this.checkString('ISc(')
		) {
			return {
				ext: 'cab',
				mime: 'application/vnd.ms-cab-compressed',
			};
		}

		if (this.check([0xED, 0xAB, 0xEE, 0xDB])) {
			return {
				ext: 'rpm',
				mime: 'application/x-rpm',
			};
		}

		if (this.check([0xC5, 0xD0, 0xD3, 0xC6])) {
			return {
				ext: 'eps',
				mime: 'application/eps',
			};
		}

		if (this.check([0x28, 0xB5, 0x2F, 0xFD])) {
			return {
				ext: 'zst',
				mime: 'application/zstd',
			};
		}

		if (this.check([0x7F, 0x45, 0x4C, 0x46])) {
			return {
				ext: 'elf',
				mime: 'application/x-elf',
			};
		}

		if (this.check([0x21, 0x42, 0x44, 0x4E])) {
			return {
				ext: 'pst',
				mime: 'application/vnd.ms-outlook',
			};
		}

		if (this.checkString('PAR1') || this.checkString('PARE')) {
			return {
				ext: 'parquet',
				mime: 'application/vnd.apache.parquet',
			};
		}

		if (this.checkString('ttcf')) {
			return {
				ext: 'ttc',
				mime: 'font/collection',
			};
		}

		if (this.check([0xCF, 0xFA, 0xED, 0xFE])) {
			return {
				ext: 'macho',
				mime: 'application/x-mach-binary',
			};
		}

		if (this.check([0x04, 0x22, 0x4D, 0x18])) {
			return {
				ext: 'lz4',
				mime: 'application/x-lz4', // Invented by us
			};
		}

		if (this.checkString('regf')) {
			return {
				ext: 'dat',
				mime: 'application/x-ft-windows-registry-hive',
			};
		}

		// -- 5-byte signatures --

		if (this.check([0x4F, 0x54, 0x54, 0x4F, 0x00])) {
			return {
				ext: 'otf',
				mime: 'font/otf',
			};
		}

		if (this.checkString('#!AMR')) {
			return {
				ext: 'amr',
				mime: 'audio/amr',
			};
		}

		if (this.checkString('{\\rtf')) {
			return {
				ext: 'rtf',
				mime: 'application/rtf',
			};
		}

		if (this.check([0x46, 0x4C, 0x56, 0x01])) {
			return {
				ext: 'flv',
				mime: 'video/x-flv',
			};
		}

		if (this.checkString('IMPM')) {
			return {
				ext: 'it',
				mime: 'audio/x-it',
			};
		}

		if (
			this.checkString('-lh0-', {offset: 2})
			|| this.checkString('-lh1-', {offset: 2})
			|| this.checkString('-lh2-', {offset: 2})
			|| this.checkString('-lh3-', {offset: 2})
			|| this.checkString('-lh4-', {offset: 2})
			|| this.checkString('-lh5-', {offset: 2})
			|| this.checkString('-lh6-', {offset: 2})
			|| this.checkString('-lh7-', {offset: 2})
			|| this.checkString('-lzs-', {offset: 2})
			|| this.checkString('-lz4-', {offset: 2})
			|| this.checkString('-lz5-', {offset: 2})
			|| this.checkString('-lhd-', {offset: 2})
		) {
			return {
				ext: 'lzh',
				mime: 'application/x-lzh-compressed',
			};
		}

		// MPEG program stream (PS or MPEG-PS)
		if (this.check([0x00, 0x00, 0x01, 0xBA])) {
			//  MPEG-PS, MPEG-1 Part 1
			if (this.check([0x21], {offset: 4, mask: [0xF1]})) {
				return {
					ext: 'mpg', // May also be .ps, .mpeg
					mime: 'video/MP1S',
				};
			}

			// MPEG-PS, MPEG-2 Part 1
			if (this.check([0x44], {offset: 4, mask: [0xC4]})) {
				return {
					ext: 'mpg', // May also be .mpg, .m2p, .vob or .sub
					mime: 'video/MP2P',
				};
			}
		}

		if (this.checkString('ITSF')) {
			return {
				ext: 'chm',
				mime: 'application/vnd.ms-htmlhelp',
			};
		}

		if (this.check([0xCA, 0xFE, 0xBA, 0xBE])) {
			return {
				ext: 'class',
				mime: 'application/java-vm',
			};
		}

		if (this.checkString('.RMF')) {
			return {
				ext: 'rm',
				mime: 'application/vnd.rn-realmedia',
			};
		}

		// -- 5-byte signatures --

		if (this.checkString('DRACO')) {
			return {
				ext: 'drc',
				mime: 'application/vnd.google.draco', // Invented by us
			};
		}

		// -- 6-byte signatures --

		if (this.check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) {
			return {
				ext: 'xz',
				mime: 'application/x-xz',
			};
		}

		if (this.checkString('<?xml ')) {
			return {
				ext: 'xml',
				mime: 'application/xml',
			};
		}

		if (this.check([0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C])) {
			return {
				ext: '7z',
				mime: 'application/x-7z-compressed',
			};
		}

		if (
			this.check([0x52, 0x61, 0x72, 0x21, 0x1A, 0x7])
			&& (this.buffer[6] === 0x0 || this.buffer[6] === 0x1)
		) {
			return {
				ext: 'rar',
				mime: 'application/x-rar-compressed',
			};
		}

		if (this.checkString('solid ')) {
			return {
				ext: 'stl',
				mime: 'model/stl',
			};
		}

		if (this.checkString('AC')) {
			const version = new StringType(4, 'latin1').get(this.buffer, 2);
			if (version.match('^d*') && version >= 1000 && version <= 1050) {
				return {
					ext: 'dwg',
					mime: 'image/vnd.dwg',
				};
			}
		}

		if (this.checkString('070707')) {
			return {
				ext: 'cpio',
				mime: 'application/x-cpio',
			};
		}

		// -- 7-byte signatures --

		if (this.checkString('BLENDER')) {
			return {
				ext: 'blend',
				mime: 'application/x-blender',
			};
		}

		if (this.checkString('!<arch>')) {
			await tokenizer.ignore(8);
			const string = await tokenizer.readToken(new StringType(13, 'ascii'));
			if (string === 'debian-binary') {
				return {
					ext: 'deb',
					mime: 'application/x-deb',
				};
			}

			return {
				ext: 'ar',
				mime: 'application/x-unix-archive',
			};
		}

		if (
			this.checkString('WEBVTT')
			&&	(
				// One of LF, CR, tab, space, or end of file must follow "WEBVTT" per the spec (see `fixture/fixture-vtt-*.vtt` for examples). Note that `\0` is technically the null character (there is no such thing as an EOF character). However, checking for `\0` gives us the same result as checking for the end of the stream.
				(['\n', '\r', '\t', ' ', '\0'].some(char7 => this.checkString(char7, {offset: 6}))))
		) {
			return {
				ext: 'vtt',
				mime: 'text/vtt',
			};
		}

		// -- 8-byte signatures --

		if (this.check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) {
			// APNG format (https://wiki.mozilla.org/APNG_Specification)
			// 1. Find the first IDAT (image data) chunk (49 44 41 54)
			// 2. Check if there is an "acTL" chunk before the IDAT one (61 63 54 4C)

			// Offset calculated as follows:
			// - 8 bytes: PNG signature
			// - 4 (length) + 4 (chunk type) + 13 (chunk data) + 4 (CRC): IHDR chunk

			await tokenizer.ignore(8); // ignore PNG signature

			async function readChunkHeader() {
				return {
					length: await tokenizer.readToken(INT32_BE),
					type: await tokenizer.readToken(new StringType(4, 'latin1')),
				};
			}

			do {
				const chunk = await readChunkHeader();
				if (chunk.length < 0) {
					return; // Invalid chunk length
				}

				switch (chunk.type) {
					case 'IDAT':
						return {
							ext: 'png',
							mime: 'image/png',
						};
					case 'acTL':
						return {
							ext: 'apng',
							mime: 'image/apng',
						};
					default:
						await tokenizer.ignore(chunk.length + 4); // Ignore chunk-data + CRC
				}
			} while (tokenizer.position + 8 < tokenizer.fileInfo.size);

			return {
				ext: 'png',
				mime: 'image/png',
			};
		}

		if (this.check([0x41, 0x52, 0x52, 0x4F, 0x57, 0x31, 0x00, 0x00])) {
			return {
				ext: 'arrow',
				mime: 'application/vnd.apache.arrow.file',
			};
		}

		if (this.check([0x67, 0x6C, 0x54, 0x46, 0x02, 0x00, 0x00, 0x00])) {
			return {
				ext: 'glb',
				mime: 'model/gltf-binary',
			};
		}

		// `mov` format variants
		if (
			this.check([0x66, 0x72, 0x65, 0x65], {offset: 4}) // `free`
			|| this.check([0x6D, 0x64, 0x61, 0x74], {offset: 4}) // `mdat` MJPEG
			|| this.check([0x6D, 0x6F, 0x6F, 0x76], {offset: 4}) // `moov`
			|| this.check([0x77, 0x69, 0x64, 0x65], {offset: 4}) // `wide`
		) {
			return {
				ext: 'mov',
				mime: 'video/quicktime',
			};
		}

		// -- 9-byte signatures --

		if (this.check([0x49, 0x49, 0x52, 0x4F, 0x08, 0x00, 0x00, 0x00, 0x18])) {
			return {
				ext: 'orf',
				mime: 'image/x-olympus-orf',
			};
		}

		if (this.checkString('gimp xcf ')) {
			return {
				ext: 'xcf',
				mime: 'image/x-xcf',
			};
		}

		// File Type Box (https://en.wikipedia.org/wiki/ISO_base_media_file_format)
		// It's not required to be first, but it's recommended to be. Almost all ISO base media files start with `ftyp` box.
		// `ftyp` box must contain a brand major identifier, which must consist of ISO 8859-1 printable characters.
		// Here we check for 8859-1 printable characters (for simplicity, it's a mask which also catches one non-printable character).
		if (
			this.checkString('ftyp', {offset: 4})
			&& (this.buffer[8] & 0x60) !== 0x00 // Brand major, first character ASCII?
		) {
			// They all can have MIME `video/mp4` except `application/mp4` special-case which is hard to detect.
			// For some cases, we're specific, everything else falls to `video/mp4` with `mp4` extension.
			const brandMajor = new StringType(4, 'latin1').get(this.buffer, 8).replace('\0', ' ').trim();
			switch (brandMajor) {
				case 'avif':
				case 'avis':
					return {ext: 'avif', mime: 'image/avif'};
				case 'mif1':
					return {ext: 'heic', mime: 'image/heif'};
				case 'msf1':
					return {ext: 'heic', mime: 'image/heif-sequence'};
				case 'heic':
				case 'heix':
					return {ext: 'heic', mime: 'image/heic'};
				case 'hevc':
				case 'hevx':
					return {ext: 'heic', mime: 'image/heic-sequence'};
				case 'qt':
					return {ext: 'mov', mime: 'video/quicktime'};
				case 'M4V':
				case 'M4VH':
				case 'M4VP':
					return {ext: 'm4v', mime: 'video/x-m4v'};
				case 'M4P':
					return {ext: 'm4p', mime: 'video/mp4'};
				case 'M4B':
					return {ext: 'm4b', mime: 'audio/mp4'};
				case 'M4A':
					return {ext: 'm4a', mime: 'audio/x-m4a'};
				case 'F4V':
					return {ext: 'f4v', mime: 'video/mp4'};
				case 'F4P':
					return {ext: 'f4p', mime: 'video/mp4'};
				case 'F4A':
					return {ext: 'f4a', mime: 'audio/mp4'};
				case 'F4B':
					return {ext: 'f4b', mime: 'audio/mp4'};
				case 'crx':
					return {ext: 'cr3', mime: 'image/x-canon-cr3'};
				default:
					if (brandMajor.startsWith('3g')) {
						if (brandMajor.startsWith('3g2')) {
							return {ext: '3g2', mime: 'video/3gpp2'};
						}

						return {ext: '3gp', mime: 'video/3gpp'};
					}

					return {ext: 'mp4', mime: 'video/mp4'};
			}
		}

		// -- 10-byte signatures --

		if (this.checkString('REGEDIT4\r\n')) {
			return {
				ext: 'reg',
				mime: 'application/x-ms-regedit',
			};
		}

		// -- 12-byte signatures --

		// RIFF file format which might be AVI, WAV, QCP, etc
		if (this.check([0x52, 0x49, 0x46, 0x46])) {
			if (this.checkString('WEBP', {offset: 8})) {
				return {
					ext: 'webp',
					mime: 'image/webp',
				};
			}

			if (this.check([0x41, 0x56, 0x49], {offset: 8})) {
				return {
					ext: 'avi',
					mime: 'video/vnd.avi',
				};
			}

			if (this.check([0x57, 0x41, 0x56, 0x45], {offset: 8})) {
				return {
					ext: 'wav',
					mime: 'audio/wav',
				};
			}

			// QLCM, QCP file
			if (this.check([0x51, 0x4C, 0x43, 0x4D], {offset: 8})) {
				return {
					ext: 'qcp',
					mime: 'audio/qcelp',
				};
			}
		}

		if (this.check([0x49, 0x49, 0x55, 0x00, 0x18, 0x00, 0x00, 0x00, 0x88, 0xE7, 0x74, 0xD8])) {
			return {
				ext: 'rw2',
				mime: 'image/x-panasonic-rw2',
			};
		}

		// ASF_Header_Object first 80 bytes
		if (this.check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) {
			async function readHeader() {
				const guid = new Uint8Array(16);
				await tokenizer.readBuffer(guid);
				return {
					id: guid,
					size: Number(await tokenizer.readToken(UINT64_LE)),
				};
			}

			await tokenizer.ignore(30);
			// Search for header should be in first 1KB of file.
			while (tokenizer.position + 24 < tokenizer.fileInfo.size) {
				const header = await readHeader();
				let payload = header.size - 24;
				if (_check(header.id, [0x91, 0x07, 0xDC, 0xB7, 0xB7, 0xA9, 0xCF, 0x11, 0x8E, 0xE6, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65])) {
					// Sync on Stream-Properties-Object (B7DC0791-A9B7-11CF-8EE6-00C00C205365)
					const typeId = new Uint8Array(16);
					payload -= await tokenizer.readBuffer(typeId);

					if (_check(typeId, [0x40, 0x9E, 0x69, 0xF8, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B])) {
						// Found audio:
						return {
							ext: 'asf',
							mime: 'audio/x-ms-asf',
						};
					}

					if (_check(typeId, [0xC0, 0xEF, 0x19, 0xBC, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B])) {
						// Found video:
						return {
							ext: 'asf',
							mime: 'video/x-ms-asf',
						};
					}

					break;
				}

				await tokenizer.ignore(payload);
			}

			// Default to ASF generic extension
			return {
				ext: 'asf',
				mime: 'application/vnd.ms-asf',
			};
		}

		if (this.check([0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A])) {
			return {
				ext: 'ktx',
				mime: 'image/ktx',
			};
		}

		if ((this.check([0x7E, 0x10, 0x04]) || this.check([0x7E, 0x18, 0x04])) && this.check([0x30, 0x4D, 0x49, 0x45], {offset: 4})) {
			return {
				ext: 'mie',
				mime: 'application/x-mie',
			};
		}

		if (this.check([0x27, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], {offset: 2})) {
			return {
				ext: 'shp',
				mime: 'application/x-esri-shape',
			};
		}

		if (this.check([0xFF, 0x4F, 0xFF, 0x51])) {
			return {
				ext: 'j2c',
				mime: 'image/j2c',
			};
		}

		if (this.check([0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A])) {
			// JPEG-2000 family

			await tokenizer.ignore(20);
			const type = await tokenizer.readToken(new StringType(4, 'ascii'));
			switch (type) {
				case 'jp2 ':
					return {
						ext: 'jp2',
						mime: 'image/jp2',
					};
				case 'jpx ':
					return {
						ext: 'jpx',
						mime: 'image/jpx',
					};
				case 'jpm ':
					return {
						ext: 'jpm',
						mime: 'image/jpm',
					};
				case 'mjp2':
					return {
						ext: 'mj2',
						mime: 'image/mj2',
					};
				default:
					return;
			}
		}

		if (
			this.check([0xFF, 0x0A])
			|| this.check([0x00, 0x00, 0x00, 0x0C, 0x4A, 0x58, 0x4C, 0x20, 0x0D, 0x0A, 0x87, 0x0A])
		) {
			return {
				ext: 'jxl',
				mime: 'image/jxl',
			};
		}

		if (this.check([0xFE, 0xFF])) { // UTF-16-BOM-BE
			if (this.checkString('<?xml ', {offset: 2, encoding: 'utf-16be'})) {
				return {
					ext: 'xml',
					mime: 'application/xml',
				};
			}

			return undefined; // Some unknown text based format
		}

		if (this.check([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])) {
			// Detected Microsoft Compound File Binary File (MS-CFB) Format.
			return {
				ext: 'cfb',
				mime: 'application/x-cfb',
			};
		}

		// Increase sample size from 32 to 256.
		await tokenizer.peekBuffer(this.buffer, {length: Math.min(256, tokenizer.fileInfo.size), mayBeLess: true});

		if (this.check([0x61, 0x63, 0x73, 0x70], {offset: 36})) {
			return {
				ext: 'icc',
				mime: 'application/vnd.iccprofile',
			};
		}

		// ACE: requires 14 bytes in the buffer
		if (this.checkString('**ACE', {offset: 7}) && this.checkString('**', {offset: 12})) {
			return {
				ext: 'ace',
				mime: 'application/x-ace-compressed',
			};
		}

		// -- 15-byte signatures --

		if (this.checkString('BEGIN:')) {
			if (this.checkString('VCARD', {offset: 6})) {
				return {
					ext: 'vcf',
					mime: 'text/vcard',
				};
			}

			if (this.checkString('VCALENDAR', {offset: 6})) {
				return {
					ext: 'ics',
					mime: 'text/calendar',
				};
			}
		}

		// `raf` is here just to keep all the raw image detectors together.
		if (this.checkString('FUJIFILMCCD-RAW')) {
			return {
				ext: 'raf',
				mime: 'image/x-fujifilm-raf',
			};
		}

		if (this.checkString('Extended Module:')) {
			return {
				ext: 'xm',
				mime: 'audio/x-xm',
			};
		}

		if (this.checkString('Creative Voice File')) {
			return {
				ext: 'voc',
				mime: 'audio/x-voc',
			};
		}

		if (this.check([0x04, 0x00, 0x00, 0x00]) && this.buffer.length >= 16) { // Rough & quick check Pickle/ASAR
			const jsonSize = new DataView(this.buffer.buffer).getUint32(12, true);

			if (jsonSize > 12 && this.buffer.length >= jsonSize + 16) {
				try {
					const header = new TextDecoder().decode(this.buffer.subarray(16, jsonSize + 16));
					const json = JSON.parse(header);
					// Check if Pickle is ASAR
					if (json.files) { // Final check, assuring Pickle/ASAR format
						return {
							ext: 'asar',
							mime: 'application/x-asar',
						};
					}
				} catch {}
			}
		}

		if (this.check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) {
			return {
				ext: 'mxf',
				mime: 'application/mxf',
			};
		}

		if (this.checkString('SCRM', {offset: 44})) {
			return {
				ext: 's3m',
				mime: 'audio/x-s3m',
			};
		}

		// Raw MPEG-2 transport stream (188-byte packets)
		if (this.check([0x47]) && this.check([0x47], {offset: 188})) {
			return {
				ext: 'mts',
				mime: 'video/mp2t',
			};
		}

		// Blu-ray Disc Audio-Video (BDAV) MPEG-2 transport stream has 4-byte TP_extra_header before each 188-byte packet
		if (this.check([0x47], {offset: 4}) && this.check([0x47], {offset: 196})) {
			return {
				ext: 'mts',
				mime: 'video/mp2t',
			};
		}

		if (this.check([0x42, 0x4F, 0x4F, 0x4B, 0x4D, 0x4F, 0x42, 0x49], {offset: 60})) {
			return {
				ext: 'mobi',
				mime: 'application/x-mobipocket-ebook',
			};
		}

		if (this.check([0x44, 0x49, 0x43, 0x4D], {offset: 128})) {
			return {
				ext: 'dcm',
				mime: 'application/dicom',
			};
		}

		if (this.check([0x4C, 0x00, 0x00, 0x00, 0x01, 0x14, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46])) {
			return {
				ext: 'lnk',
				mime: 'application/x.ms.shortcut', // Invented by us
			};
		}

		if (this.check([0x62, 0x6F, 0x6F, 0x6B, 0x00, 0x00, 0x00, 0x00, 0x6D, 0x61, 0x72, 0x6B, 0x00, 0x00, 0x00, 0x00])) {
			return {
				ext: 'alias',
				mime: 'application/x.apple.alias', // Invented by us
			};
		}

		if (this.checkString('Kaydara FBX Binary  \u0000')) {
			return {
				ext: 'fbx',
				mime: 'application/x.autodesk.fbx', // Invented by us
			};
		}

		if (
			this.check([0x4C, 0x50], {offset: 34})
			&& (
				this.check([0x00, 0x00, 0x01], {offset: 8})
				|| this.check([0x01, 0x00, 0x02], {offset: 8})
				|| this.check([0x02, 0x00, 0x02], {offset: 8})
			)
		) {
			return {
				ext: 'eot',
				mime: 'application/vnd.ms-fontobject',
			};
		}

		if (this.check([0x06, 0x06, 0xED, 0xF5, 0xD8, 0x1D, 0x46, 0xE5, 0xBD, 0x31, 0xEF, 0xE7, 0xFE, 0x74, 0xB7, 0x1D])) {
			return {
				ext: 'indd',
				mime: 'application/x-indesign',
			};
		}

		// Increase sample size from 256 to 512
		await tokenizer.peekBuffer(this.buffer, {length: Math.min(512, tokenizer.fileInfo.size), mayBeLess: true});

		// Requires a buffer size of 512 bytes
		if ((this.checkString('ustar', {offset: 257}) && (this.checkString('\0', {offset: 262}) || this.checkString(' ', {offset: 262})))
			|| (this.check([0, 0, 0, 0, 0, 0], {offset: 257}) && tarHeaderChecksumMatches(this.buffer))) {
			return {
				ext: 'tar',
				mime: 'application/x-tar',
			};
		}

		if (this.check([0xFF, 0xFE])) { // UTF-16-BOM-LE
			const encoding = 'utf-16le';
			if (this.checkString('<?xml ', {offset: 2, encoding})) {
				return {
					ext: 'xml',
					mime: 'application/xml',
				};
			}

			if (this.check([0xFF, 0x0E], {offset: 2}) && this.checkString('SketchUp Model', {offset: 4, encoding})) {
				return {
					ext: 'skp',
					mime: 'application/vnd.sketchup.skp',
				};
			}

			if (this.checkString('Windows Registry Editor Version 5.00\r\n', {offset: 2, encoding})) {
				return {
					ext: 'reg',
					mime: 'application/x-ms-regedit',
				};
			}

			return undefined; // Some text based format
		}

		if (this.checkString('-----BEGIN PGP MESSAGE-----')) {
			return {
				ext: 'pgp',
				mime: 'application/pgp-encrypted',
			};
		}
	};
	// Detections with limited supporting data, resulting in a higher likelihood of false positives
	detectImprecise = async tokenizer => {
		this.buffer = new Uint8Array(reasonableDetectionSizeInBytes);

		// Read initial sample size of 8 bytes
		await tokenizer.peekBuffer(this.buffer, {length: Math.min(8, tokenizer.fileInfo.size), mayBeLess: true});

		if (
			this.check([0x0, 0x0, 0x1, 0xBA])
			|| this.check([0x0, 0x0, 0x1, 0xB3])
		) {
			return {
				ext: 'mpg',
				mime: 'video/mpeg',
			};
		}

		if (this.check([0x00, 0x01, 0x00, 0x00, 0x00])) {
			return {
				ext: 'ttf',
				mime: 'font/ttf',
			};
		}

		if (this.check([0x00, 0x00, 0x01, 0x00])) {
			return {
				ext: 'ico',
				mime: 'image/x-icon',
			};
		}

		if (this.check([0x00, 0x00, 0x02, 0x00])) {
			return {
				ext: 'cur',
				mime: 'image/x-icon',
			};
		}

		// Adjust buffer to `mpegOffsetTolerance`
		await tokenizer.peekBuffer(this.buffer, {length: Math.min(2 + this.options.mpegOffsetTolerance, tokenizer.fileInfo.size), mayBeLess: true});

		// Check MPEG 1 or 2 Layer 3 header, or 'layer 0' for ADTS (MPEG sync-word 0xFFE)
		if (this.buffer.length >= (2 + this.options.mpegOffsetTolerance)) {
			for (let depth = 0; depth <= this.options.mpegOffsetTolerance; ++depth) {
				const type = this.scanMpeg(depth);
				if (type) {
					return type;
				}
			}
		}
	};

	async readTiffTag(bigEndian) {
		const tagId = await this.tokenizer.readToken(bigEndian ? UINT16_BE : UINT16_LE);
		this.tokenizer.ignore(10);
		switch (tagId) {
			case 50_341:
				return {
					ext: 'arw',
					mime: 'image/x-sony-arw',
				};
			case 50_706:
				return {
					ext: 'dng',
					mime: 'image/x-adobe-dng',
				};
		}
	}

	async readTiffIFD(bigEndian) {
		const numberOfTags = await this.tokenizer.readToken(bigEndian ? UINT16_BE : UINT16_LE);
		for (let n = 0; n < numberOfTags; ++n) {
			const fileType = await this.readTiffTag(bigEndian);
			if (fileType) {
				return fileType;
			}
		}
	}

	async readTiffHeader(bigEndian) {
		const version = (bigEndian ? UINT16_BE : UINT16_LE).get(this.buffer, 2);
		const ifdOffset = (bigEndian ? UINT32_BE : UINT32_LE).get(this.buffer, 4);

		if (version === 42) {
			// TIFF file header
			if (ifdOffset >= 6) {
				if (this.checkString('CR', {offset: 8})) {
					return {
						ext: 'cr2',
						mime: 'image/x-canon-cr2',
					};
				}

				if (ifdOffset >= 8) {
					const someId1 = (bigEndian ? UINT16_BE : UINT16_LE).get(this.buffer, 8);
					const someId2 = (bigEndian ? UINT16_BE : UINT16_LE).get(this.buffer, 10);

					if (
						(someId1 === 0x1C && someId2 === 0xFE)
						|| (someId1 === 0x1F && someId2 === 0x0B)) {
						return {
							ext: 'nef',
							mime: 'image/x-nikon-nef',
						};
					}
				}
			}

			await this.tokenizer.ignore(ifdOffset);
			const fileType = await this.readTiffIFD(bigEndian);
			return fileType ?? {
				ext: 'tif',
				mime: 'image/tiff',
			};
		}

		if (version === 43) {	// Big TIFF file header
			return {
				ext: 'tif',
				mime: 'image/tiff',
			};
		}
	}

	/**
	Scan check MPEG 1 or 2 Layer 3 header, or 'layer 0' for ADTS (MPEG sync-word 0xFFE).

	@param offset - Offset to scan for sync-preamble.
	@returns {{ext: string, mime: string}}
	*/
	scanMpeg(offset) {
		if (this.check([0xFF, 0xE0], {offset, mask: [0xFF, 0xE0]})) {
			if (this.check([0x10], {offset: offset + 1, mask: [0x16]})) {
				// Check for (ADTS) MPEG-2
				if (this.check([0x08], {offset: offset + 1, mask: [0x08]})) {
					return {
						ext: 'aac',
						mime: 'audio/aac',
					};
				}

				// Must be (ADTS) MPEG-4
				return {
					ext: 'aac',
					mime: 'audio/aac',
				};
			}

			// MPEG 1 or 2 Layer 3 header
			// Check for MPEG layer 3
			if (this.check([0x02], {offset: offset + 1, mask: [0x06]})) {
				return {
					ext: 'mp3',
					mime: 'audio/mpeg',
				};
			}

			// Check for MPEG layer 2
			if (this.check([0x04], {offset: offset + 1, mask: [0x06]})) {
				return {
					ext: 'mp2',
					mime: 'audio/mpeg',
				};
			}

			// Check for MPEG layer 1
			if (this.check([0x06], {offset: offset + 1, mask: [0x06]})) {
				return {
					ext: 'mp1',
					mime: 'audio/mpeg',
				};
			}
		}
	}
};

new Set(extensions);
new Set(mimeTypes$1);

/**
Node.js specific entry point.
*/


class FileTypeParser extends FileTypeParser$1 {
	async fromStream(stream) {
		const tokenizer = await (stream instanceof ReadableStream$1 ? fromWebStream(stream, this.tokenizerOptions) : fromStream(stream, this.tokenizerOptions));
		try {
			return await super.fromTokenizer(tokenizer);
		} finally {
			await tokenizer.close();
		}
	}

	async fromFile(path) {
		const tokenizer = await fromFile(path);
		try {
			return await super.fromTokenizer(tokenizer);
		} finally {
			await tokenizer.close();
		}
	}

	async toDetectionStream(readableStream, options = {}) {
		if (!(readableStream instanceof Readable)) {
			return super.toDetectionStream(readableStream, options);
		}

		const {sampleSize = reasonableDetectionSizeInBytes} = options;

		return new Promise((resolve, reject) => {
			readableStream.on('error', reject);

			readableStream.once('readable', () => {
				(async () => {
					try {
						// Set up output stream
						const pass = new PassThrough();
						const outputStream = pipeline ? pipeline(readableStream, pass, () => {}) : readableStream.pipe(pass);

						// Read the input stream and detect the filetype
						const chunk = readableStream.read(sampleSize) ?? readableStream.read() ?? new Uint8Array(0);
						try {
							pass.fileType = await this.fromBuffer(chunk);
						} catch (error) {
							if (error instanceof EndOfStreamError) {
								pass.fileType = undefined;
							} else {
								reject(error);
							}
						}

						resolve(outputStream);
					} catch (error) {
						reject(error);
					}
				})();
			});
		});
	}
}

async function fileTypeFromFile(path, options) {
	return (new FileTypeParser(options)).fromFile(path, options);
}

class RequestUtil {
  // 适用于获取服务器下发cookies时获取，仅GET
  static async HttpsGetCookies(url) {
    const client = url.startsWith("https") ? https$1 : http;
    return new Promise((resolve, reject) => {
      const req = client.get(url, (res) => {
        const cookies = {};
        res.on("data", () => {
        });
        res.on("end", () => {
          this.handleRedirect(res, url, cookies).then(resolve).catch(reject);
        });
        if (res.headers["set-cookie"]) {
          this.extractCookies(res.headers["set-cookie"], cookies);
        }
      });
      req.on("error", (error) => {
        reject(error);
      });
    });
  }
  static async handleRedirect(res, url, cookies) {
    if (res.statusCode === 301 || res.statusCode === 302) {
      if (res.headers.location) {
        const redirectUrl = new URL(res.headers.location, url);
        const redirectCookies = await this.HttpsGetCookies(redirectUrl.href);
        return { ...cookies, ...redirectCookies };
      }
    }
    return cookies;
  }
  static extractCookies(setCookieHeaders, cookies) {
    setCookieHeaders.forEach((cookie) => {
      const parts = cookie.split(";")[0]?.split("=");
      if (parts) {
        const key = parts[0];
        const value = parts[1];
        if (key && value && key.length > 0 && value.length > 0) {
          cookies[key] = value;
        }
      }
    });
  }
  // 请求和回复都是JSON data传原始内容 自动编码json
  static async HttpGetJson(url, method = "GET", data, headers = {}, isJsonRet = true, isArgJson = true) {
    const option = new URL(url);
    const protocol = url.startsWith("https://") ? https$1 : http;
    const options = {
      hostname: option.hostname,
      port: option.port,
      path: option.pathname + option.search,
      method,
      headers
    };
    return new Promise((resolve, reject) => {
      const req = protocol.request(options, (res) => {
        let responseBody = "";
        res.on("data", (chunk) => {
          responseBody += chunk.toString();
        });
        res.on("end", () => {
          try {
            if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
              if (isJsonRet) {
                const responseJson = JSON.parse(responseBody);
                resolve(responseJson);
              } else {
                resolve(responseBody);
              }
            } else {
              reject(new Error(`Unexpected status code: ${res.statusCode}`));
            }
          } catch (parseError) {
            reject(new Error(parseError.message));
          }
        });
      });
      req.on("error", (error) => {
        reject(error);
      });
      if (method === "POST" || method === "PUT" || method === "PATCH") {
        if (isArgJson) {
          req.write(JSON.stringify(data));
        } else {
          req.write(data);
        }
      }
      req.end();
    });
  }
  // 请求返回都是原始内容
  static async HttpGetText(url, method = "GET", data, headers = {}) {
    return this.HttpGetJson(url, method, data, headers, false, false);
  }
}

class RkeyManager {
  serverUrl = [];
  logger;
  rkeyData = {
    group_rkey: "",
    private_rkey: "",
    expired_time: 0
  };
  urlFailures = /* @__PURE__ */ new Map();
  FAILURE_LIMIT = 4;
  ONE_DAY = 24 * 60 * 60 * 1e3;
  constructor(serverUrl, logger) {
    this.logger = logger;
    this.serverUrl = serverUrl;
  }
  async getRkey() {
    const availableUrls = this.getAvailableUrls();
    if (availableUrls.length === 0) {
      this.logger.logError("[Rkey] 所有服务均已禁用, 图片使用FallBack机制");
      throw new Error("获取rkey失败：所有服务URL均已被禁用");
    }
    if (this.isExpired()) {
      try {
        await this.refreshRkey();
      } catch (e) {
        throw new Error(`${e}`);
      }
    }
    return this.rkeyData;
  }
  getAvailableUrls() {
    return this.serverUrl.filter((url) => !this.isUrlDisabled(url));
  }
  isUrlDisabled(url) {
    const failureInfo = this.urlFailures.get(url);
    if (!failureInfo) return false;
    const now = (/* @__PURE__ */ new Date()).getTime();
    if (now - failureInfo.lastTimestamp > this.ONE_DAY) {
      failureInfo.count = 0;
      this.urlFailures.set(url, failureInfo);
      return false;
    }
    return failureInfo.count >= this.FAILURE_LIMIT;
  }
  updateUrlFailure(url) {
    const now = (/* @__PURE__ */ new Date()).getTime();
    const failureInfo = this.urlFailures.get(url) || { count: 0, lastTimestamp: 0 };
    if (now - failureInfo.lastTimestamp > this.ONE_DAY) {
      failureInfo.count = 1;
    } else {
      failureInfo.count++;
    }
    failureInfo.lastTimestamp = now;
    this.urlFailures.set(url, failureInfo);
    if (failureInfo.count >= this.FAILURE_LIMIT) {
      this.logger.logError(`[Rkey] URL ${url} 已被禁用，失败次数达到 ${this.FAILURE_LIMIT} 次`);
    }
  }
  isExpired() {
    const now = (/* @__PURE__ */ new Date()).getTime() / 1e3;
    return now > this.rkeyData.expired_time;
  }
  async refreshRkey() {
    const availableUrls = this.getAvailableUrls();
    if (availableUrls.length === 0) {
      this.logger.logError("[Rkey] 所有服务均已禁用");
      throw new Error("获取rkey失败：所有服务URL均已被禁用");
    }
    for (const url of availableUrls) {
      try {
        let temp = await RequestUtil.HttpGetJson(url, "GET");
        if ("retcode" in temp) {
          temp = temp.data;
        }
        this.rkeyData = {
          group_rkey: temp.group_rkey.slice(6),
          private_rkey: temp.private_rkey.slice(6),
          expired_time: temp.expired_time
        };
        return;
      } catch (e) {
        this.logger.logError(`[Rkey] 异常服务 ${url} 异常 / `, e);
        this.updateUrlFailure(url);
        if (url === availableUrls[availableUrls.length - 1]) {
          throw new Error(`获取rkey失败: ${e}`);
        }
      }
    }
  }
}

async function solveProblem(func, ...args) {
  return new Promise((resolve) => {
    try {
      const result = func(...args);
      resolve(result);
    } catch {
      resolve(void 0);
    }
  });
}
async function solveAsyncProblem(func, ...args) {
  return new Promise((resolve) => {
    func(...args).then((result) => {
      resolve(result);
    }).catch(() => {
      resolve(void 0);
    });
  });
}
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
function PromiseTimer(promise, ms) {
  const timeoutPromise = new Promise(
    (_resolve, reject) => setTimeout(() => reject(new Error("PromiseTimer: Operation timed out")), ms)
  );
  return Promise.race([promise, timeoutPromise]);
}
function isNull(value) {
  return value === void 0 || value === null;
}
function isNumeric(str) {
  return /^\d+$/.test(str);
}
function truncateString(obj, maxLength = 500) {
  if (obj !== null && typeof obj === "object") {
    Object.keys(obj).forEach((key) => {
      if (typeof obj[key] === "string") {
        if (obj[key].length > maxLength) {
          obj[key] = obj[key].substring(0, maxLength) + "...";
        }
      } else if (typeof obj[key] === "object") {
        truncateString(obj[key], maxLength);
      }
    });
  }
  return obj;
}
function getDefaultQQVersionConfigInfo() {
  if (os$1.platform() === "linux") {
    return {
      baseVersion: "3.2.12.28060",
      curVersion: "3.2.12.28060",
      prevVersion: "",
      onErrorVersions: [],
      buildId: "27254"
    };
  }
  if (os$1.platform() === "darwin") {
    return {
      baseVersion: "6.9.53.28060",
      curVersion: "6.9.53.28060",
      prevVersion: "",
      onErrorVersions: [],
      buildId: "28060"
    };
  }
  return {
    baseVersion: "9.9.15-28131",
    curVersion: "9.9.15-28131",
    prevVersion: "",
    onErrorVersions: [],
    buildId: "28131"
  };
}
function getQQPackageInfoPath(exePath = "", version) {
  if (process.env["NAPCAT_QQ_PACKAGE_INFO_PATH"]) {
    return process.env["NAPCAT_QQ_PACKAGE_INFO_PATH"];
  }
  let packagePath;
  if (os$1.platform() === "darwin") {
    packagePath = path$1.join(path$1.dirname(exePath), "..", "Resources", "app", "package.json");
  } else if (os$1.platform() === "linux") {
    packagePath = path$1.join(path$1.dirname(exePath), "./resources/app/package.json");
  } else {
    packagePath = path$1.join(path$1.dirname(exePath), "./versions/" + version + "/resources/app/package.json");
  }
  if (!fs__default.existsSync(packagePath)) {
    packagePath = path$1.join(path$1.dirname(exePath), "./resources/app/versions/" + version + "/package.json");
  }
  return packagePath;
}
function getQQVersionConfigPath(exePath = "") {
  if (process.env["NAPCAT_QQ_VERSION_CONFIG_PATH"]) {
    return process.env["NAPCAT_QQ_VERSION_CONFIG_PATH"];
  }
  let configVersionInfoPath;
  if (os$1.platform() === "win32") {
    configVersionInfoPath = path$1.join(path$1.dirname(exePath), "versions", "config.json");
  } else if (os$1.platform() === "darwin") {
    const userPath = os$1.homedir();
    const appDataPath = path$1.resolve(userPath, "./Library/Application Support/QQ");
    configVersionInfoPath = path$1.resolve(appDataPath, "./versions/config.json");
  } else {
    const userPath = os$1.homedir();
    const appDataPath = path$1.resolve(userPath, "./.config/QQ");
    configVersionInfoPath = path$1.resolve(appDataPath, "./versions/config.json");
  }
  if (typeof configVersionInfoPath !== "string") {
    return void 0;
  }
  if (!fs__default.existsSync(configVersionInfoPath)) {
    configVersionInfoPath = path$1.join(path$1.dirname(exePath), "./resources/app/versions/config.json");
  }
  if (!fs__default.existsSync(configVersionInfoPath)) {
    return void 0;
  }
  return configVersionInfoPath;
}
function calcQQLevel(level) {
  if (!level) return 0;
  const { crownNum, sunNum, moonNum, starNum } = level;
  return crownNum * 64 + sunNum * 16 + moonNum * 4 + starNum;
}
function stringifyWithBigInt(obj) {
  return JSON.stringify(
    obj,
    (_key, value) => typeof value === "bigint" ? value.toString() : value
  );
}
function parseAppidFromMajor(nodeMajor) {
  const hexSequence = "A4 09 00 00 00 35";
  const sequenceBytes = Buffer.from(hexSequence.replace(/ /g, ""), "hex");
  const filePath = path$1.resolve(nodeMajor);
  const fileContent = fs__default.readFileSync(filePath);
  let searchPosition = 0;
  while (true) {
    const index = fileContent.indexOf(sequenceBytes, searchPosition);
    if (index === -1) {
      break;
    }
    const start = index + sequenceBytes.length - 1;
    const end = fileContent.indexOf(0, start);
    if (end === -1) {
      break;
    }
    const content = fileContent.subarray(start, end);
    if (!content.every((byte) => byte === 0)) {
      try {
        return content.toString("utf-8");
      } catch {
        break;
      }
    }
    searchPosition = end + 1;
  }
  return void 0;
}
const baseUrl = "https://github.com/NapNeko/NapCatQQ.git/info/refs?service=git-upload-pack";
const urls$1 = [
  "https://j.1win.ggff.net/" + baseUrl,
  "https://git.yylx.win/" + baseUrl,
  "https://ghfile.geekertao.top/" + baseUrl,
  "https://gh-proxy.net/" + baseUrl,
  "https://ghm.078465.xyz/" + baseUrl,
  "https://gitproxy.127731.xyz/" + baseUrl,
  "https://jiashu.1win.eu.org/" + baseUrl,
  baseUrl
];
async function testUrl$2(url) {
  try {
    await PromiseTimer(RequestUtil.HttpGetText(url), 5e3);
    return true;
  } catch {
    return false;
  }
}
async function findAvailableUrl$2() {
  for (const url of urls$1) {
    if (await testUrl$2(url)) {
      return url;
    }
  }
  return null;
}
async function getAllTags() {
  const availableUrl = await findAvailableUrl$2();
  if (!availableUrl) {
    throw new Error("No available URL for fetching tags");
  }
  const raw = await RequestUtil.HttpGetText(availableUrl);
  return raw.split("\n").map((line) => {
    const match = line.match(/refs\/tags\/(.+)$/);
    return match ? match[1] : null;
  }).filter((tag) => tag !== null && !tag.endsWith("^{}"));
}
async function getLatestTag() {
  const tags = await getAllTags();
  tags.sort((a, b) => compareVersion(a, b));
  const latest = tags.at(-1);
  if (!latest) {
    throw new Error("No tags found");
  }
  return latest.replace(/^v/, "");
}
function compareVersion(a, b) {
  const normalize = (v) => v.replace(/^v/, "").split(".").map((n) => parseInt(n) || 0);
  const pa = normalize(a);
  const pb = normalize(b);
  const len = Math.max(pa.length, pb.length);
  for (let i = 0; i < len; i++) {
    const na = pa[i] || 0;
    const nb = pb[i] || 0;
    if (na !== nb) return na - nb;
  }
  return 0;
}

function checkFileExist(path2, timeout = 3e3) {
  return new Promise((resolve, reject) => {
    const startTime = Date.now();
    function check() {
      if (fs__default.existsSync(path2)) {
        resolve();
      } else if (Date.now() - startTime > timeout) {
        reject(new Error(`文件不存在: ${path2}`));
      } else {
        setTimeout(check, 100);
      }
    }
    check();
  });
}
async function checkFileExistV2(path2, timeout = 3e3) {
  await Promise.race([
    checkFile(path2),
    timeoutPromise(timeout, `文件不存在: ${path2}`)
  ]);
}
function timeoutPromise(timeout, errorMsg) {
  return new Promise((_resolve, reject) => {
    setTimeout(() => {
      reject(new Error(errorMsg));
    }, timeout);
  });
}
async function checkFile(path2) {
  try {
    await stat$1(path2);
  } catch (error) {
    if (error.code === "ENOENT") {
      throw new Error(`文件不存在: ${path2}`);
    } else {
      throw error;
    }
  }
}
function calculateFileMD5(filePath) {
  return new Promise((resolve, reject) => {
    const stream = fs__default.createReadStream(filePath);
    const hash = crypto__default.createHash("md5");
    stream.on("data", (data) => {
      hash.update(data);
    });
    stream.on("end", () => {
      const md5 = hash.digest("hex");
      resolve(md5);
    });
    stream.on("error", (err) => {
      reject(err);
    });
  });
}
async function tryDownload(options, useReferer = false) {
  let url;
  let headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36"
  };
  if (typeof options === "string") {
    url = options;
    headers["Host"] = new URL(url).hostname;
  } else {
    url = options.url;
    if (options.headers) {
      if (typeof options.headers === "string") {
        headers = JSON.parse(options.headers);
      } else {
        headers = options.headers;
      }
    }
  }
  if (useReferer && !headers["Referer"]) {
    headers["Referer"] = url;
  }
  const fetchRes = await fetch(url, { headers, redirect: "follow" }).catch((err) => {
    if (err.cause) {
      throw err.cause;
    }
    throw err;
  });
  return fetchRes;
}
async function httpDownload(options) {
  const useReferer = typeof options === "string";
  let resp = await tryDownload(options);
  if (resp.status === 403 && useReferer) {
    resp = await tryDownload(options, true);
  }
  if (!resp.ok) throw new Error(`下载文件失败: ${resp.statusText}`);
  const blob = await resp.blob();
  const buffer = await blob.arrayBuffer();
  return Buffer.from(buffer);
}
async function checkUriType(Uri) {
  const LocalFileRet = await solveProblem((uri) => {
    if (fs__default.existsSync(path$1.normalize(uri))) {
      return { Uri: path$1.normalize(uri), Type: 1 /* Local */ };
    }
    return void 0;
  }, Uri);
  if (LocalFileRet) return LocalFileRet;
  const OtherFileRet = await solveProblem((uri) => {
    if (uri.startsWith("http:") || uri.startsWith("https:")) {
      return { Uri: uri, Type: 2 /* Remote */ };
    }
    if (uri.startsWith("base64:")) {
      return { Uri: uri, Type: 3 /* Base64 */ };
    }
    if (uri.startsWith("file:")) {
      const filePath = decodeURIComponent(uri.startsWith("file:///") && process.platform === "win32" ? uri.slice(8) : uri.slice(7));
      return { Uri: filePath, Type: 1 /* Local */ };
    }
    if (uri.startsWith("data:")) {
      const data = uri.split(",")[1];
      if (data) return { Uri: data, Type: 3 /* Base64 */ };
    }
    return void 0;
  }, Uri);
  if (OtherFileRet) return OtherFileRet;
  return { Uri, Type: 0 /* Unknown */ };
}
async function uriToLocalFile(dir, uri, filename = randomUUID(), headers) {
  const { Uri: HandledUri, Type: UriType } = await checkUriType(uri);
  const filePath = path$1.join(dir, filename);
  switch (UriType) {
    case 1 /* Local */: {
      const fileExt = path$1.extname(HandledUri);
      const localFileName = path$1.basename(HandledUri, fileExt) + fileExt;
      const tempFilePath = path$1.join(dir, filename + fileExt);
      fs__default.copyFileSync(HandledUri, tempFilePath);
      return { success: true, errMsg: "", fileName: localFileName, path: tempFilePath };
    }
    case 2 /* Remote */: {
      const buffer = await httpDownload({ url: HandledUri, headers: headers ?? {} });
      fs__default.writeFileSync(filePath, buffer);
      return { success: true, errMsg: "", fileName: filename, path: filePath };
    }
    case 3 /* Base64 */: {
      const base64 = HandledUri.replace(/^base64:\/\//, "");
      const base64Buffer = Buffer.from(base64, "base64");
      fs__default.writeFileSync(filePath, base64Buffer);
      return { success: true, errMsg: "", fileName: filename, path: filePath };
    }
    default:
      return { success: false, errMsg: `识别URL失败, uri= ${uri}`, fileName: "", path: "" };
  }
}

const FileId = {
  appid: ProtoField(4, ScalarType.UINT32, true),
  ttl: ProtoField(10, ScalarType.UINT32, true)
};

class NTQQFileApi {
  context;
  core;
  rkeyManager;
  packetRkey;
  fetchRkeyFailures = 0;
  MAX_RKEY_FAILURES = 8;
  constructor(context, core) {
    this.context = context;
    this.core = core;
    this.rkeyManager = new RkeyManager(
      [
        "http://ss.xingzhige.com/music_card/rkey",
        "https://secret-service.bietiaop.com/rkeys"
      ],
      this.context.logger
    );
  }
  async fetchRkeyWithRetry() {
    if (this.fetchRkeyFailures >= this.MAX_RKEY_FAILURES) {
      throw new Error("Native.FetchRkey 已被禁用");
    }
    try {
      const ret = await this.core.apis.PacketApi.pkt.operation.FetchRkey();
      this.fetchRkeyFailures = 0;
      return ret;
    } catch (error) {
      this.fetchRkeyFailures++;
      this.context.logger.logError("FetchRkey 失败", error.message);
      throw error;
    }
  }
  async getFileUrl(chatType, peer, fileUUID, file10MMd5, timeout = 5e3) {
    if (this.core.apis.PacketApi.packetStatus) {
      try {
        if (chatType === ChatType.KCHATTYPEGROUP && fileUUID) {
          return this.core.apis.PacketApi.pkt.operation.GetGroupFileUrl(+peer, fileUUID, timeout);
        } else if (file10MMd5 && fileUUID) {
          return this.core.apis.PacketApi.pkt.operation.GetPrivateFileUrl(peer, fileUUID, file10MMd5, timeout);
        }
      } catch (error) {
        this.context.logger.logError("获取文件URL失败", error.message);
      }
    }
    throw new Error("fileUUID or file10MMd5 is undefined");
  }
  async getPttUrl(peer, fileUUID, timeout = 5e3) {
    if (this.core.apis.PacketApi.packetStatus && fileUUID) {
      const appid = new NapProtoMsg(FileId).decode(Buffer.from(fileUUID.replaceAll("-", "+").replaceAll("_", "/"), "base64")).appid;
      try {
        if (appid && appid === 1403) {
          return this.core.apis.PacketApi.pkt.operation.GetGroupPttUrl(+peer, {
            fileUuid: fileUUID,
            storeId: 1,
            uploadTime: 0,
            ttl: 0,
            subType: 0
          }, timeout);
        } else if (fileUUID) {
          return this.core.apis.PacketApi.pkt.operation.GetPttUrl(peer, {
            fileUuid: fileUUID,
            storeId: 1,
            uploadTime: 0,
            ttl: 0,
            subType: 0
          }, timeout);
        }
      } catch (error) {
        this.context.logger.logError("获取文件URL失败", error.message);
      }
    }
    throw new Error("packet cant get ptt url");
  }
  async getVideoUrlPacket(peer, fileUUID, timeout = 5e3) {
    if (this.core.apis.PacketApi.packetStatus && fileUUID) {
      const appid = new NapProtoMsg(FileId).decode(Buffer.from(fileUUID.replaceAll("-", "+").replaceAll("_", "/"), "base64")).appid;
      try {
        if (appid && appid === 1415) {
          return this.core.apis.PacketApi.pkt.operation.GetGroupVideoUrl(+peer, {
            fileUuid: fileUUID,
            storeId: 1,
            uploadTime: 0,
            ttl: 0,
            subType: 0
          }, timeout);
        } else if (fileUUID) {
          return this.core.apis.PacketApi.pkt.operation.GetVideoUrl(peer, {
            fileUuid: fileUUID,
            storeId: 1,
            uploadTime: 0,
            ttl: 0,
            subType: 0
          }, timeout);
        }
      } catch (error) {
        this.context.logger.logError("获取文件URL失败", error.message);
      }
    }
    throw new Error("packet cant get video url");
  }
  async copyFile(filePath, destPath) {
    await this.core.util.copyFile(filePath, destPath);
  }
  async getFileSize(filePath) {
    return await this.core.util.getFileSize(filePath);
  }
  async getVideoUrl(peer, msgId, elementId) {
    return (await this.context.session.getRichMediaService().getVideoPlayUrlV2(peer, msgId, elementId, 0, {
      downSourceType: 1,
      triggerType: 1
    })).urlResult.domainUrl;
  }
  async uploadFile(filePath, elementType = ElementType.PIC, elementSubType = 0) {
    const fileMd5 = await calculateFileMD5(filePath);
    const extOrEmpty = await fileTypeFromFile(filePath).then((e) => e?.ext ?? "").catch(() => "");
    const ext = extOrEmpty ? `.${extOrEmpty}` : "";
    let fileName = `${path__default.basename(filePath)}`;
    if (fileName.indexOf(".") === -1) {
      fileName += ext;
    }
    const mediaPath = this.context.session.getMsgService().getRichMediaFilePathForGuild({
      md5HexStr: fileMd5,
      fileName,
      elementType,
      elementSubType,
      thumbSize: 0,
      needCreate: true,
      downloadType: 1,
      file_uuid: ""
    });
    await this.copyFile(filePath, mediaPath);
    const fileSize = await this.getFileSize(filePath);
    return {
      md5: fileMd5,
      fileName,
      path: mediaPath,
      fileSize,
      ext
    };
  }
  async downloadFileForModelId(peer, modelId, unknown, timeout = 1e3 * 60 * 2) {
    const [, fileTransNotifyInfo] = await this.core.eventWrapper.callNormalEventV2(
      "NodeIKernelRichMediaService/downloadFileForModelId",
      "NodeIKernelMsgListener/onRichMediaDownloadComplete",
      [peer, [modelId], unknown],
      () => true,
      (arg) => arg?.commonFileInfo?.fileModelId === modelId,
      1,
      timeout
    );
    return fileTransNotifyInfo.filePath;
  }
  async downloadRawMsgMedia(msg) {
    const res = await Promise.all(
      msg.map(
        (m) => Promise.all(
          m.elements.filter(
            (element) => element.elementType === ElementType.PIC || element.elementType === ElementType.VIDEO || element.elementType === ElementType.PTT || element.elementType === ElementType.FILE
          ).map(
            (element) => this.downloadMedia(m.msgId, m.chatType, m.peerUid, element.elementId, "", "", 1e3 * 60 * 2, true)
          )
        )
      )
    );
    msg.forEach((m, msgIndex) => {
      const elementResults = res[msgIndex];
      let elementIndex = 0;
      m.elements.forEach((element) => {
        if (element.elementType === ElementType.PIC || element.elementType === ElementType.VIDEO || element.elementType === ElementType.PTT || element.elementType === ElementType.FILE) {
          switch (element.elementType) {
            case ElementType.PIC:
              element.picElement.sourcePath = elementResults?.[elementIndex] ?? "";
              break;
            case ElementType.VIDEO:
              element.videoElement.filePath = elementResults?.[elementIndex] ?? "";
              break;
            case ElementType.PTT:
              element.pttElement.filePath = elementResults?.[elementIndex] ?? "";
              break;
            case ElementType.FILE:
              element.fileElement.filePath = elementResults?.[elementIndex] ?? "";
              break;
          }
          elementIndex++;
        }
      });
    });
    return res.flat();
  }
  async downloadMedia(msgId, chatType, peerUid, elementId, thumbPath, sourcePath, timeout = 1e3 * 60 * 2, force = false) {
    if (sourcePath && fs__default.existsSync(sourcePath)) {
      if (force) {
        try {
          await fsProm.unlink(sourcePath);
        } catch {
        }
      } else {
        return sourcePath;
      }
    }
    const [, completeRetData] = await this.core.eventWrapper.callNormalEventV2(
      "NodeIKernelMsgService/downloadRichMedia",
      "NodeIKernelMsgListener/onRichMediaDownloadComplete",
      [{
        fileModelId: "0",
        downSourceType: 0,
        downloadSourceType: 0,
        triggerType: 1,
        msgId,
        chatType,
        peerUid,
        elementId,
        thumbSize: 0,
        downloadType: 1,
        filePath: thumbPath
      }],
      () => true,
      (arg) => arg.msgElementId === elementId && arg.msgId === msgId,
      1,
      timeout
    );
    return completeRetData.filePath;
  }
  async searchForFile(keys) {
    const randomResultId = 1e5 + Math.floor(Math.random() * 1e4);
    let searchId = 0;
    const [, searchResult] = await this.core.eventWrapper.callNormalEventV2(
      "NodeIKernelFileAssistantService/searchFile",
      "NodeIKernelFileAssistantListener/onFileSearch",
      [
        keys,
        { resultType: 2, pageLimit: 1 },
        randomResultId
      ],
      (ret) => {
        searchId = ret;
        return true;
      },
      (result) => result.searchId === searchId && result.resultId === randomResultId
    );
    return searchResult.resultItems[0];
  }
  async downloadFileById(fileId, fileSize = 1024576, estimatedTime = fileSize * 1e3 / 1024576 + 5e3) {
    const [, fileData] = await this.core.eventWrapper.callNormalEventV2(
      "NodeIKernelFileAssistantService/downloadFile",
      "NodeIKernelFileAssistantListener/onFileStatusChanged",
      [[fileId]],
      (ret) => ret.result === 0,
      (status) => status.fileStatus === 2 && status.fileProgress === "0",
      1,
      estimatedTime
      // estimate 1MB/s
    );
    return fileData.filePath;
  }
  async getImageUrl(element) {
    if (!element) {
      return "";
    }
    const url = element.originImageUrl ?? "";
    const md5HexStr = element.md5HexStr;
    const fileMd5 = element.md5HexStr;
    const parsedUrl = new URL(IMAGE_HTTP_HOST + url);
    const imageAppid = parsedUrl.searchParams.get("appid");
    const isNTV2 = imageAppid && ["1406", "1407"].includes(imageAppid);
    const imageFileId = parsedUrl.searchParams.get("fileid");
    if (url && isNTV2 && imageFileId) {
      const rkeyData = await this.getRkeyData();
      return this.getImageUrlFromParsedUrl(imageFileId, imageAppid, rkeyData);
    }
    return this.getImageUrlFromMd5(fileMd5, md5HexStr);
  }
  async getRkeyData() {
    const rkeyData = {
      private_rkey: "CAQSKAB6JWENi5LM_xp9vumLbuThJSaYf-yzMrbZsuq7Uz2qEc3Rbib9LP4",
      group_rkey: "CAQSKAB6JWENi5LM_xp9vumLbuThJSaYf-yzMrbZsuq7Uz2qffcqm614gds",
      online_rkey: false
    };
    try {
      if (this.core.apis.PacketApi.packetStatus) {
        const rkey_expired_private = !this.packetRkey || this.packetRkey[0] && this.packetRkey[0].time + Number(this.packetRkey[0].ttl) < Date.now() / 1e3;
        const rkey_expired_group = !this.packetRkey || this.packetRkey[0] && this.packetRkey[0].time + Number(this.packetRkey[0].ttl) < Date.now() / 1e3;
        if (rkey_expired_private || rkey_expired_group) {
          this.packetRkey = await this.fetchRkeyWithRetry();
        }
        if (this.packetRkey && this.packetRkey.length > 0) {
          rkeyData.group_rkey = this.packetRkey[1]?.rkey.slice(6) ?? "";
          rkeyData.private_rkey = this.packetRkey[0]?.rkey.slice(6) ?? "";
          rkeyData.online_rkey = true;
        }
      }
    } catch (error) {
      this.context.logger.logDebug("获取native.rkey失败", error.message);
    }
    if (!rkeyData.online_rkey) {
      try {
        const tempRkeyData = await this.rkeyManager.getRkey();
        rkeyData.group_rkey = tempRkeyData.group_rkey;
        rkeyData.private_rkey = tempRkeyData.private_rkey;
        rkeyData.online_rkey = tempRkeyData.expired_time > Date.now() / 1e3;
      } catch (error) {
        this.context.logger.logDebug("获取remote.rkey失败", error.message);
      }
    }
    return rkeyData;
  }
  getImageUrlFromParsedUrl(imageFileId, appid, rkeyData) {
    const rkey = appid === "1406" ? rkeyData.private_rkey : rkeyData.group_rkey;
    if (rkeyData.online_rkey) {
      return IMAGE_HTTP_HOST_NT + `/download?appid=${appid}&fileid=${imageFileId}&rkey=${rkey}`;
    }
    return IMAGE_HTTP_HOST + `/download?appid=${appid}&fileid=${imageFileId}&rkey=${rkey}&spec=0`;
  }
  getImageUrlFromMd5(fileMd5, md5HexStr) {
    if (fileMd5 || md5HexStr) {
      return `${IMAGE_HTTP_HOST}/gchatpic_new/0/0-0-${(fileMd5 ?? md5HexStr ?? "").toUpperCase()}/0`;
    }
    this.context.logger.logDebug("图片url获取失败", { fileMd5, md5HexStr });
    return "";
  }
}

class LimitedHashTable {
  keyToValue = /* @__PURE__ */ new Map();
  valueToKey = /* @__PURE__ */ new Map();
  maxSize;
  constructor(maxSize) {
    this.maxSize = maxSize;
  }
  resize(count) {
    this.maxSize = count;
  }
  set(key, value) {
    this.keyToValue.set(key, value);
    this.valueToKey.set(value, key);
    while (this.keyToValue.size !== this.valueToKey.size) {
      this.keyToValue.clear();
      this.valueToKey.clear();
    }
    while (this.keyToValue.size > this.maxSize || this.valueToKey.size > this.maxSize) {
      const oldestKey = this.keyToValue.keys().next().value;
      if (oldestKey !== void 0) {
        this.valueToKey.delete(this.keyToValue.get(oldestKey));
        this.keyToValue.delete(oldestKey);
      }
    }
  }
  getValue(key) {
    return this.keyToValue.get(key);
  }
  getKey(value) {
    return this.valueToKey.get(value);
  }
  deleteByValue(value) {
    const key = this.valueToKey.get(value);
    if (key !== void 0) {
      this.keyToValue.delete(key);
      this.valueToKey.delete(value);
    }
  }
  deleteByKey(key) {
    const value = this.keyToValue.get(key);
    if (value !== void 0) {
      this.keyToValue.delete(key);
      this.valueToKey.delete(value);
    }
  }
  getKeyList() {
    return Array.from(this.keyToValue.keys());
  }
  // 获取最近刚写入的几个值
  getHeads(size) {
    const keyList = this.getKeyList();
    if (keyList.length === 0) {
      return void 0;
    }
    const result = [];
    const listSize = Math.min(size, keyList.length);
    for (let i = 0; i < listSize; i++) {
      const key = keyList[listSize - i];
      if (key !== void 0) {
        result.push({ key, value: this.keyToValue.get(key) });
      }
    }
    return result;
  }
}
class MessageUniqueWrapper {
  msgDataMap;
  msgIdMap;
  constructor(maxMap = 5e3) {
    this.msgIdMap = new LimitedHashTable(maxMap);
    this.msgDataMap = new LimitedHashTable(maxMap);
  }
  getRecentMsgIds(Peer2, size) {
    const heads = this.msgIdMap.getHeads(size);
    if (!heads) {
      return [];
    }
    const data = heads.map((t) => MessageUnique.getMsgIdAndPeerByShortId(t.value));
    const ret = data.filter((t) => t?.Peer.chatType === Peer2.chatType && t?.Peer.peerUid === Peer2.peerUid);
    return ret.map((t) => t?.MsgId).filter((t) => t !== void 0);
  }
  createUniqueMsgId(peer, msgId) {
    const key = `${msgId}|${peer.chatType}|${peer.peerUid}`;
    const hash = crypto__default.createHash("md5").update(key).digest();
    if (hash[0]) {
      hash[0] &= 127;
    }
    const shortId = hash.readInt32BE(0);
    this.msgIdMap.set(msgId, shortId);
    this.msgDataMap.set(key, shortId);
    return shortId;
  }
  getMsgIdAndPeerByShortId(shortId) {
    const data = this.msgDataMap.getKey(shortId);
    if (data) {
      const [msgId, chatTypeStr, peerUid] = data.split("|");
      const peer = {
        chatType: parseInt(chatTypeStr ?? "0"),
        peerUid: peerUid ?? "",
        guildId: ""
      };
      return { MsgId: msgId ?? "0", Peer: peer };
    }
    return void 0;
  }
  getShortIdByMsgId(msgId) {
    return this.msgIdMap.getValue(msgId);
  }
  getPeerByMsgId(msgId) {
    const shortId = this.msgIdMap.getValue(msgId);
    if (!shortId) return void 0;
    return this.getMsgIdAndPeerByShortId(shortId);
  }
  resize(maxSize) {
    this.msgIdMap.resize(maxSize);
    this.msgDataMap.resize(maxSize);
  }
}
const MessageUnique = new MessageUniqueWrapper();

class NTQQFriendApi {
  context;
  core;
  constructor(context, core) {
    this.context = context;
    this.core = core;
  }
  async setBuddyRemark(uid, remark) {
    return this.context.session.getBuddyService().setBuddyRemark({ uid, remark });
  }
  async getBuddyV2SimpleInfoMap() {
    const buddyService = this.context.session.getBuddyService();
    let uids = [];
    if (this.core.context.basicInfoWrapper.requireMinNTQQBuild("41679")) {
      const buddyListV2NT = await buddyService.getBuddyListV2("0", true, BuddyListReqType.KNOMAL);
      uids = buddyListV2NT.data.flatMap((item) => item.buddyUids);
    } else {
      const buddyListV2 = await buddyService.getBuddyListV2("0", BuddyListReqType.KNOMAL);
      uids = buddyListV2.data.flatMap((item) => item.buddyUids);
    }
    return await this.core.eventWrapper.callNoListenerEvent(
      "NodeIKernelProfileService/getCoreAndBaseInfo",
      "nodeStore",
      uids
    );
  }
  async getBuddy() {
    return Array.from((await this.getBuddyV2SimpleInfoMap()).values());
  }
  async getBuddyIdMap() {
    const retMap = new LimitedHashTable(5e3);
    const data = await this.getBuddyV2SimpleInfoMap();
    data.forEach((value) => retMap.set(value.uin, value.uid));
    return retMap;
  }
  async delBuudy(uid, tempBlock = false, tempBothDel = false) {
    return this.context.session.getBuddyService().delBuddy({
      friendUid: uid,
      tempBlock,
      tempBothDel
    });
  }
  async getBuddyV2ExWithCate() {
    const buddyService = this.context.session.getBuddyService();
    let uids = [];
    let buddyListV2;
    if (this.core.context.basicInfoWrapper.requireMinNTQQBuild("41679")) {
      buddyListV2 = (await buddyService.getBuddyListV2("0", true, BuddyListReqType.KNOMAL)).data;
      uids = buddyListV2.flatMap((item) => item.buddyUids);
    } else {
      buddyListV2 = (await buddyService.getBuddyListV2("0", BuddyListReqType.KNOMAL)).data;
      uids = buddyListV2.flatMap((item) => item.buddyUids);
    }
    const data = await this.core.eventWrapper.callNoListenerEvent(
      "NodeIKernelProfileService/getCoreAndBaseInfo",
      "nodeStore",
      uids
    );
    return buddyListV2.map((category) => ({
      categoryId: category.categoryId,
      categorySortId: category.categorySortId,
      categoryName: category.categroyName,
      categoryMbCount: category.categroyMbCount,
      onlineCount: category.onlineCount,
      buddyList: category.buddyUids.map((uid) => data.get(uid)).filter((value) => !!value)
    }));
  }
  async isBuddy(uid) {
    return this.context.session.getBuddyService().isBuddy(uid);
  }
  async clearBuddyReqUnreadCnt() {
    return this.context.session.getBuddyService().clearBuddyReqUnreadCnt();
  }
  async getBuddyReq() {
    const [, ret] = await this.core.eventWrapper.callNormalEventV2(
      "NodeIKernelBuddyService/getBuddyReq",
      "NodeIKernelBuddyListener/onBuddyReqChange",
      []
    );
    return ret;
  }
  async handleFriendRequest(notify, accept) {
    this.context.session.getBuddyService()?.approvalFriendRequest({
      friendUid: notify.friendUid,
      reqTime: notify.reqTime,
      accept
    });
  }
  async handleDoubtFriendRequest(friendUid, str1 = "", str2 = "") {
    this.context.session.getBuddyService().approvalDoubtBuddyReq(friendUid, str1, str2);
  }
  async getDoubtFriendRequest(count) {
    const date = Date.now().toString();
    const [, ret] = await this.core.eventWrapper.callNormalEventV2(
      "NodeIKernelBuddyService/getDoubtBuddyReq",
      "NodeIKernelBuddyListener/onDoubtBuddyReqChange",
      [date, count, ""],
      () => true,
      (data) => data.reqId === date
    );
    const requests = Promise.all(ret.doubtList.map(async (item) => {
      return {
        flag: item.uid,
        // 注意强制String 非isNumeric 不遵守则不符合设计
        uin: await this.core.apis.UserApi.getUinByUidV2(item.uid) ?? 0,
        // 信息字段
        nick: item.nick,
        // 信息字段 这个不是nickname 可能是来源的群内的昵称
        source: item.source,
        // 信息字段
        reason: item.reason,
        // 信息字段
        msg: item.msg,
        // 信息字段
        group_code: item.groupCode,
        // 信息字段
        time: item.reqTime,
        // 信息字段
        type: "doubt"
        // 保留字段
      };
    }));
    return requests;
  }
}

class CancelableTask {
  promise;
  cancelCallback = null;
  isCanceled = false;
  cancelListeners = [];
  constructor(executor) {
    this.promise = new Promise((resolve, reject) => {
      const onCancel = (callback) => {
        this.cancelCallback = callback;
      };
      const execute = async () => {
        try {
          await executor(
            (value) => {
              if (!this.isCanceled) {
                resolve(value);
              }
            },
            (reason) => {
              if (!this.isCanceled) {
                reject(reason);
              }
            },
            onCancel
          );
        } catch (error) {
          if (!this.isCanceled) {
            reject(error);
          }
        }
      };
      execute();
    });
  }
  cancel() {
    if (this.cancelCallback) {
      this.cancelCallback();
    }
    this.isCanceled = true;
    this.cancelListeners.forEach((listener) => listener());
  }
  isTaskCanceled() {
    return this.isCanceled;
  }
  onCancel(listener) {
    this.cancelListeners.push(listener);
  }
  then(onfulfilled, onrejected) {
    return this.promise.then(onfulfilled, onrejected);
  }
  catch(onrejected) {
    return this.promise.catch(onrejected);
  }
  finally(onfinally) {
    return this.promise.finally(onfinally);
  }
  [Symbol.asyncIterator]() {
    return {
      next: () => this.promise.then((value) => ({ value, done: true }))
    };
  }
}

function createGroupDetailInfoV2Param(group_code) {
  return {
    groupCode: group_code,
    filter: {
      noCodeFingerOpenFlag: 0,
      noFingerOpenFlag: 0,
      groupName: 0,
      classExt: 0,
      classText: 0,
      fingerMemo: 0,
      richFingerMemo: 0,
      tagRecord: 0,
      groupGeoInfo: {
        ownerUid: 0,
        setTime: 0,
        cityId: 0,
        longitude: 0,
        latitude: 0,
        geoContent: 0,
        poiId: 0
      },
      groupExtAdminNum: 0,
      flag: 0,
      groupMemo: 0,
      groupAioSkinUrl: 0,
      groupBoardSkinUrl: 0,
      groupCoverSkinUrl: 0,
      groupGrade: 0,
      activeMemberNum: 0,
      certificationType: 0,
      certificationText: 0,
      groupNewGuideLines: {
        enabled: 0,
        content: 0
      },
      groupFace: 0,
      addOption: 0,
      shutUpTime: 0,
      groupTypeFlag: 0,
      appPrivilegeFlag: 0,
      appPrivilegeMask: 0,
      groupExtOnly: {
        tribeId: 0,
        moneyForAddGroup: 0
      },
      groupSecLevel: 0,
      groupSecLevelInfo: 0,
      subscriptionUin: 0,
      subscriptionUid: "",
      allowMemberInvite: 0,
      groupQuestion: 0,
      groupAnswer: 0,
      groupFlagExt3: 0,
      groupFlagExt3Mask: 0,
      groupOpenAppid: 0,
      rootId: 0,
      msgLimitFrequency: 0,
      hlGuildAppid: 0,
      hlGuildSubType: 0,
      hlGuildOrgId: 0,
      groupFlagExt4: 0,
      groupFlagExt4Mask: 0,
      groupSchoolInfo: {
        location: 0,
        grade: 0,
        school: 0
      },
      groupCardPrefix: {
        introduction: 0,
        rptPrefix: 0
      },
      allianceId: 0,
      groupFlagPro1: 0,
      groupFlagPro1Mask: 0
    },
    modifyInfo: {
      noCodeFingerOpenFlag: 0,
      noFingerOpenFlag: 0,
      groupName: "",
      classExt: 0,
      classText: "",
      fingerMemo: "",
      richFingerMemo: "",
      tagRecord: [],
      groupGeoInfo: {
        ownerUid: "",
        SetTime: 0,
        CityId: 0,
        Longitude: "",
        Latitude: "",
        GeoContent: "",
        poiId: ""
      },
      groupExtAdminNum: 0,
      flag: 0,
      groupMemo: "",
      groupAioSkinUrl: "",
      groupBoardSkinUrl: "",
      groupCoverSkinUrl: "",
      groupGrade: 0,
      activeMemberNum: 0,
      certificationType: 0,
      certificationText: "",
      groupNewGuideLines: {
        enabled: false,
        content: ""
      },
      groupFace: 0,
      addOption: 0,
      shutUpTime: 0,
      groupTypeFlag: 0,
      appPrivilegeFlag: 0,
      appPrivilegeMask: 0,
      groupExtOnly: {
        tribeId: 0,
        moneyForAddGroup: 0
      },
      groupSecLevel: 0,
      groupSecLevelInfo: 0,
      subscriptionUin: "",
      subscriptionUid: "",
      allowMemberInvite: 0,
      groupQuestion: "",
      groupAnswer: "",
      groupFlagExt3: 0,
      groupFlagExt3Mask: 0,
      groupOpenAppid: 0,
      rootId: "",
      msgLimitFrequency: 0,
      hlGuildAppid: 0,
      hlGuildSubType: 0,
      hlGuildOrgId: 0,
      groupFlagExt4: 0,
      groupFlagExt4Mask: 0,
      groupSchoolInfo: {
        location: "",
        grade: 0,
        school: ""
      },
      groupCardPrefix: {
        introduction: "",
        rptPrefix: []
      },
      allianceId: "",
      groupFlagPro1: 0,
      groupFlagPro1Mask: 0
    }
  };
}
function createGroupExtInfo(group_code) {
  return {
    groupCode: group_code,
    resultCode: 0,
    extInfo: {
      groupInfoExtSeq: 0,
      reserve: 0,
      luckyWordId: "",
      lightCharNum: 0,
      luckyWord: "",
      starId: 0,
      essentialMsgSwitch: 0,
      todoSeq: 0,
      blacklistExpireTime: 0,
      isLimitGroupRtc: 0,
      companyId: 0,
      hasGroupCustomPortrait: 0,
      bindGuildId: "",
      groupOwnerId: {
        memberUin: "",
        memberUid: "",
        memberQid: ""
      },
      essentialMsgPrivilege: 0,
      msgEventSeq: "",
      inviteRobotSwitch: 0,
      gangUpId: "",
      qqMusicMedalSwitch: 0,
      showPlayTogetherSwitch: 0,
      groupFlagPro1: "",
      groupBindGuildIds: {
        guildIds: []
      },
      viewedMsgDisappearTime: "",
      groupExtFlameData: {
        switchState: 0,
        state: 0,
        dayNums: [],
        version: 0,
        updateTime: "",
        isDisplayDayNum: false
      },
      groupBindGuildSwitch: 0,
      groupAioBindGuildId: "",
      groupExcludeGuildIds: {
        guildIds: []
      },
      fullGroupExpansionSwitch: 0,
      fullGroupExpansionSeq: "",
      inviteRobotMemberSwitch: 0,
      inviteRobotMemberExamine: 0,
      groupSquareSwitch: 0
    }
  };
}
function createGroupExtFilter() {
  return {
    groupInfoExtSeq: 0,
    reserve: 0,
    luckyWordId: 0,
    lightCharNum: 0,
    luckyWord: 0,
    starId: 0,
    essentialMsgSwitch: 0,
    todoSeq: 0,
    blacklistExpireTime: 0,
    isLimitGroupRtc: 0,
    companyId: 0,
    hasGroupCustomPortrait: 0,
    bindGuildId: 0,
    groupOwnerId: 0,
    essentialMsgPrivilege: 0,
    msgEventSeq: 0,
    inviteRobotSwitch: 0,
    gangUpId: 0,
    qqMusicMedalSwitch: 0,
    showPlayTogetherSwitch: 0,
    groupFlagPro1: 0,
    groupBindGuildIds: 0,
    viewedMsgDisappearTime: 0,
    groupExtFlameData: 0,
    groupBindGuildSwitch: 0,
    groupAioBindGuildId: 0,
    groupExcludeGuildIds: 0,
    fullGroupExpansionSwitch: 0,
    fullGroupExpansionSeq: 0,
    inviteRobotMemberSwitch: 0,
    inviteRobotMemberExamine: 0,
    groupSquareSwitch: 0
  };
}

class NTQQGroupApi {
  context;
  core;
  groupMemberCache = /* @__PURE__ */ new Map();
  essenceLRU = new LimitedHashTable(1e3);
  constructor(context, core) {
    this.context = context;
    this.core = core;
  }
  async setGroupRemark(groupCode, remark) {
    return this.context.session.getGroupService().modifyGroupRemark(groupCode, remark);
  }
  async fetchGroupDetail(groupCode) {
    const [, detailInfo] = await this.core.eventWrapper.callNormalEventV2(
      "NodeIKernelGroupService/getGroupDetailInfo",
      "NodeIKernelGroupListener/onGroupDetailInfoChange",
      [groupCode, GroupInfoSource.KDATACARD],
      (ret) => ret.result === 0,
      (detailInfo2) => detailInfo2.groupCode === groupCode,
      1,
      5e3
    );
    return detailInfo;
  }
  async initApi() {
    this.initCache().then().catch((e) => this.context.logger.logError(e));
  }
  async createGrayTip(groupCode, tip) {
    return this.context.session.getMsgService().addLocalJsonGrayTipMsg(
      {
        chatType: ChatType.KCHATTYPEGROUP,
        peerUid: groupCode
      },
      {
        busiId: 2201,
        jsonStr: JSON.stringify({ align: "center", items: [{ txt: tip, type: "nor" }] }),
        recentAbstract: tip,
        isServer: false
      },
      true,
      true
    );
  }
  async initCache() {
    for (const group of await this.getGroups(true)) {
      this.refreshGroupMemberCache(group.groupCode, false).then().catch((e) => this.context.logger.logError(e));
    }
  }
  async fetchGroupEssenceList(groupCode) {
    const pskey = (await this.core.apis.UserApi.getPSkey(["qun.qq.com"])).domainPskeyMap.get("qun.qq.com");
    return this.context.session.getGroupService().fetchGroupEssenceList({
      groupCode,
      pageStart: 0,
      pageLimit: 300
    }, pskey);
  }
  async getGroupShutUpMemberList(groupCode) {
    const executor = async (resolve, reject, onCancel) => {
      this.core.eventWrapper.registerListen(
        "NodeIKernelGroupListener/onShutUpMemberListChanged",
        (group_id) => group_id === groupCode,
        1,
        1e3
      ).then((data) => {
        resolve(data[1]);
      }).catch(reject);
      onCancel(() => {
        reject(new Error("Task was canceled"));
      });
    };
    const task = new CancelableTask(executor);
    this.context.session.getGroupService().getGroupShutUpMemberList(groupCode).then((e) => {
      if (e.result !== 0) {
        task.cancel();
      }
    });
    return await task.catch(() => []);
  }
  async clearGroupNotifiesUnreadCount(doubt) {
    return this.context.session.getGroupService().clearGroupNotifiesUnreadCount(doubt);
  }
  async setGroupAvatar(groupCode, filePath) {
    return this.context.session.getGroupService().setHeader(groupCode, filePath);
  }
  // 0 0 无需管理员审核
  // 0 2 需要管理员审核
  // 1 2 禁止Bot入群( 最好只传一个1 ？)
  async setGroupRobotAddOption(groupCode, robotMemberSwitch, robotMemberExamine) {
    const extInfo = createGroupExtInfo(groupCode);
    const groupExtFilter = createGroupExtFilter();
    if (robotMemberSwitch !== void 0) {
      extInfo.extInfo.inviteRobotMemberSwitch = robotMemberSwitch;
      groupExtFilter.inviteRobotMemberSwitch = 1;
    }
    if (robotMemberExamine !== void 0) {
      extInfo.extInfo.inviteRobotMemberExamine = robotMemberExamine;
      groupExtFilter.inviteRobotMemberExamine = 1;
    }
    return this.context.session.getGroupService().modifyGroupExtInfoV2(extInfo, groupExtFilter);
  }
  async setGroupAddOption(groupCode, option) {
    const param = createGroupDetailInfoV2Param(groupCode);
    param.filter.addOption = 1;
    if (option.addOption === 4 || option.addOption === 5) {
      param.filter.groupQuestion = 1;
      param.filter.groupAnswer = option.addOption === 4 ? 1 : 0;
      param.modifyInfo.groupQuestion = option.groupQuestion || "";
      param.modifyInfo.groupAnswer = option.addOption === 4 ? option.groupAnswer || "" : "";
    }
    param.modifyInfo.addOption = option.addOption;
    return this.context.session.getGroupService().modifyGroupDetailInfoV2(param, 0);
  }
  async setGroupSearch(groupCode, option) {
    const param = createGroupDetailInfoV2Param(groupCode);
    if (option.noCodeFingerOpenFlag) {
      param.filter.noCodeFingerOpenFlag = 1;
      param.modifyInfo.noCodeFingerOpenFlag = option.noCodeFingerOpenFlag;
    }
    if (option.noFingerOpenFlag) {
      param.filter.noFingerOpenFlag = 1;
      param.modifyInfo.noFingerOpenFlag = option.noFingerOpenFlag;
    }
    return this.context.session.getGroupService().modifyGroupDetailInfoV2(param, 0);
  }
  async getGroups(forced = false) {
    const [, , groupList] = await this.core.eventWrapper.callNormalEventV2(
      "NodeIKernelGroupService/getGroupList",
      "NodeIKernelGroupListener/onGroupListUpdate",
      [forced]
    );
    return groupList;
  }
  async getGroupExtFE0Info(groupCodes, forced = true) {
    return this.context.session.getGroupService().getGroupExt0xEF0Info(
      groupCodes,
      [],
      {
        bindGuildId: 1,
        blacklistExpireTime: 1,
        companyId: 1,
        essentialMsgPrivilege: 1,
        essentialMsgSwitch: 1,
        fullGroupExpansionSeq: 1,
        fullGroupExpansionSwitch: 1,
        gangUpId: 1,
        groupAioBindGuildId: 1,
        groupBindGuildIds: 1,
        groupBindGuildSwitch: 1,
        groupExcludeGuildIds: 1,
        groupExtFlameData: 1,
        groupFlagPro1: 1,
        groupInfoExtSeq: 1,
        groupOwnerId: 1,
        groupSquareSwitch: 1,
        hasGroupCustomPortrait: 1,
        inviteRobotMemberExamine: 1,
        inviteRobotMemberSwitch: 1,
        inviteRobotSwitch: 1,
        isLimitGroupRtc: 1,
        lightCharNum: 1,
        luckyWord: 1,
        luckyWordId: 1,
        msgEventSeq: 1,
        qqMusicMedalSwitch: 1,
        reserve: 1,
        showPlayTogetherSwitch: 1,
        starId: 1,
        todoSeq: 1,
        viewedMsgDisappearTime: 1
      },
      forced
    );
  }
  async getGroupMemberAll(groupCode, forced = false) {
    return this.context.session.getGroupService().getAllMemberList(groupCode, forced);
  }
  async refreshGroupMemberCache(groupCode, isWait = true) {
    const updateCache = async () => {
      try {
        const members = await this.getGroupMemberAll(groupCode, true);
        this.groupMemberCache.set(groupCode, members.result.infos);
      } catch (e) {
        this.context.logger.logError(`刷新群成员缓存失败, 群号: ${groupCode}, 错误: ${e}`);
      }
    };
    if (isWait) {
      await updateCache();
    } else {
      updateCache();
    }
    return this.groupMemberCache.get(groupCode);
  }
  async refreshGroupMemberCachePartial(groupCode, uid) {
    const member = await this.getGroupMemberEx(groupCode, uid, true);
    if (member) {
      this.groupMemberCache.get(groupCode)?.set(uid, member);
    }
    return member;
  }
  async getGroupMember(groupCode, memberUinOrUid) {
    const groupCodeStr = groupCode.toString();
    const memberUinOrUidStr = memberUinOrUid.toString();
    let members = this.groupMemberCache.get(groupCodeStr);
    if (!members) {
      members = await this.refreshGroupMemberCache(groupCodeStr, true);
    }
    const getMember = () => {
      if (isNumeric(memberUinOrUidStr)) {
        return Array.from(members.values()).find((member2) => member2.uin === memberUinOrUidStr);
      } else {
        return members.get(memberUinOrUidStr);
      }
    };
    let member = getMember();
    if (!member) {
      members = await this.refreshGroupMemberCache(groupCodeStr, true);
      member = getMember();
    }
    return member;
  }
  async getGroupRecommendContactArkJson(groupCode) {
    return this.context.session.getGroupService().getGroupRecommendContactArkJson(groupCode);
  }
  async creatGroupFileFolder(groupCode, folderName) {
    return this.context.session.getRichMediaService().createGroupFolder(groupCode, folderName);
  }
  async delGroupFile(groupCode, files) {
    return this.context.session.getRichMediaService().deleteGroupFile(groupCode, [102], files);
  }
  async delGroupFileFolder(groupCode, folderId) {
    return this.context.session.getRichMediaService().deleteGroupFolder(groupCode, folderId);
  }
  async transGroupFile(groupCode, fileId) {
    return this.context.session.getRichMediaService().transGroupFile(groupCode, fileId);
  }
  async addGroupEssence(groupCode, msgId) {
    const MsgData = await this.context.session.getMsgService().getMsgsIncludeSelf({
      chatType: 2,
      guildId: "",
      peerUid: groupCode
    }, msgId, 1, false);
    if (!MsgData.msgList[0]) {
      throw new Error("消息不存在");
    }
    const param = {
      groupCode,
      msgRandom: parseInt(MsgData.msgList[0].msgRandom),
      msgSeq: parseInt(MsgData.msgList[0].msgSeq)
    };
    return this.context.session.getGroupService().addGroupEssence(param);
  }
  async kickMemberV2Inner(param) {
    return this.context.session.getGroupService().kickMemberV2(param);
  }
  async deleteGroupBulletin(groupCode, noticeId) {
    const psKey = (await this.core.apis.UserApi.getPSkey(["qun.qq.com"])).domainPskeyMap.get("qun.qq.com");
    return this.context.session.getGroupService().deleteGroupBulletin(groupCode, psKey, noticeId);
  }
  async quitGroupV2(GroupCode, needDeleteLocalMsg) {
    const param = {
      groupCode: GroupCode,
      needDeleteLocalMsg
    };
    return this.context.session.getGroupService().quitGroupV2(param);
  }
  async removeGroupEssenceBySeq(groupCode, msgRandom, msgSeq) {
    const param = {
      groupCode,
      msgRandom: parseInt(msgRandom),
      msgSeq: parseInt(msgSeq)
    };
    return this.context.session.getGroupService().removeGroupEssence(param);
  }
  async removeGroupEssence(groupCode, msgId) {
    const MsgData = await this.context.session.getMsgService().getMsgsIncludeSelf({
      chatType: 2,
      guildId: "",
      peerUid: groupCode
    }, msgId, 1, false);
    if (!MsgData.msgList[0]) {
      throw new Error("消息不存在");
    }
    const param = {
      groupCode,
      msgRandom: parseInt(MsgData.msgList[0].msgRandom),
      msgSeq: parseInt(MsgData.msgList[0].msgSeq)
    };
    return this.context.session.getGroupService().removeGroupEssence(param);
  }
  async getSingleScreenNotifies(doubt, count) {
    const [, , , notifies] = await this.core.eventWrapper.callNormalEventV2(
      "NodeIKernelGroupService/getSingleScreenNotifies",
      "NodeIKernelGroupListener/onGroupSingleScreenNotifies",
      [
        doubt,
        "",
        count
      ]
    );
    return notifies;
  }
  async searchGroup(groupCode) {
    const [, ret] = await this.core.eventWrapper.callNormalEventV2(
      "NodeIKernelSearchService/searchGroup",
      "NodeIKernelSearchListener/onSearchGroupResult",
      [{
        keyWords: groupCode,
        groupNum: 25,
        exactSearch: false,
        penetrate: ""
      }],
      (ret2) => ret2.result === 0,
      (params) => !!params.groupInfos.find((g) => g.groupCode === groupCode),
      1,
      5e3
    );
    return ret.groupInfos.find((g) => g.groupCode === groupCode);
  }
  async getGroupMemberEx(groupCode, uid, forced = false, retry = 2) {
    const data = await solveAsyncProblem((eventWrapper, GroupCode, uid2, forced2 = false) => {
      return eventWrapper.callNormalEventV2(
        "NodeIKernelGroupService/getMemberInfo",
        "NodeIKernelGroupListener/onMemberInfoChange",
        [groupCode, [uid2], forced2],
        (ret) => ret.result === 0,
        (params, _, members) => params === GroupCode && members.size > 0 && members.has(uid2),
        1,
        forced2 ? 2500 : 250
      );
    }, this.core.eventWrapper, groupCode, uid, forced);
    if (data && data[3] instanceof Map && data[3].has(uid)) {
      return data[3].get(uid);
    }
    if (retry > 0) {
      const trydata = await this.getGroupMemberEx(groupCode, uid, true, retry - 1);
      if (trydata) return trydata;
    }
    return void 0;
  }
  async getGroupFileCount(groupCodes) {
    return this.context.session.getRichMediaService().batchGetGroupFileCount(groupCodes);
  }
  async getArkJsonGroupShare(groupCode) {
    const ret = await this.core.eventWrapper.callNoListenerEvent(
      "NodeIKernelGroupService/getGroupRecommendContactArkJson",
      groupCode
    );
    return ret.arkJson;
  }
  async uploadGroupBulletinPic(groupCode, imageurl) {
    const _Pskey = (await this.core.apis.UserApi.getPSkey(["qun.qq.com"])).domainPskeyMap.get("qun.qq.com");
    return this.context.session.getGroupService().uploadGroupBulletinPic(groupCode, _Pskey, imageurl);
  }
  async handleGroupRequest(doubt, notify, operateType, reason) {
    return this.context.session.getGroupService().operateSysNotify(
      doubt,
      {
        operateType,
        targetMsg: {
          seq: notify.seq,
          // 通知序列号
          type: notify.type,
          groupCode: notify.group.groupCode,
          postscript: reason ?? " "
          // 仅传空值可能导致处理失败，故默认给个空格
        }
      }
    );
  }
  async quitGroup(groupCode) {
    return this.context.session.getGroupService().quitGroup(groupCode);
  }
  async kickMember(groupCode, kickUids, refuseForever = false, kickReason = "") {
    return this.context.session.getGroupService().kickMember(groupCode, kickUids, refuseForever, kickReason);
  }
  async banMember(groupCode, memList) {
    return this.context.session.getGroupService().setMemberShutUp(groupCode, memList);
  }
  async banGroup(groupCode, shutUp) {
    return this.context.session.getGroupService().setGroupShutUp(groupCode, shutUp);
  }
  async setMemberCard(groupCode, memberUid, cardName) {
    return this.context.session.getGroupService().modifyMemberCardName(groupCode, memberUid, cardName);
  }
  async setMemberRole(groupCode, memberUid, role) {
    return this.context.session.getGroupService().modifyMemberRole(groupCode, memberUid, role);
  }
  async setGroupName(groupCode, groupName) {
    return this.context.session.getGroupService().modifyGroupName(groupCode, groupName, false);
  }
  async publishGroupBulletin(groupCode, content, picInfo = void 0, pinned = 0, confirmRequired = 0) {
    const psKey = (await this.core.apis.UserApi.getPSkey(["qun.qq.com"])).domainPskeyMap.get("qun.qq.com");
    const data = {
      text: encodeURI(content),
      picInfo,
      oldFeedsId: "",
      pinned,
      confirmRequired
    };
    return this.context.session.getGroupService().publishGroupBulletin(groupCode, psKey, data);
  }
  async getGroupRemainAtTimes(groupCode) {
    return this.context.session.getGroupService().getGroupRemainAtTimes(groupCode);
  }
  async getMemberExtInfo(groupCode, uin) {
    return this.context.session.getGroupService().getMemberExtInfo(
      {
        groupCode,
        sourceType: MemberExtSourceType.TITLETYPE,
        beginUin: "0",
        dataTime: "0",
        uinList: [uin],
        uinNum: "",
        seq: "",
        groupType: "",
        richCardNameVer: "",
        memberExtFilter: {
          memberLevelInfoUin: 1,
          memberLevelInfoPoint: 1,
          memberLevelInfoActiveDay: 1,
          memberLevelInfoLevel: 1,
          memberLevelInfoName: 1,
          levelName: 1,
          dataTime: 1,
          userShowFlag: 1,
          sysShowFlag: 1,
          timeToUpdate: 1,
          nickName: 1,
          specialTitle: 1,
          levelNameNew: 1,
          userShowFlagNew: 1,
          msgNeedField: 1,
          cmdUinFlagExt3Grocery: 1,
          memberIcon: 1,
          memberInfoSeq: 1
        }
      }
    );
  }
}

class NTQQMsgApi {
  context;
  core;
  constructor(context, core) {
    this.context = context;
    this.core = core;
  }
  async clickInlineKeyboardButton(...params) {
    return this.context.session.getMsgService().clickInlineKeyboardButton(...params);
  }
  getMsgByClientSeqAndTime(peer, replyMsgClientSeq, replyMsgTime) {
    return this.context.session.getMsgService().getMsgByClientSeqAndTime(peer, replyMsgClientSeq, replyMsgTime);
  }
  async getAioFirstViewLatestMsgs(peer, MsgCount) {
    return this.context.session.getMsgService().getAioFirstViewLatestMsgs(peer, MsgCount);
  }
  async sendShowInputStatusReq(peer, eventType) {
    return this.context.session.getMsgService().sendShowInputStatusReq(peer.chatType, eventType, peer.peerUid);
  }
  async getSourceOfReplyMsgV2(peer, clientSeq, time) {
    return this.context.session.getMsgService().getSourceOfReplyMsgV2(peer, clientSeq, time);
  }
  async getMsgEmojiLikesList(peer, msgSeq, emojiId, emojiType, count = 20) {
    return this.context.session.getMsgService().getMsgEmojiLikesList(peer, msgSeq, emojiId, emojiType, "", false, count);
  }
  async setEmojiLike(peer, msgSeq, emojiId, set = true) {
    emojiId = emojiId.toString();
    return this.context.session.getMsgService().setMsgEmojiLikes(peer, msgSeq, emojiId, emojiId.length > 3 ? "2" : "1", set);
  }
  async getMultiMsg(peer, rootMsgId, parentMsgId) {
    return this.context.session.getMsgService().getMultiMsg(peer, rootMsgId, parentMsgId);
  }
  async ForwardMsg(peer, msgIds) {
    return this.context.session.getMsgService().forwardMsg(msgIds, peer, [peer], /* @__PURE__ */ new Map());
  }
  async getMsgsByMsgId(peer, msgIds) {
    if (!peer) throw new Error("peer is not allowed");
    if (!msgIds) throw new Error("msgIds is not allowed");
    return await this.context.session.getMsgService().getMsgsByMsgId(peer, msgIds);
  }
  async getSingleMsg(peer, seq) {
    return await this.context.session.getMsgService().getSingleMsg(peer, seq);
  }
  async fetchFavEmojiList(num) {
    return this.context.session.getMsgService().fetchFavEmojiList("", num, true, true);
  }
  async queryMsgsWithFilterExWithSeq(peer, msgSeq) {
    return await this.context.session.getMsgService().queryMsgsWithFilterEx("0", "0", msgSeq, {
      chatInfo: peer,
      // searchFields: 3,
      filterMsgType: [],
      filterSendersUid: [],
      filterMsgToTime: "0",
      filterMsgFromTime: "0",
      isReverseOrder: false,
      isIncludeCurrent: true,
      pageLimit: 1
    });
  }
  async queryMsgsWithFilterExWithSeqV2(peer, msgSeq, MsgTime, SendersUid) {
    return await this.context.session.getMsgService().queryMsgsWithFilterEx("0", "0", msgSeq, {
      chatInfo: peer,
      filterMsgType: [],
      // searchFields: 3,
      filterSendersUid: SendersUid,
      filterMsgToTime: MsgTime,
      filterMsgFromTime: MsgTime,
      isReverseOrder: false,
      isIncludeCurrent: true,
      pageLimit: 1
    });
  }
  async queryMsgsWithFilterExWithSeqV3(peer, msgSeq, SendersUid) {
    return await this.context.session.getMsgService().queryMsgsWithFilterEx("0", "0", msgSeq, {
      chatInfo: peer,
      filterMsgType: [],
      filterSendersUid: SendersUid,
      filterMsgToTime: "0",
      filterMsgFromTime: "0",
      isReverseOrder: false,
      // searchFields: 3,
      isIncludeCurrent: true,
      pageLimit: 1
    });
  }
  async queryFirstMsgBySeq(peer, msgSeq) {
    return await this.context.session.getMsgService().queryMsgsWithFilterEx("0", "0", msgSeq, {
      chatInfo: peer,
      filterMsgType: [],
      filterSendersUid: [],
      filterMsgToTime: "0",
      // searchFields: 3,
      filterMsgFromTime: "0",
      isReverseOrder: true,
      isIncludeCurrent: true,
      pageLimit: 1
    });
  }
  // 客户端还在用别慌
  async getMsgsBySeqAndCount(peer, seq, count, desc, isReverseOrder) {
    return await this.context.session.getMsgService().getMsgsBySeqAndCount(peer, seq, count, desc, isReverseOrder);
  }
  async getMsgExBySeq(peer, msgSeq) {
    const DateNow = Math.floor(Date.now() / 1e3);
    const filterMsgFromTime = (DateNow - 300).toString();
    const filterMsgToTime = DateNow.toString();
    return await this.context.session.getMsgService().queryMsgsWithFilterEx("0", "0", msgSeq, {
      chatInfo: peer,
      // 此处为Peer 为关键查询参数 没有啥也没有 by mlik iowa
      filterMsgType: [],
      filterSendersUid: [],
      // searchFields: 3,
      filterMsgToTime,
      filterMsgFromTime,
      isReverseOrder: false,
      isIncludeCurrent: true,
      pageLimit: 100
    });
  }
  async queryFirstMsgBySender(peer, SendersUid) {
    return await this.context.session.getMsgService().queryMsgsWithFilterEx("0", "0", "0", {
      chatInfo: peer,
      filterMsgType: [],
      filterSendersUid: SendersUid,
      // searchFields: 3,
      filterMsgToTime: "0",
      filterMsgFromTime: "0",
      isReverseOrder: true,
      isIncludeCurrent: true,
      pageLimit: 2e4
    });
  }
  async setMsgRead(peer) {
    return this.context.session.getMsgService().setMsgRead(peer);
  }
  async getGroupFileList(GroupCode, params) {
    const item = [];
    let index = params.startIndex;
    while (true) {
      params.startIndex = index;
      const [, groupFileListResult] = await this.core.eventWrapper.callNormalEventV2(
        "NodeIKernelRichMediaService/getGroupFileList",
        "NodeIKernelMsgListener/onGroupFileInfoUpdate",
        [
          GroupCode,
          params
        ],
        () => true,
        () => true,
        // 应当通过 groupFileListResult 判断
        1,
        5e3
      );
      if (!groupFileListResult?.item?.length) break;
      item.push(...groupFileListResult.item);
      if (groupFileListResult.isEnd) break;
      if (item.length === params.fileCount) break;
      index = groupFileListResult.nextIndex;
    }
    return item;
  }
  async getMsgHistory(peer, msgId, count, isReverseOrder = false) {
    return this.context.session.getMsgService().getMsgsIncludeSelf(peer, msgId, count, isReverseOrder);
  }
  async recallMsg(peer, msgId) {
    return await this.core.eventWrapper.callNormalEventV2(
      "NodeIKernelMsgService/recallMsg",
      "NodeIKernelMsgListener/onMsgInfoListUpdate",
      [peer, [msgId]],
      () => true,
      (updatedList) => updatedList.find((m) => m.msgId === msgId && m.recallTime !== "0") !== void 0,
      1,
      1e3
    );
  }
  async PrepareTempChat(toUserUid, GroupCode, nickname) {
    return this.context.session.getMsgService().prepareTempChat({
      chatType: ChatType.KCHATTYPETEMPC2CFROMGROUP,
      peerUid: toUserUid,
      peerNickname: nickname,
      fromGroupCode: GroupCode,
      sig: "",
      selfPhone: "",
      selfUid: this.core.selfInfo.uid,
      gameSession: {
        nickname: "",
        gameAppId: "",
        selfTinyId: "",
        peerRoleId: "",
        peerOpenId: ""
      }
    });
  }
  async getTempChatInfo(chatType, peerUid) {
    return this.context.session.getMsgService().getTempChatInfo(chatType, peerUid);
  }
  async sendMsg(peer, msgElements, timeout = 1e4) {
    if (peer.chatType === ChatType.KCHATTYPETEMPC2CFROMGROUP && peer.guildId && peer.guildId !== "") {
      const member = await this.core.apis.GroupApi.getGroupMember(peer.guildId, peer.peerUid);
      if (member) {
        await this.PrepareTempChat(peer.peerUid, peer.guildId, member.nick);
      }
    }
    const msgId = await this.generateMsgUniqueId(peer.chatType);
    peer.guildId = msgId;
    const [, msgList] = await this.core.eventWrapper.callNormalEventV2(
      "NodeIKernelMsgService/sendMsg",
      "NodeIKernelMsgListener/onMsgInfoListUpdate",
      [
        "0",
        peer,
        msgElements,
        /* @__PURE__ */ new Map()
      ],
      (ret) => ret.result === 0,
      (msgRecords) => {
        for (const msgRecord of msgRecords) {
          if (msgRecord.guildId === msgId && msgRecord.sendStatus === SendStatusType.KSEND_STATUS_SUCCESS) {
            return true;
          }
        }
        return false;
      },
      1,
      timeout
    );
    return msgList.find((msgRecord) => msgRecord.guildId === msgId);
  }
  async generateMsgUniqueId(chatType) {
    return this.context.session.getMsgService().generateMsgUniqueId(chatType, this.context.session.getMSFService().getServerTime());
  }
  async forwardMsg(srcPeer, destPeer, msgIds) {
    return this.context.session.getMsgService().forwardMsg(msgIds, srcPeer, [destPeer], /* @__PURE__ */ new Map());
  }
  async multiForwardMsg(srcPeer, destPeer, msgIds) {
    const msgInfos = msgIds.map((id) => {
      return { msgId: id, senderShowName: this.core.selfInfo.nick };
    });
    const [, msgList] = await this.core.eventWrapper.callNormalEventV2(
      "NodeIKernelMsgService/multiForwardMsgWithComment",
      "NodeIKernelMsgListener/onMsgInfoListUpdate",
      [
        msgInfos,
        srcPeer,
        destPeer,
        [],
        /* @__PURE__ */ new Map()
      ],
      () => true,
      (msgRecords) => msgRecords.some(
        (msgRecord) => msgRecord.peerUid === destPeer.peerUid && msgRecord.senderUid === this.core.selfInfo.uid
      )
    );
    for (const msg of msgList) {
      const arkElement = msg.elements.find((ele) => ele.arkElement);
      if (!arkElement) {
        continue;
      }
      const forwardData = JSON.parse(arkElement.arkElement?.bytesData ?? "");
      if (forwardData.app !== "com.tencent.multimsg") {
        continue;
      }
      if (msg.peerUid === destPeer.peerUid && msg.senderUid === this.core.selfInfo.uid) {
        return msg;
      }
    }
    throw new Error("转发消息超时");
  }
  async markAllMsgAsRead() {
    return this.context.session.getMsgService().setAllC2CAndGroupMsgRead();
  }
}

class Fallback {
  handlers = [];
  checker;
  constructor(checker) {
    this.checker = checker || (async (result) => result);
  }
  add(handler) {
    this.handlers.push(handler);
    return this;
  }
  // 执行处理程序链
  async run() {
    const errors = [];
    for (const handler of this.handlers) {
      try {
        const result = await handler();
        const data = await this.checker(result);
        if (data) {
          return data;
        }
      } catch (error) {
        errors.push(error instanceof Error ? error : new Error(String(error)));
      }
    }
    throw new AggregateError(errors, "All handlers failed");
  }
}
class FallbackUtil {
  static boolchecker(value, condition) {
    if (condition) {
      return value;
    } else {
      throw new Error("Condition is false, throwing error");
    }
  }
}

class NTQQUserApi {
  context;
  core;
  constructor(context, core) {
    this.context = context;
    this.core = core;
  }
  async getCoreAndBaseInfo(uids) {
    return await this.core.eventWrapper.callNoListenerEvent(
      "NodeIKernelProfileService/getCoreAndBaseInfo",
      "nodeStore",
      uids
    );
  }
  // 默认获取自己的 type = 2 获取别人 type = 1
  async getProfileLike(uid, start, count, type = 2) {
    return this.context.session.getProfileLikeService().getBuddyProfileLike({
      friendUids: [uid],
      basic: 1,
      vote: 1,
      favorite: 0,
      userProfile: 1,
      type,
      start,
      limit: count
    });
  }
  async setLongNick(longNick) {
    return this.context.session.getProfileService().setLongNick(longNick);
  }
  async setSelfOnlineStatus(status, extStatus, batteryStatus) {
    return this.context.session.getMsgService().setStatus({
      status,
      extStatus,
      batteryStatus
    });
  }
  async setDiySelfOnlineStatus(faceId, wording, faceType) {
    return this.context.session.getMsgService().setStatus({
      status: 10,
      extStatus: 2e3,
      customStatus: { faceId, wording, faceType },
      batteryStatus: 0
    });
  }
  async getBuddyRecommendContactArkJson(uin, sencenID = "") {
    return this.context.session.getBuddyService().getBuddyRecommendContactArkJson(uin, sencenID);
  }
  async like(uid, count = 1) {
    return this.context.session.getProfileLikeService().setBuddyProfileLike({
      friendUid: uid,
      sourceId: 71,
      doLikeCount: count,
      doLikeTollCount: 0
    });
  }
  async setQQAvatar(filePath) {
    const ret = await this.context.session.getProfileService().setHeader(filePath);
    return { result: ret?.result, errMsg: ret?.errMsg };
  }
  async setGroupAvatar(gc, filePath) {
    return this.context.session.getGroupService().setHeader(gc, filePath);
  }
  async fetchUserDetailInfo(uid, mode = UserDetailSource.KDB) {
    const [, profile] = await this.core.eventWrapper.callNormalEventV2(
      "NodeIKernelProfileService/fetchUserDetailInfo",
      "NodeIKernelProfileListener/onUserDetailInfoChanged",
      [
        "BuddyProfileStore",
        [uid],
        mode,
        [ProfileBizType.KALL]
      ],
      () => true,
      (profile2) => profile2.uid === uid
    );
    return profile;
  }
  async getUserDetailInfo(uid, no_cache = false) {
    let profile = await solveAsyncProblem(async (uid2) => this.fetchUserDetailInfo(uid2, no_cache ? UserDetailSource.KSERVER : UserDetailSource.KDB), uid);
    if (profile && profile.uin !== "0" && profile.commonExt) {
      return {
        ...profile.simpleInfo.status,
        ...profile.simpleInfo.vasInfo,
        ...profile.commonExt,
        ...profile.simpleInfo.baseInfo,
        ...profile.simpleInfo.coreInfo,
        qqLevel: profile.commonExt?.qqLevel,
        age: profile.simpleInfo.baseInfo.age,
        pendantId: "",
        nick: profile.simpleInfo.coreInfo.nick || ""
      };
    }
    this.context.logger.logDebug("[NapCat] [Mark] getUserDetailInfo Mode1 Failed.");
    profile = await this.fetchUserDetailInfo(uid, UserDetailSource.KSERVER);
    if (profile && profile.uin === "0") {
      profile.uin = await this.core.apis.UserApi.getUidByUinV2(uid) ?? "0";
    }
    return {
      ...profile.simpleInfo.status,
      ...profile.simpleInfo.vasInfo,
      ...profile.commonExt,
      ...profile.simpleInfo.baseInfo,
      ...profile.simpleInfo.coreInfo,
      qqLevel: profile.commonExt?.qqLevel,
      age: profile.simpleInfo.baseInfo.age,
      pendantId: "",
      nick: profile.simpleInfo.coreInfo.nick || ""
    };
  }
  async modifySelfProfile(param) {
    return this.context.session.getProfileService().modifyDesktopMiniProfile(param);
  }
  async getCookies(domain) {
    const ClientKeyData = await this.forceFetchClientKey();
    const requestUrl = "https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=" + this.core.selfInfo.uin + "&clientkey=" + ClientKeyData.clientKey + "&u1=https%3A%2F%2F" + domain + "%2F" + this.core.selfInfo.uin + "%2Finfocenter&keyindex=19%27";
    const data = await RequestUtil.HttpsGetCookies(requestUrl);
    if (!data["p_skey"] || data["p_skey"].length === 0) {
      try {
        const pskey = (await this.getPSkey([domain])).domainPskeyMap.get(domain);
        if (pskey) data["p_skey"] = pskey;
      } catch {
        return data;
      }
    }
    return data;
  }
  async getPSkey(domainList) {
    return await this.context.session.getTipOffService().getPskey(domainList, true);
  }
  async getRobotUinRange() {
    const robotUinRanges = await this.context.session.getRobotService().getRobotUinRange({
      justFetchMsgConfig: "1",
      type: 1,
      version: 0,
      aioKeywordVersion: 0
    });
    return robotUinRanges?.response?.robotUinRanges;
  }
  // 需要异常处理
  async getQzoneCookies() {
    const ClientKeyData = await this.forceFetchClientKey();
    const requestUrl = "https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=" + this.core.selfInfo.uin + "&clientkey=" + ClientKeyData.clientKey + "&u1=https%3A%2F%2Fuser.qzone.qq.com%2F" + this.core.selfInfo.uin + "%2Finfocenter&keyindex=19%27";
    return await RequestUtil.HttpsGetCookies(requestUrl);
  }
  // 需要异常处理
  async getSKey() {
    const ClientKeyData = await this.forceFetchClientKey();
    if (ClientKeyData.result !== 0) {
      throw new Error("getClientKey Error");
    }
    const clientKey = ClientKeyData.clientKey;
    const requestUrl = "https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=" + this.core.selfInfo.uin + "&clientkey=" + clientKey + "&u1=https%3A%2F%2Fh5.qzone.qq.com%2Fqqnt%2Fqzoneinpcqq%2Ffriend%3Frefresh%3D0%26clientuin%3D0%26darkMode%3D0&keyindex=19%27";
    const cookies = await RequestUtil.HttpsGetCookies(requestUrl);
    const skey = cookies["skey"];
    if (!skey) {
      throw new Error("SKey is Empty");
    }
    return skey;
  }
  async getUidByUinV2(uin) {
    if (!uin) {
      return "";
    }
    const fallback = new Fallback((uid2) => FallbackUtil.boolchecker(uid2, uid2 !== void 0 && uid2.indexOf("*") === -1 && uid2 !== "")).add(() => this.context.session.getUixConvertService().getUid([uin]).then((data) => data.uidInfo.get(uin))).add(() => this.context.session.getProfileService().getUidByUin("FriendsServiceImpl", [uin]).get(uin)).add(() => this.context.session.getGroupService().getUidByUins([uin]).then((data) => data.uids.get(uin))).add(() => this.getUserDetailInfoByUin(uin).then((data) => data.detail.uid));
    const uid = await fallback.run().catch(() => "");
    return uid ?? "";
  }
  async getUinByUidV2(uid) {
    if (!uid) {
      return "0";
    }
    const fallback = new Fallback((uin2) => FallbackUtil.boolchecker(uin2, uin2 !== void 0 && uin2 !== "0" && uin2 !== "")).add(() => this.context.session.getUixConvertService().getUin([uid]).then((data) => data.uinInfo.get(uid))).add(() => this.context.session.getProfileService().getUinByUid("FriendsServiceImpl", [uid]).get(uid)).add(() => this.context.session.getGroupService().getUinByUids([uid]).then((data) => data.uins.get(uid))).add(() => this.getUserDetailInfo(uid).then((data) => data.uin));
    const uin = await fallback.run().catch(() => "0");
    return uin ?? "0";
  }
  async getRecentContactListSnapShot(count) {
    return await this.context.session.getRecentContactService().getRecentContactListSnapShot(count);
  }
  async getRecentContactListSyncLimit(count) {
    return await this.context.session.getRecentContactService().getRecentContactListSyncLimit(count);
  }
  async getRecentContactListSync() {
    return await this.context.session.getRecentContactService().getRecentContactListSync();
  }
  async getRecentContactList() {
    return await this.context.session.getRecentContactService().getRecentContactList();
  }
  async getUserDetailInfoByUin(Uin) {
    return await this.core.eventWrapper.callNoListenerEvent(
      "NodeIKernelProfileService/getUserDetailInfoByUin",
      Uin
    );
  }
  async forceFetchClientKey() {
    return await this.context.session.getTicketService().forceFetchClientKey("");
  }
}

function qunAlbumControl({
  uin,
  group_id,
  pskey,
  pic_md5,
  img_size,
  img_name,
  sAlbumName,
  sAlbumID,
  photo_num = "1",
  video_num = "0",
  batch_num = "1"
}) {
  const timestamp = Math.floor(Date.now() / 1e3);
  return {
    control_req: [
      {
        uin,
        token: {
          type: 4,
          data: pskey,
          appid: 5
        },
        appid: "qun",
        checksum: pic_md5,
        check_type: 0,
        file_len: img_size,
        env: {
          refer: "qzone",
          deviceInfo: "h5"
        },
        model: 0,
        biz_req: {
          sPicTitle: img_name,
          sPicDesc: "",
          sAlbumName,
          sAlbumID,
          iAlbumTypeID: 0,
          iBitmap: 0,
          iUploadType: 0,
          iUpPicType: 0,
          iBatchID: timestamp,
          sPicPath: "",
          iPicWidth: 0,
          iPicHight: 0,
          iWaterType: 0,
          iDistinctUse: 0,
          iNeedFeeds: 1,
          iUploadTime: timestamp,
          mapExt: {
            appid: "qun",
            userid: group_id
          },
          stExtendInfo: {
            mapParams: {
              photo_num,
              video_num,
              batch_num
            }
          }
        },
        session: "",
        asy_upload: 0,
        cmd: "FileUpload"
      }
    ]
  };
}

function createAlbumMediaFeed(uin, albumId, lloc) {
  return {
    cell_common: {
      time: ""
    },
    cell_user_info: {
      user: {
        uin
      }
    },
    cell_media: {
      album_id: albumId,
      batch_id: "",
      media_items: [{
        image: {
          lloc
        }
      }]
    }
  };
}
function createAlbumCommentRequest(uin, content, client_key) {
  return {
    client_key,
    // 暂时只支持纯文本吧
    content: [{
      type: 0 /* KRICHMSGTYPEPLAINTEXT */,
      content,
      who: 0,
      uid: "",
      name: "",
      url: ""
    }],
    user: {
      uin
    }
  };
}
function createAlbumFeedPublish(qunId, uin, albumId, lloc, sloc) {
  return {
    cell_common: {
      time: Date.now(),
      feed_id: ""
    },
    cell_user_info: {
      user: {
        uin
      }
    },
    cell_media: {
      album_id: albumId,
      batch_id: 0,
      media_items: [{
        type: 0,
        image: {
          lloc,
          sloc: sloc || lloc
        }
      }]
    },
    cell_qun_info: {
      qun_id: qunId
    }
  };
}

class NTQQWebApi {
  context;
  core;
  constructor(context, core) {
    this.context = context;
    this.core = core;
  }
  async shareDigest(groupCode, msgSeq, msgRandom, targetGroupCode) {
    const cookieObject = await this.core.apis.UserApi.getCookies("qun.qq.com");
    const url = `https://qun.qq.com/cgi-bin/group_digest/share_digest?${new URLSearchParams({
      bkn: this.getBknFromCookie(cookieObject),
      group_code: groupCode,
      msg_seq: msgSeq,
      msg_random: msgRandom,
      target_group_code: targetGroupCode
    }).toString()}`;
    try {
      return RequestUtil.HttpGetText(url, "GET", "", { Cookie: this.cookieToString(cookieObject) });
    } catch {
      return void 0;
    }
  }
  async getGroupEssenceMsgAll(GroupCode) {
    const ret = [];
    for (let i = 0; i < 20; i++) {
      const data = await this.getGroupEssenceMsg(GroupCode, i, 50);
      if (!data) break;
      ret.push(data);
      if (data.data.is_end) break;
    }
    return ret;
  }
  async getGroupEssenceMsg(GroupCode, page_start = 0, page_limit = 50) {
    const cookieObject = await this.core.apis.UserApi.getCookies("qun.qq.com");
    const url = `https://qun.qq.com/cgi-bin/group_digest/digest_list?${new URLSearchParams({
      bkn: this.getBknFromCookie(cookieObject),
      page_start: page_start.toString(),
      page_limit: page_limit.toString(),
      group_code: GroupCode
    }).toString()}`;
    try {
      const ret = await RequestUtil.HttpGetJson(
        url,
        "GET",
        "",
        { Cookie: this.cookieToString(cookieObject) }
      );
      return ret.retcode === 0 ? ret : void 0;
    } catch {
      return void 0;
    }
  }
  async getGroupMembers(GroupCode) {
    const memberData = new Array();
    const cookieObject = await this.core.apis.UserApi.getCookies("qun.qq.com");
    const retList = [];
    const fastRet = await RequestUtil.HttpGetJson(
      `https://qun.qq.com/cgi-bin/qun_mgr/search_group_members?${new URLSearchParams({
        st: "0",
        end: "40",
        sort: "1",
        gc: GroupCode,
        bkn: this.getBknFromCookie(cookieObject)
      }).toString()}`,
      "POST",
      "",
      { Cookie: this.cookieToString(cookieObject) }
    );
    if (!fastRet?.count || fastRet?.errcode !== 0 || !fastRet?.mems) {
      return [];
    } else {
      for (const key in fastRet.mems) {
        if (fastRet.mems[key]) {
          memberData.push(fastRet.mems[key]);
        }
      }
    }
    const PageNum = Math.ceil(fastRet.count / 40);
    for (let i = 2; i <= PageNum; i++) {
      const ret = RequestUtil.HttpGetJson(
        `https://qun.qq.com/cgi-bin/qun_mgr/search_group_members?${new URLSearchParams({
          st: ((i - 1) * 40).toString(),
          end: (i * 40).toString(),
          sort: "1",
          gc: GroupCode,
          bkn: this.getBknFromCookie(cookieObject)
        }).toString()}`,
        "POST",
        "",
        { Cookie: this.cookieToString(cookieObject) }
      );
      retList.push(ret);
    }
    for (let i = 1; i <= PageNum; i++) {
      const ret = await retList[i];
      if (!ret?.count || ret?.errcode !== 0 || !ret?.mems) {
        continue;
      }
      for (const key in ret.mems) {
        if (ret.mems[key]) {
          memberData.push(ret.mems[key]);
        }
      }
    }
    return memberData;
  }
  // public  async addGroupDigest(groupCode: string, msgSeq: string) {
  //   const url = `https://qun.qq.com/cgi-bin/group_digest/cancel_digest?random=665&X-CROSS-ORIGIN=fetch&group_code=${groupCode}&msg_seq=${msgSeq}&msg_random=444021292`;
  //   const res = await this.request(url);
  //   return await res.json();
  // }
  // public async getGroupDigest(groupCode: string) {
  //   const url = `https://qun.qq.com/cgi-bin/group_digest/digest_list?random=665&X-CROSS-ORIGIN=fetch&group_code=${groupCode}&page_start=0&page_limit=20`;
  //   const res = await this.request(url);
  //   return await res.json();
  // }
  async setGroupNotice(GroupCode, Content, pinned = 0, type = 1, is_show_edit_card = 1, tip_window_type = 1, confirm_required = 1, picId = "", imgWidth = 540, imgHeight = 300) {
    const cookieObject = await this.core.apis.UserApi.getCookies("qun.qq.com");
    try {
      const settings = JSON.stringify({
        is_show_edit_card,
        tip_window_type,
        confirm_required
      });
      const externalParam = {
        pic: picId,
        imgWidth: imgWidth.toString(),
        imgHeight: imgHeight.toString()
      };
      const ret = await RequestUtil.HttpGetJson(
        `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?${new URLSearchParams({
          bkn: this.getBknFromCookie(cookieObject),
          qid: GroupCode,
          text: Content,
          pinned: pinned.toString(),
          type: type.toString(),
          settings,
          ...picId === "" ? {} : externalParam
        }).toString()}`,
        "POST",
        "",
        { Cookie: this.cookieToString(cookieObject) }
      );
      return ret;
    } catch {
      return void 0;
    }
  }
  async getGroupNotice(GroupCode) {
    const cookieObject = await this.core.apis.UserApi.getCookies("qun.qq.com");
    try {
      const ret = await RequestUtil.HttpGetJson(
        `https://web.qun.qq.com/cgi-bin/announce/get_t_list?${new URLSearchParams({
          bkn: this.getBknFromCookie(cookieObject),
          qid: GroupCode,
          ft: "23",
          ni: "1",
          n: "1",
          i: "1",
          log_read: "1",
          platform: "1",
          s: "-1"
        }).toString()}&n=20`,
        "GET",
        "",
        { Cookie: this.cookieToString(cookieObject) }
      );
      return ret?.ec === 0 ? ret : void 0;
    } catch {
      return void 0;
    }
  }
  async getDataInternal(cookieObject, groupCode, type) {
    let resJson;
    try {
      const res = await RequestUtil.HttpGetText(
        `https://qun.qq.com/interactive/honorlist?${new URLSearchParams({
          gc: groupCode,
          type: type.toString()
        }).toString()}`,
        "GET",
        "",
        { Cookie: this.cookieToString(cookieObject) }
      );
      const match = /window\.__INITIAL_STATE__=(.*?);/.exec(res);
      if (match?.[1]) {
        resJson = JSON.parse(match[1].trim());
      }
      return type === 1 ? resJson?.talkativeList : resJson?.actorList;
    } catch (e) {
      this.context.logger.logDebug("获取当前群荣耀失败", e);
      return void 0;
    }
  }
  async getHonorList(cookieObject, groupCode, type) {
    const data = await this.getDataInternal(cookieObject, groupCode, type);
    if (!data) {
      this.context.logger.logError(`获取类型 ${type} 的荣誉信息失败`);
      return [];
    }
    return data.map((item) => ({
      user_id: item?.uin,
      nickname: item?.name,
      avatar: item?.avatar,
      description: item?.desc
    }));
  }
  async getGroupHonorInfo(groupCode, getType) {
    const cookieObject = await this.core.apis.UserApi.getCookies("qun.qq.com");
    const HonorInfo = {
      group_id: Number(groupCode),
      current_talkative: {},
      talkative_list: [],
      performer_list: [],
      legend_list: [],
      emotion_list: [],
      strong_newbie_list: []
    };
    if (getType === WebHonorType.TALKATIVE || getType === WebHonorType.ALL) {
      const talkativeList = await this.getHonorList(cookieObject, groupCode, 1);
      if (talkativeList.length > 0) {
        HonorInfo.current_talkative = talkativeList[0];
        HonorInfo.talkative_list = talkativeList;
      }
    }
    if (getType === WebHonorType.PERFORMER || getType === WebHonorType.ALL) {
      HonorInfo.performer_list = await this.getHonorList(cookieObject, groupCode, 2);
    }
    if (getType === WebHonorType.LEGEND || getType === WebHonorType.ALL) {
      HonorInfo.legend_list = await this.getHonorList(cookieObject, groupCode, 3);
    }
    if (getType === WebHonorType.EMOTION || getType === WebHonorType.ALL) {
      HonorInfo.emotion_list = await this.getHonorList(cookieObject, groupCode, 6);
    }
    if (getType === WebHonorType.EMOTION || getType === WebHonorType.ALL) {
      HonorInfo.strong_newbie_list = [];
    }
    return HonorInfo;
  }
  cookieToString(cookieObject) {
    return Object.entries(cookieObject).map(([key, value]) => `${key}=${value}`).join("; ");
  }
  getBknFromCookie(cookieObject) {
    const sKey = cookieObject["skey"];
    let hash = 5381;
    for (let i = 0; i < sKey.length; i++) {
      const code = sKey.charCodeAt(i);
      hash = hash + (hash << 5) + code;
    }
    return (hash & 2147483647).toString();
  }
  getBknFromSKey(sKey) {
    let hash = 5381;
    for (let i = 0; i < sKey.length; i++) {
      const code = sKey.charCodeAt(i);
      hash = hash + (hash << 5) + code;
    }
    return (hash & 2147483647).toString();
  }
  async getAlbumListByNTQQ(gc) {
    return await this.context.session.getAlbumService().getAlbumList({
      qun_id: gc,
      attach_info: "",
      seq: 3331,
      request_time_line: {
        request_invoke_time: "0"
      }
    });
  }
  async getAlbumList(gc) {
    const skey = await this.core.apis.UserApi.getSKey() || "";
    const pskey = (await this.core.apis.UserApi.getPSkey(["qzone.qq.com"])).domainPskeyMap.get("qzone.qq.com") || "";
    const bkn = this.getBknFromSKey(skey);
    const uin = this.core.selfInfo.uin || "10001";
    const cookies = `p_uin=o${this.core.selfInfo.uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin} `;
    const api = "https://h5.qzone.qq.com/proxy/domain/u.photo.qzone.qq.com/cgi-bin/upp/qun_list_album_v2?";
    const params = new URLSearchParams({
      random: "7570",
      g_tk: bkn,
      format: "json",
      inCharset: "utf-8",
      outCharset: "utf-8",
      qua: "V1_IPH_SQ_6.2.0_0_HDBM_T",
      cmd: "qunGetAlbumList",
      qunId: gc,
      qunid: gc,
      start: "0",
      num: "1000",
      uin,
      getMemberRole: "0"
    });
    const response = await RequestUtil.HttpGetJson(api + params.toString(), "GET", "", {
      Cookie: cookies
    });
    return response.data.album;
  }
  async createQunAlbumSession(gc, sAlbumID, sAlbumName, path, skey, pskey, img_md5, uin) {
    const img = readFileSync(path);
    const img_size = img.length;
    const img_name = basename(path);
    const GTK = this.getBknFromSKey(skey);
    const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
    const body = qunAlbumControl({
      uin,
      group_id: gc,
      pskey,
      pic_md5: img_md5,
      img_size,
      img_name,
      sAlbumName,
      sAlbumID
    });
    const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${img_md5}?g_tk=${GTK}`;
    const post = await RequestUtil.HttpGetJson(api, "POST", body, {
      Cookie: cookie,
      "Content-Type": "application/json"
    });
    return post;
  }
  async uploadQunAlbumSlice(path, session, skey, pskey, uin, slice_size) {
    const img_size = statSync(path).size;
    let seq = 0;
    let offset = 0;
    const GTK = this.getBknFromSKey(skey);
    const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
    const stream = createReadStream(path, { highWaterMark: slice_size });
    for await (const chunk of stream) {
      const end = Math.min(offset + chunk.length, img_size);
      const form = new FormData();
      form.append("uin", uin);
      form.append("appid", "qun");
      form.append("session", session);
      form.append("offset", offset.toString());
      form.append("data", new Blob([chunk], { type: "application/octet-stream" }), "blob");
      form.append("checksum", "");
      form.append("check_type", "0");
      form.append("retry", "0");
      form.append("seq", seq.toString());
      form.append("end", end.toString());
      form.append("cmd", "FileUpload");
      form.append("slice_size", slice_size.toString());
      form.append("biz_req.iUploadType", "0");
      const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileUpload?seq=${seq}&retry=0&offset=${offset}&end=${end}&total=${img_size}&type=form&g_tk=${GTK}`;
      const response = await fetch(api, {
        method: "POST",
        headers: {
          Cookie: cookie
        },
        body: form
      });
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const post = await response.json();
      if (post.ret !== 0) {
        throw new Error(`分片 ${seq} 上传失败: ${post.msg}`);
      }
      offset += chunk.length;
      seq++;
    }
    return { success: true, message: "上传完成" };
  }
  async uploadImageToQunAlbum(gc, sAlbumID, sAlbumName, path) {
    const skey = await this.core.apis.UserApi.getSKey() || "";
    const pskey = (await this.core.apis.UserApi.getPSkey(["qzone.qq.com"])).domainPskeyMap.get("qzone.qq.com") || "";
    const img_md5 = createHash("md5").update(readFileSync(path)).digest("hex");
    const uin = this.core.selfInfo.uin || "10001";
    const session = (await this.createQunAlbumSession(gc, sAlbumID, sAlbumName, path, skey, pskey, img_md5, uin)).data.session;
    if (!session) throw new Error("创建群相册会话失败");
    await this.uploadQunAlbumSlice(path, session, skey, pskey, uin, 16384);
  }
  async getAlbumMediaListByNTQQ(gc, albumId, attach_info = "") {
    return (await this.context.session.getAlbumService().getMediaList({
      qun_id: gc,
      attach_info,
      seq: 0,
      request_time_line: {
        request_invoke_time: "0"
      },
      album_id: albumId,
      lloc: "",
      batch_id: ""
    })).response;
  }
  async doAlbumMediaPlainCommentByNTQQ(qunId, albumId, lloc, content) {
    const random_seq = Math.floor(Math.random() * 9e3) + 1e3;
    const uin = this.core.selfInfo.uin || "10001";
    const client_key = Date.now() * 1e3;
    return await this.context.session.getAlbumService().doQunComment(
      random_seq,
      {
        map_info: [],
        map_bytes_info: [],
        map_user_account: []
      },
      qunId,
      2,
      createAlbumMediaFeed(uin, albumId, lloc),
      createAlbumCommentRequest(uin, content, client_key)
    );
  }
  async deleteAlbumMediaByNTQQ(qunId, albumId, lloc) {
    const random_seq = Math.floor(Math.random() * 9e3) + 1e3;
    return await this.context.session.getAlbumService().deleteMedias(
      random_seq,
      qunId,
      albumId,
      [lloc],
      []
    );
  }
  async doAlbumMediaLikeByNTQQ(qunId, albumId, lloc, id) {
    const random_seq = Math.floor(Math.random() * 9e3) + 1e3;
    const uin = this.core.selfInfo.uin || "10001";
    return await this.context.session.getAlbumService().doQunLike(
      random_seq,
      {
        map_info: [],
        map_bytes_info: [],
        map_user_account: []
      },
      {
        id,
        status: 1
      },
      createAlbumFeedPublish(qunId, uin, albumId, lloc)
    );
  }
}

class NTQQSystemApi {
  context;
  core;
  constructor(context, core) {
    this.context = context;
    this.core = core;
  }
  async hasOtherRunningQQProcess() {
    return this.core.util.hasOtherRunningQQProcess();
  }
  async ocrImage(filePath) {
    return this.context.session.getNodeMiscService().wantWinScreenOCR(filePath);
  }
  async translateEnWordToZn(words) {
    return this.context.session.getRichMediaService().translateEnWordToZn(words);
  }
  async getOnlineDev() {
    this.context.session.getMsgService().getOnLineDev();
  }
  async getArkJsonCollection() {
    return await this.core.eventWrapper.callNoListenerEvent("NodeIKernelCollectionService/collectionArkShare", "1717662698058");
  }
  async bootMiniApp(appFile, params) {
    await this.context.session.getNodeMiscService().setMiniAppVersion("2.16.4");
    return this.context.session.getNodeMiscService().startNewMiniApp(appFile, params);
  }
}

const offset$1 = {
  "9.9.22-40990-x64": {"send":"1B5699C","recv":"1D8CA9D"},
  "9.9.22-40824-x64": {"send":"1B5699C","recv":"1D8CA9D"},
  "9.9.22-40768-x64": {"send":"1B5699C","recv":"1D8CA9D"},
  "3.2.20-40768-x64": {"send":"2A1B840","recv":"2D28F20"},
  "3.2.20-40824-x64": {"send":"2A1B840","recv":"2D28F20"},
  "3.2.20-40990-x64": {"send":"2A1B840","recv":"2D28F20"},
  "3.2.20-40990-arm64": {"send":"157C0E8","recv":"1546658"},
  "3.2.20-40824-arm64": {"send":"157C0E8","recv":"1546658"},
  "3.2.20-40768-arm64": {"send":"157C0E8","recv":"1546658"},
  "9.9.23-41679-x64": {"send":"09FF0F4","recv":"1D1A039"},
  "6.9.82-40824-arm64": {"send":"05FA930","recv":"0B41B90"},
  "6.9.82-40768-arm64": {"send":"05FA930","recv":"0B41B90"},
  "6.9.82-40990-arm64": {"send":"05FA930","recv":"0B41B90"},
  "6.9.83-41679-arm64": {"send":"237D114","recv":"0957648"},
  "6.9.83-41785-arm64": {"send":"23B0BF0","recv":"095567C"},
  "9.9.23-41785-x64": {"send":"09FF0A4","recv":"1D19FF9"},
  "6.9.83-41857-arm64": {"send":"0815774","recv":"0958B3C"},
  "3.2.21-41857-x64": {"send":"5B44510","recv":"2FDB0B0"},
  "3.2.21-41857-arm64": {"send":"3D6EE6C","recv":"1479EDC"},
  "9.9.23-41857-x64": {"send":"0A01394","recv":"1D1C4F9"},
  "9.9.23-42086-x64": {"send":"0A01814","recv":"1D1C9B9"},
  "6.9.85-42086-arm64": {"send":"23B0330","recv":"0957648"},
  "3.2.21-42086-x64": {"send":"5B42CF0","recv":"2FDA6F0"},
  "9.9.23-42430-x64": {"send":"0A01A34","recv":"1D1CFF9"},
  "9.9.25-42744-x64": {"send":"0A0D104","recv":"1D3E7F9"},
  "6.9.85-42744-arm64": {"send":"23DFEF0","recv":"095FD80"},
  "9.9.25-42905-x64": {"send":"0A12E74","recv":"1D450FD"},
  "6.9.86-42905-arm64": {"send":"2342408","recv":"09639B8"},
  "3.2.22-42941-x64": {"send":"5BC1630","recv":"3011E00"},
  "3.2.22-42941-arm64": {"send":"3DC90AC","recv":"1497A70"},
  "9.9.25-42941-x64": {"send":"0A131D4","recv":"1D4547D"},
  "6.9.86-42941-arm64": {"send":"2346108","recv":"09675F0"},
  "9.9.26-44175-x64": {"send":"0A0F2EC","recv":"1D3AD4D"},
};

class Frame {
  static pack(head, body) {
    const totalLength = 9 + head.length + body.length + 1;
    const buffer = Buffer.allocUnsafe(totalLength);
    buffer[0] = 40;
    buffer.writeUInt32BE(head.length, 1);
    buffer.writeUInt32BE(body.length, 5);
    head.copy(buffer, 9);
    body.copy(buffer, 9 + head.length);
    buffer[totalLength - 1] = 41;
    return buffer;
  }
  static unpack(frame) {
    assert$1(frame[0] === 40 && frame[frame.length - 1] === 41, "Invalid frame!");
    const headLen = frame.readUInt32BE(1);
    const bodyLen = frame.readUInt32BE(5);
    return [frame.subarray(9, 9 + headLen), frame.subarray(9 + headLen, 9 + headLen + bodyLen)];
  }
}

({
  selfUin: ProtoField(2, ScalarType.UINT32),
  subCmd: ProtoField(3, ScalarType.UINT32),
  field6: ProtoField(6, ScalarType.UINT32)
});
({
  imPlat: ProtoField(1, ScalarType.UINT32),
  osVersion: ProtoField(2, ScalarType.STRING, true),
  qVersion: ProtoField(3, ScalarType.STRING, true)
});
({
  retCode: ProtoField(1, ScalarType.UINT32),
  errMsg: ProtoField(2, ScalarType.STRING),
  subCmd: ProtoField(3, ScalarType.UINT32)});
({
  fileName: ProtoField(1, ScalarType.STRING, false, true),
  deleteFile: ProtoField(2, ScalarType.STRING, false, true),
  bid: ProtoField(3, ScalarType.STRING),
  maxRoamSize: ProtoField(4, ScalarType.UINT32),
  emojiType: ProtoField(5, ScalarType.UINT32, false, true)
});
({
  state: ProtoField(1, ScalarType.INT32),
  sizeCache: ProtoField(2, ScalarType.INT32),
  unknownFields: ProtoField(3, ScalarType.BYTES),
  msgSeq: ProtoField(7, ScalarType.INT32),
  msgRand: ProtoField(8, ScalarType.INT32),
  syncCookie: ProtoField(9, ScalarType.BYTES),
  msgVia: ProtoField(10, ScalarType.INT32),
  dataStatist: ProtoField(11, ScalarType.INT32),
  multiSendSeq: ProtoField(13, ScalarType.INT32)
});
({
  result: ProtoField(1, ScalarType.INT32),
  errMsg: ProtoField(2, ScalarType.STRING, true),
  timestamp1: ProtoField(3, ScalarType.UINT32),
  field10: ProtoField(10, ScalarType.UINT32),
  groupSequence: ProtoField(11, ScalarType.UINT32, true),
  timestamp2: ProtoField(12, ScalarType.UINT32),
  privateSequence: ProtoField(14, ScalarType.UINT32)
});
({
  status: ProtoField(1, ScalarType.UINT32),
  extStatus: ProtoField(2, ScalarType.UINT32),
  batteryStatus: ProtoField(3, ScalarType.UINT32)});
({
  faceId: ProtoField(1, ScalarType.UINT32),
  text: ProtoField(2, ScalarType.STRING, true),
  field3: ProtoField(3, ScalarType.UINT32)
});
({
  message: ProtoField(2, ScalarType.STRING)
});
const HttpConn = {
  field1: ProtoField(1, ScalarType.INT32),
  field2: ProtoField(2, ScalarType.INT32),
  field3: ProtoField(3, ScalarType.INT32),
  field4: ProtoField(4, ScalarType.INT32),
  tgt: ProtoField(5, ScalarType.STRING),
  field6: ProtoField(6, ScalarType.INT32),
  serviceTypes: ProtoField(7, ScalarType.INT32, false, true),
  field9: ProtoField(9, ScalarType.INT32),
  field10: ProtoField(10, ScalarType.INT32),
  field11: ProtoField(11, ScalarType.INT32),
  ver: ProtoField(15, ScalarType.STRING)
};
const HttpConn0x6ff_501 = {
  httpConn: ProtoField(1281, () => HttpConn)
};
const HttpConn0x6ff_501Response = {
  httpConn: ProtoField(1281, () => HttpConnResponse)
};
const HttpConnResponse = {
  sigSession: ProtoField(1, ScalarType.BYTES),
  sessionKey: ProtoField(2, ScalarType.BYTES),
  serverInfos: ProtoField(3, () => ServerInfo, false, true)
};
const ServerAddr = {
  type: ProtoField(1, ScalarType.UINT32),
  ip: ProtoField(2, ScalarType.FIXED32),
  port: ProtoField(3, ScalarType.UINT32),
  area: ProtoField(4, ScalarType.UINT32)
};
const ServerInfo = {
  serviceType: ProtoField(1, ScalarType.UINT32),
  serverAddrs: ProtoField(2, () => ServerAddr, false, true)
};

const MiniAppAdaptShareInfoReq = {
  appId: ProtoField(2, ScalarType.STRING),
  body: ProtoField(4, () => MiniAppAdaptShareInfoReqBody)
};
const MiniAppAdaptShareInfoReqBody = {
  extInfo: ProtoField(1, () => ExtInfo),
  appid: ProtoField(2, ScalarType.STRING),
  title: ProtoField(3, ScalarType.STRING),
  desc: ProtoField(4, ScalarType.STRING),
  time: ProtoField(5, ScalarType.UINT64),
  scene: ProtoField(6, ScalarType.UINT32),
  templateType: ProtoField(7, ScalarType.UINT32),
  businessType: ProtoField(8, ScalarType.UINT32),
  picUrl: ProtoField(9, ScalarType.STRING),
  vidUrl: ProtoField(10, ScalarType.STRING),
  jumpUrl: ProtoField(11, ScalarType.STRING),
  iconUrl: ProtoField(12, ScalarType.STRING),
  verType: ProtoField(13, ScalarType.UINT32),
  shareType: ProtoField(14, ScalarType.UINT32),
  versionId: ProtoField(15, ScalarType.STRING),
  withShareTicket: ProtoField(16, ScalarType.UINT32),
  webURL: ProtoField(17, ScalarType.STRING),
  appidRich: ProtoField(18, ScalarType.BYTES),
  template: ProtoField(19, () => Template),
  field20: ProtoField(20, ScalarType.STRING)
};
const ExtInfo = {
  field2: ProtoField(2, ScalarType.BYTES)
};
const Template = {
  templateId: ProtoField(1, ScalarType.STRING),
  templateData: ProtoField(2, ScalarType.STRING)
};
const MiniAppAdaptShareInfoResp = {
  field2: ProtoField(2, ScalarType.UINT32),
  field3: ProtoField(3, ScalarType.STRING),
  content: ProtoField(4, () => MiniAppAdaptShareInfoRespContent)
};
const MiniAppAdaptShareInfoRespContent = {
  jsonContent: ProtoField(2, ScalarType.STRING)
};

const DataHighwayHead = {
  version: ProtoField(1, ScalarType.UINT32),
  uin: ProtoField(2, ScalarType.STRING, true),
  command: ProtoField(3, ScalarType.STRING, true),
  seq: ProtoField(4, ScalarType.UINT32, true),
  retryTimes: ProtoField(5, ScalarType.UINT32, true),
  appId: ProtoField(6, ScalarType.UINT32),
  dataFlag: ProtoField(7, ScalarType.UINT32),
  commandId: ProtoField(8, ScalarType.UINT32),
  buildVer: ProtoField(9, ScalarType.BYTES, true)
};
const FileUploadExt = {
  unknown1: ProtoField(1, ScalarType.INT32),
  unknown2: ProtoField(2, ScalarType.INT32),
  unknown3: ProtoField(3, ScalarType.INT32),
  entry: ProtoField(100, () => FileUploadEntry),
  unknown200: ProtoField(200, ScalarType.INT32)
};
const FileUploadEntry = {
  busiBuff: ProtoField(100, () => ExcitingBusiInfo),
  fileEntry: ProtoField(200, () => ExcitingFileEntry),
  clientInfo: ProtoField(300, () => ExcitingClientInfo),
  fileNameInfo: ProtoField(400, () => ExcitingFileNameInfo),
  host: ProtoField(500, () => ExcitingHostConfig)
};
const ExcitingBusiInfo = {
  busId: ProtoField(1, ScalarType.INT32),
  senderUin: ProtoField(100, ScalarType.UINT64),
  receiverUin: ProtoField(200, ScalarType.UINT64),
  groupCode: ProtoField(400, ScalarType.UINT64)
};
const ExcitingFileEntry = {
  fileSize: ProtoField(100, ScalarType.UINT64),
  md5: ProtoField(200, ScalarType.BYTES),
  checkKey: ProtoField(300, ScalarType.BYTES),
  md5S2: ProtoField(400, ScalarType.BYTES),
  fileId: ProtoField(600, ScalarType.STRING),
  uploadKey: ProtoField(700, ScalarType.BYTES)
};
const ExcitingClientInfo = {
  clientType: ProtoField(100, ScalarType.INT32),
  appId: ProtoField(200, ScalarType.STRING),
  terminalType: ProtoField(300, ScalarType.INT32),
  clientVer: ProtoField(400, ScalarType.STRING),
  unknown: ProtoField(600, ScalarType.INT32)
};
const ExcitingFileNameInfo = {
  fileName: ProtoField(100, ScalarType.STRING)
};
const ExcitingHostConfig = {
  hosts: ProtoField(200, () => ExcitingHostInfo, false, true)
};
const ExcitingHostInfo = {
  url: ProtoField(1, () => ExcitingUrlInfo),
  port: ProtoField(2, ScalarType.UINT32)
};
const ExcitingUrlInfo = {
  unknown: ProtoField(1, ScalarType.INT32),
  host: ProtoField(2, ScalarType.STRING)
};
const LoginSigHead = {
  uint32LoginSigType: ProtoField(1, ScalarType.UINT32),
  bytesLoginSig: ProtoField(2, ScalarType.BYTES),
  appId: ProtoField(3, ScalarType.UINT32)
};
const NTV2RichMediaHighwayExt = {
  fileUuid: ProtoField(1, ScalarType.STRING),
  uKey: ProtoField(2, ScalarType.STRING),
  network: ProtoField(5, () => NTHighwayNetwork),
  msgInfoBody: ProtoField(6, () => MsgInfoBody, false, true),
  blockSize: ProtoField(10, ScalarType.UINT32),
  hash: ProtoField(11, () => NTHighwayHash)
};
const NTHighwayHash = {
  fileSha1: ProtoField(1, ScalarType.BYTES, false, true)
};
const NTHighwayNetwork = {
  ipv4s: ProtoField(1, () => NTHighwayIPv4, false, true)
};
const NTHighwayIPv4 = {
  domain: ProtoField(1, () => NTHighwayDomain),
  port: ProtoField(2, ScalarType.UINT32)
};
const NTHighwayDomain = {
  isEnable: ProtoField(1, ScalarType.BOOL),
  ip: ProtoField(2, ScalarType.STRING)
};
const ReqDataHighwayHead = {
  msgBaseHead: ProtoField(1, () => DataHighwayHead, true),
  msgSegHead: ProtoField(2, () => SegHead, true),
  bytesReqExtendInfo: ProtoField(3, ScalarType.BYTES, true),
  timestamp: ProtoField(4, ScalarType.UINT64),
  msgLoginSigHead: ProtoField(5, () => LoginSigHead, true)
};
const RespDataHighwayHead = {
  msgBaseHead: ProtoField(1, () => DataHighwayHead, true),
  msgSegHead: ProtoField(2, () => SegHead, true),
  errorCode: ProtoField(3, ScalarType.UINT32),
  allowRetry: ProtoField(4, ScalarType.UINT32),
  cacheCost: ProtoField(5, ScalarType.UINT32),
  htCost: ProtoField(6, ScalarType.UINT32),
  bytesRspExtendInfo: ProtoField(7, ScalarType.BYTES, true),
  timestamp: ProtoField(8, ScalarType.UINT64),
  range: ProtoField(9, ScalarType.UINT64),
  isReset: ProtoField(10, ScalarType.UINT32)
};
const SegHead = {
  serviceId: ProtoField(1, ScalarType.UINT32, true),
  filesize: ProtoField(2, ScalarType.UINT64),
  dataOffset: ProtoField(3, ScalarType.UINT64, true),
  dataLength: ProtoField(4, ScalarType.UINT32),
  retCode: ProtoField(5, ScalarType.UINT32, true),
  serviceTicket: ProtoField(6, ScalarType.BYTES),
  flag: ProtoField(7, ScalarType.UINT32, true),
  md5: ProtoField(8, ScalarType.BYTES),
  fileMd5: ProtoField(9, ScalarType.BYTES),
  cacheAddr: ProtoField(10, ScalarType.UINT32, true),
  queryTimes: ProtoField(11, ScalarType.UINT32),
  updateCacheIp: ProtoField(12, ScalarType.UINT32),
  cachePort: ProtoField(13, ScalarType.UINT32, true)
};
({
  type: ProtoField(1, ScalarType.UINT32),
  groupUin: ProtoField(2, ScalarType.UINT32),
  field5: ProtoField(5, ScalarType.UINT32),
  field6: ProtoField(6, ScalarType.UINT32)
});
({
  field1: ProtoField(1, ScalarType.UINT32)
});

const LongMsgResult = {
  action: ProtoField(2, () => LongMsgAction, false, true)
};
const LongMsgAction = {
  actionCommand: ProtoField(1, ScalarType.STRING),
  actionData: ProtoField(2, () => LongMsgContent)
};
const LongMsgContent = {
  msgBody: ProtoField(1, () => PushMsgBody, false, true)
};
const RecvLongMsgReq = {
  info: ProtoField(1, () => RecvLongMsgInfo, true),
  settings: ProtoField(15, () => LongMsgSettings, true)
};
const RecvLongMsgInfo = {
  uid: ProtoField(1, () => LongMsgUid, true),
  resId: ProtoField(2, ScalarType.STRING, true),
  acquire: ProtoField(3, ScalarType.BOOL)
};
const LongMsgUid = {
  uid: ProtoField(2, ScalarType.STRING, true)
};
const LongMsgSettings = {
  field1: ProtoField(1, ScalarType.UINT32),
  field2: ProtoField(2, ScalarType.UINT32),
  field3: ProtoField(3, ScalarType.UINT32),
  field4: ProtoField(4, ScalarType.UINT32)
};
const RecvLongMsgResp = {
  result: ProtoField(1, () => RecvLongMsgResult),
  settings: ProtoField(15, () => LongMsgSettings)
};
const RecvLongMsgResult = {
  resId: ProtoField(3, ScalarType.STRING),
  payload: ProtoField(4, ScalarType.BYTES)
};
const SendLongMsgReq = {
  info: ProtoField(2, () => SendLongMsgInfo),
  settings: ProtoField(15, () => LongMsgSettings)
};
const SendLongMsgInfo = {
  type: ProtoField(1, ScalarType.UINT32),
  uid: ProtoField(2, () => LongMsgUid, true),
  groupUin: ProtoField(3, ScalarType.UINT32, true),
  payload: ProtoField(4, ScalarType.BYTES, true)
};
const SendLongMsgResp = {
  result: ProtoField(2, () => SendLongMsgResult),
  settings: ProtoField(15, () => LongMsgSettings)
};
const SendLongMsgResult = {
  resId: ProtoField(3, ScalarType.STRING)
};
const SsoGetGroupMsg = {
  info: ProtoField(1, () => SsoGetGroupMsgInfo),
  direction: ProtoField(2, ScalarType.BOOL)
};
const SsoGetGroupMsgInfo = {
  groupUin: ProtoField(1, ScalarType.UINT32),
  startSequence: ProtoField(2, ScalarType.UINT32),
  endSequence: ProtoField(3, ScalarType.UINT32)
};
const SsoGetGroupMsgResponse = {
  body: ProtoField(3, () => SsoGetGroupMsgResponseBody)
};
const SsoGetGroupMsgResponseBody = {
  groupUin: ProtoField(3, ScalarType.UINT32),
  startSequence: ProtoField(4, ScalarType.UINT32),
  endSequence: ProtoField(5, ScalarType.UINT32),
  messages: ProtoField(6, () => PushMsgBody, false, true)
};
({
  friendUid: ProtoField(1, ScalarType.STRING, true),
  time: ProtoField(2, ScalarType.UINT32),
  random: ProtoField(3, ScalarType.UINT32),
  count: ProtoField(4, ScalarType.UINT32),
  direction: ProtoField(5, ScalarType.BOOL)
});
({
  friendUid: ProtoField(3, ScalarType.STRING),
  timestamp: ProtoField(5, ScalarType.UINT32),
  random: ProtoField(6, ScalarType.UINT32)});
const SsoGetC2cMsg = {
  friendUid: ProtoField(2, ScalarType.STRING, true),
  startSequence: ProtoField(3, ScalarType.UINT32),
  endSequence: ProtoField(4, ScalarType.UINT32)
};
const SsoGetC2cMsgResponse = {
  friendUid: ProtoField(4, ScalarType.STRING),
  messages: ProtoField(7, () => PushMsgBody, false, true)
};

({
  uin: ProtoField(1, ScalarType.UINT32, true),
  uid: ProtoField(2, ScalarType.STRING, true),
  field3: ProtoField(3, ScalarType.UINT32, true),
  sig: ProtoField(4, ScalarType.UINT32, true),
  receiverUin: ProtoField(5, ScalarType.UINT32, true),
  receiverUid: ProtoField(6, ScalarType.STRING, true)
});

const Attr = {
  codePage: ProtoField(1, ScalarType.INT32),
  time: ProtoField(2, ScalarType.INT32),
  random: ProtoField(3, ScalarType.INT32),
  color: ProtoField(4, ScalarType.INT32),
  size: ProtoField(5, ScalarType.INT32),
  effect: ProtoField(6, ScalarType.INT32),
  charSet: ProtoField(7, ScalarType.INT32),
  pitchAndFamily: ProtoField(8, ScalarType.INT32),
  fontName: ProtoField(9, ScalarType.STRING),
  reserveData: ProtoField(10, ScalarType.BYTES)
};
const NotOnlineFile = {
  fileType: ProtoField(1, ScalarType.INT32, true),
  sig: ProtoField(2, ScalarType.BYTES, true),
  fileUuid: ProtoField(3, ScalarType.STRING, true),
  fileMd5: ProtoField(4, ScalarType.BYTES, true),
  fileName: ProtoField(5, ScalarType.STRING, true),
  fileSize: ProtoField(6, ScalarType.INT64, true),
  note: ProtoField(7, ScalarType.BYTES, true),
  reserved: ProtoField(8, ScalarType.INT32, true),
  subcmd: ProtoField(9, ScalarType.INT32, true),
  microCloud: ProtoField(10, ScalarType.INT32, true),
  bytesFileUrls: ProtoField(11, ScalarType.BYTES, false, true),
  downloadFlag: ProtoField(12, ScalarType.INT32, true),
  dangerEvel: ProtoField(50, ScalarType.INT32, true),
  lifeTime: ProtoField(51, ScalarType.INT32, true),
  uploadTime: ProtoField(52, ScalarType.INT32, true),
  absFileType: ProtoField(53, ScalarType.INT32, true),
  clientType: ProtoField(54, ScalarType.INT32, true),
  expireTime: ProtoField(55, ScalarType.INT32, true),
  pbReserve: ProtoField(56, ScalarType.BYTES, true),
  fileHash: ProtoField(57, ScalarType.STRING, true)
};
const Ptt = {
  fileType: ProtoField(1, ScalarType.INT32),
  srcUin: ProtoField(2, ScalarType.UINT64),
  fileUuid: ProtoField(3, ScalarType.STRING),
  fileMd5: ProtoField(4, ScalarType.BYTES),
  fileName: ProtoField(5, ScalarType.STRING),
  fileSize: ProtoField(6, ScalarType.INT32),
  reserve: ProtoField(7, ScalarType.BYTES),
  fileId: ProtoField(8, ScalarType.INT32),
  serverIp: ProtoField(9, ScalarType.INT32),
  serverPort: ProtoField(10, ScalarType.INT32),
  boolValid: ProtoField(11, ScalarType.BOOL),
  signature: ProtoField(12, ScalarType.BYTES),
  shortcut: ProtoField(13, ScalarType.BYTES),
  fileKey: ProtoField(14, ScalarType.BYTES),
  magicPttIndex: ProtoField(15, ScalarType.INT32),
  voiceSwitch: ProtoField(16, ScalarType.INT32),
  pttUrl: ProtoField(17, ScalarType.BYTES),
  groupFileKey: ProtoField(18, ScalarType.STRING),
  time: ProtoField(19, ScalarType.INT32),
  downPara: ProtoField(20, ScalarType.BYTES),
  format: ProtoField(29, ScalarType.INT32),
  pbReserve: ProtoField(30, ScalarType.BYTES),
  bytesPttUrls: ProtoField(31, ScalarType.BYTES, false, true),
  downloadFlag: ProtoField(32, ScalarType.INT32)
};
const RichText = {
  attr: ProtoField(1, () => Attr, true),
  elems: ProtoField(2, () => Elem, false, true),
  notOnlineFile: ProtoField(3, () => NotOnlineFile, true),
  ptt: ProtoField(4, () => Ptt, true)
};
({
  id: ProtoField(1, ScalarType.STRING)});
({
  label: ProtoField(1, ScalarType.STRING),
  visitedLabel: ProtoField(2, ScalarType.STRING),
  style: ProtoField(3, ScalarType.INT32)
});
({
  type: ProtoField(1, ScalarType.INT32),
  unsupportTips: ProtoField(4, ScalarType.STRING),
  data: ProtoField(5, ScalarType.STRING),
  reply: ProtoField(7, ScalarType.BOOL),
  enter: ProtoField(8, ScalarType.BOOL)
});
({
  type: ProtoField(1, ScalarType.INT32),
  specifyRoleIds: ProtoField(2, ScalarType.STRING, false, true),
  specifyUserIds: ProtoField(3, ScalarType.STRING, false, true)
});
const FileExtra = {
  file: ProtoField(1, () => NotOnlineFile),
  field6: ProtoField(6, () => PrivateFileExtra)
};
const PrivateFileExtra = {
  field2: ProtoField(2, () => PrivateFileExtraField2)
};
const PrivateFileExtraField2 = {
  field1: ProtoField(1, ScalarType.UINT32),
  fileUuid: ProtoField(4, ScalarType.STRING),
  fileName: ProtoField(5, ScalarType.STRING),
  field6: ProtoField(6, ScalarType.UINT32),
  field7: ProtoField(7, ScalarType.BYTES),
  field8: ProtoField(8, ScalarType.BYTES),
  timestamp1: ProtoField(9, ScalarType.UINT32),
  fileHash: ProtoField(14, ScalarType.STRING),
  selfUid: ProtoField(15, ScalarType.STRING),
  destUid: ProtoField(16, ScalarType.STRING)
};
const GroupFileExtra = {
  field1: ProtoField(1, ScalarType.UINT32),
  fileName: ProtoField(2, ScalarType.STRING),
  display: ProtoField(3, ScalarType.STRING),
  inner: ProtoField(7, () => GroupFileExtraInner)
};
const GroupFileExtraInner = {
  info: ProtoField(2, () => GroupFileExtraInfo)
};
const GroupFileExtraInfo = {
  busId: ProtoField(1, ScalarType.UINT32),
  fileId: ProtoField(2, ScalarType.STRING),
  fileSize: ProtoField(3, ScalarType.UINT64),
  fileName: ProtoField(4, ScalarType.STRING),
  field5: ProtoField(5, ScalarType.UINT32),
  fileSha: ProtoField(6, ScalarType.BYTES),
  extInfoString: ProtoField(7, ScalarType.STRING),
  fileMd5: ProtoField(8, ScalarType.BYTES)
};
({
  origUrl: ProtoField(30, ScalarType.STRING)
});
({
  type: ProtoField(1, ScalarType.UINT32),
  field7: ProtoField(7, ScalarType.UINT32),
  field8: ProtoField(8, ScalarType.UINT32)
});

const Elem = {
  text: ProtoField(1, () => Text, true),
  face: ProtoField(2, () => Face, true),
  onlineImage: ProtoField(3, () => OnlineImage, true),
  notOnlineImage: ProtoField(4, () => NotOnlineImage, true),
  transElem: ProtoField(5, () => TransElem, true),
  marketFace: ProtoField(6, () => MarketFace, true),
  customFace: ProtoField(8, () => CustomFace, true),
  elemFlags2: ProtoField(9, () => ElemFlags2, true),
  richMsg: ProtoField(12, () => RichMsg, true),
  groupFile: ProtoField(13, () => GroupFile, true),
  extraInfo: ProtoField(16, () => ExtraInfo, true),
  videoFile: ProtoField(19, () => VideoFile, true),
  anonymousGroupMessage: ProtoField(21, () => AnonymousGroupMessage, true),
  customElem: ProtoField(31, () => CustomElem, true),
  generalFlags: ProtoField(37, () => GeneralFlags, true),
  srcMsg: ProtoField(45, () => SrcMsg, true),
  lightAppElem: ProtoField(51, () => LightAppElem, true),
  commonElem: ProtoField(53, () => CommonElem, true)
};
const Text = {
  str: ProtoField(1, ScalarType.STRING, true),
  lint: ProtoField(2, ScalarType.STRING, true),
  attr6Buf: ProtoField(3, ScalarType.BYTES, true),
  attr7Buf: ProtoField(4, ScalarType.BYTES, true),
  buf: ProtoField(11, ScalarType.BYTES, true),
  pbReserve: ProtoField(12, ScalarType.BYTES, true)
};
const Face = {
  index: ProtoField(1, ScalarType.INT32, true),
  old: ProtoField(2, ScalarType.BYTES, true),
  buf: ProtoField(11, ScalarType.BYTES, true)
};
const OnlineImage = {
  guid: ProtoField(1, ScalarType.BYTES),
  filePath: ProtoField(2, ScalarType.BYTES),
  oldVerSendFile: ProtoField(3, ScalarType.BYTES)
};
const NotOnlineImage = {
  filePath: ProtoField(1, ScalarType.STRING),
  fileLen: ProtoField(2, ScalarType.UINT32),
  downloadPath: ProtoField(3, ScalarType.STRING),
  oldVerSendFile: ProtoField(4, ScalarType.BYTES),
  imgType: ProtoField(5, ScalarType.INT32),
  previewsImage: ProtoField(6, ScalarType.BYTES),
  picMd5: ProtoField(7, ScalarType.BYTES),
  picHeight: ProtoField(8, ScalarType.UINT32),
  picWidth: ProtoField(9, ScalarType.UINT32),
  resId: ProtoField(10, ScalarType.STRING),
  flag: ProtoField(11, ScalarType.BYTES),
  thumbUrl: ProtoField(12, ScalarType.STRING),
  original: ProtoField(13, ScalarType.INT32),
  bigUrl: ProtoField(14, ScalarType.STRING),
  origUrl: ProtoField(15, ScalarType.STRING),
  bizType: ProtoField(16, ScalarType.INT32),
  result: ProtoField(17, ScalarType.INT32),
  index: ProtoField(18, ScalarType.INT32),
  opFaceBuf: ProtoField(19, ScalarType.BYTES),
  oldPicMd5: ProtoField(20, ScalarType.BOOL),
  thumbWidth: ProtoField(21, ScalarType.INT32),
  thumbHeight: ProtoField(22, ScalarType.INT32),
  fileId: ProtoField(23, ScalarType.INT32),
  showLen: ProtoField(24, ScalarType.UINT32),
  downloadLen: ProtoField(25, ScalarType.UINT32),
  x400Url: ProtoField(26, ScalarType.STRING),
  x400Width: ProtoField(27, ScalarType.INT32),
  x400Height: ProtoField(28, ScalarType.INT32),
  pbRes: ProtoField(29, () => NotOnlineImage_PbReserve)
};
const NotOnlineImage_PbReserve = {
  subType: ProtoField(1, ScalarType.INT32),
  field3: ProtoField(3, ScalarType.INT32),
  field4: ProtoField(4, ScalarType.INT32),
  summary: ProtoField(8, ScalarType.STRING),
  field10: ProtoField(10, ScalarType.INT32),
  field20: ProtoField(20, () => NotOnlineImage_PbReserve2),
  url: ProtoField(30, ScalarType.STRING),
  md5Str: ProtoField(31, ScalarType.STRING)
};
const NotOnlineImage_PbReserve2 = {
  field1: ProtoField(1, ScalarType.INT32),
  field2: ProtoField(2, ScalarType.STRING),
  field3: ProtoField(3, ScalarType.INT32),
  field4: ProtoField(4, ScalarType.INT32),
  field5: ProtoField(5, ScalarType.INT32),
  field7: ProtoField(7, ScalarType.STRING)
};
const TransElem = {
  elemType: ProtoField(1, ScalarType.INT32),
  elemValue: ProtoField(2, ScalarType.BYTES)
};
const MarketFace = {
  faceName: ProtoField(1, ScalarType.STRING),
  itemType: ProtoField(2, ScalarType.INT32),
  faceInfo: ProtoField(3, ScalarType.INT32),
  faceId: ProtoField(4, ScalarType.BYTES),
  tabId: ProtoField(5, ScalarType.INT32),
  subType: ProtoField(6, ScalarType.INT32),
  key: ProtoField(7, ScalarType.STRING),
  param: ProtoField(8, ScalarType.BYTES),
  mediaType: ProtoField(9, ScalarType.INT32),
  imageWidth: ProtoField(10, ScalarType.INT32),
  imageHeight: ProtoField(11, ScalarType.INT32),
  mobileparam: ProtoField(12, ScalarType.BYTES),
  pbReserve: ProtoField(13, () => MarketFacePbRes)
};
const MarketFacePbRes = {
  field8: ProtoField(8, ScalarType.INT32)
};
const CustomFace = {
  guid: ProtoField(1, ScalarType.BYTES),
  filePath: ProtoField(2, ScalarType.STRING),
  shortcut: ProtoField(3, ScalarType.STRING),
  buffer: ProtoField(4, ScalarType.BYTES),
  flag: ProtoField(5, ScalarType.BYTES),
  oldData: ProtoField(6, ScalarType.BYTES, true),
  fileId: ProtoField(7, ScalarType.UINT32),
  serverIp: ProtoField(8, ScalarType.INT32, true),
  serverPort: ProtoField(9, ScalarType.INT32, true),
  fileType: ProtoField(10, ScalarType.INT32),
  signature: ProtoField(11, ScalarType.BYTES),
  useful: ProtoField(12, ScalarType.INT32),
  md5: ProtoField(13, ScalarType.BYTES),
  thumbUrl: ProtoField(14, ScalarType.STRING),
  bigUrl: ProtoField(15, ScalarType.STRING),
  origUrl: ProtoField(16, ScalarType.STRING),
  bizType: ProtoField(17, ScalarType.INT32),
  repeatIndex: ProtoField(18, ScalarType.INT32),
  repeatImage: ProtoField(19, ScalarType.INT32),
  imageType: ProtoField(20, ScalarType.INT32),
  index: ProtoField(21, ScalarType.INT32),
  width: ProtoField(22, ScalarType.INT32),
  height: ProtoField(23, ScalarType.INT32),
  source: ProtoField(24, ScalarType.INT32),
  size: ProtoField(25, ScalarType.UINT32),
  origin: ProtoField(26, ScalarType.INT32),
  thumbWidth: ProtoField(27, ScalarType.INT32, true),
  thumbHeight: ProtoField(28, ScalarType.INT32, true),
  showLen: ProtoField(29, ScalarType.INT32),
  downloadLen: ProtoField(30, ScalarType.INT32),
  x400Url: ProtoField(31, ScalarType.STRING, true),
  x400Width: ProtoField(32, ScalarType.INT32),
  x400Height: ProtoField(33, ScalarType.INT32),
  pbRes: ProtoField(34, () => CustomFace_PbReserve, true)
};
const CustomFace_PbReserve = {
  subType: ProtoField(1, ScalarType.INT32),
  summary: ProtoField(9, ScalarType.STRING)
};
const ElemFlags2 = {
  colorTextId: ProtoField(1, ScalarType.UINT32),
  msgId: ProtoField(2, ScalarType.UINT64),
  whisperSessionId: ProtoField(3, ScalarType.UINT32),
  pttChangeBit: ProtoField(4, ScalarType.UINT32),
  vipStatus: ProtoField(5, ScalarType.UINT32),
  compatibleId: ProtoField(6, ScalarType.UINT32),
  insts: ProtoField(7, () => Instance, false, true),
  msgRptCnt: ProtoField(8, ScalarType.UINT32),
  srcInst: ProtoField(9, () => Instance),
  longtitude: ProtoField(10, ScalarType.UINT32),
  latitude: ProtoField(11, ScalarType.UINT32),
  customFont: ProtoField(12, ScalarType.UINT32),
  pcSupportDef: ProtoField(13, () => PcSupportDef),
  crmFlags: ProtoField(14, ScalarType.UINT32, true)
};
const PcSupportDef = {
  pcPtlBegin: ProtoField(1, ScalarType.UINT32),
  pcPtlEnd: ProtoField(2, ScalarType.UINT32),
  macPtlBegin: ProtoField(3, ScalarType.UINT32),
  macPtlEnd: ProtoField(4, ScalarType.UINT32),
  ptlsSupport: ProtoField(5, ScalarType.INT32, false, true),
  ptlsNotSupport: ProtoField(6, ScalarType.UINT32, false, true)
};
const Instance = {
  appId: ProtoField(1, ScalarType.UINT32),
  instId: ProtoField(2, ScalarType.UINT32)
};
const RichMsg = {
  template1: ProtoField(1, ScalarType.BYTES, true),
  serviceId: ProtoField(2, ScalarType.INT32, true),
  msgResId: ProtoField(3, ScalarType.BYTES, true),
  rand: ProtoField(4, ScalarType.INT32, true),
  seq: ProtoField(5, ScalarType.UINT32, true)
};
const GroupFile = {
  filename: ProtoField(1, ScalarType.BYTES),
  fileSize: ProtoField(2, ScalarType.UINT64),
  fileId: ProtoField(3, ScalarType.BYTES),
  batchId: ProtoField(4, ScalarType.BYTES),
  fileKey: ProtoField(5, ScalarType.BYTES),
  mark: ProtoField(6, ScalarType.BYTES),
  sequence: ProtoField(7, ScalarType.UINT64),
  batchItemId: ProtoField(8, ScalarType.BYTES),
  feedMsgTime: ProtoField(9, ScalarType.INT32),
  pbReserve: ProtoField(10, ScalarType.BYTES)
};
const ExtraInfo = {
  nick: ProtoField(1, ScalarType.BYTES),
  groupCard: ProtoField(2, ScalarType.BYTES),
  level: ProtoField(3, ScalarType.INT32),
  flags: ProtoField(4, ScalarType.INT32),
  groupMask: ProtoField(5, ScalarType.INT32),
  msgTailId: ProtoField(6, ScalarType.INT32),
  senderTitle: ProtoField(7, ScalarType.BYTES),
  apnsTips: ProtoField(8, ScalarType.BYTES),
  uin: ProtoField(9, ScalarType.UINT64),
  msgStateFlag: ProtoField(10, ScalarType.INT32),
  apnsSoundType: ProtoField(11, ScalarType.INT32),
  newGroupFlag: ProtoField(12, ScalarType.INT32)
};
const VideoFile = {
  fileUuid: ProtoField(1, ScalarType.STRING),
  fileMd5: ProtoField(2, ScalarType.BYTES),
  fileName: ProtoField(3, ScalarType.STRING),
  fileFormat: ProtoField(4, ScalarType.INT32),
  fileTime: ProtoField(5, ScalarType.INT32),
  fileSize: ProtoField(6, ScalarType.INT32),
  thumbWidth: ProtoField(7, ScalarType.INT32),
  thumbHeight: ProtoField(8, ScalarType.INT32),
  thumbFileMd5: ProtoField(9, ScalarType.BYTES),
  source: ProtoField(10, ScalarType.BYTES),
  thumbFileSize: ProtoField(11, ScalarType.INT32),
  busiType: ProtoField(12, ScalarType.INT32),
  fromChatType: ProtoField(13, ScalarType.INT32),
  toChatType: ProtoField(14, ScalarType.INT32),
  boolSupportProgressive: ProtoField(15, ScalarType.BOOL),
  fileWidth: ProtoField(16, ScalarType.INT32),
  fileHeight: ProtoField(17, ScalarType.INT32),
  subBusiType: ProtoField(18, ScalarType.INT32),
  videoAttr: ProtoField(19, ScalarType.INT32),
  bytesThumbFileUrls: ProtoField(20, ScalarType.BYTES, false, true),
  bytesVideoFileUrls: ProtoField(21, ScalarType.BYTES, false, true),
  thumbDownloadFlag: ProtoField(22, ScalarType.INT32),
  videoDownloadFlag: ProtoField(23, ScalarType.INT32),
  pbReserve: ProtoField(24, ScalarType.BYTES)
};
const AnonymousGroupMessage = {
  flags: ProtoField(1, ScalarType.INT32),
  anonId: ProtoField(2, ScalarType.BYTES),
  anonNick: ProtoField(3, ScalarType.BYTES),
  headPortrait: ProtoField(4, ScalarType.INT32),
  expireTime: ProtoField(5, ScalarType.INT32),
  bubbleId: ProtoField(6, ScalarType.INT32),
  rankColor: ProtoField(7, ScalarType.BYTES)
};
const CustomElem = {
  desc: ProtoField(1, ScalarType.BYTES),
  data: ProtoField(2, ScalarType.BYTES),
  enumType: ProtoField(3, ScalarType.INT32),
  ext: ProtoField(4, ScalarType.BYTES),
  sound: ProtoField(5, ScalarType.BYTES)
};
const GeneralFlags = {
  bubbleDiyTextId: ProtoField(1, ScalarType.INT32),
  groupFlagNew: ProtoField(2, ScalarType.INT32),
  uin: ProtoField(3, ScalarType.UINT64),
  rpId: ProtoField(4, ScalarType.BYTES),
  prpFold: ProtoField(5, ScalarType.INT32),
  longTextFlag: ProtoField(6, ScalarType.INT32),
  longTextResId: ProtoField(7, ScalarType.STRING, true),
  groupType: ProtoField(8, ScalarType.INT32),
  toUinFlag: ProtoField(9, ScalarType.INT32),
  glamourLevel: ProtoField(10, ScalarType.INT32),
  memberLevel: ProtoField(11, ScalarType.INT32),
  groupRankSeq: ProtoField(12, ScalarType.UINT64),
  olympicTorch: ProtoField(13, ScalarType.INT32),
  babyqGuideMsgCookie: ProtoField(14, ScalarType.BYTES),
  uin32ExpertFlag: ProtoField(15, ScalarType.INT32),
  bubbleSubId: ProtoField(16, ScalarType.INT32),
  pendantId: ProtoField(17, ScalarType.UINT64),
  rpIndex: ProtoField(18, ScalarType.BYTES),
  pbReserve: ProtoField(19, ScalarType.BYTES)
};
const SrcMsg = {
  origSeqs: ProtoField(1, ScalarType.UINT32, false, true),
  senderUin: ProtoField(2, ScalarType.UINT64),
  time: ProtoField(3, ScalarType.INT32, true),
  flag: ProtoField(4, ScalarType.INT32, true),
  elems: ProtoField(5, () => Elem, false, true),
  type: ProtoField(6, ScalarType.INT32, true),
  richMsg: ProtoField(7, ScalarType.BYTES, true),
  pbReserve: ProtoField(8, () => SrcMsgPbRes, true),
  sourceMsg: ProtoField(9, ScalarType.BYTES, true),
  toUin: ProtoField(10, ScalarType.UINT64, true),
  troopName: ProtoField(11, ScalarType.BYTES, true)
};
const SrcMsgPbRes = {
  messageId: ProtoField(3, ScalarType.UINT64),
  senderUid: ProtoField(6, ScalarType.STRING, true),
  receiverUid: ProtoField(7, ScalarType.STRING, true),
  friendSeq: ProtoField(8, ScalarType.UINT32, true)
};
const LightAppElem = {
  data: ProtoField(1, ScalarType.BYTES),
  msgResid: ProtoField(2, ScalarType.BYTES, true)
};
const CommonElem = {
  serviceType: ProtoField(1, ScalarType.INT32),
  pbElem: ProtoField(2, ScalarType.BYTES),
  businessType: ProtoField(3, ScalarType.UINT32)
};
({
  faceId: ProtoField(1, ScalarType.INT32, true)
});
const MentionExtra = {
  type: ProtoField(3, ScalarType.INT32, true),
  uin: ProtoField(4, ScalarType.UINT32, true),
  field5: ProtoField(5, ScalarType.INT32, true),
  uid: ProtoField(9, ScalarType.STRING, true)
};
const QBigFaceExtra = {
  AniStickerPackId: ProtoField(1, ScalarType.STRING, true),
  AniStickerId: ProtoField(2, ScalarType.STRING, true),
  faceId: ProtoField(3, ScalarType.INT32, true),
  sourceType: ProtoField(4, ScalarType.INT32, true),
  AniStickerType: ProtoField(5, ScalarType.INT32, true),
  resultId: ProtoField(6, ScalarType.STRING, true),
  preview: ProtoField(7, ScalarType.STRING, true),
  randomType: ProtoField(9, ScalarType.INT32, true)
};
const QSmallFaceExtra = {
  faceId: ProtoField(1, ScalarType.UINT32),
  preview: ProtoField(2, ScalarType.STRING),
  preview2: ProtoField(3, ScalarType.STRING)
};
const MarkdownData = {
  content: ProtoField(1, ScalarType.STRING)
};

({
  type: ProtoField(1, ScalarType.UINT32),
  groupUin: ProtoField(2, ScalarType.UINT32)});
({
  sequence: ProtoField(1, ScalarType.UINT32),
  random: ProtoField(2, ScalarType.UINT32),
  field3: ProtoField(3, ScalarType.UINT32)
});
({
  field1: ProtoField(1, ScalarType.UINT32)
});

const ContentHead = {
  type: ProtoField(1, ScalarType.UINT32),
  subType: ProtoField(2, ScalarType.UINT32, true),
  c2cCmd: ProtoField(3, ScalarType.UINT32, true),
  ranDom: ProtoField(4, ScalarType.UINT32, true),
  sequence: ProtoField(5, ScalarType.UINT32, true),
  timeStamp: ProtoField(6, ScalarType.UINT32, true),
  pkgNum: ProtoField(7, ScalarType.UINT64, true),
  pkgIndex: ProtoField(8, ScalarType.UINT32, true),
  divSeq: ProtoField(9, ScalarType.UINT32, true),
  autoReply: ProtoField(10, ScalarType.UINT32),
  ntMsgSeq: ProtoField(10, ScalarType.UINT32, true),
  newId: ProtoField(12, ScalarType.UINT64, true),
  forward: ProtoField(15, () => ForwardHead, true)
};
const MessageBody = {
  richText: ProtoField(1, () => RichText, true),
  msgContent: ProtoField(2, ScalarType.BYTES, true),
  msgEncryptContent: ProtoField(3, ScalarType.BYTES, true)
};
({
  clientSequence: ProtoField(4, ScalarType.UINT32, true),
  random: ProtoField(5, ScalarType.UINT32, true),
  syncCookie: ProtoField(6, ScalarType.BYTES, true),
  via: ProtoField(8, ScalarType.UINT32, true),
  dataStatist: ProtoField(9, ScalarType.UINT32, true),
  multiSendSeq: ProtoField(14, ScalarType.UINT32)
});
({
  msgFlag: ProtoField(1, ScalarType.INT32)
});
const PushMsg = {
  message: ProtoField(1, () => PushMsgBody),
  status: ProtoField(3, ScalarType.INT32, true),
  pingFlag: ProtoField(5, ScalarType.INT32, true),
  generalFlag: ProtoField(9, ScalarType.INT32, true)
};
const GroupChangeInfo = {
  operator: ProtoField(1, () => GroupChangeOperator, true)
};
const GroupChangeOperator = {
  operatorUid: ProtoField(1, ScalarType.STRING, true)
};
const GroupChange = {
  groupUin: ProtoField(1, ScalarType.UINT32),
  flag: ProtoField(2, ScalarType.UINT32),
  memberUid: ProtoField(3, ScalarType.STRING, true),
  decreaseType: ProtoField(4, ScalarType.UINT32),
  operatorInfo: ProtoField(5, ScalarType.BYTES, true),
  increaseType: ProtoField(6, ScalarType.UINT32),
  field7: ProtoField(7, ScalarType.BYTES, true)
};
const GroupReactionDataInnerDataTarget = {
  seq: ProtoField(1, ScalarType.UINT64, true)
};
const GroupReactionDataContent = {
  code: ProtoField(1, ScalarType.STRING, true),
  count: ProtoField(3, ScalarType.UINT32, true),
  operatorUid: ProtoField(4, ScalarType.STRING, true),
  type: ProtoField(5, ScalarType.UINT32, true)
};
const GroupReactionDataInnerData = {
  groupReactionTarget: ProtoField(2, () => GroupReactionDataInnerDataTarget, true),
  groupReactionDataContent: ProtoField(3, () => GroupReactionDataContent, true)
};
const GroupReactionDataInner = {
  data: ProtoField(1, () => GroupReactionDataInnerData, true)
};
const GroupReactionData = {
  data: ProtoField(1, () => GroupReactionDataInner, true)
};
const GroupReactNotify = {
  groupUin: ProtoField(4, ScalarType.UINT64, true),
  field13: ProtoField(13, ScalarType.UINT32, true),
  groupReactionData: ProtoField(44, () => GroupReactionData, true)
};
const GroupInvite = {
  groupUin: ProtoField(1, ScalarType.UINT32),
  field2: ProtoField(2, ScalarType.UINT32),
  field3: ProtoField(2, ScalarType.UINT32),
  field4: ProtoField(2, ScalarType.UINT32),
  invitorUid: ProtoField(5, ScalarType.STRING)
};
const PushMsgBody = {
  responseHead: ProtoField(1, () => ResponseHead),
  contentHead: ProtoField(2, () => ContentHead),
  body: ProtoField(3, () => MessageBody, true)
};
const ResponseHead = {
  fromUin: ProtoField(1, ScalarType.UINT32),
  fromUid: ProtoField(2, ScalarType.STRING, true),
  type: ProtoField(3, ScalarType.UINT32),
  sigMap: ProtoField(4, ScalarType.UINT32),
  toUin: ProtoField(5, ScalarType.UINT32),
  toUid: ProtoField(6, ScalarType.STRING, true),
  forward: ProtoField(7, () => ResponseForward, true),
  grp: ProtoField(8, () => ResponseGrp, true)
};

({
  instId: ProtoField(2, ScalarType.UINT32),
  appId: ProtoField(3, ScalarType.UINT32),
  longMessageFlag: ProtoField(4, ScalarType.UINT32),
  reserved: ProtoField(5, ScalarType.BYTES)
});
({
  fromUid: ProtoField(1, ScalarType.STRING),
  toUid: ProtoField(2, ScalarType.STRING),
  sequence: ProtoField(3, ScalarType.UINT32),
  newId: ProtoField(4, ScalarType.UINT64),
  time: ProtoField(5, ScalarType.UINT32),
  random: ProtoField(6, ScalarType.UINT32),
  pkgNum: ProtoField(7, ScalarType.UINT32),
  pkgIndex: ProtoField(8, ScalarType.UINT32),
  divSeq: ProtoField(9, ScalarType.UINT32)
});

const ForwardHead = {
  field1: ProtoField(1, ScalarType.UINT32, true),
  field2: ProtoField(2, ScalarType.UINT32, true),
  field3: ProtoField(3, ScalarType.UINT32, true),
  unknownBase64: ProtoField(5, ScalarType.STRING, true),
  avatar: ProtoField(6, ScalarType.STRING, true)
};
({
  groupCode: ProtoField(1, ScalarType.UINT32, true)
});
({
  groupUin: ProtoField(1, ScalarType.UINT32, true),
  toUin: ProtoField(2, ScalarType.UINT32, true)
});
const ResponseForward = {
  friendName: ProtoField(6, ScalarType.STRING, true)
};
const ResponseGrp = {
  groupUin: ProtoField(1, ScalarType.UINT32),
  memberName: ProtoField(4, ScalarType.STRING),
  unknown5: ProtoField(5, ScalarType.UINT32),
  groupName: ProtoField(7, ScalarType.STRING)
};
({
  toUin: ProtoField(1, ScalarType.UINT64, true),
  ccCmd: ProtoField(2, ScalarType.UINT32, true),
  uid: ProtoField(8, ScalarType.STRING, true)
});
({
  toUin: ProtoField(1, ScalarType.UINT64),
  sig: ProtoField(2, ScalarType.BYTES)
});

const NTV2RichMediaReq = {
  ReqHead: ProtoField(1, () => MultiMediaReqHead),
  Upload: ProtoField(2, () => UploadReq),
  Download: ProtoField(3, () => DownloadReq),
  DownloadRKey: ProtoField(4, () => DownloadRKeyReq),
  Delete: ProtoField(5, () => DeleteReq),
  UploadCompleted: ProtoField(6, () => UploadCompletedReq),
  MsgInfoAuth: ProtoField(7, () => MsgInfoAuthReq),
  UploadKeyRenewal: ProtoField(8, () => UploadKeyRenewalReq),
  DownloadSafe: ProtoField(9, () => DownloadSafeReq),
  Extension: ProtoField(99, ScalarType.BYTES, true)
};
const MultiMediaReqHead = {
  Common: ProtoField(1, () => CommonHead),
  Scene: ProtoField(2, () => SceneInfo),
  Client: ProtoField(3, () => ClientMeta)
};
const CommonHead = {
  RequestId: ProtoField(1, ScalarType.UINT32),
  Command: ProtoField(2, ScalarType.UINT32)
};
const SceneInfo = {
  RequestType: ProtoField(101, ScalarType.UINT32),
  BusinessType: ProtoField(102, ScalarType.UINT32),
  SceneType: ProtoField(200, ScalarType.UINT32),
  C2C: ProtoField(201, () => C2CUserInfo, true),
  Group: ProtoField(202, () => NTGroupInfo, true)
};
const C2CUserInfo = {
  AccountType: ProtoField(1, ScalarType.UINT32),
  TargetUid: ProtoField(2, ScalarType.STRING)
};
const NTGroupInfo = {
  GroupUin: ProtoField(1, ScalarType.UINT32)
};
const ClientMeta = {
  AgentType: ProtoField(1, ScalarType.UINT32)
};
const DownloadReq = {
  Node: ProtoField(1, () => IndexNode),
  Download: ProtoField(2, () => DownloadExt)
};
const IndexNode = {
  Info: ProtoField(1, () => FileInfo),
  FileUuid: ProtoField(2, ScalarType.STRING),
  StoreId: ProtoField(3, ScalarType.UINT32),
  UploadTime: ProtoField(4, ScalarType.UINT32),
  Ttl: ProtoField(5, ScalarType.UINT32),
  SubType: ProtoField(6, ScalarType.UINT32)
};
const FileInfo = {
  FileSize: ProtoField(1, ScalarType.UINT32),
  FileHash: ProtoField(2, ScalarType.STRING),
  FileSha1: ProtoField(3, ScalarType.STRING),
  FileName: ProtoField(4, ScalarType.STRING),
  Type: ProtoField(5, () => FileType),
  Width: ProtoField(6, ScalarType.UINT32),
  Height: ProtoField(7, ScalarType.UINT32),
  Time: ProtoField(8, ScalarType.UINT32),
  Original: ProtoField(9, ScalarType.UINT32)
};
const FileType = {
  Type: ProtoField(1, ScalarType.UINT32),
  PicFormat: ProtoField(2, ScalarType.UINT32),
  VideoFormat: ProtoField(3, ScalarType.UINT32),
  VoiceFormat: ProtoField(4, ScalarType.UINT32)
};
const DownloadExt = {
  Pic: ProtoField(1, () => PicDownloadExt),
  Video: ProtoField(2, () => VideoDownloadExt),
  Ptt: ProtoField(3, () => PttDownloadExt)
};
const VideoDownloadExt = {
  BusiType: ProtoField(1, ScalarType.UINT32),
  SceneType: ProtoField(2, ScalarType.UINT32),
  SubBusiType: ProtoField(3, ScalarType.UINT32)
};
const PicDownloadExt = {};
const PttDownloadExt = {};
const DownloadRKeyReq = {
  Types: ProtoField(1, ScalarType.INT32, false, true)
};
const DeleteReq = {
  Index: ProtoField(1, () => IndexNode, false, true),
  NeedRecallMsg: ProtoField(2, ScalarType.BOOL),
  MsgSeq: ProtoField(3, ScalarType.UINT64),
  MsgRandom: ProtoField(4, ScalarType.UINT64),
  MsgTime: ProtoField(5, ScalarType.UINT64)
};
const UploadCompletedReq = {
  SrvSendMsg: ProtoField(1, ScalarType.BOOL),
  ClientRandomId: ProtoField(2, ScalarType.UINT64),
  MsgInfo: ProtoField(3, () => MsgInfo),
  ClientSeq: ProtoField(4, ScalarType.UINT32)
};
const MsgInfoAuthReq = {
  Msg: ProtoField(1, ScalarType.BYTES),
  AuthTime: ProtoField(2, ScalarType.UINT64)
};
const DownloadSafeReq = {
  Index: ProtoField(1, () => IndexNode)
};
const UploadKeyRenewalReq = {
  OldUKey: ProtoField(1, ScalarType.STRING),
  SubType: ProtoField(2, ScalarType.UINT32)
};
const MsgInfo = {
  MsgInfoBody: ProtoField(1, () => MsgInfoBody, false, true),
  ExtBizInfo: ProtoField(2, () => ExtBizInfo)
};
const MsgInfoBody = {
  Index: ProtoField(1, () => IndexNode),
  Picture: ProtoField(2, () => PictureInfo),
  Video: ProtoField(3, () => VideoInfo),
  Audio: ProtoField(4, () => AudioInfo),
  FileExist: ProtoField(5, ScalarType.BOOL),
  HashSum: ProtoField(6, ScalarType.BYTES)
};
const VideoInfo = {};
const AudioInfo = {};
const PictureInfo = {
  UrlPath: ProtoField(1, ScalarType.STRING),
  Ext: ProtoField(2, () => PicUrlExtInfo),
  Domain: ProtoField(3, ScalarType.STRING)
};
const PicUrlExtInfo = {
  OriginalParameter: ProtoField(1, ScalarType.STRING),
  BigParameter: ProtoField(2, ScalarType.STRING),
  ThumbParameter: ProtoField(3, ScalarType.STRING)
};
const VideoExtInfo = {
  VideoCodecFormat: ProtoField(1, ScalarType.UINT32)
};
const ExtBizInfo = {
  Pic: ProtoField(1, () => PicExtBizInfo),
  Video: ProtoField(2, () => VideoExtBizInfo),
  Ptt: ProtoField(3, () => PttExtBizInfo),
  BusiType: ProtoField(10, ScalarType.UINT32)
};
const PttExtBizInfo = {
  SrcUin: ProtoField(1, ScalarType.UINT64),
  PttScene: ProtoField(2, ScalarType.UINT32),
  PttType: ProtoField(3, ScalarType.UINT32),
  ChangeVoice: ProtoField(4, ScalarType.UINT32),
  Waveform: ProtoField(5, ScalarType.BYTES),
  AutoConvertText: ProtoField(6, ScalarType.UINT32),
  BytesReserve: ProtoField(11, ScalarType.BYTES),
  BytesPbReserve: ProtoField(12, ScalarType.BYTES),
  BytesGeneralFlags: ProtoField(13, ScalarType.BYTES)
};
const VideoExtBizInfo = {
  FromScene: ProtoField(1, ScalarType.UINT32),
  ToScene: ProtoField(2, ScalarType.UINT32),
  BytesPbReserve: ProtoField(3, ScalarType.BYTES)
};
const PicExtBizInfo = {
  BizType: ProtoField(1, ScalarType.UINT32),
  TextSummary: ProtoField(2, ScalarType.STRING),
  BytesPbReserveC2c: ProtoField(11, () => BytesPbReserveC2c),
  BytesPbReserveTroop: ProtoField(12, () => BytesPbReserveTroop),
  FromScene: ProtoField(1001, ScalarType.UINT32),
  ToScene: ProtoField(1002, ScalarType.UINT32),
  OldFileId: ProtoField(1003, ScalarType.UINT32)
};
const UploadReq = {
  UploadInfo: ProtoField(1, () => UploadInfo, false, true),
  TryFastUploadCompleted: ProtoField(2, ScalarType.BOOL),
  SrvSendMsg: ProtoField(3, ScalarType.BOOL),
  ClientRandomId: ProtoField(4, ScalarType.UINT64),
  CompatQMsgSceneType: ProtoField(5, ScalarType.UINT32),
  ExtBizInfo: ProtoField(6, () => ExtBizInfo),
  ClientSeq: ProtoField(7, ScalarType.UINT32),
  NoNeedCompatMsg: ProtoField(8, ScalarType.BOOL)
};
const UploadInfo = {
  FileInfo: ProtoField(1, () => FileInfo),
  SubFileType: ProtoField(2, ScalarType.UINT32)
};
const BytesPbReserveC2c = {
  subType: ProtoField(1, ScalarType.UINT32),
  field3: ProtoField(3, ScalarType.UINT32),
  field4: ProtoField(4, ScalarType.UINT32),
  field8: ProtoField(8, ScalarType.STRING),
  field10: ProtoField(10, ScalarType.UINT32),
  field12: ProtoField(12, ScalarType.STRING),
  field18: ProtoField(18, ScalarType.STRING),
  field19: ProtoField(19, ScalarType.STRING),
  field20: ProtoField(20, ScalarType.BYTES)
};
const BytesPbReserveTroop = {
  subType: ProtoField(1, ScalarType.UINT32),
  field3: ProtoField(3, ScalarType.UINT32),
  field4: ProtoField(4, ScalarType.UINT32),
  field9: ProtoField(9, ScalarType.STRING),
  field10: ProtoField(10, ScalarType.UINT32),
  field12: ProtoField(12, ScalarType.STRING),
  field18: ProtoField(18, ScalarType.STRING),
  field19: ProtoField(19, ScalarType.STRING),
  field21: ProtoField(21, ScalarType.BYTES)
};

const NTV2RichMediaResp = {
  respHead: ProtoField(1, () => MultiMediaRespHead),
  upload: ProtoField(2, () => UploadResp),
  download: ProtoField(3, () => DownloadResp),
  downloadRKey: ProtoField(4, () => DownloadRKeyResp),
  delete: ProtoField(5, () => DeleteResp),
  uploadCompleted: ProtoField(6, () => UploadCompletedResp),
  msgInfoAuth: ProtoField(7, () => MsgInfoAuthResp),
  uploadKeyRenewal: ProtoField(8, () => UploadKeyRenewalResp),
  downloadSafe: ProtoField(9, () => DownloadSafeResp),
  extension: ProtoField(99, ScalarType.BYTES, true)
};
const MultiMediaRespHead = {
  common: ProtoField(1, () => CommonHead),
  retCode: ProtoField(2, ScalarType.UINT32),
  message: ProtoField(3, ScalarType.STRING)
};
const DownloadResp = {
  rKeyParam: ProtoField(1, ScalarType.STRING),
  rKeyTtlSecond: ProtoField(2, ScalarType.UINT32),
  info: ProtoField(3, () => DownloadInfo),
  rKeyCreateTime: ProtoField(4, ScalarType.UINT32)
};
const DownloadInfo = {
  domain: ProtoField(1, ScalarType.STRING),
  urlPath: ProtoField(2, ScalarType.STRING),
  httpsPort: ProtoField(3, ScalarType.UINT32),
  ipv4s: ProtoField(4, () => IPv4, false, true),
  ipv6s: ProtoField(5, () => IPv6, false, true),
  picUrlExtInfo: ProtoField(6, () => PicUrlExtInfo),
  videoExtInfo: ProtoField(7, () => VideoExtInfo)
};
const IPv4 = {
  outIP: ProtoField(1, ScalarType.UINT32),
  outPort: ProtoField(2, ScalarType.UINT32),
  inIP: ProtoField(3, ScalarType.UINT32),
  inPort: ProtoField(4, ScalarType.UINT32),
  ipType: ProtoField(5, ScalarType.UINT32)
};
const IPv6 = {
  outIP: ProtoField(1, ScalarType.BYTES),
  outPort: ProtoField(2, ScalarType.UINT32),
  inIP: ProtoField(3, ScalarType.BYTES),
  inPort: ProtoField(4, ScalarType.UINT32),
  ipType: ProtoField(5, ScalarType.UINT32)
};
const UploadResp = {
  uKey: ProtoField(1, ScalarType.STRING, true),
  uKeyTtlSecond: ProtoField(2, ScalarType.UINT32),
  ipv4s: ProtoField(3, () => IPv4, false, true),
  ipv6s: ProtoField(4, () => IPv6, false, true),
  msgSeq: ProtoField(5, ScalarType.UINT64),
  msgInfo: ProtoField(6, () => MsgInfo),
  ext: ProtoField(7, () => RichMediaStorageTransInfo, false, true),
  compatQMsg: ProtoField(8, ScalarType.BYTES),
  subFileInfos: ProtoField(10, () => SubFileInfo, false, true)
};
const RichMediaStorageTransInfo = {
  subType: ProtoField(1, ScalarType.UINT32),
  extType: ProtoField(2, ScalarType.UINT32),
  extValue: ProtoField(3, ScalarType.BYTES)
};
const SubFileInfo = {
  subType: ProtoField(1, ScalarType.UINT32),
  uKey: ProtoField(2, ScalarType.STRING),
  uKeyTtlSecond: ProtoField(3, ScalarType.UINT32),
  ipv4s: ProtoField(4, () => IPv4, false, true),
  ipv6s: ProtoField(5, () => IPv6, false, true)
};
const DownloadSafeResp = {};
const UploadKeyRenewalResp = {
  ukey: ProtoField(1, ScalarType.STRING),
  ukeyTtlSec: ProtoField(2, ScalarType.UINT64)
};
const MsgInfoAuthResp = {
  authCode: ProtoField(1, ScalarType.UINT32),
  msg: ProtoField(2, ScalarType.BYTES),
  resultTime: ProtoField(3, ScalarType.UINT64)
};
const UploadCompletedResp = {
  msgSeq: ProtoField(1, ScalarType.UINT64)
};
const DeleteResp = {};
const DownloadRKeyResp = {
  rKeys: ProtoField(1, () => RKeyInfo, false, true)
};
const RKeyInfo = {
  rkey: ProtoField(1, ScalarType.STRING),
  rkeyTtlSec: ProtoField(2, ScalarType.UINT64),
  storeId: ProtoField(3, ScalarType.UINT32),
  rkeyCreateTime: ProtoField(4, ScalarType.UINT32, true),
  type: ProtoField(5, ScalarType.UINT32, true)
};

const OidbSvcTrpcTcp0x6D6 = {
  file: ProtoField(1, () => OidbSvcTrpcTcp0x6D6Upload, true),
  download: ProtoField(3, () => OidbSvcTrpcTcp0x6D6Download, true),
  delete: ProtoField(4, () => OidbSvcTrpcTcp0x6D6Delete, true),
  rename: ProtoField(5, () => OidbSvcTrpcTcp0x6D6Rename, true),
  move: ProtoField(6, () => OidbSvcTrpcTcp0x6D6Move, true)
};
const OidbSvcTrpcTcp0x6D6Upload = {
  groupUin: ProtoField(1, ScalarType.UINT32),
  appId: ProtoField(2, ScalarType.UINT32),
  busId: ProtoField(3, ScalarType.UINT32),
  entrance: ProtoField(4, ScalarType.UINT32),
  targetDirectory: ProtoField(5, ScalarType.STRING),
  fileName: ProtoField(6, ScalarType.STRING),
  localDirectory: ProtoField(7, ScalarType.STRING),
  fileSize: ProtoField(8, ScalarType.UINT64),
  fileSha1: ProtoField(9, ScalarType.BYTES),
  fileSha3: ProtoField(10, ScalarType.BYTES),
  fileMd5: ProtoField(11, ScalarType.BYTES),
  field15: ProtoField(15, ScalarType.BOOL)
};
const OidbSvcTrpcTcp0x6D6Download = {
  groupUin: ProtoField(1, ScalarType.UINT32),
  appId: ProtoField(2, ScalarType.UINT32),
  busId: ProtoField(3, ScalarType.UINT32),
  fileId: ProtoField(4, ScalarType.STRING)
};
const OidbSvcTrpcTcp0x6D6Delete = {
  groupUin: ProtoField(1, ScalarType.UINT32),
  busId: ProtoField(3, ScalarType.UINT32),
  fileId: ProtoField(5, ScalarType.STRING)
};
const OidbSvcTrpcTcp0x6D6Rename = {
  groupUin: ProtoField(1, ScalarType.UINT32),
  busId: ProtoField(3, ScalarType.UINT32),
  fileId: ProtoField(4, ScalarType.STRING),
  parentFolder: ProtoField(5, ScalarType.STRING),
  newFileName: ProtoField(6, ScalarType.STRING)
};
const OidbSvcTrpcTcp0x6D6Move = {
  groupUin: ProtoField(1, ScalarType.UINT32),
  appId: ProtoField(2, ScalarType.UINT32),
  busId: ProtoField(3, ScalarType.UINT32),
  fileId: ProtoField(4, ScalarType.STRING),
  parentDirectory: ProtoField(5, ScalarType.STRING),
  targetDirectory: ProtoField(6, ScalarType.STRING)
};
const OidbSvcTrpcTcp0x6D6Response = {
  upload: ProtoField(1, () => OidbSvcTrpcTcp0x6D6_0Response),
  download: ProtoField(3, () => OidbSvcTrpcTcp0x6D6_2Response),
  delete: ProtoField(4, () => OidbSvcTrpcTcp0x6D6_3_4_5Response),
  rename: ProtoField(5, () => OidbSvcTrpcTcp0x6D6_3_4_5Response),
  move: ProtoField(6, () => OidbSvcTrpcTcp0x6D6_3_4_5Response)
};
const OidbSvcTrpcTcp0x6D6_0Response = {
  retCode: ProtoField(1, ScalarType.INT32),
  retMsg: ProtoField(2, ScalarType.STRING),
  clientWording: ProtoField(3, ScalarType.STRING),
  uploadIp: ProtoField(4, ScalarType.STRING),
  serverDns: ProtoField(5, ScalarType.STRING),
  busId: ProtoField(6, ScalarType.INT32),
  fileId: ProtoField(7, ScalarType.STRING),
  checkKey: ProtoField(8, ScalarType.BYTES),
  fileKey: ProtoField(9, ScalarType.BYTES),
  boolFileExist: ProtoField(10, ScalarType.BOOL),
  uploadIpLanV4: ProtoField(12, ScalarType.STRING, false, true),
  uploadIpLanV6: ProtoField(13, ScalarType.STRING, false, true),
  uploadPort: ProtoField(14, ScalarType.UINT32)
};
const OidbSvcTrpcTcp0x6D6_2Response = {
  retCode: ProtoField(1, ScalarType.INT32),
  retMsg: ProtoField(2, ScalarType.STRING),
  clientWording: ProtoField(3, ScalarType.STRING),
  downloadIp: ProtoField(4, ScalarType.STRING),
  downloadDns: ProtoField(5, ScalarType.STRING),
  downloadUrl: ProtoField(6, ScalarType.BYTES),
  fileSha1: ProtoField(7, ScalarType.BYTES),
  fileSha3: ProtoField(8, ScalarType.BYTES),
  fileMd5: ProtoField(9, ScalarType.BYTES),
  cookieVal: ProtoField(10, ScalarType.BYTES),
  saveFileName: ProtoField(11, ScalarType.STRING),
  previewPort: ProtoField(12, ScalarType.UINT32)
};
const OidbSvcTrpcTcp0x6D6_3_4_5Response = {
  retCode: ProtoField(1, ScalarType.INT32),
  retMsg: ProtoField(2, ScalarType.STRING),
  clientWording: ProtoField(3, ScalarType.STRING)
};

const OidbSvcTrpcTcp0X8FC_2_Body = {
  targetUid: ProtoField(1, ScalarType.STRING),
  specialTitle: ProtoField(5, ScalarType.STRING, true),
  expiredTime: ProtoField(6, ScalarType.INT32),
  uinName: ProtoField(7, ScalarType.STRING, true),
  targetName: ProtoField(8, ScalarType.STRING)
};
const OidbSvcTrpcTcp0X8FC_2 = {
  groupUin: ProtoField(1, ScalarType.UINT32),
  body: ProtoField(3, () => OidbSvcTrpcTcp0X8FC_2_Body)
};

const OidbSvcTrpcTcp0X9067_202 = {
  ReqHead: ProtoField(1, () => MultiMediaReqHead),
  DownloadRKeyReq: ProtoField(4, () => OidbSvcTrpcTcp0X9067_202Key)
};
const OidbSvcTrpcTcp0X9067_202Key = {
  key: ProtoField(1, ScalarType.INT32, false, true)
};
const OidbSvcTrpcTcp0X9067_202_RkeyList = {
  rkey: ProtoField(1, ScalarType.STRING),
  ttl: ProtoField(2, ScalarType.UINT64),
  time: ProtoField(4, ScalarType.UINT32),
  type: ProtoField(5, ScalarType.UINT32)
};
const OidbSvcTrpcTcp0X9067_202_Data = {
  rkeyList: ProtoField(1, () => OidbSvcTrpcTcp0X9067_202_RkeyList, false, true)
};
const OidbSvcTrpcTcp0X9067_202_Rsp_Body = {
  data: ProtoField(4, () => OidbSvcTrpcTcp0X9067_202_Data)
};

const OidbSvcTrpcTcp0X929D_0 = {
  groupUin: ProtoField(1, ScalarType.UINT32),
  chatType: ProtoField(2, ScalarType.UINT32)
};
const OidbSvcTrpcTcp0X929D_0Resp = {
  content: ProtoField(1, () => OidbSvcTrpcTcp0X929D_0RespContent, false, true)
};
const OidbSvcTrpcTcp0X929D_0RespContent = {
  category: ProtoField(1, ScalarType.STRING),
  voices: ProtoField(2, () => OidbSvcTrpcTcp0X929D_0RespContentVoice, false, true)
};
const OidbSvcTrpcTcp0X929D_0RespContentVoice = {
  voiceId: ProtoField(1, ScalarType.STRING),
  voiceDisplayName: ProtoField(2, ScalarType.STRING),
  voiceExampleUrl: ProtoField(3, ScalarType.STRING)
};
const OidbSvcTrpcTcp0X929B_0 = {
  groupUin: ProtoField(1, ScalarType.UINT32),
  voiceId: ProtoField(2, ScalarType.STRING),
  text: ProtoField(3, ScalarType.STRING),
  chatType: ProtoField(4, ScalarType.UINT32),
  session: ProtoField(5, () => OidbSvcTrpcTcp0X929B_0_Session)
};
const OidbSvcTrpcTcp0X929B_0_Session = {
  sessionId: ProtoField(1, ScalarType.UINT32)
};
const OidbSvcTrpcTcp0X929B_0Resp = {
  statusCode: ProtoField(1, ScalarType.UINT32),
  field2: ProtoField(2, ScalarType.UINT32, true),
  field3: ProtoField(3, ScalarType.UINT32),
  msgInfo: ProtoField(4, () => MsgInfo, true)
};

const OidbSvcTrpcTcp0XE37_1200 = {
  subCommand: ProtoField(1, ScalarType.UINT32, true),
  field2: ProtoField(2, ScalarType.INT32, true),
  body: ProtoField(14, () => OidbSvcTrpcTcp0XE37_1200Body, true),
  field101: ProtoField(101, ScalarType.INT32, true),
  field102: ProtoField(102, ScalarType.INT32, true),
  field200: ProtoField(200, ScalarType.INT32, true),
  field99999: ProtoField(99999, ScalarType.BYTES, true)
};
const OidbSvcTrpcTcp0XE37_1200Body = {
  receiverUid: ProtoField(10, ScalarType.STRING, true),
  fileUuid: ProtoField(20, ScalarType.STRING, true),
  type: ProtoField(30, ScalarType.INT32, true),
  fileHash: ProtoField(60, ScalarType.STRING, true),
  t2: ProtoField(601, ScalarType.INT32, true)
};
const OidbSvcTrpcTcp0XE37_1200Response = {
  command: ProtoField(1, ScalarType.UINT32, true),
  subCommand: ProtoField(2, ScalarType.UINT32, true),
  body: ProtoField(14, () => OidbSvcTrpcTcp0XE37_1200ResponseBody, true),
  field50: ProtoField(50, ScalarType.UINT32, true)
};
const OidbSvcTrpcTcp0XE37_1200ResponseBody = {
  field10: ProtoField(10, ScalarType.UINT32, true),
  state: ProtoField(20, ScalarType.STRING, true),
  result: ProtoField(30, () => OidbSvcTrpcTcp0XE37_1200Result, true),
  metadata: ProtoField(40, () => OidbSvcTrpcTcp0XE37_800_1200Metadata, true)
};
const OidbSvcTrpcTcp0XE37_1200Result = {
  server: ProtoField(20, ScalarType.STRING, true),
  port: ProtoField(40, ScalarType.UINT32, true),
  url: ProtoField(50, ScalarType.STRING, true),
  additionalServer: ProtoField(60, ScalarType.STRING, false, true),
  ssoPort: ProtoField(80, ScalarType.UINT32, true),
  ssoUrl: ProtoField(90, ScalarType.STRING, true),
  extra: ProtoField(120, ScalarType.BYTES, true)
};
const OidbSvcTrpcTcp0XE37_800_1200Metadata = {
  uin: ProtoField(1, ScalarType.UINT32, true),
  field2: ProtoField(2, ScalarType.UINT32, true),
  field3: ProtoField(3, ScalarType.UINT32, true),
  size: ProtoField(4, ScalarType.UINT32, true),
  timestamp: ProtoField(5, ScalarType.UINT32, true),
  fileUuid: ProtoField(6, ScalarType.STRING, true),
  fileName: ProtoField(7, ScalarType.STRING, true),
  field100: ProtoField(100, ScalarType.BYTES, true),
  field101: ProtoField(101, ScalarType.BYTES, true),
  field110: ProtoField(110, ScalarType.UINT32, true),
  timestamp1: ProtoField(130, ScalarType.UINT32, true),
  fileHash: ProtoField(140, ScalarType.STRING, true),
  field141: ProtoField(141, ScalarType.BYTES, true),
  field142: ProtoField(142, ScalarType.BYTES, true)
};

const OidbSvcTrpcTcp0XE37_1700 = {
  command: ProtoField(1, ScalarType.UINT32, true),
  seq: ProtoField(2, ScalarType.INT32, true),
  upload: ProtoField(19, () => ApplyUploadReqV3, true),
  businessId: ProtoField(101, ScalarType.INT32, true),
  clientType: ProtoField(102, ScalarType.INT32, true),
  flagSupportMediaPlatform: ProtoField(200, ScalarType.INT32, true)
};
const ApplyUploadReqV3 = {
  senderUid: ProtoField(10, ScalarType.STRING, true),
  receiverUid: ProtoField(20, ScalarType.STRING, true),
  fileSize: ProtoField(30, ScalarType.UINT32, true),
  fileName: ProtoField(40, ScalarType.STRING, true),
  md510MCheckSum: ProtoField(50, ScalarType.BYTES, true),
  sha1CheckSum: ProtoField(60, ScalarType.BYTES, true),
  localPath: ProtoField(70, ScalarType.STRING, true),
  md5CheckSum: ProtoField(110, ScalarType.BYTES, true),
  sha3CheckSum: ProtoField(120, ScalarType.BYTES, true)
};

const OidbSvcTrpcTcp0XE37_800 = {
  subCommand: ProtoField(1, ScalarType.UINT32),
  field2: ProtoField(2, ScalarType.INT32),
  body: ProtoField(10, () => OidbSvcTrpcTcp0XE37_800Body, true),
  field101: ProtoField(101, ScalarType.INT32),
  field102: ProtoField(102, ScalarType.INT32),
  field200: ProtoField(200, ScalarType.INT32)
};
const OidbSvcTrpcTcp0XE37_800Body = {
  senderUid: ProtoField(10, ScalarType.STRING, true),
  receiverUid: ProtoField(20, ScalarType.STRING, true),
  fileUuid: ProtoField(30, ScalarType.STRING, true),
  fileHash: ProtoField(40, ScalarType.STRING, true)
};
const OidbSvcTrpcTcp0XE37Response = {
  command: ProtoField(1, ScalarType.UINT32),
  seq: ProtoField(2, ScalarType.INT32),
  upload: ProtoField(19, () => ApplyUploadRespV3, true),
  businessId: ProtoField(101, ScalarType.INT32),
  clientType: ProtoField(102, ScalarType.INT32),
  flagSupportMediaPlatform: ProtoField(200, ScalarType.INT32)
};
const ApplyUploadRespV3 = {
  retCode: ProtoField(10, ScalarType.INT32),
  retMsg: ProtoField(20, ScalarType.STRING, true),
  totalSpace: ProtoField(30, ScalarType.INT64),
  usedSpace: ProtoField(40, ScalarType.INT64),
  uploadedSize: ProtoField(50, ScalarType.INT64),
  uploadIp: ProtoField(60, ScalarType.STRING, true),
  uploadDomain: ProtoField(70, ScalarType.STRING, true),
  uploadPort: ProtoField(80, ScalarType.UINT32),
  uuid: ProtoField(90, ScalarType.STRING, true),
  uploadKey: ProtoField(100, ScalarType.BYTES, true),
  boolFileExist: ProtoField(110, ScalarType.BOOL),
  packSize: ProtoField(120, ScalarType.INT32),
  uploadIpList: ProtoField(130, ScalarType.STRING, false, true),
  // repeated
  uploadHttpsPort: ProtoField(140, ScalarType.INT32),
  uploadHttpsDomain: ProtoField(150, ScalarType.STRING, true),
  uploadDns: ProtoField(160, ScalarType.STRING, true),
  uploadLanip: ProtoField(170, ScalarType.STRING, true),
  fileAddon: ProtoField(200, ScalarType.STRING, true),
  mediaPlatformUploadKey: ProtoField(220, ScalarType.BYTES, true)
};
({
  command: ProtoField(1, ScalarType.UINT32, true),
  subCommand: ProtoField(2, ScalarType.UINT32, true),
  field50: ProtoField(50, ScalarType.UINT32, true)
});
({
  field10: ProtoField(10, ScalarType.UINT32, true)});

const OidbSvcTrpcTcp0XEB7_Body = {
  uin: ProtoField(1, ScalarType.STRING),
  groupUin: ProtoField(2, ScalarType.STRING),
  version: ProtoField(3, ScalarType.STRING)
};
const OidbSvcTrpcTcp0XEB7 = {
  body: ProtoField(2, () => OidbSvcTrpcTcp0XEB7_Body)
};

const OidbSvcTrpcTcp0XED3_1 = {
  uin: ProtoField(1, ScalarType.UINT32),
  groupUin: ProtoField(2, ScalarType.UINT32),
  friendUin: ProtoField(5, ScalarType.UINT32),
  ext: ProtoField(6, ScalarType.UINT32, true)
};

const OidbSvcTrpcTcp0XFE1_2 = {
  uin: ProtoField(1, ScalarType.UINT32),
  key: ProtoField(3, () => OidbSvcTrpcTcp0XFE1_2Key, false, true)
};
const OidbSvcTrpcTcp0XFE1_2Key = {
  key: ProtoField(1, ScalarType.UINT32)
};
const OidbSvcTrpcTcp0XFE1_2RSP_Status = {
  key: ProtoField(1, ScalarType.UINT32),
  value: ProtoField(2, ScalarType.UINT64)
};
const OidbSvcTrpcTcp0XFE1_2RSP_Data = {
  status: ProtoField(2, () => OidbSvcTrpcTcp0XFE1_2RSP_Status)
};
const OidbSvcTrpcTcp0XFE1_2RSP = {
  data: ProtoField(1, () => OidbSvcTrpcTcp0XFE1_2RSP_Data)
};

const OidbSvcTrpcTcpBase = {
  command: ProtoField(1, ScalarType.UINT32),
  subCommand: ProtoField(2, ScalarType.UINT32),
  errorCode: ProtoField(3, ScalarType.UINT32),
  body: ProtoField(4, ScalarType.BYTES),
  errorMsg: ProtoField(5, ScalarType.STRING, true),
  isReserved: ProtoField(12, ScalarType.UINT32)
};
({
  body: ProtoField(4, ScalarType.BYTES)
});

const OidbSvcTrpcTcp0xE07_0 = {
  version: ProtoField(1, ScalarType.UINT32),
  client: ProtoField(2, ScalarType.UINT32),
  entrance: ProtoField(3, ScalarType.UINT32),
  ocrReqBody: ProtoField(10, () => OcrReqBody, true)
};
const OcrReqBody = {
  imageUrl: ProtoField(1, ScalarType.STRING),
  languageType: ProtoField(2, ScalarType.UINT32),
  scene: ProtoField(3, ScalarType.UINT32),
  originMd5: ProtoField(10, ScalarType.STRING),
  afterCompressMd5: ProtoField(11, ScalarType.STRING),
  afterCompressFileSize: ProtoField(12, ScalarType.STRING),
  afterCompressWeight: ProtoField(13, ScalarType.STRING),
  afterCompressHeight: ProtoField(14, ScalarType.STRING),
  isCut: ProtoField(15, ScalarType.BOOL)
};
const OidbSvcTrpcTcp0xE07_0_Response = {
  retCode: ProtoField(1, ScalarType.INT32),
  errMsg: ProtoField(2, ScalarType.STRING),
  wording: ProtoField(3, ScalarType.STRING),
  ocrRspBody: ProtoField(10, () => OcrRspBody)
};
const OcrRspBody = {
  textDetections: ProtoField(1, () => TextDetection, false, true),
  language: ProtoField(2, ScalarType.STRING),
  requestId: ProtoField(3, ScalarType.STRING),
  ocrLanguageList: ProtoField(101, ScalarType.STRING, false, true),
  dstTranslateLanguageList: ProtoField(102, ScalarType.STRING, false, true),
  languageList: ProtoField(103, () => Language, false, true),
  afterCompressWeight: ProtoField(111, ScalarType.UINT32),
  afterCompressHeight: ProtoField(112, ScalarType.UINT32)
};
const TextDetection = {
  detectedText: ProtoField(1, ScalarType.STRING),
  confidence: ProtoField(2, ScalarType.UINT32),
  polygon: ProtoField(3, () => Polygon),
  advancedInfo: ProtoField(4, ScalarType.STRING)
};
const Polygon = {
  coordinates: ProtoField(1, () => Coordinate, false, true)
};
const Coordinate = {
  x: ProtoField(1, ScalarType.INT32),
  y: ProtoField(2, ScalarType.INT32)
};
const Language = {
  languageCode: ProtoField(1, ScalarType.STRING),
  languageDesc: ProtoField(2, ScalarType.STRING)
};

const OidbSvcTrpcTcp0XF90_1 = {
  groupUin: ProtoField(1, ScalarType.UINT32),
  msgSeq: ProtoField(2, ScalarType.UINT64)
};

class IHighwayUploader {
  trans;
  logger;
  constructor(trans, logger) {
    this.trans = trans;
    this.logger = logger;
  }
  // TODO: 没用到的加密方法先注释掉
  // private encryptTransExt (key: Uint8Array) {
  //   if (!this.trans.encrypt) return;
  //   this.trans.ext = tea.encrypt(Buffer.from(this.trans.ext), Buffer.from(key));
  // }
  timeout() {
    return new Promise((_resolve, reject) => {
      setTimeout(
        () => {
          reject(new Error(`[Highway] timeout after ${this.trans.timeout}s`));
        },
        (this.trans.timeout ?? Infinity) * 1e3
      );
    });
  }
  buildPicUpHead(offset, bodyLength, bodyMd5) {
    return new NapProtoMsg(ReqDataHighwayHead).encode({
      msgBaseHead: {
        version: 1,
        uin: this.trans.uin,
        command: "PicUp.DataUp",
        seq: 0,
        retryTimes: 0,
        appId: 1600001604,
        dataFlag: 16,
        commandId: this.trans.cmd
      },
      msgSegHead: {
        serviceId: 0,
        filesize: BigInt(this.trans.size),
        dataOffset: BigInt(offset),
        dataLength: bodyLength,
        serviceTicket: this.trans.ticket,
        md5: bodyMd5,
        fileMd5: this.trans.sum,
        cacheAddr: 0,
        cachePort: 0
      },
      bytesReqExtendInfo: this.trans.ext,
      timestamp: BigInt(0),
      msgLoginSigHead: {
        uint32LoginSigType: 8,
        appId: 1600001604
      }
    });
  }
}

class HighwayTcpUploaderTransform extends stream__default.Transform {
  uploader;
  offset;
  constructor(uploader) {
    super();
    this.uploader = uploader;
    this.offset = 0;
  }
  _transform(data, _, callback) {
    let chunkOffset = 0;
    while (chunkOffset < data.length) {
      const chunkSize = Math.min(BlockSize, data.length - chunkOffset);
      const chunk = data.subarray(chunkOffset, chunkOffset + chunkSize);
      const chunkMd5 = crypto__default$1.createHash("md5").update(chunk).digest();
      const head = this.uploader.buildPicUpHead(this.offset, chunk.length, chunkMd5);
      chunkOffset += chunk.length;
      this.offset += chunk.length;
      this.push(Frame.pack(Buffer.from(head), chunk));
    }
    callback(null);
  }
}
class HighwayTcpUploader extends IHighwayUploader {
  async upload() {
    const controller = new AbortController();
    const { signal } = controller;
    const upload = new Promise((resolve, reject) => {
      const highwayTransForm = new HighwayTcpUploaderTransform(this);
      const socket = net__default.connect(this.trans.port, this.trans.server, () => {
        this.trans.data.pipe(highwayTransForm).pipe(socket, { end: false });
      });
      const handleRspHeader = (header) => {
        const rsp = new NapProtoMsg(RespDataHighwayHead).decode(header);
        if (rsp.errorCode !== 0) {
          socket.end();
          reject(new Error(`[Highway] tcpUpload failed (code=${rsp.errorCode})`));
        }
        const percent = ((Number(rsp.msgSegHead?.dataOffset) + Number(rsp.msgSegHead?.dataLength)) / Number(rsp.msgSegHead?.filesize)).toFixed(2);
        this.logger.debug(`[Highway] tcpUpload ${rsp.errorCode} | ${percent} | ${Buffer.from(header).toString("hex")}`);
        if (Number(rsp.msgSegHead?.dataOffset) + Number(rsp.msgSegHead?.dataLength) >= Number(rsp.msgSegHead?.filesize)) {
          this.logger.debug("[Highway] tcpUpload finished.");
          socket.end();
          resolve();
        }
      };
      socket.on("data", (chunk) => {
        if (signal.aborted) {
          socket.end();
          reject(new Error("Upload aborted due to timeout"));
        }
        const [head] = Frame.unpack(chunk);
        handleRspHeader(head);
      });
      socket.on("close", () => {
        this.logger.debug("[Highway] tcpUpload socket closed.");
        resolve();
      });
      socket.on("error", (err) => {
        socket.end();
        reject(new Error(`[Highway] tcpUpload socket.on error: ${err}`));
      });
      this.trans.data.on("error", (err) => {
        socket.end();
        reject(new Error(`[Highway] tcpUpload readable error: ${err}`));
      });
    });
    const timeout = this.timeout().catch((err) => {
      controller.abort();
      throw new Error(err.message);
    });
    await Promise.race([upload, timeout]);
  }
}

class HighwayHttpUploader extends IHighwayUploader {
  async upload() {
    const controller = new AbortController();
    const { signal } = controller;
    const upload = (async () => {
      let offset = 0;
      for await (const chunk of this.trans.data) {
        if (signal.aborted) {
          throw new Error("Upload aborted due to timeout");
        }
        const block = chunk;
        try {
          await this.uploadBlock(block, offset);
        } catch (err) {
          throw new Error(`[Highway] httpUpload Error uploading block at offset ${offset}: ${err}`);
        }
        offset += block.length;
      }
    })();
    const timeout = this.timeout().catch((err) => {
      controller.abort();
      throw new Error(err.message);
    });
    await Promise.race([upload, timeout]);
  }
  async uploadBlock(block, offset) {
    const chunkMD5 = crypto__default$1.createHash("md5").update(block).digest();
    const payload = this.buildPicUpHead(offset, block.length, chunkMD5);
    const frame = Frame.pack(Buffer.from(payload), block);
    const resp = await this.httpPostHighwayContent(frame, `http://${this.trans.server}:${this.trans.port}/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${this.trans.uin}`);
    const [head, body] = Frame.unpack(resp);
    const headData = new NapProtoMsg(RespDataHighwayHead).decode(head);
    this.logger.debug(`[Highway] httpUploadBlock: ${headData.errorCode} | ${headData.msgSegHead?.retCode} | ${headData.bytesRspExtendInfo} | ${head.toString("hex")} | ${body.toString("hex")}`);
    if (headData.errorCode !== 0) throw new Error(`[Highway] httpUploadBlock failed (code=${headData.errorCode})`);
  }
  async httpPostHighwayContent(frame, serverURL) {
    return new Promise((resolve, reject) => {
      try {
        const options = {
          method: "POST",
          headers: {
            Connection: "keep-alive",
            "Accept-Encoding": "identity",
            "User-Agent": "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)",
            "Content-Length": frame.length.toString()
          }
        };
        const req = http.request(serverURL, options, (res) => {
          const data = [];
          res.on("data", (chunk) => {
            data.push(chunk);
          });
          res.on("end", () => {
            resolve(Buffer.concat(data));
          });
        });
        req.write(frame);
        req.on("error", (error) => {
          reject(error);
        });
      } catch (error) {
        reject(new Error(error.message));
      }
    });
  }
}

class PacketHighwayClient {
  sig;
  server = "htdata3.qq.com";
  port = 80;
  logger;
  constructor(sig, logger, _server = "htdata3.qq.com", _port = 80) {
    this.sig = sig;
    this.logger = logger;
  }
  changeServer(server, port) {
    this.server = server;
    this.port = port;
  }
  buildDataUpTrans(cmd, data, fileSize, md5, extendInfo, timeout = 1200) {
    return {
      uin: this.sig.uin,
      cmd,
      command: "PicUp.DataUp",
      data,
      sum: md5,
      size: fileSize,
      ticket: this.sig.sigSession,
      ext: extendInfo,
      encrypt: false,
      timeout,
      server: this.server,
      port: this.port
    };
  }
  async upload(cmd, data, fileSize, md5, extendInfo) {
    const trans = this.buildDataUpTrans(cmd, data, fileSize, md5, extendInfo);
    try {
      const tcpUploader = new HighwayTcpUploader(trans, this.logger);
      await tcpUploader.upload();
    } catch (e) {
      this.logger.error(`[Highway] upload failed: ${e}, fallback to http upload`);
      try {
        const httpUploader = new HighwayHttpUploader(trans, this.logger);
        await httpUploader.upload();
      } catch (e2) {
        this.logger.error(`[Highway] http upload failed: ${e2}`);
        throw e2;
      }
    }
  }
}

class ForwardMsgBuilder {
  static build(resId, msg, source, news, summary, prompt) {
    const id = crypto$1.randomUUID();
    const isGroupMsg = msg.some((m) => m.isGroupMsg);
    if (!source) {
      source = msg.length === 0 ? "聊天记录" : isGroupMsg ? "群聊的聊天记录" : msg.map((m) => m.senderName).filter((v, i, a) => a.indexOf(v) === i).slice(0, 4).join("和") + "的聊天记录";
    }
    if (!news) {
      news = msg.length === 0 ? [{
        text: "Nya~ This message is send from NapCat.Packet!"
      }] : msg.map((m) => ({
        text: `${m.senderName}: ${m.msg?.map((msg2) => msg2.preview).join("")}`
      }));
    }
    if (!summary) {
      summary = `查看${msg.length}条转发消息`;
    }
    if (!prompt) {
      prompt = "[聊天记录]";
    }
    return {
      app: "com.tencent.multimsg",
      config: {
        autosize: 1,
        forward: 1,
        round: 1,
        type: "normal",
        width: 300
      },
      desc: prompt,
      extra: {
        filename: id,
        tsum: msg.length
      },
      meta: {
        detail: {
          news,
          resid: resId,
          source,
          summary,
          uniseq: id
        }
      },
      prompt,
      ver: "0.0.0.5",
      view: "contact"
    };
  }
  static fromResId(resId) {
    return this.build(resId, []);
  }
  static fromPacketMsg(resId, packetMsg, source, news, summary, prompt) {
    return this.build(resId, packetMsg.map((msg) => ({
      senderName: msg.senderName,
      isGroupMsg: msg.groupId !== void 0,
      msg: msg.msg.map((m) => ({
        preview: m.valid ? m.toPreview() : "[该消息类型暂不支持查看]"
      }))
    })), source, news, summary, prompt);
  }
}

class IPacketMsgElement {
  constructor(_rawElement) {
  }
  get valid() {
    return true;
  }
  buildContent() {
    return void 0;
  }
  buildElement() {
    return [];
  }
  static parseElement;
  toPreview() {
    return "[暂不支持该消息类型喵~]";
  }
}
class PacketMsgTextElement extends IPacketMsgElement {
  text;
  constructor(element) {
    super(element);
    this.text = element.textElement.content;
  }
  buildElement() {
    return [{
      text: {
        str: this.text
      }
    }];
  }
  static parseElement = (elem) => {
    if (elem.text?.str && (elem.text?.attr6Buf === void 0 || elem.text?.attr6Buf?.length === 0)) {
      return [{
        textElement: {
          content: elem.text?.str,
          atType: NTMsgAtType.ATTYPEUNKNOWN,
          atUid: "",
          atTinyId: "",
          atNtUid: ""
        },
        elementType: ElementType.UNKNOWN,
        elementId: ""
      }, null];
    }
    return void 0;
  };
  toPreview() {
    return this.text;
  }
}
class PacketMsgAtElement extends PacketMsgTextElement {
  targetUid;
  atAll;
  constructor(element) {
    super(element);
    this.targetUid = element.textElement.atNtUid;
    this.atAll = element.textElement.atType === NTMsgAtType.ATTYPEALL;
  }
  buildElement() {
    return [{
      text: {
        str: this.text,
        pbReserve: new NapProtoMsg(MentionExtra).encode(
          {
            type: this.atAll ? 1 : 2,
            uin: 0,
            field5: 0,
            uid: this.targetUid
          }
        )
      }
    }];
  }
  static parseElement = (elem) => {
    if (elem.text?.str && (elem.text?.attr6Buf?.length ?? 100) >= 11) {
      return [{
        textElement: {
          content: elem.text?.str,
          atType: NTMsgAtType.ATTYPEONE,
          atUid: String(Buffer.from(elem.text.attr6Buf).readUInt32BE(7)),
          // FIXME: hack
          atTinyId: "",
          atNtUid: ""
        },
        elementType: ElementType.UNKNOWN,
        elementId: ""
      }, null];
    }
    return void 0;
  };
}
class PacketMsgReplyElement extends IPacketMsgElement {
  time;
  targetMessageId;
  targetMessageSeq;
  targetMessageClientSeq;
  targetUin;
  targetUid;
  targetElems;
  targetSourceMsg;
  targetPeer;
  constructor(element) {
    super(element);
    this.time = +(element.replyElement.replyMsgTime ?? Math.floor(Date.now() / 1e3));
    this.targetMessageId = BigInt(element.replyElement.replayMsgId ?? 0);
    this.targetMessageSeq = +(element.replyElement.replayMsgSeq ?? 0);
    this.targetMessageClientSeq = +(element.replyElement.replyMsgClientSeq ?? 0);
    this.targetUin = +(element.replyElement.senderUin ?? 0);
    this.targetUid = element.replyElement.senderUidStr ?? "";
    this.targetPeer = element.replyElement._replyMsgPeer;
  }
  get isGroupReply() {
    return this.targetMessageClientSeq === 0;
  }
  buildElement() {
    return [{
      srcMsg: {
        origSeqs: [this.isGroupReply ? this.targetMessageSeq : this.targetMessageClientSeq],
        senderUin: BigInt(this.targetUin),
        time: this.time,
        elems: this.targetElems ?? [],
        sourceMsg: new NapProtoMsg(PushMsgBody).encode(this.targetSourceMsg ?? {}),
        toUin: BigInt(0)
      }
    }];
  }
  static parseElement = (elem) => {
    if (elem.srcMsg && elem.srcMsg.pbReserve) {
      const reserve = elem.srcMsg.pbReserve;
      return [{
        replyElement: {
          replayMsgSeq: String(reserve.friendSeq ?? elem.srcMsg?.origSeqs?.[0] ?? 0),
          replayMsgId: String(reserve.messageId ?? 0),
          senderUin: String(elem?.srcMsg ?? 0)
        },
        elementType: ElementType.UNKNOWN,
        elementId: ""
      }, null];
    }
    return void 0;
  };
  toPreview() {
    return "[回复消息]";
  }
}
class PacketMsgFaceElement extends IPacketMsgElement {
  faceId;
  isLargeFace;
  resultId;
  constructor(element) {
    super(element);
    this.faceId = element.faceElement.faceIndex;
    this.resultId = element.faceElement.resultId;
    this.isLargeFace = element.faceElement.faceType === FaceType.AniSticke;
  }
  buildElement() {
    if (this.isLargeFace) {
      return [{
        commonElem: {
          serviceType: 37,
          pbElem: new NapProtoMsg(QBigFaceExtra).encode({
            aniStickerPackId: "1",
            aniStickerId: "8",
            faceId: this.faceId,
            sourceType: 1,
            resultId: this.resultId,
            preview: "",
            randomType: 1
          }),
          businessType: 1
        }
      }];
    } else if (this.faceId < 260) {
      return [{
        face: {
          index: this.faceId
        }
      }];
    } else {
      return [{
        commonElem: {
          serviceType: 33,
          pbElem: new NapProtoMsg(QSmallFaceExtra).encode({
            faceId: this.faceId,
            preview: "",
            preview2: ""
          }),
          businessType: 1
        }
      }];
    }
  }
  static parseElement = (elem) => {
    if (elem.face?.index) {
      return [{
        faceElement: {
          faceIndex: elem.face.index,
          faceType: FaceType.Normal
        },
        elementType: ElementType.UNKNOWN,
        elementId: ""
      }, null];
    }
    if (elem?.commonElem?.serviceType === 37 && elem?.commonElem?.pbElem) {
      const qface = new NapProtoMsg(QBigFaceExtra).decode(elem?.commonElem?.pbElem);
      if (qface?.faceId) {
        return [{
          faceElement: {
            faceIndex: qface.faceId,
            faceType: FaceType.Normal
          },
          elementType: ElementType.UNKNOWN,
          elementId: ""
        }, null];
      }
    }
    if (elem?.commonElem?.serviceType === 33 && elem?.commonElem?.pbElem) {
      const qface = new NapProtoMsg(QSmallFaceExtra).decode(elem?.commonElem?.pbElem);
      if (qface?.faceId) {
        return [{
          faceElement: {
            faceIndex: qface.faceId,
            faceType: FaceType.Normal
          },
          elementType: ElementType.UNKNOWN,
          elementId: ""
        }, null];
      }
    }
    return void 0;
  };
  toPreview() {
    return "[表情]";
  }
}
class PacketMsgMarkFaceElement extends IPacketMsgElement {
  emojiName;
  emojiId;
  emojiPackageId;
  emojiKey;
  constructor(element) {
    super(element);
    this.emojiName = element.marketFaceElement.faceName;
    this.emojiId = element.marketFaceElement.emojiId;
    this.emojiPackageId = element.marketFaceElement.emojiPackageId;
    this.emojiKey = element.marketFaceElement.key;
  }
  buildElement() {
    return [{
      marketFace: {
        faceName: this.emojiName,
        itemType: 6,
        faceInfo: 1,
        faceId: Buffer.from(this.emojiId, "hex"),
        tabId: this.emojiPackageId,
        subType: 3,
        key: this.emojiKey,
        imageWidth: 300,
        imageHeight: 300,
        pbReserve: {
          field8: 1
        }
      }
    }];
  }
  toPreview() {
    return `${this.emojiName}`;
  }
}
class PacketMsgPicElement extends IPacketMsgElement {
  path;
  name;
  size;
  md5;
  width;
  height;
  picType;
  picSubType;
  summary;
  sha1 = null;
  msgInfo = null;
  groupPicExt = null;
  c2cPicExt = null;
  constructor(element) {
    super(element);
    this.path = element.picElement.sourcePath;
    this.name = element.picElement.fileName;
    this.size = +element.picElement.fileSize;
    this.md5 = element.picElement.md5HexStr ?? "";
    this.width = element.picElement.picWidth;
    this.height = element.picElement.picHeight;
    this.picType = element.picElement.picType;
    this.picSubType = element.picElement.picSubType ?? 0;
    this.summary = element.picElement.summary === "" ? element.picElement.picSubType === 0 ? "[图片]" : "[动画表情]" : element.picElement.summary;
  }
  get valid() {
    return !!this.msgInfo;
  }
  buildElement() {
    if (!this.msgInfo) return [];
    return [{
      commonElem: {
        serviceType: 48,
        pbElem: new NapProtoMsg(MsgInfo).encode(this.msgInfo),
        businessType: 10
      }
    }];
  }
  static parseElement = (elem) => {
    if (elem?.commonElem?.serviceType === 48 || [10, 20].includes(elem?.commonElem?.businessType ?? 0)) {
      const extra = new NapProtoMsg(MsgInfo).decode(elem.commonElem.pbElem);
      const msgInfoBody = extra.msgInfoBody[0];
      const index = msgInfoBody?.index;
      return [{
        picElement: {
          fileSize: index?.info.fileSize ?? 0,
          picWidth: index?.info?.width ?? 0,
          picHeight: index?.info?.height ?? 0,
          fileName: index?.info?.fileHash ?? "",
          sourcePath: "",
          original: false,
          picType: PicType.NEWPIC_APNG,
          fileUuid: "",
          fileSubId: "",
          thumbFileSize: 0,
          summary: "[图片]",
          thumbPath: /* @__PURE__ */ new Map()
        },
        elementType: ElementType.UNKNOWN,
        elementId: ""
      }, elem];
    }
    if (elem?.notOnlineImage) {
      const img = elem?.notOnlineImage;
      const preImg = {
        picElement: {
          fileSize: img.fileLen ?? 0,
          picWidth: img.picWidth ?? 0,
          picHeight: img.picHeight ?? 0,
          fileName: Buffer.from(img.picMd5).toString("hex") ?? "",
          sourcePath: "",
          original: false,
          picType: PicType.NEWPIC_APNG,
          fileUuid: "",
          fileSubId: "",
          thumbFileSize: 0,
          summary: "[图片]",
          thumbPath: /* @__PURE__ */ new Map()
        },
        elementType: ElementType.UNKNOWN,
        elementId: ""
      };
      if (img.origUrl?.includes("&fileid=")) {
        preImg.picElement.originImageUrl = `https://multimedia.nt.qq.com.cn${img.origUrl}`;
      } else {
        preImg.picElement.originImageUrl = `https://gchat.qpic.cn${img.origUrl}`;
      }
      return [preImg, elem];
    }
    return void 0;
  };
  toPreview() {
    return this.summary;
  }
}
class PacketMsgVideoElement extends IPacketMsgElement {
  fileSize;
  filePath;
  thumbSize;
  thumbPath;
  fileMd5;
  fileSha1;
  thumbMd5;
  thumbSha1;
  thumbWidth;
  thumbHeight;
  msgInfo = null;
  constructor(element) {
    super(element);
    this.fileSize = element.videoElement.fileSize;
    this.filePath = element.videoElement.filePath;
    this.thumbSize = element.videoElement.thumbSize;
    this.thumbPath = element.videoElement.thumbPath?.get(0);
    this.fileMd5 = element.videoElement.videoMd5;
    this.thumbMd5 = element.videoElement.thumbMd5;
    this.thumbWidth = element.videoElement.thumbWidth;
    this.thumbHeight = element.videoElement.thumbHeight;
  }
  get valid() {
    return !!this.msgInfo;
  }
  buildElement() {
    if (!this.msgInfo) return [];
    return [{
      commonElem: {
        serviceType: 48,
        pbElem: new NapProtoMsg(MsgInfo).encode(this.msgInfo),
        businessType: 21
      }
    }];
  }
  toPreview() {
    return "[视频]";
  }
}
class PacketMsgPttElement extends IPacketMsgElement {
  filePath;
  fileSize;
  fileMd5;
  fileSha1;
  fileDuration;
  msgInfo = null;
  constructor(element) {
    super(element);
    this.filePath = element.pttElement.filePath;
    this.fileSize = +element.pttElement.fileSize;
    this.fileMd5 = element.pttElement.md5HexStr;
    this.fileDuration = Math.round(element.pttElement.duration);
  }
  get valid() {
    return false;
  }
  buildElement() {
    return [];
  }
  toPreview() {
    return "[语音]";
  }
}
class PacketMsgFileElement extends IPacketMsgElement {
  fileName;
  filePath;
  fileSize;
  fileSha1;
  fileMd5;
  fileUuid;
  fileHash;
  isGroupFile;
  _private_send_uid;
  _private_recv_uid;
  _e37_800_rsp;
  constructor(element) {
    super(element);
    this.fileName = element.fileElement.fileName;
    this.filePath = element.fileElement.filePath;
    this.fileSize = +element.fileElement.fileSize;
  }
  get valid() {
    return this.isGroupFile || Boolean(this._e37_800_rsp);
  }
  buildContent() {
    if (this.isGroupFile || !this._e37_800_rsp) return void 0;
    return new NapProtoMsg(FileExtra).encode({
      file: {
        fileType: 0,
        fileUuid: this.fileUuid,
        fileMd5: this.fileMd5,
        fileName: this.fileName,
        fileSize: BigInt(this.fileSize),
        subcmd: 1,
        dangerEvel: 0,
        expireTime: Math.floor(Date.now() / 1e3) + 7 * 24 * 60 * 60,
        fileHash: this.fileHash
      },
      field6: {
        field2: {
          field1: this._e37_800_rsp?.body?.field30?.field110,
          fileUuid: this.fileUuid,
          fileName: this.fileName,
          field6: this._e37_800_rsp?.body?.field30?.field3,
          field7: this._e37_800_rsp?.body?.field30?.field101,
          field8: this._e37_800_rsp?.body?.field30?.field100,
          timestamp1: this._e37_800_rsp?.body?.field30?.timestamp1,
          fileHash: this.fileHash,
          selfUid: this._private_send_uid,
          destUid: this._private_recv_uid
        }
      }
    });
  }
  buildElement() {
    if (!this.isGroupFile) return [];
    const lb = Buffer.alloc(2);
    const transElemVal = new NapProtoMsg(GroupFileExtra).encode({
      field1: 6,
      fileName: this.fileName,
      inner: {
        info: {
          busId: 102,
          fileId: this.fileUuid,
          fileSize: BigInt(this.fileSize),
          fileName: this.fileName,
          fileSha: this.fileSha1,
          extInfoString: "",
          fileMd5: this.fileMd5
        }
      }
    });
    lb.writeUInt16BE(transElemVal.length);
    return [{
      transElem: {
        elemType: 24,
        elemValue: Buffer.concat([Buffer.from([1]), lb, transElemVal])
        // TLV
      }
    }];
  }
  toPreview() {
    return `[文件]${this.fileName}`;
  }
}
class PacketMsgLightAppElement extends IPacketMsgElement {
  payload;
  constructor(element) {
    super(element);
    this.payload = element.arkElement.bytesData;
  }
  buildElement() {
    return [{
      lightAppElem: {
        data: Buffer.concat([
          Buffer.from([1]),
          zlib.deflateSync(Buffer.from(this.payload, "utf-8"))
        ])
      }
    }];
  }
  toPreview() {
    return "[卡片消息]";
  }
}
class PacketMsgMarkDownElement extends IPacketMsgElement {
  content;
  constructor(element) {
    super(element);
    this.content = element.markdownElement.content;
  }
  buildElement() {
    return [{
      commonElem: {
        serviceType: 45,
        pbElem: new NapProtoMsg(MarkdownData).encode({
          content: this.content
        }),
        businessType: 1
      }
    }];
  }
  toPreview() {
    return `[Markdown消息 ${this.content}]`;
  }
}
class PacketMultiMsgElement extends IPacketMsgElement {
  resid;
  message;
  constructor(rawElement, message) {
    super(rawElement);
    this.resid = rawElement.multiForwardMsgElement.resId;
    this.message = message ?? [];
  }
  buildElement() {
    return [{
      lightAppElem: {
        data: Buffer.concat([
          Buffer.from([1]),
          zlib.deflateSync(Buffer.from(JSON.stringify(ForwardMsgBuilder.fromPacketMsg(this.resid, this.message)), "utf-8"))
        ])
      }
    }];
  }
  toPreview() {
    return "[聊天记录]";
  }
}

class PacketMsgBuilder {
  static failBackText = new PacketMsgTextElement(
    {
      textElement: { content: "[该消息类型暂不支持查看]" }
    }
  );
  buildFakeMsg(selfUid, element) {
    return element.map((node) => {
      const avatar = `https://q.qlogo.cn/headimg_dl?dst_uin=${node.senderUin}&spec=0&img_type=jpg`;
      const msgContent = node.msg.reduceRight((acc, msg) => {
        return acc ?? msg.buildContent();
      }, void 0);
      const msgElement = node.msg.flatMap((msg) => msg.buildElement() ?? []);
      if (!msgContent && !msgElement.length) {
        msgElement.push(PacketMsgBuilder.failBackText.buildElement());
      }
      return {
        responseHead: {
          fromUin: node.senderUin,
          type: 0,
          sigMap: 0,
          toUin: 0,
          fromUid: "",
          forward: node.groupId ? void 0 : {
            friendName: node.senderName
          },
          toUid: node.groupId ? void 0 : selfUid,
          grp: node.groupId ? {
            groupUin: node.groupId,
            memberName: node.senderName,
            unknown5: 2
          } : void 0
        },
        contentHead: {
          type: node.groupId ? 82 : 9,
          subType: node.groupId ? void 0 : 4,
          divSeq: node.groupId ? void 0 : 4,
          autoReply: 0,
          sequence: crypto$2.randomBytes(4).readUInt32LE(0),
          timeStamp: +node.time.toString().substring(0, 10),
          forward: {
            field1: 0,
            field2: 0,
            field3: node.groupId ? 1 : 2,
            unknownBase64: avatar,
            avatar
          }
        },
        body: {
          richText: {
            elems: msgElement
          },
          msgContent
        }
      };
    });
  }
}

const PacketBufBuilder = (str) => {
  return Buffer.from(str);
};
class PacketTransformer {
  msgBuilder;
  constructor() {
    this.msgBuilder = new PacketMsgBuilder();
  }
}

class FetchSessionKey extends PacketTransformer {
  build() {
    const req = new NapProtoMsg(HttpConn0x6ff_501).encode({
      httpConn: {
        field1: 0,
        field2: 0,
        field3: 16,
        field4: 1,
        field6: 3,
        serviceTypes: [1, 5, 10, 21],
        // tgt: "",  // TODO: do we really need tgt? seems not
        field9: 2,
        field10: 9,
        field11: 8,
        ver: "1.0.1"
      }
    });
    return {
      cmd: "HttpConn.0x6ff_501",
      data: PacketBufBuilder(req)
    };
  }
  parse(data) {
    return new NapProtoMsg(HttpConn0x6ff_501Response).decode(data);
  }
}
const FetchSessionKey$1 = new FetchSessionKey();

const int32ip2str = (ip) => {
  ip = ip & 4294967295;
  return [ip & 255, (ip & 65280) >> 8, (ip & 16711680) >> 16, (ip & 4278190080) >> 24 & 255].join(".");
};
const oidbIpv4s2HighwayIpv4s = (ipv4s) => {
  return ipv4s.map((ip) => {
    return {
      domain: {
        isEnable: true,
        ip: int32ip2str(ip.outIP ?? 0)
      },
      port: ip.outPort
    };
  });
};

class Sha1Stream {
  Sha1BlockSize = 64;
  Sha1DigestSize = 20;
  _padding = Buffer.concat([Buffer.from([128]), Buffer.alloc(63)]);
  _state = new Uint32Array(5);
  _count = new Uint32Array(2);
  _buffer = Buffer.allocUnsafe(this.Sha1BlockSize);
  _w = new Uint32Array(80);
  constructor() {
    this.reset();
  }
  reset() {
    this._state[0] = 1732584193;
    this._state[1] = 4023233417;
    this._state[2] = 2562383102;
    this._state[3] = 271733878;
    this._state[4] = 3285377520;
    this._count[0] = 0;
    this._count[1] = 0;
    this._buffer.fill(0);
  }
  rotateLeft(v, o) {
    return (v << o | v >>> 32 - o) >>> 0;
  }
  transform(chunk, offset) {
    const w = this._w;
    const view = new DataView(chunk.buffer, chunk.byteOffset + offset, 64);
    for (let i = 0; i < 16; i++) {
      w[i] = view.getUint32(i * 4, false);
    }
    for (let i = 16; i < 80; i++) {
      w[i] = this.rotateLeft(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1) >>> 0;
    }
    let a = this._state[0];
    let b = this._state[1];
    let c = this._state[2];
    let d = this._state[3];
    let e = this._state[4];
    for (let i = 0; i < 80; i++) {
      let temp;
      if (i < 20) {
        temp = (b & c | ~b & d) + 1518500249;
      } else if (i < 40) {
        temp = (b ^ c ^ d) + 1859775393;
      } else if (i < 60) {
        temp = (b & c | b & d | c & d) + 2400959708;
      } else {
        temp = (b ^ c ^ d) + 3395469782;
      }
      temp += this.rotateLeft(a, 5) + e + w[i] >>> 0;
      e = d;
      d = c;
      c = this.rotateLeft(b, 30) >>> 0;
      b = a;
      a = temp;
    }
    this._state[0] = this._state[0] + a >>> 0;
    this._state[1] = this._state[1] + b >>> 0;
    this._state[2] = this._state[2] + c >>> 0;
    this._state[3] = this._state[3] + d >>> 0;
    this._state[4] = this._state[4] + e >>> 0;
  }
  update(data, len) {
    let index = (this._count[0] >>> 3 & 63) >>> 0;
    const dataLen = len ?? data.length;
    this._count[0] = this._count[0] + (dataLen << 3) >>> 0;
    if (this._count[0] < dataLen << 3) this._count[1] = this._count[1] + 1 >>> 0;
    this._count[1] = this._count[1] + (dataLen >>> 29) >>> 0;
    const partLen = this.Sha1BlockSize - index >>> 0;
    let i = 0;
    if (dataLen >= partLen) {
      data.copy(this._buffer, index, 0, partLen);
      this.transform(this._buffer, 0);
      for (i = partLen; i + this.Sha1BlockSize <= dataLen; i = i + this.Sha1BlockSize >>> 0) {
        this.transform(data, i);
      }
      index = 0;
    }
    data.copy(this._buffer, index, i, dataLen);
  }
  hash(bigEndian = true) {
    const digest = Buffer.allocUnsafe(this.Sha1DigestSize);
    if (bigEndian) {
      for (let i = 0; i < 5; i++) digest.writeUInt32BE(this._state[i], i * 4);
    } else {
      for (let i = 0; i < 5; i++) digest.writeUInt32LE(this._state[i], i * 4);
    }
    return digest;
  }
  final() {
    const digest = Buffer.allocUnsafe(this.Sha1DigestSize);
    const bits = Buffer.allocUnsafe(8);
    bits.writeUInt32BE(this._count[1], 0);
    bits.writeUInt32BE(this._count[0], 4);
    const index = (this._count[0] >>> 3 & 63) >>> 0;
    const padLen = (index < 56 ? 56 - index : 120 - index) >>> 0;
    this.update(this._padding, padLen);
    this.update(bits);
    for (let i = 0; i < 5; i++) {
      digest.writeUInt32BE(this._state[i], i * 4);
    }
    return digest;
  }
}

class CalculateStreamBytesTransform extends stream$3.Transform {
  blockSize = 1024 * 1024;
  sha1;
  buffer;
  bytesRead;
  byteArrayList;
  constructor() {
    super();
    this.sha1 = new Sha1Stream();
    this.buffer = Buffer.alloc(0);
    this.bytesRead = 0;
    this.byteArrayList = [];
  }
  _transform(chunk, _, callback) {
    try {
      this.buffer = Buffer.concat([this.buffer, chunk]);
      let offset = 0;
      while (this.buffer.length - offset >= this.sha1.Sha1BlockSize) {
        const block = this.buffer.subarray(offset, offset + this.sha1.Sha1BlockSize);
        this.sha1.update(block);
        offset += this.sha1.Sha1BlockSize;
        this.bytesRead += this.sha1.Sha1BlockSize;
        if (this.bytesRead % this.blockSize === 0) {
          const digest = this.sha1.hash(false);
          this.byteArrayList.push(Buffer.from(digest));
        }
      }
      this.buffer = this.buffer.subarray(offset);
      callback(null);
    } catch (err) {
      callback(err);
    }
  }
  _flush(callback) {
    try {
      if (this.buffer.length > 0) this.sha1.update(this.buffer);
      const finalDigest = this.sha1.final();
      this.byteArrayList.push(Buffer.from(finalDigest));
      for (const digest of this.byteArrayList) {
        this.push(digest);
      }
      callback(null);
    } catch (err) {
      callback(err);
    }
  }
}

function sha1Stream(readable) {
  return new Promise((resolve, reject) => {
    readable.on("error", reject);
    readable.pipe(crypto$2.createHash("sha1").on("error", reject).on("data", resolve));
  });
}
function md5Stream(readable) {
  return new Promise((resolve, reject) => {
    readable.on("error", reject);
    readable.pipe(crypto$2.createHash("md5").on("error", reject).on("data", resolve));
  });
}
function calculateSha1(filePath) {
  const readable = fs.createReadStream(filePath);
  return sha1Stream(readable);
}
function computeMd5AndLengthWithLimit(filePath, limit) {
  const readStream = fs.createReadStream(filePath, limit ? { start: 0, end: limit - 1 } : {});
  return md5Stream(readStream);
}
function calculateSha1StreamBytes(filePath) {
  return new Promise((resolve, reject) => {
    const readable = fs.createReadStream(filePath);
    const calculateStreamBytes = new CalculateStreamBytesTransform();
    const byteArrayList = [];
    calculateStreamBytes.on("data", (chunk) => {
      byteArrayList.push(chunk);
    });
    calculateStreamBytes.on("end", () => {
      resolve(byteArrayList);
    });
    calculateStreamBytes.on("error", (err) => {
      reject(err);
    });
    readable.pipe(calculateStreamBytes);
  });
}

class OidbBase extends PacketTransformer {
  build(cmd, subCmd, body, isUid = true, _isLafter = false) {
    const data = new NapProtoMsg(OidbSvcTrpcTcpBase).encode({
      command: cmd,
      subCommand: subCmd,
      body,
      isReserved: isUid ? 1 : 0
    });
    return {
      cmd: `OidbSvcTrpcTcp.0x${cmd.toString(16).toUpperCase()}_${subCmd}`,
      data: PacketBufBuilder(data)
    };
  }
  parse(data) {
    const res = new NapProtoMsg(OidbSvcTrpcTcpBase).decode(data);
    if (res.errorCode !== 0) {
      throw new Error(`OidbSvcTrpcTcpBase parse error: ${res.errorMsg} (code=${res.errorCode})`);
    }
    return res;
  }
}
const OidbBase$1 = new OidbBase();

class UploadGroupImage extends PacketTransformer {
  build(groupUin, img) {
    const data = new NapProtoMsg(NTV2RichMediaReq).encode(
      {
        reqHead: {
          common: {
            requestId: 1,
            command: 100
          },
          scene: {
            requestType: 2,
            businessType: 1,
            sceneType: 2,
            group: {
              groupUin
            }
          },
          client: {
            agentType: 2
          }
        },
        upload: {
          uploadInfo: [
            {
              fileInfo: {
                fileSize: +img.size,
                fileHash: img.md5,
                fileSha1: img.sha1,
                fileName: img.name,
                type: {
                  type: 1,
                  picFormat: img.picType,
                  // TODO: extend NapCat imgType /cc @MliKiowa
                  videoFormat: 0,
                  voiceFormat: 0
                },
                width: img.width,
                height: img.height,
                time: 0,
                original: 1
              },
              subFileType: 0
            }
          ],
          tryFastUploadCompleted: true,
          srvSendMsg: false,
          clientRandomId: crypto__default$1.randomBytes(8).readBigUInt64BE() & BigInt("0x7FFFFFFFFFFFFFFF"),
          compatQMsgSceneType: 2,
          extBizInfo: {
            pic: {
              bizType: img.picSubType,
              bytesPbReserveTroop: {
                subType: img.picSubType
              },
              textSummary: img.summary
            },
            video: {
              bytesPbReserve: Buffer.alloc(0)
            },
            ptt: {
              bytesPbReserve: Buffer.alloc(0),
              bytesReserve: Buffer.alloc(0),
              bytesGeneralFlags: Buffer.alloc(0)
            }
          },
          clientSeq: 0,
          noNeedCompatMsg: false
        }
      }
    );
    return OidbBase$1.build(4548, 100, data, true, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(NTV2RichMediaResp).decode(oidbBody);
  }
}
const UploadGroupImage$1 = new UploadGroupImage();

class FetchAiVoiceList extends PacketTransformer {
  build(groupUin, chatType) {
    const data = new NapProtoMsg(OidbSvcTrpcTcp0X929D_0).encode({
      groupUin,
      chatType
    });
    return OidbBase$1.build(37533, 0, data);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(OidbSvcTrpcTcp0X929D_0Resp).decode(oidbBody);
  }
}
const FetchAiVoiceList_default = new FetchAiVoiceList();

class GetAiVoice extends PacketTransformer {
  build(groupUin, voiceId, text, sessionId, chatType) {
    const data = new NapProtoMsg(OidbSvcTrpcTcp0X929B_0).encode({
      groupUin,
      voiceId,
      text,
      chatType,
      session: {
        sessionId
      }
    });
    return OidbBase$1.build(37531, 0, data);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(OidbSvcTrpcTcp0X929B_0Resp).decode(oidbBody);
  }
}
const GetAiVoice_default = new GetAiVoice();

class GetMiniAppAdaptShareInfo extends PacketTransformer {
  build(req) {
    const data = new NapProtoMsg(MiniAppAdaptShareInfoReq).encode({
      appId: req.sdkId,
      body: {
        extInfo: {
          field2: Buffer.alloc(0)
        },
        appid: req.appId,
        title: req.title,
        desc: req.desc,
        time: BigInt(Date.now()),
        scene: req.scene,
        templateType: req.templateType,
        businessType: req.businessType,
        picUrl: req.picUrl,
        vidUrl: "",
        jumpUrl: req.jumpUrl,
        iconUrl: req.iconUrl,
        verType: req.verType,
        shareType: req.shareType,
        versionId: req.versionId,
        withShareTicket: req.withShareTicket,
        webURL: req.webUrl ?? "",
        appidRich: Buffer.alloc(0),
        template: {
          templateId: "",
          templateData: ""
        },
        field20: ""
      }
    });
    return {
      cmd: "LightAppSvc.mini_app_share.AdaptShareInfo",
      data: PacketBufBuilder(data)
    };
  }
  parse(data) {
    return new NapProtoMsg(MiniAppAdaptShareInfoResp).decode(data);
  }
}
const GetMiniAppAdaptShareInfo_default = new GetMiniAppAdaptShareInfo();

class GroupSign extends PacketTransformer {
  build(uin, groupCode) {
    const body = new NapProtoMsg(OidbSvcTrpcTcp0XEB7).encode(
      {
        body: {
          uin: String(uin),
          groupUin: String(groupCode),
          version: "9.0.90"
        }
      }
    );
    return OidbBase$1.build(3767, 1, body, false, false);
  }
  parse(data) {
    return OidbBase$1.parse(data);
  }
}
const GroupSign_default = new GroupSign();

class GetStrangerInfo extends PacketTransformer {
  build(uin) {
    const body = new NapProtoMsg(OidbSvcTrpcTcp0XFE1_2).encode({
      uin,
      key: [{ key: 27372 }]
    });
    return OidbBase$1.build(4065, 2, body);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(OidbSvcTrpcTcp0XFE1_2RSP).decode(oidbBody);
  }
}
const GetStrangerInfo_default = new GetStrangerInfo();

let SendPoke$1 = class SendPoke extends PacketTransformer {
  build(is_group, peer, target) {
    const payload = {
      uin: target,
      ext: 0,
      ...is_group ? { groupUin: peer } : { friendUin: peer }
    };
    const data = new NapProtoMsg(OidbSvcTrpcTcp0XED3_1).encode(payload);
    return OidbBase$1.build(3795, 1, data);
  }
  parse(data) {
    return OidbBase$1.parse(data);
  }
};
const SendPoke_default = new SendPoke$1();

let SetSpecialTitle$1 = class SetSpecialTitle extends PacketTransformer {
  build(groupCode, uid, title) {
    const oidb_0x8FC_2 = new NapProtoMsg(OidbSvcTrpcTcp0X8FC_2).encode({
      groupUin: +groupCode,
      body: {
        targetUid: uid,
        specialTitle: title,
        expiredTime: -1,
        uinName: title
      }
    });
    return OidbBase$1.build(2300, 2, oidb_0x8FC_2, false, false);
  }
  parse(data) {
    return OidbBase$1.parse(data);
  }
};
const SetSpecialTitle_default = new SetSpecialTitle$1();

class ImageOCR extends PacketTransformer {
  build(url) {
    const body = new NapProtoMsg(OidbSvcTrpcTcp0xE07_0).encode(
      {
        version: 1,
        client: 0,
        entrance: 1,
        ocrReqBody: {
          imageUrl: url,
          originMd5: "",
          afterCompressMd5: "",
          afterCompressFileSize: "",
          afterCompressWeight: "",
          afterCompressHeight: "",
          isCut: false
        }
      }
    );
    return OidbBase$1.build(3767, 1, body, false, false);
  }
  parse(data) {
    const base = OidbBase$1.parse(data);
    return new NapProtoMsg(OidbSvcTrpcTcp0xE07_0_Response).decode(base.body);
  }
}
const ImageOCR_default = new ImageOCR();

let MoveGroupFile$1 = class MoveGroupFile extends PacketTransformer {
  build(groupUin, fileUUID, currentParentDirectory, targetParentDirectory) {
    const body = new NapProtoMsg(OidbSvcTrpcTcp0x6D6).encode({
      move: {
        groupUin,
        appId: 5,
        busId: 102,
        fileId: fileUUID,
        parentDirectory: currentParentDirectory,
        targetDirectory: targetParentDirectory
      }
    });
    return OidbBase$1.build(1750, 5, body, true, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    const res = new NapProtoMsg(OidbSvcTrpcTcp0x6D6Response).decode(oidbBody);
    if (res.move.retCode !== 0) {
      throw new Error(`sendGroupFileMoveReq error: ${res.move.clientWording} (code=${res.move.retCode})`);
    }
    return res;
  }
};
const MoveGroupFile_default = new MoveGroupFile$1();

let RenameGroupFile$1 = class RenameGroupFile extends PacketTransformer {
  build(groupUin, fileUUID, currentParentDirectory, newName) {
    const body = new NapProtoMsg(OidbSvcTrpcTcp0x6D6).encode({
      rename: {
        groupUin,
        busId: 102,
        fileId: fileUUID,
        parentFolder: currentParentDirectory,
        newFileName: newName
      }
    });
    return OidbBase$1.build(1750, 4, body, true, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    const res = new NapProtoMsg(OidbSvcTrpcTcp0x6D6Response).decode(oidbBody);
    if (res.rename.retCode !== 0) {
      throw new Error(`sendGroupFileRenameReq error: ${res.rename.clientWording} (code=${res.rename.retCode})`);
    }
    return res;
  }
};
const RenameGroupFile_default = new RenameGroupFile$1();

let SetGroupTodo$1 = class SetGroupTodo extends PacketTransformer {
  build(peer, msgSeq) {
    const data = new NapProtoMsg(OidbSvcTrpcTcp0XF90_1).encode({
      groupUin: peer,
      msgSeq: BigInt(msgSeq)
    });
    return OidbBase$1.build(3984, 1, data);
  }
  parse(data) {
    return OidbBase$1.parse(data);
  }
};
const SetGroupTodo_default = new SetGroupTodo$1();

class DownloadGroupFile extends PacketTransformer {
  build(groupUin, fileUUID) {
    const body = new NapProtoMsg(OidbSvcTrpcTcp0x6D6).encode({
      download: {
        groupUin,
        appId: 7,
        busId: 102,
        fileId: fileUUID
      }
    });
    return OidbBase$1.build(1750, 2, body, true, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    const res = new NapProtoMsg(OidbSvcTrpcTcp0x6D6Response).decode(oidbBody);
    if (res.download.retCode !== 0) {
      throw new Error(`sendGroupFileDownloadReq error: ${res.download.clientWording} (code=${res.download.retCode})`);
    }
    return res;
  }
}
const DownloadGroupFile_default = new DownloadGroupFile();

class DownloadGroupPtt extends PacketTransformer {
  build(groupUin, node) {
    const body = new NapProtoMsg(NTV2RichMediaReq).encode({
      reqHead: {
        common: {
          requestId: 4,
          command: 200
        },
        scene: {
          requestType: 1,
          businessType: 3,
          sceneType: 2,
          group: {
            groupUin
          }
        },
        client: {
          agentType: 2
        }
      },
      download: {
        node,
        download: {
          video: {
            busiType: 0,
            sceneType: 0
          }
        }
      }
    });
    return OidbBase$1.build(4718, 200, body, true, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(NTV2RichMediaResp).decode(oidbBody);
  }
}
const DownloadGroupPtt_default = new DownloadGroupPtt();

class DownloadOfflineFile extends PacketTransformer {
  build(fileUUID, fileHash, senderUid, receiverUid) {
    const body = new NapProtoMsg(OidbSvcTrpcTcp0XE37_800).encode({
      subCommand: 800,
      field2: 0,
      body: {
        senderUid,
        receiverUid,
        fileUuid: fileUUID,
        fileHash
      },
      field101: 3,
      field102: 1,
      field200: 1
    });
    return OidbBase$1.build(3639, 800, body, false, false);
  }
  // TODO:check
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(OidbSvcTrpcTcp0XE37Response).decode(oidbBody);
  }
}
const DownloadOfflineFile_default = new DownloadOfflineFile();

class DownloadPrivateFile extends PacketTransformer {
  build(selfUid, fileUUID, fileHash) {
    const body = new NapProtoMsg(OidbSvcTrpcTcp0XE37_1200).encode({
      subCommand: 1200,
      field2: 1,
      body: {
        receiverUid: selfUid,
        fileUuid: fileUUID,
        type: 2,
        fileHash,
        t2: 0
      },
      field101: 3,
      field102: 103,
      field200: 1,
      field99999: Buffer.from([192, 133, 44, 1])
    });
    return OidbBase$1.build(3639, 1200, body, false, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(OidbSvcTrpcTcp0XE37_1200Response).decode(oidbBody);
  }
}
const DownloadPrivateFile_default = new DownloadPrivateFile();

class UploadGroupFile extends PacketTransformer {
  build(groupUin, file) {
    const body = new NapProtoMsg(OidbSvcTrpcTcp0x6D6).encode({
      file: {
        groupUin,
        appId: 4,
        busId: 102,
        entrance: 6,
        targetDirectory: "/",
        // TODO:
        fileName: file.fileName,
        localDirectory: `/${file.fileName}`,
        fileSize: BigInt(file.fileSize),
        fileMd5: file.fileMd5,
        fileSha1: file.fileSha1,
        fileSha3: Buffer.alloc(0),
        field15: true
      }
    });
    return OidbBase$1.build(1750, 0, body, true, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(OidbSvcTrpcTcp0x6D6Response).decode(oidbBody);
  }
}
const UploadGroupFile_default = new UploadGroupFile();

class UploadGroupPtt extends PacketTransformer {
  build(groupUin, ptt) {
    const data = new NapProtoMsg(NTV2RichMediaReq).encode({
      reqHead: {
        common: {
          requestId: 1,
          command: 100
        },
        scene: {
          requestType: 2,
          businessType: 3,
          sceneType: 2,
          group: {
            groupUin
          }
        },
        client: {
          agentType: 2
        }
      },
      upload: {
        uploadInfo: [
          {
            fileInfo: {
              fileSize: ptt.fileSize,
              fileHash: ptt.fileMd5,
              fileSha1: ptt.fileSha1,
              fileName: `${ptt.fileMd5}.amr`,
              type: {
                type: 3,
                picFormat: 0,
                videoFormat: 0,
                voiceFormat: 1
              },
              height: 0,
              width: 0,
              time: ptt.fileDuration,
              original: 0
            },
            subFileType: 0
          }
        ],
        tryFastUploadCompleted: true,
        srvSendMsg: false,
        clientRandomId: crypto__default$1.randomBytes(8).readBigUInt64BE() & BigInt("0x7FFFFFFFFFFFFFFF"),
        compatQMsgSceneType: 2,
        extBizInfo: {
          pic: {
            textSummary: "Nya~"
          },
          video: {
            bytesPbReserve: Buffer.alloc(0)
          },
          ptt: {
            bytesPbReserve: Buffer.alloc(0),
            bytesReserve: Buffer.from([8, 0, 56, 0]),
            bytesGeneralFlags: Buffer.from([154, 1, 7, 170, 3, 4, 8, 8, 18, 0])
          }
        },
        clientSeq: 0,
        noNeedCompatMsg: false
      }
    });
    return OidbBase$1.build(4718, 100, data, true, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(NTV2RichMediaResp).decode(oidbBody);
  }
}
const instance$1 = new UploadGroupPtt();

class UploadGroupVideo extends PacketTransformer {
  build(groupUin, video) {
    if (!video.fileSize || !video.thumbSize) throw new Error("video.fileSize or video.thumbSize is empty");
    const data = new NapProtoMsg(NTV2RichMediaReq).encode({
      reqHead: {
        common: {
          requestId: 3,
          command: 100
        },
        scene: {
          requestType: 2,
          businessType: 2,
          sceneType: 2,
          group: {
            groupUin
          }
        },
        client: {
          agentType: 2
        }
      },
      upload: {
        uploadInfo: [
          {
            fileInfo: {
              fileSize: +video.fileSize,
              fileHash: video.fileMd5,
              fileSha1: video.fileSha1,
              fileName: "nya.mp4",
              type: {
                type: 2,
                picFormat: 0,
                videoFormat: 0,
                voiceFormat: 0
              },
              height: 0,
              width: 0,
              time: 0,
              original: 0
            },
            subFileType: 0
          },
          {
            fileInfo: {
              fileSize: +video.thumbSize,
              fileHash: video.thumbMd5,
              fileSha1: video.thumbSha1,
              fileName: "nya.jpg",
              type: {
                type: 1,
                picFormat: 0,
                videoFormat: 0,
                voiceFormat: 0
              },
              height: video.thumbHeight,
              width: video.thumbWidth,
              time: 0,
              original: 0
            },
            subFileType: 100
          }
        ],
        tryFastUploadCompleted: true,
        srvSendMsg: false,
        clientRandomId: crypto__default$1.randomBytes(8).readBigUInt64BE() & BigInt("0x7FFFFFFFFFFFFFFF"),
        compatQMsgSceneType: 2,
        extBizInfo: {
          pic: {
            bizType: 0,
            textSummary: "Nya~"
          },
          video: {
            bytesPbReserve: Buffer.from([128, 1, 0])
          },
          ptt: {
            bytesPbReserve: Buffer.alloc(0),
            bytesReserve: Buffer.alloc(0),
            bytesGeneralFlags: Buffer.alloc(0)
          }
        },
        clientSeq: 0,
        noNeedCompatMsg: false
      }
    });
    return OidbBase$1.build(4586, 100, data, true, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(NTV2RichMediaResp).decode(oidbBody);
  }
}
const UploadGroupVideo_default = new UploadGroupVideo();

class UploadPrivateFile extends PacketTransformer {
  async build(selfUid, peerUid, file) {
    const body = new NapProtoMsg(OidbSvcTrpcTcp0XE37_1700).encode({
      command: 1700,
      seq: 0,
      upload: {
        senderUid: selfUid,
        receiverUid: peerUid,
        fileSize: file.fileSize,
        fileName: file.fileName,
        md510MCheckSum: await computeMd5AndLengthWithLimit(file.filePath, 10 * 1024 * 1024),
        sha1CheckSum: file.fileSha1,
        localPath: "/",
        md5CheckSum: file.fileMd5,
        sha3CheckSum: Buffer.alloc(0)
      },
      businessId: 3,
      clientType: 1,
      flagSupportMediaPlatform: 1
    });
    return OidbBase$1.build(3639, 1700, body, false, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(OidbSvcTrpcTcp0XE37Response).decode(oidbBody);
  }
}
const UploadPrivateFile_default = new UploadPrivateFile();

class UploadPrivateImage extends PacketTransformer {
  build(peerUin, img) {
    const data = new NapProtoMsg(NTV2RichMediaReq).encode(
      {
        reqHead: {
          common: {
            requestId: 1,
            command: 100
          },
          scene: {
            requestType: 2,
            businessType: 1,
            sceneType: 1,
            c2C: {
              accountType: 2,
              targetUid: peerUin
            }
          },
          client: {
            agentType: 2
          }
        },
        upload: {
          uploadInfo: [
            {
              fileInfo: {
                fileSize: +img.size,
                fileHash: img.md5,
                fileSha1: img.sha1,
                fileName: img.name,
                type: {
                  type: 1,
                  picFormat: img.picType,
                  // TODO: extend NapCat imgType /cc @MliKiowa
                  videoFormat: 0,
                  voiceFormat: 0
                },
                width: img.width,
                height: img.height,
                time: 0,
                original: 1
              },
              subFileType: 0
            }
          ],
          tryFastUploadCompleted: true,
          srvSendMsg: false,
          clientRandomId: crypto__default$1.randomBytes(8).readBigUInt64BE() & BigInt("0x7FFFFFFFFFFFFFFF"),
          compatQMsgSceneType: 1,
          extBizInfo: {
            pic: {
              bizType: img.picSubType,
              bytesPbReserveC2C: {
                subType: img.picSubType
              },
              textSummary: img.summary
            },
            video: {
              bytesPbReserve: Buffer.alloc(0)
            },
            ptt: {
              bytesPbReserve: Buffer.alloc(0),
              bytesReserve: Buffer.alloc(0),
              bytesGeneralFlags: Buffer.alloc(0)
            }
          },
          clientSeq: 0,
          noNeedCompatMsg: false
        }
      }
    );
    return OidbBase$1.build(4549, 100, data, true, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(NTV2RichMediaResp).decode(oidbBody);
  }
}
const UploadPrivateImage_default = new UploadPrivateImage();

class UploadPrivatePtt extends PacketTransformer {
  build(peerUin, ptt) {
    const data = new NapProtoMsg(NTV2RichMediaReq).encode({
      reqHead: {
        common: {
          requestId: 4,
          command: 100
        },
        scene: {
          requestType: 2,
          businessType: 3,
          sceneType: 1,
          c2C: {
            accountType: 2,
            targetUid: peerUin
          }
        },
        client: {
          agentType: 2
        }
      },
      upload: {
        uploadInfo: [
          {
            fileInfo: {
              fileSize: ptt.fileSize,
              fileHash: ptt.fileMd5,
              fileSha1: ptt.fileSha1,
              fileName: `${ptt.fileMd5}.amr`,
              type: {
                type: 3,
                picFormat: 0,
                videoFormat: 0,
                voiceFormat: 1
              },
              height: 0,
              width: 0,
              time: ptt.fileDuration,
              original: 0
            },
            subFileType: 0
          }
        ],
        tryFastUploadCompleted: true,
        srvSendMsg: false,
        clientRandomId: crypto__default$1.randomBytes(8).readBigUInt64BE() & BigInt("0x7FFFFFFFFFFFFFFF"),
        compatQMsgSceneType: 1,
        extBizInfo: {
          pic: {
            textSummary: "Nya~"
          },
          ptt: {
            bytesReserve: Buffer.from([8, 0, 56, 0]),
            bytesGeneralFlags: Buffer.from([154, 1, 11, 170, 3, 8, 8, 4, 18, 4, 0, 0, 0, 0])
          }
        },
        clientSeq: 0,
        noNeedCompatMsg: false
      }
    });
    return OidbBase$1.build(4717, 100, data, true, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(NTV2RichMediaResp).decode(oidbBody);
  }
}
const UploadPrivatePtt_default = new UploadPrivatePtt();

class UploadPrivateVideo extends PacketTransformer {
  build(peerUin, video) {
    if (!video.fileSize || !video.thumbSize) throw new Error("video.fileSize or video.thumbSize is empty");
    const data = new NapProtoMsg(NTV2RichMediaReq).encode({
      reqHead: {
        common: {
          requestId: 3,
          command: 100
        },
        scene: {
          requestType: 2,
          businessType: 2,
          sceneType: 1,
          c2C: {
            accountType: 2,
            targetUid: peerUin
          }
        },
        client: {
          agentType: 2
        }
      },
      upload: {
        uploadInfo: [
          {
            fileInfo: {
              fileSize: +video.fileSize,
              fileHash: video.fileMd5,
              fileSha1: video.fileSha1,
              fileName: "nya.mp4",
              type: {
                type: 2,
                picFormat: 0,
                videoFormat: 0,
                voiceFormat: 0
              },
              height: 0,
              width: 0,
              time: 0,
              original: 0
            },
            subFileType: 0
          },
          {
            fileInfo: {
              fileSize: +video.thumbSize,
              fileHash: video.thumbMd5,
              fileSha1: video.thumbSha1,
              fileName: "nya.jpg",
              type: {
                type: 1,
                picFormat: 0,
                videoFormat: 0,
                voiceFormat: 0
              },
              height: video.thumbHeight,
              width: video.thumbWidth,
              time: 0,
              original: 0
            },
            subFileType: 100
          }
        ],
        tryFastUploadCompleted: true,
        srvSendMsg: false,
        clientRandomId: crypto__default$1.randomBytes(8).readBigUInt64BE() & BigInt("0x7FFFFFFFFFFFFFFF"),
        compatQMsgSceneType: 2,
        extBizInfo: {
          pic: {
            bizType: 0,
            textSummary: "Nya~"
          },
          video: {
            bytesPbReserve: Buffer.from([128, 1, 0])
          },
          ptt: {
            bytesPbReserve: Buffer.alloc(0),
            bytesReserve: Buffer.alloc(0),
            bytesGeneralFlags: Buffer.alloc(0)
          }
        },
        clientSeq: 0,
        noNeedCompatMsg: false
      }
    });
    return OidbBase$1.build(4585, 100, data, true, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(NTV2RichMediaResp).decode(oidbBody);
  }
}
const UploadPrivateVideo_default = new UploadPrivateVideo();

class DownloadImage extends PacketTransformer {
  build(selfUid, node) {
    const body = new NapProtoMsg(NTV2RichMediaReq).encode({
      reqHead: {
        common: {
          requestId: 1,
          command: 200
        },
        scene: {
          requestType: 2,
          businessType: 1,
          sceneType: 1,
          c2C: {
            accountType: 2,
            targetUid: selfUid
          }
        },
        client: {
          agentType: 2
        }
      },
      download: {
        node,
        download: {
          video: {
            busiType: 0,
            sceneType: 0
          }
        }
      }
    });
    return OidbBase$1.build(4549, 200, body, true, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(NTV2RichMediaResp).decode(oidbBody);
  }
}
const DownloadImage_default = new DownloadImage();

class DownloadGroupImage extends PacketTransformer {
  build(group_uin, node) {
    const body = new NapProtoMsg(NTV2RichMediaReq).encode({
      reqHead: {
        common: {
          requestId: 1,
          command: 200
        },
        scene: {
          requestType: 2,
          businessType: 1,
          sceneType: 2,
          group: {
            groupUin: group_uin
          }
        },
        client: {
          agentType: 2
        }
      },
      download: {
        node,
        download: {
          video: {
            busiType: 0,
            sceneType: 0
          }
        }
      }
    });
    return OidbBase$1.build(4548, 200, body, true, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(NTV2RichMediaResp).decode(oidbBody);
  }
}
const DownloadGroupImage_default = new DownloadGroupImage();

class DownloadVideo extends PacketTransformer {
  build(selfUid, node) {
    const body = new NapProtoMsg(NTV2RichMediaReq).encode({
      reqHead: {
        common: {
          requestId: 1,
          command: 200
        },
        scene: {
          requestType: 2,
          businessType: 2,
          sceneType: 1,
          c2C: {
            accountType: 2,
            targetUid: selfUid
          }
        },
        client: {
          agentType: 2
        }
      },
      download: {
        node,
        download: {
          video: {
            busiType: 0,
            sceneType: 0
          }
        }
      }
    });
    return OidbBase$1.build(4585, 200, body, true, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(NTV2RichMediaResp).decode(oidbBody);
  }
}
const DownloadVideo_default = new DownloadVideo();

class DownloadGroupVideo extends PacketTransformer {
  build(groupUin, node) {
    const body = new NapProtoMsg(NTV2RichMediaReq).encode({
      reqHead: {
        common: {
          requestId: 1,
          command: 200
        },
        scene: {
          requestType: 2,
          businessType: 2,
          sceneType: 2,
          group: {
            groupUin
          }
        },
        client: {
          agentType: 2
        }
      },
      download: {
        node,
        download: {
          video: {
            busiType: 0,
            sceneType: 0
          }
        }
      }
    });
    return OidbBase$1.build(4586, 200, body, true, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(NTV2RichMediaResp).decode(oidbBody);
  }
}
const DownloadGroupVideo_default = new DownloadGroupVideo();

class DownloadPtt extends PacketTransformer {
  build(selfUid, node) {
    const body = new NapProtoMsg(NTV2RichMediaReq).encode({
      reqHead: {
        common: {
          requestId: 1,
          command: 200
        },
        scene: {
          requestType: 1,
          businessType: 3,
          sceneType: 1,
          c2C: {
            accountType: 2,
            targetUid: selfUid
          }
        },
        client: {
          agentType: 2
        }
      },
      download: {
        node,
        download: {
          video: {
            busiType: 0,
            sceneType: 0
          }
        }
      }
    });
    return OidbBase$1.build(4717, 200, body, true, false);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(NTV2RichMediaResp).decode(oidbBody);
  }
}
const DownloadPtt_default = new DownloadPtt();

class UploadForwardMsg extends PacketTransformer {
  build(selfUid, msg, groupUin = 0) {
    const msgBody = this.msgBuilder.buildFakeMsg(selfUid, msg);
    const longMsgResultData = new NapProtoMsg(LongMsgResult).encode(
      {
        action: [{
          actionCommand: "MultiMsg",
          actionData: {
            msgBody
          }
        }]
      }
    );
    const payload = zlib__default.gzipSync(Buffer.from(longMsgResultData));
    const req = new NapProtoMsg(SendLongMsgReq).encode(
      {
        info: {
          type: groupUin === 0 ? 1 : 3,
          uid: {
            uid: groupUin === 0 ? selfUid : groupUin.toString()
          },
          groupUin,
          payload
        },
        settings: {
          field1: 4,
          field2: 1,
          field3: 7,
          field4: 0
        }
      }
    );
    return {
      cmd: "trpc.group.long_msg_interface.MsgService.SsoSendLongMsg",
      data: PacketBufBuilder(req)
    };
  }
  parse(data) {
    return new NapProtoMsg(SendLongMsgResp).decode(data);
  }
}
const UploadForwardMsg_default = new UploadForwardMsg();

class FetchGroupMessage extends PacketTransformer {
  build(groupUin, startSeq, endSeq) {
    const req = new NapProtoMsg(SsoGetGroupMsg).encode({
      info: {
        groupUin,
        startSequence: startSeq,
        endSequence: endSeq
      },
      direction: true
    });
    return {
      cmd: "trpc.msg.register_proxy.RegisterProxy.SsoGetGroupMsg",
      data: PacketBufBuilder(req)
    };
  }
  parse(data) {
    return new NapProtoMsg(SsoGetGroupMsgResponse).decode(data);
  }
}
const FetchGroupMessage_default = new FetchGroupMessage();

class FetchC2CMessage extends PacketTransformer {
  build(targetUid, startSeq, endSeq) {
    const req = new NapProtoMsg(SsoGetC2cMsg).encode({
      friendUid: targetUid,
      startSequence: startSeq,
      endSequence: endSeq
    });
    return {
      cmd: "trpc.msg.register_proxy.RegisterProxy.SsoGetC2cMsg",
      data: PacketBufBuilder(req)
    };
  }
  parse(data) {
    return new NapProtoMsg(SsoGetC2cMsgResponse).decode(data);
  }
}
const FetchC2CMessage_default = new FetchC2CMessage();

class DownloadForwardMsg extends PacketTransformer {
  build(uid, resId) {
    const req = new NapProtoMsg(RecvLongMsgReq).encode({
      info: {
        uid: {
          uid
        },
        resId,
        acquire: true
      },
      settings: {
        field1: 2,
        field2: 0,
        field3: 0,
        field4: 0
      }
    });
    return {
      cmd: "trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg",
      data: PacketBufBuilder(req)
    };
  }
  parse(data) {
    return new NapProtoMsg(RecvLongMsgResp).decode(data);
  }
}
const DownloadForwardMsg_default = new DownloadForwardMsg();

class FetchRkey extends PacketTransformer {
  build() {
    const data = new NapProtoMsg(OidbSvcTrpcTcp0X9067_202).encode({
      reqHead: {
        common: {
          requestId: 1,
          command: 202
        },
        scene: {
          requestType: 2,
          businessType: 1,
          sceneType: 0
        },
        client: {
          agentType: 2
        }
      },
      downloadRKeyReq: {
        key: [10, 20, 2]
      }
    });
    return OidbBase$1.build(36967, 202, data);
  }
  parse(data) {
    const oidbBody = OidbBase$1.parse(data).body;
    return new NapProtoMsg(OidbSvcTrpcTcp0X9067_202_Rsp_Body).decode(oidbBody);
  }
}
const FetchRkey_default = new FetchRkey();

function getAddonPath(binaryPath) {
  const platformName = platform();
  const archName = arch();
  const addonFileName = process.platform + "." + process.arch;
  const addonPath = path$1.join(binaryPath, "./native/ffmpeg/", `ffmpegAddon.${addonFileName}.node`);
  if (!existsSync(addonPath)) {
    throw new Error(`Unsupported platform: ${platformName} ${archName} - Addon not found at ${addonPath}`);
  }
  return addonPath;
}
class FFmpegAddonAdapter {
  name = "FFmpegAddon";
  addon = null;
  binaryPath;
  constructor(binaryPath) {
    this.binaryPath = binaryPath;
  }
  /**
     * 检查 Addon 是否可用
     */
  async isAvailable() {
    try {
      const temp_addon = { exports: {} };
      dlopen(temp_addon, getAddonPath(this.binaryPath));
      this.addon = temp_addon.exports;
      return this.addon !== null;
    } catch (error) {
      console.log("[FFmpegAddonAdapter] Failed to load addon:", error);
      return false;
    }
  }
  ensureAddon() {
    if (!this.addon) {
      throw new Error("FFmpeg Addon is not available");
    }
    return this.addon;
  }
  /**
     * 获取视频信息
     */
  async getVideoInfo(videoPath) {
    const addon = this.ensureAddon();
    const info = await addon.getVideoInfo(videoPath);
    const format = info.format.includes(",") ? info.format.split(",")[0] ?? info.format : info.format;
    console.log("[FFmpegAddonAdapter] Detected format:", format);
    return {
      width: info.width,
      height: info.height,
      duration: info.duration,
      format,
      thumbnail: info.image
    };
  }
  /**
     * 获取时长
     */
  async getDuration(filePath) {
    const addon = this.ensureAddon();
    return addon.getDuration(filePath);
  }
  /**
     * 转换为 PCM
     */
  async convertToPCM(filePath, pcmPath) {
    const addon = this.ensureAddon();
    const result = await addon.decodeAudioToPCM(filePath, pcmPath, 24e3);
    return result;
  }
  /**
     * 转换文件
     */
  async convertFile(inputFile, outputFile, format) {
    const addon = this.ensureAddon();
    console.log("[FFmpegAddonAdapter] Converting file:", inputFile, "to", outputFile, "as", format);
    await addon.decodeAudioToFmt(inputFile, outputFile, format);
  }
  /**
     * 提取缩略图
     */
  async extractThumbnail(videoPath, thumbnailPath) {
    const addon = this.ensureAddon();
    const info = await addon.getVideoInfo(videoPath);
    await writeFile(thumbnailPath, info.image);
  }
}

function matchMagic(buffer, magic, offset = 0) {
  if (buffer.length < offset + magic.length) {
    return false;
  }
  for (let i = 0; i < magic.length; i++) {
    if (buffer[offset + i] !== magic[i]) {
      return false;
    }
  }
  return true;
}
class PngParser {
  type = "png" /* PNG */;
  // PNG 魔术头：89 50 4E 47 0D 0A 1A 0A
  PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
  canParse(buffer) {
    return matchMagic(buffer, this.PNG_SIGNATURE);
  }
  async parseSize(stream) {
    return new Promise((resolve, reject) => {
      stream.once("error", reject);
      stream.once("readable", () => {
        const buf = stream.read(24);
        if (!buf || buf.length < 24) {
          return resolve(void 0);
        }
        if (this.canParse(buf)) {
          const width = buf.readUInt32BE(16);
          const height = buf.readUInt32BE(20);
          resolve({ width, height });
        } else {
          resolve(void 0);
        }
      });
    });
  }
}
class JpegParser {
  type = "jpeg" /* JPEG */;
  // JPEG 魔术头：FF D8
  JPEG_SIGNATURE = [255, 216];
  // JPEG标记常量
  SOF_MARKERS = {
    SOF0: 192,
    // 基线DCT
    SOF1: 193,
    // 扩展顺序DCT
    SOF2: 194,
    // 渐进式DCT
    SOF3: 195
    // 无损
  };
  // 非SOF标记
  NON_SOF_MARKERS = [
    196,
    // DHT
    200,
    // JPEG扩展
    204
    // DAC
  ];
  canParse(buffer) {
    return matchMagic(buffer, this.JPEG_SIGNATURE);
  }
  isSOFMarker(marker) {
    return marker === this.SOF_MARKERS.SOF0 || marker === this.SOF_MARKERS.SOF1 || marker === this.SOF_MARKERS.SOF2 || marker === this.SOF_MARKERS.SOF3;
  }
  isNonSOFMarker(marker) {
    return this.NON_SOF_MARKERS.includes(marker);
  }
  async parseSize(stream) {
    return new Promise((resolve, reject) => {
      const BUFFER_SIZE = 1024;
      let buffer = Buffer.alloc(0);
      let offset = 0;
      let found = false;
      stream.on("error", (err) => {
        stream.destroy();
        reject(err);
      });
      stream.on("data", (chunk) => {
        const chunkBuffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
        buffer = Buffer.concat([buffer.subarray(offset), chunkBuffer]);
        offset = 0;
        const bufferSize = buffer.length;
        const MIN_REQUIRED_BYTES = 10;
        while (offset < bufferSize - MIN_REQUIRED_BYTES) {
          if (buffer[offset] === 255 && buffer[offset + 1] >= 192 && buffer[offset + 1] <= 207) {
            const marker = buffer[offset + 1];
            if (!marker) {
              break;
            }
            if (this.isNonSOFMarker(marker)) {
              offset += 2;
              continue;
            }
            if (this.isSOFMarker(marker)) {
              if (offset + 9 < bufferSize) {
                const height = buffer.readUInt16BE(offset + 5);
                const width = buffer.readUInt16BE(offset + 7);
                found = true;
                stream.destroy();
                resolve({ width, height });
                return;
              } else {
                break;
              }
            }
          }
          offset++;
        }
        if (offset > BUFFER_SIZE) {
          const KEEP_BYTES = 20;
          if (offset > KEEP_BYTES) {
            buffer = buffer.subarray(offset - KEEP_BYTES);
            offset = KEEP_BYTES;
          }
        }
      });
      stream.on("end", () => {
        if (!found) {
          resolve(void 0);
        }
      });
    });
  }
}
class BmpParser {
  type = "bmp" /* BMP */;
  // BMP 魔术头：42 4D (BM)
  BMP_SIGNATURE = [66, 77];
  canParse(buffer) {
    return matchMagic(buffer, this.BMP_SIGNATURE);
  }
  async parseSize(stream) {
    return new Promise((resolve, reject) => {
      stream.once("error", reject);
      stream.once("readable", () => {
        const buf = stream.read(26);
        if (!buf || buf.length < 26) {
          return resolve(void 0);
        }
        if (this.canParse(buf)) {
          const width = buf.readUInt32LE(18);
          const height = buf.readUInt32LE(22);
          resolve({ width, height });
        } else {
          resolve(void 0);
        }
      });
    });
  }
}
class GifParser {
  type = "gif" /* GIF */;
  // GIF87a 魔术头：47 49 46 38 37 61
  GIF87A_SIGNATURE = [71, 73, 70, 56, 55, 97];
  // GIF89a 魔术头：47 49 46 38 39 61
  GIF89A_SIGNATURE = [71, 73, 70, 56, 57, 97];
  canParse(buffer) {
    return matchMagic(buffer, this.GIF87A_SIGNATURE) || matchMagic(buffer, this.GIF89A_SIGNATURE);
  }
  async parseSize(stream) {
    return new Promise((resolve, reject) => {
      stream.once("error", reject);
      stream.once("readable", () => {
        const buf = stream.read(10);
        if (!buf || buf.length < 10) {
          return resolve(void 0);
        }
        if (this.canParse(buf)) {
          const width = buf.readUInt16LE(6);
          const height = buf.readUInt16LE(8);
          resolve({ width, height });
        } else {
          resolve(void 0);
        }
      });
    });
  }
}
class WebpParser {
  type = "webp" /* WEBP */;
  // WEBP RIFF 头：52 49 46 46 (RIFF)
  RIFF_SIGNATURE = [82, 73, 70, 70];
  // WEBP 魔术头：57 45 42 50 (WEBP)
  WEBP_SIGNATURE = [87, 69, 66, 80];
  // WEBP 块头
  CHUNK_VP8 = [86, 80, 56, 32];
  // "VP8 "
  CHUNK_VP8L = [86, 80, 56, 76];
  // "VP8L"
  CHUNK_VP8X = [86, 80, 56, 88];
  // "VP8X"
  canParse(buffer) {
    return buffer.length >= 12 && matchMagic(buffer, this.RIFF_SIGNATURE, 0) && matchMagic(buffer, this.WEBP_SIGNATURE, 8);
  }
  isChunkType(buffer, offset, chunkType) {
    return buffer.length >= offset + 4 && matchMagic(buffer, chunkType, offset);
  }
  async parseSize(stream) {
    return new Promise((resolve, reject) => {
      const MAX_HEADER_SIZE = 32;
      let totalBytes = 0;
      let buffer = Buffer.alloc(0);
      stream.on("error", reject);
      stream.on("data", (chunk) => {
        const chunkBuffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
        buffer = Buffer.concat([buffer, chunkBuffer]);
        totalBytes += chunk.length;
        if (totalBytes >= MAX_HEADER_SIZE) {
          stream.destroy();
          if (!this.canParse(buffer)) {
            return resolve(void 0);
          }
          if (this.isChunkType(buffer, 12, this.CHUNK_VP8)) {
            const width = buffer.readUInt16LE(26) & 16383;
            const height = buffer.readUInt16LE(28) & 16383;
            return resolve({ width, height });
          } else if (this.isChunkType(buffer, 12, this.CHUNK_VP8L)) {
            const bits = buffer.readUInt32LE(21);
            const width = 1 + (bits & 16383);
            const height = 1 + (bits >> 14 & 16383);
            return resolve({ width, height });
          } else if (this.isChunkType(buffer, 12, this.CHUNK_VP8X)) {
            if (!buffer[24] || !buffer[25] || !buffer[26] || !buffer[27] || !buffer[28] || !buffer[29]) {
              return resolve(void 0);
            }
            const width = 1 + ((buffer[24] | buffer[25] << 8 | buffer[26] << 16) & 16777215);
            const height = 1 + ((buffer[27] | buffer[28] << 8 | buffer[29] << 16) & 16777215);
            return resolve({ width, height });
          } else {
            return resolve(void 0);
          }
        }
      });
      stream.on("end", () => {
        if (totalBytes < MAX_HEADER_SIZE) {
          resolve(void 0);
        }
      });
    });
  }
}
const parsers = [
  new PngParser(),
  new JpegParser(),
  new BmpParser(),
  new GifParser(),
  new WebpParser()
];
async function detectImageType(filePath) {
  return new Promise((resolve, reject) => {
    const stream = fs.createReadStream(filePath, {
      highWaterMark: 64,
      // 优化读取buffer大小
      start: 0,
      end: 63
    });
    let buffer = null;
    stream.once("error", (err) => {
      stream.destroy();
      reject(err);
    });
    stream.once("readable", () => {
      buffer = stream.read(64);
      stream.destroy();
      if (!buffer) {
        return resolve("unknown" /* UNKNOWN */);
      }
      for (const parser of parsers) {
        if (parser.canParse(buffer)) {
          return resolve(parser.type);
        }
      }
      resolve("unknown" /* UNKNOWN */);
    });
    stream.once("end", () => {
      if (!buffer) {
        resolve("unknown" /* UNKNOWN */);
      }
    });
  });
}
async function imageSizeFromFile(filePath) {
  try {
    const type = await detectImageType(filePath);
    const parser = parsers.find((p) => p.type === type);
    if (!parser) {
      return void 0;
    }
    const stream = fs.createReadStream(filePath);
    try {
      return await parser.parseSize(stream);
    } catch (err) {
      console.error(`解析图片尺寸出错: ${err}`);
      return void 0;
    } finally {
      if (!stream.destroyed) {
        stream.destroy();
      }
    }
  } catch (err) {
    console.error(`检测图片类型出错: ${err}`);
    return void 0;
  }
}
async function imageSizeFallBack(filePath, fallback = {
  width: 1024,
  height: 1024
}) {
  return await imageSizeFromFile(filePath) ?? fallback;
}

var compressing$1 = {};

var zip = {};

var utils$2 = {};

var mkdirp;
var hasRequiredMkdirp;

function requireMkdirp () {
	if (hasRequiredMkdirp) return mkdirp;
	hasRequiredMkdirp = 1;
	var path = path__default;
	var fs = fs__default;
	var _0777 = parseInt('0777', 8);

	mkdirp = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;

	function mkdirP (p, opts, f, made) {
	    if (typeof opts === 'function') {
	        f = opts;
	        opts = {};
	    }
	    else if (!opts || typeof opts !== 'object') {
	        opts = { mode: opts };
	    }
	    
	    var mode = opts.mode;
	    var xfs = opts.fs || fs;
	    
	    if (mode === undefined) {
	        mode = _0777;
	    }
	    if (!made) made = null;
	    
	    var cb = f || /* istanbul ignore next */ function () {};
	    p = path.resolve(p);
	    
	    xfs.mkdir(p, mode, function (er) {
	        if (!er) {
	            made = made || p;
	            return cb(null, made);
	        }
	        switch (er.code) {
	            case 'ENOENT':
	                /* istanbul ignore if */
	                if (path.dirname(p) === p) return cb(er);
	                mkdirP(path.dirname(p), opts, function (er, made) {
	                    /* istanbul ignore if */
	                    if (er) cb(er, made);
	                    else mkdirP(p, opts, cb, made);
	                });
	                break;

	            // In the case of any other error, just see if there's a dir
	            // there already.  If so, then hooray!  If not, then something
	            // is borked.
	            default:
	                xfs.stat(p, function (er2, stat) {
	                    // if the stat fails, then that's super weird.
	                    // let the original error be the failure reason.
	                    if (er2 || !stat.isDirectory()) cb(er, made);
	                    else cb(null, made);
	                });
	                break;
	        }
	    });
	}

	mkdirP.sync = function sync (p, opts, made) {
	    if (!opts || typeof opts !== 'object') {
	        opts = { mode: opts };
	    }
	    
	    var mode = opts.mode;
	    var xfs = opts.fs || fs;
	    
	    if (mode === undefined) {
	        mode = _0777;
	    }
	    if (!made) made = null;

	    p = path.resolve(p);

	    try {
	        xfs.mkdirSync(p, mode);
	        made = made || p;
	    }
	    catch (err0) {
	        switch (err0.code) {
	            case 'ENOENT' :
	                made = sync(path.dirname(p), opts, made);
	                sync(p, opts, made);
	                break;

	            // In the case of any other error, just see if there's a dir
	            // there already.  If so, then hooray!  If not, then something
	            // is borked.
	            default:
	                var stat;
	                try {
	                    stat = xfs.statSync(p);
	                }
	                catch (err1) /* istanbul ignore next */ {
	                    throw err0;
	                }
	                /* istanbul ignore if */
	                if (!stat.isDirectory()) throw err0;
	                break;
	        }
	    }

	    return made;
	};
	return mkdirp;
}

var once$1 = {exports: {}};

var wrappy_1;
var hasRequiredWrappy;

function requireWrappy () {
	if (hasRequiredWrappy) return wrappy_1;
	hasRequiredWrappy = 1;
	// Returns a wrapper function that returns a wrapped callback
	// The wrapper function should do some stuff, and return a
	// presumably different callback function.
	// This makes sure that own properties are retained, so that
	// decorations and such are not lost along the way.
	wrappy_1 = wrappy;
	function wrappy (fn, cb) {
	  if (fn && cb) return wrappy(fn)(cb)

	  if (typeof fn !== 'function')
	    throw new TypeError('need wrapper function')

	  Object.keys(fn).forEach(function (k) {
	    wrapper[k] = fn[k];
	  });

	  return wrapper

	  function wrapper() {
	    var args = new Array(arguments.length);
	    for (var i = 0; i < args.length; i++) {
	      args[i] = arguments[i];
	    }
	    var ret = fn.apply(this, args);
	    var cb = args[args.length-1];
	    if (typeof ret === 'function' && ret !== cb) {
	      Object.keys(cb).forEach(function (k) {
	        ret[k] = cb[k];
	      });
	    }
	    return ret
	  }
	}
	return wrappy_1;
}

var hasRequiredOnce$1;

function requireOnce$1 () {
	if (hasRequiredOnce$1) return once$1.exports;
	hasRequiredOnce$1 = 1;
	var wrappy = requireWrappy();
	once$1.exports = wrappy(once);
	once$1.exports.strict = wrappy(onceStrict);

	once.proto = once(function () {
	  Object.defineProperty(Function.prototype, 'once', {
	    value: function () {
	      return once(this)
	    },
	    configurable: true
	  });

	  Object.defineProperty(Function.prototype, 'onceStrict', {
	    value: function () {
	      return onceStrict(this)
	    },
	    configurable: true
	  });
	});

	function once (fn) {
	  var f = function () {
	    if (f.called) return f.value
	    f.called = true;
	    return f.value = fn.apply(this, arguments)
	  };
	  f.called = false;
	  return f
	}

	function onceStrict (fn) {
	  var f = function () {
	    if (f.called)
	      throw new Error(f.onceError)
	    f.called = true;
	    return f.value = fn.apply(this, arguments)
	  };
	  var name = fn.name || 'Function wrapped with `once`';
	  f.onceError = name + " shouldn't be called more than once";
	  f.called = false;
	  return f
	}
	return once$1.exports;
}

var endOfStream$1;
var hasRequiredEndOfStream$1;

function requireEndOfStream$1 () {
	if (hasRequiredEndOfStream$1) return endOfStream$1;
	hasRequiredEndOfStream$1 = 1;
	var once = requireOnce$1();

	var noop = function() {};

	var qnt = commonjsGlobal.Bare ? queueMicrotask : process.nextTick.bind(process);

	var isRequest = function(stream) {
		return stream.setHeader && typeof stream.abort === 'function';
	};

	var isChildProcess = function(stream) {
		return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
	};

	var eos = function(stream, opts, callback) {
		if (typeof opts === 'function') return eos(stream, null, opts);
		if (!opts) opts = {};

		callback = once(callback || noop);

		var ws = stream._writableState;
		var rs = stream._readableState;
		var readable = opts.readable || (opts.readable !== false && stream.readable);
		var writable = opts.writable || (opts.writable !== false && stream.writable);
		var cancelled = false;

		var onlegacyfinish = function() {
			if (!stream.writable) onfinish();
		};

		var onfinish = function() {
			writable = false;
			if (!readable) callback.call(stream);
		};

		var onend = function() {
			readable = false;
			if (!writable) callback.call(stream);
		};

		var onexit = function(exitCode) {
			callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
		};

		var onerror = function(err) {
			callback.call(stream, err);
		};

		var onclose = function() {
			qnt(onclosenexttick);
		};

		var onclosenexttick = function() {
			if (cancelled) return;
			if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));
			if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));
		};

		var onrequest = function() {
			stream.req.on('finish', onfinish);
		};

		if (isRequest(stream)) {
			stream.on('complete', onfinish);
			stream.on('abort', onclose);
			if (stream.req) onrequest();
			else stream.on('request', onrequest);
		} else if (writable && !ws) { // legacy streams
			stream.on('end', onlegacyfinish);
			stream.on('close', onlegacyfinish);
		}

		if (isChildProcess(stream)) stream.on('exit', onexit);

		stream.on('end', onend);
		stream.on('finish', onfinish);
		if (opts.error !== false) stream.on('error', onerror);
		stream.on('close', onclose);

		return function() {
			cancelled = true;
			stream.removeListener('complete', onfinish);
			stream.removeListener('abort', onclose);
			stream.removeListener('request', onrequest);
			if (stream.req) stream.req.removeListener('finish', onfinish);
			stream.removeListener('end', onlegacyfinish);
			stream.removeListener('close', onlegacyfinish);
			stream.removeListener('finish', onfinish);
			stream.removeListener('exit', onexit);
			stream.removeListener('end', onend);
			stream.removeListener('error', onerror);
			stream.removeListener('close', onclose);
		};
	};

	endOfStream$1 = eos;
	return endOfStream$1;
}

var pump_1;
var hasRequiredPump;

function requirePump () {
	if (hasRequiredPump) return pump_1;
	hasRequiredPump = 1;
	var once = requireOnce$1();
	var eos = requireEndOfStream$1();
	var fs;

	try {
	  fs = require('fs'); // we only need fs to get the ReadStream and WriteStream prototypes
	} catch (e) {}

	var noop = function () {};
	var ancient = typeof process === 'undefined' ? false : /^v?\.0/.test(process.version);

	var isFn = function (fn) {
	  return typeof fn === 'function'
	};

	var isFS = function (stream) {
	  if (!ancient) return false // newer node version do not need to care about fs is a special way
	  if (!fs) return false // browser
	  return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close)
	};

	var isRequest = function (stream) {
	  return stream.setHeader && isFn(stream.abort)
	};

	var destroyer = function (stream, reading, writing, callback) {
	  callback = once(callback);

	  var closed = false;
	  stream.on('close', function () {
	    closed = true;
	  });

	  eos(stream, {readable: reading, writable: writing}, function (err) {
	    if (err) return callback(err)
	    closed = true;
	    callback();
	  });

	  var destroyed = false;
	  return function (err) {
	    if (closed) return
	    if (destroyed) return
	    destroyed = true;

	    if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks
	    if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want

	    if (isFn(stream.destroy)) return stream.destroy()

	    callback(err || new Error('stream was destroyed'));
	  }
	};

	var call = function (fn) {
	  fn();
	};

	var pipe = function (from, to) {
	  return from.pipe(to)
	};

	var pump = function () {
	  var streams = Array.prototype.slice.call(arguments);
	  var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop;

	  if (Array.isArray(streams[0])) streams = streams[0];
	  if (streams.length < 2) throw new Error('pump requires two streams per minimum')

	  var error;
	  var destroys = streams.map(function (stream, i) {
	    var reading = i < streams.length - 1;
	    var writing = i > 0;
	    return destroyer(stream, reading, writing, function (err) {
	      if (!error) error = err;
	      if (err) destroys.forEach(call);
	      if (reading) return
	      destroys.forEach(call);
	      callback(error);
	    })
	  });

	  return streams.reduce(pipe)
	};

	pump_1 = pump;
	return pump_1;
}

var hasRequiredUtils$2;

function requireUtils$2 () {
	if (hasRequiredUtils$2) return utils$2;
	hasRequiredUtils$2 = 1;

	const fs = fs__default;
	const path = path__default;
	const mkdirp = requireMkdirp();
	const pump = requirePump();

	// file/fileBuffer/stream
	utils$2.sourceType = source => {
	  if (!source) return undefined;

	  if (source instanceof Buffer) return 'buffer';
	  if (typeof source._read === 'function' || typeof source._transform === 'function') return 'stream';
	  if (typeof source !== 'string') {
	    const err = new Error('Type is not supported, must be a file path, file buffer, or a readable stream');
	    err.name = 'IlligalSourceError';
	    throw err;
	  }

	  return 'file';
	};

	function destType(dest) {
	  if (typeof dest._write === 'function' || typeof dest._transform === 'function') return 'stream';
	  if (typeof dest !== 'string') {
	    const err = new Error('Type is not supported, must be a file path, or a writable stream');
	    err.name = 'IlligalDestinationError';
	    throw err;
	  }
	  return 'path';
	}

	utils$2.destType = destType;

	const illigalEntryError = new Error('Type is not supported, must be a file path, directory path, file buffer, or a readable stream');
	illigalEntryError.name = 'IlligalEntryError';

	// fileOrDir/fileBuffer/stream
	utils$2.entryType = entry => {
	  if (!entry) return;

	  if (entry instanceof Buffer) return 'buffer';
	  if (typeof entry._read === 'function' || typeof entry._transform === 'function') return 'stream';
	  if (typeof entry !== 'string') throw illigalEntryError;

	  return 'fileOrDir';
	};


	utils$2.clone = obj => {
	  const newObj = {};
	  for (const i in obj) {
	    newObj[i] = obj[i];
	  }
	  return newObj;
	};

	utils$2.makeFileProcessFn = StreamClass => {
	  return (source, dest, opts) => {
	    opts = opts || {};
	    opts.source = source;
	    const destStream = destType(dest) === 'path' ? fs.createWriteStream(dest) : dest;
	    const compressStream = new StreamClass(opts);
	    return safePipe([ compressStream, destStream ]);
	  };
	};

	utils$2.makeCompressDirFn = StreamClass => {
	  return (dir, dest, opts) => {
	    const destStream = destType(dest) === 'path' ? fs.createWriteStream(dest) : dest;
	    const compressStream = new StreamClass();
	    compressStream.addEntry(dir, opts);
	    return safePipe([ compressStream, destStream ]);
	  };
	};

	utils$2.makeUncompressFn = StreamClass => {
	  return (source, destDir, opts) => {
	    opts = opts || {};
	    opts.source = source;
	    if (!source) { // !source 和 sourceType中返回undeined对应
	      const error = new Error('Type is not supported, must be a file path, file buffer, or a readable stream');
	      error.name = 'IlligalSourceError';
	      throw error;
	    }
	    if (destType(destDir) !== 'path') {
	      const error = new Error('uncompress destination must be a directory');
	      error.name = 'IlligalDestError';
	      throw error;
	    }

	    return new Promise((resolve, reject) => {
	      mkdirp(destDir, err => {
	        if (err) return reject(err);

	        let entryCount = 0;
	        let successCount = 0;
	        let isFinish = false;
	        function done() {
	          // resolve when both stream finish and file write finish
	          if (isFinish && entryCount === successCount) resolve();
	        }

	        new StreamClass(opts)
	          .on('finish', () => {
	            isFinish = true;
	            done();
	          })
	          .on('error', reject)
	          .on('entry', (header, stream, next) => {
	            stream.on('end', next);
	            const destFilePath = path.join(destDir, header.name);

	            if (header.type === 'file') {
	              const dir = path.dirname(destFilePath);
	              mkdirp(dir, err => {
	                if (err) return reject(err);

	                entryCount++;
	                pump(stream, fs.createWriteStream(destFilePath, { mode: opts.mode || header.mode }), err => {
	                  if (err) return reject(err);
	                  successCount++;
	                  done();
	                });
	              });
	            } else if (header.type === 'symlink') {
	              const dir = path.dirname(destFilePath);
	              const target = path.resolve(dir, header.linkname);
	              entryCount++;

	              mkdirp(dir, err => {
	                if (err) return reject(err);

	                const relativeTarget = path.relative(dir, target);
	                fs.symlink(relativeTarget, destFilePath, err => {
	                  if (err) return reject(err);
	                  successCount++;
	                  stream.resume();
	                });
	              });
	            } else { // directory
	              mkdirp(destFilePath, err => {
	                if (err) return reject(err);
	                stream.resume();
	              });
	            }
	          });
	      });
	    });
	  };
	};

	utils$2.streamToBuffer = stream => {
	  return new Promise((resolve, reject) => {
	    const chunks = [];
	    stream
	      .on('readable', () => {
	        let chunk;
	        while ((chunk = stream.read())) chunks.push(chunk);
	      })
	      .on('end', () => resolve(Buffer.concat(chunks)))
	      .on('error', err => reject(err));
	  });
	};

	function safePipe(streams) {
	  return new Promise((resolve, reject) => {
	    pump(streams[0], streams[1], err => {
	      if (err) return reject(err);
	      resolve();
	    });
	  });
	}

	utils$2.safePipe = safePipe;

	function normalizePath(fileName) {
	  fileName = path.normalize(fileName);
	  // https://nodejs.org/api/path.html#path_path_normalize_path
	  if (process.platform === 'win32') fileName = fileName.replace(/\\+/g, '/');
	  return fileName;
	}

	function stripFileName(strip, fileName, type) {
	  // before
	  // node/package.json
	  // node/lib/index.js
	  //
	  // when strip 1
	  // package.json
	  // lib/index.js
	  //
	  // when strip 2
	  // package.json
	  // index.js
	  if (Buffer.isBuffer(fileName)) fileName = fileName.toString();

	  // use / instead of \\
	  if (fileName.indexOf('\\') !== -1) fileName = fileName.replace(/\\+/g, '/');

	  // fix absolute path
	  // /foo => foo
	  if (fileName[0] === '/') fileName = fileName.replace(/^\/+/, '');

	  // fix case
	  // ./foo/bar => foo/bar
	  if (fileName) {
	    fileName = normalizePath(fileName);
	  }

	  let s = fileName.split('/');

	  // fix relative path
	  // foo/../bar/../../asdf/
	  //  => asdf/
	  if (s.indexOf('..') !== -1) {
	    // replace '../' on ../../foo/bar
	    fileName = fileName.replace(/(\.\.\/)+/, '');
	    if (type === 'directory' && fileName && fileName[fileName.length - 1] !== '/') {
	      fileName += '/';
	    }
	    s = fileName.split('/');
	  }

	  strip = Math.min(strip, s.length - 1);
	  return s.slice(strip).join('/') || '/';
	}

	utils$2.stripFileName = stripFileName;
	return utils$2;
}

var yazl = {};

var bufferCrc32;
var hasRequiredBufferCrc32;

function requireBufferCrc32 () {
	if (hasRequiredBufferCrc32) return bufferCrc32;
	hasRequiredBufferCrc32 = 1;
	var Buffer = require$$0$4.Buffer;

	var CRC_TABLE = [
	  0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
	  0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
	  0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
	  0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
	  0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
	  0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
	  0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
	  0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
	  0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
	  0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
	  0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
	  0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
	  0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
	  0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
	  0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
	  0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
	  0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
	  0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
	  0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
	  0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
	  0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
	  0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
	  0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
	  0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
	  0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
	  0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
	  0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
	  0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
	  0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
	  0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
	  0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
	  0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
	  0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
	  0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
	  0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
	  0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
	  0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
	  0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
	  0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
	  0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
	  0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
	  0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
	  0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
	  0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
	  0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
	  0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
	  0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
	  0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
	  0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
	  0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
	  0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
	  0x2d02ef8d
	];

	if (typeof Int32Array !== 'undefined') {
	  CRC_TABLE = new Int32Array(CRC_TABLE);
	}

	function ensureBuffer(input) {
	  if (Buffer.isBuffer(input)) {
	    return input;
	  }

	  var hasNewBufferAPI =
	      typeof Buffer.alloc === "function" &&
	      typeof Buffer.from === "function";

	  if (typeof input === "number") {
	    return hasNewBufferAPI ? Buffer.alloc(input) : new Buffer(input);
	  }
	  else if (typeof input === "string") {
	    return hasNewBufferAPI ? Buffer.from(input) : new Buffer(input);
	  }
	  else {
	    throw new Error("input must be buffer, number, or string, received " +
	                    typeof input);
	  }
	}

	function bufferizeInt(num) {
	  var tmp = ensureBuffer(4);
	  tmp.writeInt32BE(num, 0);
	  return tmp;
	}

	function _crc32(buf, previous) {
	  buf = ensureBuffer(buf);
	  if (Buffer.isBuffer(previous)) {
	    previous = previous.readUInt32BE(0);
	  }
	  var crc = ~~previous ^ -1;
	  for (var n = 0; n < buf.length; n++) {
	    crc = CRC_TABLE[(crc ^ buf[n]) & 0xff] ^ (crc >>> 8);
	  }
	  return (crc ^ -1);
	}

	function crc32() {
	  return bufferizeInt(_crc32.apply(null, arguments));
	}
	crc32.signed = function () {
	  return _crc32.apply(null, arguments);
	};
	crc32.unsigned = function () {
	  return _crc32.apply(null, arguments) >>> 0;
	};

	bufferCrc32 = crc32;
	return bufferCrc32;
}

var hasRequiredYazl;

function requireYazl () {
	if (hasRequiredYazl) return yazl;
	hasRequiredYazl = 1;
	var fs = fs__default;
	var Transform = require$$1$1.Transform;
	var PassThrough = require$$1$1.PassThrough;
	var zlib = require$$1$2;
	var util = require$$0$6;
	var EventEmitter = require$$0$5.EventEmitter;
	var crc32 = requireBufferCrc32();

	yazl.ZipFile = ZipFile;
	yazl.dateToDosDateTime = dateToDosDateTime;

	util.inherits(ZipFile, EventEmitter);
	function ZipFile() {
	  this.outputStream = new PassThrough();
	  this.entries = [];
	  this.outputStreamCursor = 0;
	  this.ended = false; // .end() sets this
	  this.allDone = false; // set when we've written the last bytes
	  this.forceZip64Eocd = false; // configurable in .end()
	}

	ZipFile.prototype.addFile = function(realPath, metadataPath, options) {
	  var self = this;
	  metadataPath = validateMetadataPath(metadataPath, false);
	  if (options == null) options = {};

	  var entry = new Entry(metadataPath, false, options);
	  self.entries.push(entry);
	  fs.stat(realPath, function(err, stats) {
	    if (err) return self.emit("error", err);
	    if (!stats.isFile()) return self.emit("error", new Error("not a file: " + realPath));
	    entry.uncompressedSize = stats.size;
	    if (options.mtime == null) entry.setLastModDate(stats.mtime);
	    if (options.mode == null) entry.setFileAttributesMode(stats.mode);
	    entry.setFileDataPumpFunction(function() {
	      var readStream = fs.createReadStream(realPath);
	      entry.state = Entry.FILE_DATA_IN_PROGRESS;
	      readStream.on("error", function(err) {
	        self.emit("error", err);
	      });
	      pumpFileDataReadStream(self, entry, readStream);
	    });
	    pumpEntries(self);
	  });
	};

	ZipFile.prototype.addReadStream = function(readStream, metadataPath, options) {
	  var self = this;
	  metadataPath = validateMetadataPath(metadataPath, false);
	  if (options == null) options = {};
	  var entry = new Entry(metadataPath, false, options);
	  self.entries.push(entry);
	  entry.setFileDataPumpFunction(function() {
	    entry.state = Entry.FILE_DATA_IN_PROGRESS;
	    pumpFileDataReadStream(self, entry, readStream);
	  });
	  pumpEntries(self);
	};

	ZipFile.prototype.addBuffer = function(buffer, metadataPath, options) {
	  var self = this;
	  metadataPath = validateMetadataPath(metadataPath, false);
	  if (buffer.length > 0x3fffffff) throw new Error("buffer too large: " + buffer.length + " > " + 0x3fffffff);
	  if (options == null) options = {};
	  if (options.size != null) throw new Error("options.size not allowed");
	  var entry = new Entry(metadataPath, false, options);
	  entry.uncompressedSize = buffer.length;
	  entry.crc32 = crc32.unsigned(buffer);
	  entry.crcAndFileSizeKnown = true;
	  self.entries.push(entry);
	  if (!entry.compress) {
	    setCompressedBuffer(buffer);
	  } else {
	    zlib.deflateRaw(buffer, function(err, compressedBuffer) {
	      setCompressedBuffer(compressedBuffer);
	    });
	  }
	  function setCompressedBuffer(compressedBuffer) {
	    entry.compressedSize = compressedBuffer.length;
	    entry.setFileDataPumpFunction(function() {
	      writeToOutputStream(self, compressedBuffer);
	      writeToOutputStream(self, entry.getDataDescriptor());
	      entry.state = Entry.FILE_DATA_DONE;

	      // don't call pumpEntries() recursively.
	      // (also, don't call process.nextTick recursively.)
	      setImmediate(function() {
	        pumpEntries(self);
	      });
	    });
	    pumpEntries(self);
	  }
	};

	ZipFile.prototype.addEmptyDirectory = function(metadataPath, options) {
	  var self = this;
	  metadataPath = validateMetadataPath(metadataPath, true);
	  if (options == null) options = {};
	  if (options.size != null) throw new Error("options.size not allowed");
	  if (options.compress != null) throw new Error("options.compress not allowed");
	  var entry = new Entry(metadataPath, true, options);
	  self.entries.push(entry);
	  entry.setFileDataPumpFunction(function() {
	    writeToOutputStream(self, entry.getDataDescriptor());
	    entry.state = Entry.FILE_DATA_DONE;
	    pumpEntries(self);
	  });
	  pumpEntries(self);
	};

	var eocdrSignatureBuffer = bufferFrom([0x50, 0x4b, 0x05, 0x06]);

	ZipFile.prototype.end = function(options, finalSizeCallback) {
	  if (typeof options === "function") {
	    finalSizeCallback = options;
	    options = null;
	  }
	  if (options == null) options = {};
	  if (this.ended) return;
	  this.ended = true;
	  this.finalSizeCallback = finalSizeCallback;
	  this.forceZip64Eocd = !!options.forceZip64Format;
	  if (options.comment) {
	    if (typeof options.comment === "string") {
	      this.comment = encodeCp437(options.comment);
	    } else {
	      // It should be a Buffer
	      this.comment = options.comment;
	    }
	    if (this.comment.length > 0xffff) throw new Error("comment is too large");
	    // gotta check for this, because the zipfile format is actually ambiguous.
	    if (bufferIncludes(this.comment, eocdrSignatureBuffer)) throw new Error("comment contains end of central directory record signature");
	  } else {
	    // no comment.
	    this.comment = EMPTY_BUFFER;
	  }
	  pumpEntries(this);
	};

	function writeToOutputStream(self, buffer) {
	  self.outputStream.write(buffer);
	  self.outputStreamCursor += buffer.length;
	}

	function pumpFileDataReadStream(self, entry, readStream) {
	  var crc32Watcher = new Crc32Watcher();
	  var uncompressedSizeCounter = new ByteCounter();
	  var compressor = entry.compress ? new zlib.DeflateRaw() : new PassThrough();
	  var compressedSizeCounter = new ByteCounter();
	  readStream.pipe(crc32Watcher)
	            .pipe(uncompressedSizeCounter)
	            .pipe(compressor)
	            .pipe(compressedSizeCounter)
	            .pipe(self.outputStream, {end: false});
	  compressedSizeCounter.on("end", function() {
	    entry.crc32 = crc32Watcher.crc32;
	    if (entry.uncompressedSize == null) {
	      entry.uncompressedSize = uncompressedSizeCounter.byteCount;
	    } else {
	      if (entry.uncompressedSize !== uncompressedSizeCounter.byteCount) return self.emit("error", new Error("file data stream has unexpected number of bytes"));
	    }
	    entry.compressedSize = compressedSizeCounter.byteCount;
	    self.outputStreamCursor += entry.compressedSize;
	    writeToOutputStream(self, entry.getDataDescriptor());
	    entry.state = Entry.FILE_DATA_DONE;
	    pumpEntries(self);
	  });
	}

	function pumpEntries(self) {
	  if (self.allDone) return;
	  // first check if finalSize is finally known
	  if (self.ended && self.finalSizeCallback != null) {
	    var finalSize = calculateFinalSize(self);
	    if (finalSize != null) {
	      // we have an answer
	      self.finalSizeCallback(finalSize);
	      self.finalSizeCallback = null;
	    }
	  }

	  // pump entries
	  var entry = getFirstNotDoneEntry();
	  function getFirstNotDoneEntry() {
	    for (var i = 0; i < self.entries.length; i++) {
	      var entry = self.entries[i];
	      if (entry.state < Entry.FILE_DATA_DONE) return entry;
	    }
	    return null;
	  }
	  if (entry != null) {
	    // this entry is not done yet
	    if (entry.state < Entry.READY_TO_PUMP_FILE_DATA) return; // input file not open yet
	    if (entry.state === Entry.FILE_DATA_IN_PROGRESS) return; // we'll get there
	    // start with local file header
	    entry.relativeOffsetOfLocalHeader = self.outputStreamCursor;
	    var localFileHeader = entry.getLocalFileHeader();
	    writeToOutputStream(self, localFileHeader);
	    entry.doFileDataPump();
	  } else {
	    // all cought up on writing entries
	    if (self.ended) {
	      // head for the exit
	      self.offsetOfStartOfCentralDirectory = self.outputStreamCursor;
	      self.entries.forEach(function(entry) {
	        var centralDirectoryRecord = entry.getCentralDirectoryRecord();
	        writeToOutputStream(self, centralDirectoryRecord);
	      });
	      writeToOutputStream(self, getEndOfCentralDirectoryRecord(self));
	      self.outputStream.end();
	      self.allDone = true;
	    }
	  }
	}

	function calculateFinalSize(self) {
	  var pretendOutputCursor = 0;
	  var centralDirectorySize = 0;
	  for (var i = 0; i < self.entries.length; i++) {
	    var entry = self.entries[i];
	    // compression is too hard to predict
	    if (entry.compress) return -1;
	    if (entry.state >= Entry.READY_TO_PUMP_FILE_DATA) {
	      // if addReadStream was called without providing the size, we can't predict the final size
	      if (entry.uncompressedSize == null) return -1;
	    } else {
	      // if we're still waiting for fs.stat, we might learn the size someday
	      if (entry.uncompressedSize == null) return null;
	    }
	    // we know this for sure, and this is important to know if we need ZIP64 format.
	    entry.relativeOffsetOfLocalHeader = pretendOutputCursor;
	    var useZip64Format = entry.useZip64Format();

	    pretendOutputCursor += LOCAL_FILE_HEADER_FIXED_SIZE + entry.utf8FileName.length;
	    pretendOutputCursor += entry.uncompressedSize;
	    if (!entry.crcAndFileSizeKnown) {
	      // use a data descriptor
	      if (useZip64Format) {
	        pretendOutputCursor += ZIP64_DATA_DESCRIPTOR_SIZE;
	      } else {
	        pretendOutputCursor += DATA_DESCRIPTOR_SIZE;
	      }
	    }

	    centralDirectorySize += CENTRAL_DIRECTORY_RECORD_FIXED_SIZE + entry.utf8FileName.length + entry.fileComment.length;
	    if (useZip64Format) {
	      centralDirectorySize += ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE;
	    }
	  }

	  var endOfCentralDirectorySize = 0;
	  if (self.forceZip64Eocd ||
	      self.entries.length >= 0xffff ||
	      centralDirectorySize >= 0xffff ||
	      pretendOutputCursor >= 0xffffffff) {
	    // use zip64 end of central directory stuff
	    endOfCentralDirectorySize += ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE;
	  }
	  endOfCentralDirectorySize += END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + self.comment.length;
	  return pretendOutputCursor + centralDirectorySize + endOfCentralDirectorySize;
	}

	var ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE = 56;
	var ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE = 20;
	var END_OF_CENTRAL_DIRECTORY_RECORD_SIZE = 22;
	function getEndOfCentralDirectoryRecord(self, actuallyJustTellMeHowLongItWouldBe) {
	  var needZip64Format = false;
	  var normalEntriesLength = self.entries.length;
	  if (self.forceZip64Eocd || self.entries.length >= 0xffff) {
	    normalEntriesLength = 0xffff;
	    needZip64Format = true;
	  }
	  var sizeOfCentralDirectory = self.outputStreamCursor - self.offsetOfStartOfCentralDirectory;
	  var normalSizeOfCentralDirectory = sizeOfCentralDirectory;
	  if (self.forceZip64Eocd || sizeOfCentralDirectory >= 0xffffffff) {
	    normalSizeOfCentralDirectory = 0xffffffff;
	    needZip64Format = true;
	  }
	  var normalOffsetOfStartOfCentralDirectory = self.offsetOfStartOfCentralDirectory;
	  if (self.forceZip64Eocd || self.offsetOfStartOfCentralDirectory >= 0xffffffff) {
	    normalOffsetOfStartOfCentralDirectory = 0xffffffff;
	    needZip64Format = true;
	  }

	  var eocdrBuffer = bufferAlloc(END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + self.comment.length);
	  // end of central dir signature                       4 bytes  (0x06054b50)
	  eocdrBuffer.writeUInt32LE(0x06054b50, 0);
	  // number of this disk                                2 bytes
	  eocdrBuffer.writeUInt16LE(0, 4);
	  // number of the disk with the start of the central directory  2 bytes
	  eocdrBuffer.writeUInt16LE(0, 6);
	  // total number of entries in the central directory on this disk  2 bytes
	  eocdrBuffer.writeUInt16LE(normalEntriesLength, 8);
	  // total number of entries in the central directory   2 bytes
	  eocdrBuffer.writeUInt16LE(normalEntriesLength, 10);
	  // size of the central directory                      4 bytes
	  eocdrBuffer.writeUInt32LE(normalSizeOfCentralDirectory, 12);
	  // offset of start of central directory with respect to the starting disk number  4 bytes
	  eocdrBuffer.writeUInt32LE(normalOffsetOfStartOfCentralDirectory, 16);
	  // .ZIP file comment length                           2 bytes
	  eocdrBuffer.writeUInt16LE(self.comment.length, 20);
	  // .ZIP file comment                                  (variable size)
	  self.comment.copy(eocdrBuffer, 22);

	  if (!needZip64Format) return eocdrBuffer;

	  // ZIP64 format
	  // ZIP64 End of Central Directory Record
	  var zip64EocdrBuffer = bufferAlloc(ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE);
	  // zip64 end of central dir signature                                             4 bytes  (0x06064b50)
	  zip64EocdrBuffer.writeUInt32LE(0x06064b50, 0);
	  // size of zip64 end of central directory record                                  8 bytes
	  writeUInt64LE(zip64EocdrBuffer, ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE - 12, 4);
	  // version made by                                                                2 bytes
	  zip64EocdrBuffer.writeUInt16LE(VERSION_MADE_BY, 12);
	  // version needed to extract                                                      2 bytes
	  zip64EocdrBuffer.writeUInt16LE(VERSION_NEEDED_TO_EXTRACT_ZIP64, 14);
	  // number of this disk                                                            4 bytes
	  zip64EocdrBuffer.writeUInt32LE(0, 16);
	  // number of the disk with the start of the central directory                     4 bytes
	  zip64EocdrBuffer.writeUInt32LE(0, 20);
	  // total number of entries in the central directory on this disk                  8 bytes
	  writeUInt64LE(zip64EocdrBuffer, self.entries.length, 24);
	  // total number of entries in the central directory                               8 bytes
	  writeUInt64LE(zip64EocdrBuffer, self.entries.length, 32);
	  // size of the central directory                                                  8 bytes
	  writeUInt64LE(zip64EocdrBuffer, sizeOfCentralDirectory, 40);
	  // offset of start of central directory with respect to the starting disk number  8 bytes
	  writeUInt64LE(zip64EocdrBuffer, self.offsetOfStartOfCentralDirectory, 48);
	  // zip64 extensible data sector                                                   (variable size)
	  // nothing in the zip64 extensible data sector


	  // ZIP64 End of Central Directory Locator
	  var zip64EocdlBuffer = bufferAlloc(ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE);
	  // zip64 end of central dir locator signature                               4 bytes  (0x07064b50)
	  zip64EocdlBuffer.writeUInt32LE(0x07064b50, 0);
	  // number of the disk with the start of the zip64 end of central directory  4 bytes
	  zip64EocdlBuffer.writeUInt32LE(0, 4);
	  // relative offset of the zip64 end of central directory record             8 bytes
	  writeUInt64LE(zip64EocdlBuffer, self.outputStreamCursor, 8);
	  // total number of disks                                                    4 bytes
	  zip64EocdlBuffer.writeUInt32LE(1, 16);


	  return Buffer.concat([
	    zip64EocdrBuffer,
	    zip64EocdlBuffer,
	    eocdrBuffer,
	  ]);
	}

	function validateMetadataPath(metadataPath, isDirectory) {
	  if (metadataPath === "") throw new Error("empty metadataPath");
	  metadataPath = metadataPath.replace(/\\/g, "/");
	  if (/^[a-zA-Z]:/.test(metadataPath) || /^\//.test(metadataPath)) throw new Error("absolute path: " + metadataPath);
	  if (metadataPath.split("/").indexOf("..") !== -1) throw new Error("invalid relative path: " + metadataPath);
	  var looksLikeDirectory = /\/$/.test(metadataPath);
	  if (isDirectory) {
	    // append a trailing '/' if necessary.
	    if (!looksLikeDirectory) metadataPath += "/";
	  } else {
	    if (looksLikeDirectory) throw new Error("file path cannot end with '/': " + metadataPath);
	  }
	  return metadataPath;
	}

	var EMPTY_BUFFER = bufferAlloc(0);

	// this class is not part of the public API
	function Entry(metadataPath, isDirectory, options) {
	  this.utf8FileName = bufferFrom(metadataPath);
	  if (this.utf8FileName.length > 0xffff) throw new Error("utf8 file name too long. " + utf8FileName.length + " > " + 0xffff);
	  this.isDirectory = isDirectory;
	  this.state = Entry.WAITING_FOR_METADATA;
	  this.setLastModDate(options.mtime != null ? options.mtime : new Date());
	  if (options.mode != null) {
	    this.setFileAttributesMode(options.mode);
	  } else {
	    this.setFileAttributesMode(isDirectory ? 0o40775 : 0o100664);
	  }
	  if (isDirectory) {
	    this.crcAndFileSizeKnown = true;
	    this.crc32 = 0;
	    this.uncompressedSize = 0;
	    this.compressedSize = 0;
	  } else {
	    // unknown so far
	    this.crcAndFileSizeKnown = false;
	    this.crc32 = null;
	    this.uncompressedSize = null;
	    this.compressedSize = null;
	    if (options.size != null) this.uncompressedSize = options.size;
	  }
	  if (isDirectory) {
	    this.compress = false;
	  } else {
	    this.compress = true; // default
	    if (options.compress != null) this.compress = !!options.compress;
	  }
	  this.forceZip64Format = !!options.forceZip64Format;
	  if (options.fileComment) {
	    if (typeof options.fileComment === "string") {
	      this.fileComment = bufferFrom(options.fileComment, "utf-8");
	    } else {
	      // It should be a Buffer
	      this.fileComment = options.fileComment;
	    }
	    if (this.fileComment.length > 0xffff) throw new Error("fileComment is too large");
	  } else {
	    // no comment.
	    this.fileComment = EMPTY_BUFFER;
	  }
	}
	Entry.WAITING_FOR_METADATA = 0;
	Entry.READY_TO_PUMP_FILE_DATA = 1;
	Entry.FILE_DATA_IN_PROGRESS = 2;
	Entry.FILE_DATA_DONE = 3;
	Entry.prototype.setLastModDate = function(date) {
	  var dosDateTime = dateToDosDateTime(date);
	  this.lastModFileTime = dosDateTime.time;
	  this.lastModFileDate = dosDateTime.date;
	};
	Entry.prototype.setFileAttributesMode = function(mode) {
	  if ((mode & 0xffff) !== mode) throw new Error("invalid mode. expected: 0 <= " + mode + " <= " + 0xffff);
	  // http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute/14727#14727
	  this.externalFileAttributes = (mode << 16) >>> 0;
	};
	// doFileDataPump() should not call pumpEntries() directly. see issue #9.
	Entry.prototype.setFileDataPumpFunction = function(doFileDataPump) {
	  this.doFileDataPump = doFileDataPump;
	  this.state = Entry.READY_TO_PUMP_FILE_DATA;
	};
	Entry.prototype.useZip64Format = function() {
	  return (
	    (this.forceZip64Format) ||
	    (this.uncompressedSize != null && this.uncompressedSize > 0xfffffffe) ||
	    (this.compressedSize != null && this.compressedSize > 0xfffffffe) ||
	    (this.relativeOffsetOfLocalHeader != null && this.relativeOffsetOfLocalHeader > 0xfffffffe)
	  );
	};
	var LOCAL_FILE_HEADER_FIXED_SIZE = 30;
	var VERSION_NEEDED_TO_EXTRACT_UTF8 = 20;
	var VERSION_NEEDED_TO_EXTRACT_ZIP64 = 45;
	// 3 = unix. 63 = spec version 6.3
	var VERSION_MADE_BY = (3 << 8) | 63;
	var FILE_NAME_IS_UTF8 = 1 << 11;
	var UNKNOWN_CRC32_AND_FILE_SIZES = 1 << 3;
	Entry.prototype.getLocalFileHeader = function() {
	  var crc32 = 0;
	  var compressedSize = 0;
	  var uncompressedSize = 0;
	  if (this.crcAndFileSizeKnown) {
	    crc32 = this.crc32;
	    compressedSize = this.compressedSize;
	    uncompressedSize = this.uncompressedSize;
	  }

	  var fixedSizeStuff = bufferAlloc(LOCAL_FILE_HEADER_FIXED_SIZE);
	  var generalPurposeBitFlag = FILE_NAME_IS_UTF8;
	  if (!this.crcAndFileSizeKnown) generalPurposeBitFlag |= UNKNOWN_CRC32_AND_FILE_SIZES;

	  // local file header signature     4 bytes  (0x04034b50)
	  fixedSizeStuff.writeUInt32LE(0x04034b50, 0);
	  // version needed to extract       2 bytes
	  fixedSizeStuff.writeUInt16LE(VERSION_NEEDED_TO_EXTRACT_UTF8, 4);
	  // general purpose bit flag        2 bytes
	  fixedSizeStuff.writeUInt16LE(generalPurposeBitFlag, 6);
	  // compression method              2 bytes
	  fixedSizeStuff.writeUInt16LE(this.getCompressionMethod(), 8);
	  // last mod file time              2 bytes
	  fixedSizeStuff.writeUInt16LE(this.lastModFileTime, 10);
	  // last mod file date              2 bytes
	  fixedSizeStuff.writeUInt16LE(this.lastModFileDate, 12);
	  // crc-32                          4 bytes
	  fixedSizeStuff.writeUInt32LE(crc32, 14);
	  // compressed size                 4 bytes
	  fixedSizeStuff.writeUInt32LE(compressedSize, 18);
	  // uncompressed size               4 bytes
	  fixedSizeStuff.writeUInt32LE(uncompressedSize, 22);
	  // file name length                2 bytes
	  fixedSizeStuff.writeUInt16LE(this.utf8FileName.length, 26);
	  // extra field length              2 bytes
	  fixedSizeStuff.writeUInt16LE(0, 28);
	  return Buffer.concat([
	    fixedSizeStuff,
	    // file name (variable size)
	    this.utf8FileName,
	    // extra field (variable size)
	    // no extra fields
	  ]);
	};
	var DATA_DESCRIPTOR_SIZE = 16;
	var ZIP64_DATA_DESCRIPTOR_SIZE = 24;
	Entry.prototype.getDataDescriptor = function() {
	  if (this.crcAndFileSizeKnown) {
	    // the Mac Archive Utility requires this not be present unless we set general purpose bit 3
	    return EMPTY_BUFFER;
	  }
	  if (!this.useZip64Format()) {
	    var buffer = bufferAlloc(DATA_DESCRIPTOR_SIZE);
	    // optional signature (required according to Archive Utility)
	    buffer.writeUInt32LE(0x08074b50, 0);
	    // crc-32                          4 bytes
	    buffer.writeUInt32LE(this.crc32, 4);
	    // compressed size                 4 bytes
	    buffer.writeUInt32LE(this.compressedSize, 8);
	    // uncompressed size               4 bytes
	    buffer.writeUInt32LE(this.uncompressedSize, 12);
	    return buffer;
	  } else {
	    // ZIP64 format
	    var buffer = bufferAlloc(ZIP64_DATA_DESCRIPTOR_SIZE);
	    // optional signature (unknown if anyone cares about this)
	    buffer.writeUInt32LE(0x08074b50, 0);
	    // crc-32                          4 bytes
	    buffer.writeUInt32LE(this.crc32, 4);
	    // compressed size                 8 bytes
	    writeUInt64LE(buffer, this.compressedSize, 8);
	    // uncompressed size               8 bytes
	    writeUInt64LE(buffer, this.uncompressedSize, 16);
	    return buffer;
	  }
	};
	var CENTRAL_DIRECTORY_RECORD_FIXED_SIZE = 46;
	var ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE = 28;
	Entry.prototype.getCentralDirectoryRecord = function() {
	  var fixedSizeStuff = bufferAlloc(CENTRAL_DIRECTORY_RECORD_FIXED_SIZE);
	  var generalPurposeBitFlag = FILE_NAME_IS_UTF8;
	  if (!this.crcAndFileSizeKnown) generalPurposeBitFlag |= UNKNOWN_CRC32_AND_FILE_SIZES;

	  var normalCompressedSize = this.compressedSize;
	  var normalUncompressedSize = this.uncompressedSize;
	  var normalRelativeOffsetOfLocalHeader = this.relativeOffsetOfLocalHeader;
	  var versionNeededToExtract;
	  var zeiefBuffer;
	  if (this.useZip64Format()) {
	    normalCompressedSize = 0xffffffff;
	    normalUncompressedSize = 0xffffffff;
	    normalRelativeOffsetOfLocalHeader = 0xffffffff;
	    versionNeededToExtract = VERSION_NEEDED_TO_EXTRACT_ZIP64;

	    // ZIP64 extended information extra field
	    zeiefBuffer = bufferAlloc(ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE);
	    // 0x0001                  2 bytes    Tag for this "extra" block type
	    zeiefBuffer.writeUInt16LE(0x0001, 0);
	    // Size                    2 bytes    Size of this "extra" block
	    zeiefBuffer.writeUInt16LE(ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE - 4, 2);
	    // Original Size           8 bytes    Original uncompressed file size
	    writeUInt64LE(zeiefBuffer, this.uncompressedSize, 4);
	    // Compressed Size         8 bytes    Size of compressed data
	    writeUInt64LE(zeiefBuffer, this.compressedSize, 12);
	    // Relative Header Offset  8 bytes    Offset of local header record
	    writeUInt64LE(zeiefBuffer, this.relativeOffsetOfLocalHeader, 20);
	    // Disk Start Number       4 bytes    Number of the disk on which this file starts
	    // (omit)
	  } else {
	    versionNeededToExtract = VERSION_NEEDED_TO_EXTRACT_UTF8;
	    zeiefBuffer = EMPTY_BUFFER;
	  }

	  // central file header signature   4 bytes  (0x02014b50)
	  fixedSizeStuff.writeUInt32LE(0x02014b50, 0);
	  // version made by                 2 bytes
	  fixedSizeStuff.writeUInt16LE(VERSION_MADE_BY, 4);
	  // version needed to extract       2 bytes
	  fixedSizeStuff.writeUInt16LE(versionNeededToExtract, 6);
	  // general purpose bit flag        2 bytes
	  fixedSizeStuff.writeUInt16LE(generalPurposeBitFlag, 8);
	  // compression method              2 bytes
	  fixedSizeStuff.writeUInt16LE(this.getCompressionMethod(), 10);
	  // last mod file time              2 bytes
	  fixedSizeStuff.writeUInt16LE(this.lastModFileTime, 12);
	  // last mod file date              2 bytes
	  fixedSizeStuff.writeUInt16LE(this.lastModFileDate, 14);
	  // crc-32                          4 bytes
	  fixedSizeStuff.writeUInt32LE(this.crc32, 16);
	  // compressed size                 4 bytes
	  fixedSizeStuff.writeUInt32LE(normalCompressedSize, 20);
	  // uncompressed size               4 bytes
	  fixedSizeStuff.writeUInt32LE(normalUncompressedSize, 24);
	  // file name length                2 bytes
	  fixedSizeStuff.writeUInt16LE(this.utf8FileName.length, 28);
	  // extra field length              2 bytes
	  fixedSizeStuff.writeUInt16LE(zeiefBuffer.length, 30);
	  // file comment length             2 bytes
	  fixedSizeStuff.writeUInt16LE(this.fileComment.length, 32);
	  // disk number start               2 bytes
	  fixedSizeStuff.writeUInt16LE(0, 34);
	  // internal file attributes        2 bytes
	  fixedSizeStuff.writeUInt16LE(0, 36);
	  // external file attributes        4 bytes
	  fixedSizeStuff.writeUInt32LE(this.externalFileAttributes, 38);
	  // relative offset of local header 4 bytes
	  fixedSizeStuff.writeUInt32LE(normalRelativeOffsetOfLocalHeader, 42);

	  return Buffer.concat([
	    fixedSizeStuff,
	    // file name (variable size)
	    this.utf8FileName,
	    // extra field (variable size)
	    zeiefBuffer,
	    // file comment (variable size)
	    this.fileComment,
	  ]);
	};
	Entry.prototype.getCompressionMethod = function() {
	  var NO_COMPRESSION = 0;
	  var DEFLATE_COMPRESSION = 8;
	  return this.compress ? DEFLATE_COMPRESSION : NO_COMPRESSION;
	};

	function dateToDosDateTime(jsDate) {
	  var date = 0;
	  date |= jsDate.getDate() & 0x1f; // 1-31
	  date |= ((jsDate.getMonth() + 1) & 0xf) << 5; // 0-11, 1-12
	  date |= ((jsDate.getFullYear() - 1980) & 0x7f) << 9; // 0-128, 1980-2108

	  var time = 0;
	  time |= Math.floor(jsDate.getSeconds() / 2); // 0-59, 0-29 (lose odd numbers)
	  time |= (jsDate.getMinutes() & 0x3f) << 5; // 0-59
	  time |= (jsDate.getHours() & 0x1f) << 11; // 0-23

	  return {date: date, time: time};
	}

	function writeUInt64LE(buffer, n, offset) {
	  // can't use bitshift here, because JavaScript only allows bitshifting on 32-bit integers.
	  var high = Math.floor(n / 0x100000000);
	  var low = n % 0x100000000;
	  buffer.writeUInt32LE(low, offset);
	  buffer.writeUInt32LE(high, offset + 4);
	}

	util.inherits(ByteCounter, Transform);
	function ByteCounter(options) {
	  Transform.call(this, options);
	  this.byteCount = 0;
	}
	ByteCounter.prototype._transform = function(chunk, encoding, cb) {
	  this.byteCount += chunk.length;
	  cb(null, chunk);
	};

	util.inherits(Crc32Watcher, Transform);
	function Crc32Watcher(options) {
	  Transform.call(this, options);
	  this.crc32 = 0;
	}
	Crc32Watcher.prototype._transform = function(chunk, encoding, cb) {
	  this.crc32 = crc32.unsigned(chunk, this.crc32);
	  cb(null, chunk);
	};

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

	function encodeCp437(string) {
	  if (/^[\x20-\x7e]*$/.test(string)) {
	    // CP437, ASCII, and UTF-8 overlap in this range.
	    return bufferFrom(string, "utf-8");
	  }

	  // This is the slow path.
	  if (reverseCp437 == null) {
	    // cache this once
	    reverseCp437 = {};
	    for (var i = 0; i < cp437.length; i++) {
	      reverseCp437[cp437[i]] = i;
	    }
	  }

	  var result = bufferAlloc(string.length);
	  for (var i = 0; i < string.length; i++) {
	    var b = reverseCp437[string[i]];
	    if (b == null) throw new Error("character not encodable in CP437: " + JSON.stringify(string[i]));
	    result[i] = b;
	  }

	  return result;
	}

	function bufferAlloc(size) {
	  bufferAlloc = modern;
	  try {
	    return bufferAlloc(size);
	  } catch (e) {
	    bufferAlloc = legacy;
	    return bufferAlloc(size);
	  }
	  function modern(size) {
	    return Buffer.allocUnsafe(size);
	  }
	  function legacy(size) {
	    return new Buffer(size);
	  }
	}
	function bufferFrom(something, encoding) {
	  bufferFrom = modern;
	  try {
	    return bufferFrom(something, encoding);
	  } catch (e) {
	    bufferFrom = legacy;
	    return bufferFrom(something, encoding);
	  }
	  function modern(something, encoding) {
	    return Buffer.from(something, encoding);
	  }
	  function legacy(something, encoding) {
	    return new Buffer(something, encoding);
	  }
	}
	function bufferIncludes(buffer, content) {
	  bufferIncludes = modern;
	  try {
	    return bufferIncludes(buffer, content);
	  } catch (e) {
	    bufferIncludes = legacy;
	    return bufferIncludes(buffer, content);
	  }
	  function modern(buffer, content) {
	    return buffer.includes(content);
	  }
	  function legacy(buffer, content) {
	    for (var i = 0; i <= buffer.length - content.length; i++) {
	      for (var j = 0;; j++) {
	        if (j === content.length) return true;
	        if (buffer[i + j] !== content[j]) break;
	      }
	    }
	    return false;
	  }
	}
	return yazl;
}

var tarStream = {};

var processNextickArgs = {exports: {}};

var hasRequiredProcessNextickArgs;

function requireProcessNextickArgs () {
	if (hasRequiredProcessNextickArgs) return processNextickArgs.exports;
	hasRequiredProcessNextickArgs = 1;

	if (typeof process === 'undefined' ||
	    !process.version ||
	    process.version.indexOf('v0.') === 0 ||
	    process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
	  processNextickArgs.exports = { nextTick: nextTick };
	} else {
	  processNextickArgs.exports = process;
	}

	function nextTick(fn, arg1, arg2, arg3) {
	  if (typeof fn !== 'function') {
	    throw new TypeError('"callback" argument must be a function');
	  }
	  var len = arguments.length;
	  var args, i;
	  switch (len) {
	  case 0:
	  case 1:
	    return process.nextTick(fn);
	  case 2:
	    return process.nextTick(function afterTickOne() {
	      fn.call(null, arg1);
	    });
	  case 3:
	    return process.nextTick(function afterTickTwo() {
	      fn.call(null, arg1, arg2);
	    });
	  case 4:
	    return process.nextTick(function afterTickThree() {
	      fn.call(null, arg1, arg2, arg3);
	    });
	  default:
	    args = new Array(len - 1);
	    i = 0;
	    while (i < args.length) {
	      args[i++] = arguments[i];
	    }
	    return process.nextTick(function afterTick() {
	      fn.apply(null, args);
	    });
	  }
	}
	return processNextickArgs.exports;
}

var util$3 = {};

var hasRequiredUtil$2;

function requireUtil$2 () {
	if (hasRequiredUtil$2) return util$3;
	hasRequiredUtil$2 = 1;
	// Copyright Joyent, Inc. and other Node contributors.
	//
	// Permission is hereby granted, free of charge, to any person obtaining a
	// copy of this software and associated documentation files (the
	// "Software"), to deal in the Software without restriction, including
	// without limitation the rights to use, copy, modify, merge, publish,
	// distribute, sublicense, and/or sell copies of the Software, and to permit
	// persons to whom the Software is furnished to do so, subject to the
	// following conditions:
	//
	// The above copyright notice and this permission notice shall be included
	// in all copies or substantial portions of the Software.
	//
	// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
	// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
	// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
	// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
	// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
	// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
	// USE OR OTHER DEALINGS IN THE SOFTWARE.

	// NOTE: These type checking functions intentionally don't use `instanceof`
	// because it is fragile and can be easily faked with `Object.create()`.

	function isArray(arg) {
	  if (Array.isArray) {
	    return Array.isArray(arg);
	  }
	  return objectToString(arg) === '[object Array]';
	}
	util$3.isArray = isArray;

	function isBoolean(arg) {
	  return typeof arg === 'boolean';
	}
	util$3.isBoolean = isBoolean;

	function isNull(arg) {
	  return arg === null;
	}
	util$3.isNull = isNull;

	function isNullOrUndefined(arg) {
	  return arg == null;
	}
	util$3.isNullOrUndefined = isNullOrUndefined;

	function isNumber(arg) {
	  return typeof arg === 'number';
	}
	util$3.isNumber = isNumber;

	function isString(arg) {
	  return typeof arg === 'string';
	}
	util$3.isString = isString;

	function isSymbol(arg) {
	  return typeof arg === 'symbol';
	}
	util$3.isSymbol = isSymbol;

	function isUndefined(arg) {
	  return arg === void 0;
	}
	util$3.isUndefined = isUndefined;

	function isRegExp(re) {
	  return objectToString(re) === '[object RegExp]';
	}
	util$3.isRegExp = isRegExp;

	function isObject(arg) {
	  return typeof arg === 'object' && arg !== null;
	}
	util$3.isObject = isObject;

	function isDate(d) {
	  return objectToString(d) === '[object Date]';
	}
	util$3.isDate = isDate;

	function isError(e) {
	  return (objectToString(e) === '[object Error]' || e instanceof Error);
	}
	util$3.isError = isError;

	function isFunction(arg) {
	  return typeof arg === 'function';
	}
	util$3.isFunction = isFunction;

	function isPrimitive(arg) {
	  return arg === null ||
	         typeof arg === 'boolean' ||
	         typeof arg === 'number' ||
	         typeof arg === 'string' ||
	         typeof arg === 'symbol' ||  // ES6 symbol
	         typeof arg === 'undefined';
	}
	util$3.isPrimitive = isPrimitive;

	util$3.isBuffer = require$$0$4.Buffer.isBuffer;

	function objectToString(o) {
	  return Object.prototype.toString.call(o);
	}
	return util$3;
}

var inherits_browser = {exports: {}};

var hasRequiredInherits_browser;

function requireInherits_browser () {
	if (hasRequiredInherits_browser) return inherits_browser.exports;
	hasRequiredInherits_browser = 1;
	if (typeof Object.create === 'function') {
	  // implementation from standard node.js 'util' module
	  inherits_browser.exports = function inherits(ctor, superCtor) {
	    if (superCtor) {
	      ctor.super_ = superCtor;
	      ctor.prototype = Object.create(superCtor.prototype, {
	        constructor: {
	          value: ctor,
	          enumerable: false,
	          writable: true,
	          configurable: true
	        }
	      });
	    }
	  };
	} else {
	  // old school shim for old browsers
	  inherits_browser.exports = function inherits(ctor, superCtor) {
	    if (superCtor) {
	      ctor.super_ = superCtor;
	      var TempCtor = function () {};
	      TempCtor.prototype = superCtor.prototype;
	      ctor.prototype = new TempCtor();
	      ctor.prototype.constructor = ctor;
	    }
	  };
	}
	return inherits_browser.exports;
}

var isarray$1;
var hasRequiredIsarray$1;

function requireIsarray$1 () {
	if (hasRequiredIsarray$1) return isarray$1;
	hasRequiredIsarray$1 = 1;
	var toString = {}.toString;

	isarray$1 = Array.isArray || function (arr) {
	  return toString.call(arr) == '[object Array]';
	};
	return isarray$1;
}

var streamBrowser$1;
var hasRequiredStreamBrowser$1;

function requireStreamBrowser$1 () {
	if (hasRequiredStreamBrowser$1) return streamBrowser$1;
	hasRequiredStreamBrowser$1 = 1;
	streamBrowser$1 = require$$0$5.EventEmitter;
	return streamBrowser$1;
}

var safeBuffer$1 = {exports: {}};

/* eslint-disable node/no-deprecated-api */

var hasRequiredSafeBuffer$1;

function requireSafeBuffer$1 () {
	if (hasRequiredSafeBuffer$1) return safeBuffer$1.exports;
	hasRequiredSafeBuffer$1 = 1;
	(function (module, exports$1) {
		var buffer = require$$0$4;
		var Buffer = buffer.Buffer;

		// alternative to using Object.keys for old browsers
		function copyProps (src, dst) {
		  for (var key in src) {
		    dst[key] = src[key];
		  }
		}
		if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
		  module.exports = buffer;
		} else {
		  // Copy properties from require('buffer')
		  copyProps(buffer, exports$1);
		  exports$1.Buffer = SafeBuffer;
		}

		function SafeBuffer (arg, encodingOrOffset, length) {
		  return Buffer(arg, encodingOrOffset, length)
		}

		// Copy static methods from Buffer
		copyProps(Buffer, SafeBuffer);

		SafeBuffer.from = function (arg, encodingOrOffset, length) {
		  if (typeof arg === 'number') {
		    throw new TypeError('Argument must not be a number')
		  }
		  return Buffer(arg, encodingOrOffset, length)
		};

		SafeBuffer.alloc = function (size, fill, encoding) {
		  if (typeof size !== 'number') {
		    throw new TypeError('Argument must be a number')
		  }
		  var buf = Buffer(size);
		  if (fill !== undefined) {
		    if (typeof encoding === 'string') {
		      buf.fill(fill, encoding);
		    } else {
		      buf.fill(fill);
		    }
		  } else {
		    buf.fill(0);
		  }
		  return buf
		};

		SafeBuffer.allocUnsafe = function (size) {
		  if (typeof size !== 'number') {
		    throw new TypeError('Argument must be a number')
		  }
		  return Buffer(size)
		};

		SafeBuffer.allocUnsafeSlow = function (size) {
		  if (typeof size !== 'number') {
		    throw new TypeError('Argument must be a number')
		  }
		  return buffer.SlowBuffer(size)
		}; 
	} (safeBuffer$1, safeBuffer$1.exports));
	return safeBuffer$1.exports;
}

var BufferList = {exports: {}};

var hasRequiredBufferList;

function requireBufferList () {
	if (hasRequiredBufferList) return BufferList.exports;
	hasRequiredBufferList = 1;
	(function (module) {

		function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

		var Buffer = requireSafeBuffer$1().Buffer;
		var util = require$$0$6;

		function copyBuffer(src, target, offset) {
		  src.copy(target, offset);
		}

		module.exports = function () {
		  function BufferList() {
		    _classCallCheck(this, BufferList);

		    this.head = null;
		    this.tail = null;
		    this.length = 0;
		  }

		  BufferList.prototype.push = function push(v) {
		    var entry = { data: v, next: null };
		    if (this.length > 0) this.tail.next = entry;else this.head = entry;
		    this.tail = entry;
		    ++this.length;
		  };

		  BufferList.prototype.unshift = function unshift(v) {
		    var entry = { data: v, next: this.head };
		    if (this.length === 0) this.tail = entry;
		    this.head = entry;
		    ++this.length;
		  };

		  BufferList.prototype.shift = function shift() {
		    if (this.length === 0) return;
		    var ret = this.head.data;
		    if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
		    --this.length;
		    return ret;
		  };

		  BufferList.prototype.clear = function clear() {
		    this.head = this.tail = null;
		    this.length = 0;
		  };

		  BufferList.prototype.join = function join(s) {
		    if (this.length === 0) return '';
		    var p = this.head;
		    var ret = '' + p.data;
		    while (p = p.next) {
		      ret += s + p.data;
		    }return ret;
		  };

		  BufferList.prototype.concat = function concat(n) {
		    if (this.length === 0) return Buffer.alloc(0);
		    var ret = Buffer.allocUnsafe(n >>> 0);
		    var p = this.head;
		    var i = 0;
		    while (p) {
		      copyBuffer(p.data, ret, i);
		      i += p.data.length;
		      p = p.next;
		    }
		    return ret;
		  };

		  return BufferList;
		}();

		if (util && util.inspect && util.inspect.custom) {
		  module.exports.prototype[util.inspect.custom] = function () {
		    var obj = util.inspect({ length: this.length });
		    return this.constructor.name + ' ' + obj;
		  };
		} 
	} (BufferList));
	return BufferList.exports;
}

var destroy_1$1;
var hasRequiredDestroy$1;

function requireDestroy$1 () {
	if (hasRequiredDestroy$1) return destroy_1$1;
	hasRequiredDestroy$1 = 1;

	/*<replacement>*/

	var pna = requireProcessNextickArgs();
	/*</replacement>*/

	// undocumented cb() API, needed for core, not for public API
	function destroy(err, cb) {
	  var _this = this;

	  var readableDestroyed = this._readableState && this._readableState.destroyed;
	  var writableDestroyed = this._writableState && this._writableState.destroyed;

	  if (readableDestroyed || writableDestroyed) {
	    if (cb) {
	      cb(err);
	    } else if (err) {
	      if (!this._writableState) {
	        pna.nextTick(emitErrorNT, this, err);
	      } else if (!this._writableState.errorEmitted) {
	        this._writableState.errorEmitted = true;
	        pna.nextTick(emitErrorNT, this, err);
	      }
	    }

	    return this;
	  }

	  // we set destroyed to true before firing error callbacks in order
	  // to make it re-entrance safe in case destroy() is called within callbacks

	  if (this._readableState) {
	    this._readableState.destroyed = true;
	  }

	  // if this is a duplex stream mark the writable part as destroyed as well
	  if (this._writableState) {
	    this._writableState.destroyed = true;
	  }

	  this._destroy(err || null, function (err) {
	    if (!cb && err) {
	      if (!_this._writableState) {
	        pna.nextTick(emitErrorNT, _this, err);
	      } else if (!_this._writableState.errorEmitted) {
	        _this._writableState.errorEmitted = true;
	        pna.nextTick(emitErrorNT, _this, err);
	      }
	    } else if (cb) {
	      cb(err);
	    }
	  });

	  return this;
	}

	function undestroy() {
	  if (this._readableState) {
	    this._readableState.destroyed = false;
	    this._readableState.reading = false;
	    this._readableState.ended = false;
	    this._readableState.endEmitted = false;
	  }

	  if (this._writableState) {
	    this._writableState.destroyed = false;
	    this._writableState.ended = false;
	    this._writableState.ending = false;
	    this._writableState.finalCalled = false;
	    this._writableState.prefinished = false;
	    this._writableState.finished = false;
	    this._writableState.errorEmitted = false;
	  }
	}

	function emitErrorNT(self, err) {
	  self.emit('error', err);
	}

	destroy_1$1 = {
	  destroy: destroy,
	  undestroy: undestroy
	};
	return destroy_1$1;
}

var string_decoder$1 = {};

var hasRequiredString_decoder$1;

function requireString_decoder$1 () {
	if (hasRequiredString_decoder$1) return string_decoder$1;
	hasRequiredString_decoder$1 = 1;

	/*<replacement>*/

	var Buffer = requireSafeBuffer$1().Buffer;
	/*</replacement>*/

	var isEncoding = Buffer.isEncoding || function (encoding) {
	  encoding = '' + encoding;
	  switch (encoding && encoding.toLowerCase()) {
	    case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
	      return true;
	    default:
	      return false;
	  }
	};

	function _normalizeEncoding(enc) {
	  if (!enc) return 'utf8';
	  var retried;
	  while (true) {
	    switch (enc) {
	      case 'utf8':
	      case 'utf-8':
	        return 'utf8';
	      case 'ucs2':
	      case 'ucs-2':
	      case 'utf16le':
	      case 'utf-16le':
	        return 'utf16le';
	      case 'latin1':
	      case 'binary':
	        return 'latin1';
	      case 'base64':
	      case 'ascii':
	      case 'hex':
	        return enc;
	      default:
	        if (retried) return; // undefined
	        enc = ('' + enc).toLowerCase();
	        retried = true;
	    }
	  }
	}
	// Do not cache `Buffer.isEncoding` when checking encoding names as some
	// modules monkey-patch it to support additional encodings
	function normalizeEncoding(enc) {
	  var nenc = _normalizeEncoding(enc);
	  if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
	  return nenc || enc;
	}

	// StringDecoder provides an interface for efficiently splitting a series of
	// buffers into a series of JS strings without breaking apart multi-byte
	// characters.
	string_decoder$1.StringDecoder = StringDecoder;
	function StringDecoder(encoding) {
	  this.encoding = normalizeEncoding(encoding);
	  var nb;
	  switch (this.encoding) {
	    case 'utf16le':
	      this.text = utf16Text;
	      this.end = utf16End;
	      nb = 4;
	      break;
	    case 'utf8':
	      this.fillLast = utf8FillLast;
	      nb = 4;
	      break;
	    case 'base64':
	      this.text = base64Text;
	      this.end = base64End;
	      nb = 3;
	      break;
	    default:
	      this.write = simpleWrite;
	      this.end = simpleEnd;
	      return;
	  }
	  this.lastNeed = 0;
	  this.lastTotal = 0;
	  this.lastChar = Buffer.allocUnsafe(nb);
	}

	StringDecoder.prototype.write = function (buf) {
	  if (buf.length === 0) return '';
	  var r;
	  var i;
	  if (this.lastNeed) {
	    r = this.fillLast(buf);
	    if (r === undefined) return '';
	    i = this.lastNeed;
	    this.lastNeed = 0;
	  } else {
	    i = 0;
	  }
	  if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
	  return r || '';
	};

	StringDecoder.prototype.end = utf8End;

	// Returns only complete characters in a Buffer
	StringDecoder.prototype.text = utf8Text;

	// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
	StringDecoder.prototype.fillLast = function (buf) {
	  if (this.lastNeed <= buf.length) {
	    buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
	    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
	  }
	  buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
	  this.lastNeed -= buf.length;
	};

	// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
	// continuation byte. If an invalid byte is detected, -2 is returned.
	function utf8CheckByte(byte) {
	  if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
	  return byte >> 6 === 0x02 ? -1 : -2;
	}

	// Checks at most 3 bytes at the end of a Buffer in order to detect an
	// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
	// needed to complete the UTF-8 character (if applicable) are returned.
	function utf8CheckIncomplete(self, buf, i) {
	  var j = buf.length - 1;
	  if (j < i) return 0;
	  var nb = utf8CheckByte(buf[j]);
	  if (nb >= 0) {
	    if (nb > 0) self.lastNeed = nb - 1;
	    return nb;
	  }
	  if (--j < i || nb === -2) return 0;
	  nb = utf8CheckByte(buf[j]);
	  if (nb >= 0) {
	    if (nb > 0) self.lastNeed = nb - 2;
	    return nb;
	  }
	  if (--j < i || nb === -2) return 0;
	  nb = utf8CheckByte(buf[j]);
	  if (nb >= 0) {
	    if (nb > 0) {
	      if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
	    }
	    return nb;
	  }
	  return 0;
	}

	// Validates as many continuation bytes for a multi-byte UTF-8 character as
	// needed or are available. If we see a non-continuation byte where we expect
	// one, we "replace" the validated continuation bytes we've seen so far with
	// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
	// behavior. The continuation byte check is included three times in the case
	// where all of the continuation bytes for a character exist in the same buffer.
	// It is also done this way as a slight performance increase instead of using a
	// loop.
	function utf8CheckExtraBytes(self, buf, p) {
	  if ((buf[0] & 0xC0) !== 0x80) {
	    self.lastNeed = 0;
	    return '\ufffd';
	  }
	  if (self.lastNeed > 1 && buf.length > 1) {
	    if ((buf[1] & 0xC0) !== 0x80) {
	      self.lastNeed = 1;
	      return '\ufffd';
	    }
	    if (self.lastNeed > 2 && buf.length > 2) {
	      if ((buf[2] & 0xC0) !== 0x80) {
	        self.lastNeed = 2;
	        return '\ufffd';
	      }
	    }
	  }
	}

	// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
	function utf8FillLast(buf) {
	  var p = this.lastTotal - this.lastNeed;
	  var r = utf8CheckExtraBytes(this, buf);
	  if (r !== undefined) return r;
	  if (this.lastNeed <= buf.length) {
	    buf.copy(this.lastChar, p, 0, this.lastNeed);
	    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
	  }
	  buf.copy(this.lastChar, p, 0, buf.length);
	  this.lastNeed -= buf.length;
	}

	// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
	// partial character, the character's bytes are buffered until the required
	// number of bytes are available.
	function utf8Text(buf, i) {
	  var total = utf8CheckIncomplete(this, buf, i);
	  if (!this.lastNeed) return buf.toString('utf8', i);
	  this.lastTotal = total;
	  var end = buf.length - (total - this.lastNeed);
	  buf.copy(this.lastChar, 0, end);
	  return buf.toString('utf8', i, end);
	}

	// For UTF-8, a replacement character is added when ending on a partial
	// character.
	function utf8End(buf) {
	  var r = buf && buf.length ? this.write(buf) : '';
	  if (this.lastNeed) return r + '\ufffd';
	  return r;
	}

	// UTF-16LE typically needs two bytes per character, but even if we have an even
	// number of bytes available, we need to check if we end on a leading/high
	// surrogate. In that case, we need to wait for the next two bytes in order to
	// decode the last character properly.
	function utf16Text(buf, i) {
	  if ((buf.length - i) % 2 === 0) {
	    var r = buf.toString('utf16le', i);
	    if (r) {
	      var c = r.charCodeAt(r.length - 1);
	      if (c >= 0xD800 && c <= 0xDBFF) {
	        this.lastNeed = 2;
	        this.lastTotal = 4;
	        this.lastChar[0] = buf[buf.length - 2];
	        this.lastChar[1] = buf[buf.length - 1];
	        return r.slice(0, -1);
	      }
	    }
	    return r;
	  }
	  this.lastNeed = 1;
	  this.lastTotal = 2;
	  this.lastChar[0] = buf[buf.length - 1];
	  return buf.toString('utf16le', i, buf.length - 1);
	}

	// For UTF-16LE we do not explicitly append special replacement characters if we
	// end on a partial character, we simply let v8 handle that.
	function utf16End(buf) {
	  var r = buf && buf.length ? this.write(buf) : '';
	  if (this.lastNeed) {
	    var end = this.lastTotal - this.lastNeed;
	    return r + this.lastChar.toString('utf16le', 0, end);
	  }
	  return r;
	}

	function base64Text(buf, i) {
	  var n = (buf.length - i) % 3;
	  if (n === 0) return buf.toString('base64', i);
	  this.lastNeed = 3 - n;
	  this.lastTotal = 3;
	  if (n === 1) {
	    this.lastChar[0] = buf[buf.length - 1];
	  } else {
	    this.lastChar[0] = buf[buf.length - 2];
	    this.lastChar[1] = buf[buf.length - 1];
	  }
	  return buf.toString('base64', i, buf.length - n);
	}

	function base64End(buf) {
	  var r = buf && buf.length ? this.write(buf) : '';
	  if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
	  return r;
	}

	// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
	function simpleWrite(buf) {
	  return buf.toString(this.encoding);
	}

	function simpleEnd(buf) {
	  return buf && buf.length ? this.write(buf) : '';
	}
	return string_decoder$1;
}

var _stream_readable$1;
var hasRequired_stream_readable$1;

function require_stream_readable$1 () {
	if (hasRequired_stream_readable$1) return _stream_readable$1;
	hasRequired_stream_readable$1 = 1;

	/*<replacement>*/

	var pna = requireProcessNextickArgs();
	/*</replacement>*/

	_stream_readable$1 = Readable;

	/*<replacement>*/
	var isArray = requireIsarray$1();
	/*</replacement>*/

	/*<replacement>*/
	var Duplex;
	/*</replacement>*/

	Readable.ReadableState = ReadableState;

	/*<replacement>*/
	require$$0$5.EventEmitter;

	var EElistenerCount = function (emitter, type) {
	  return emitter.listeners(type).length;
	};
	/*</replacement>*/

	/*<replacement>*/
	var Stream = requireStreamBrowser$1();
	/*</replacement>*/

	/*<replacement>*/

	var Buffer = requireSafeBuffer$1().Buffer;
	var OurUint8Array = (typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
	function _uint8ArrayToBuffer(chunk) {
	  return Buffer.from(chunk);
	}
	function _isUint8Array(obj) {
	  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
	}

	/*</replacement>*/

	/*<replacement>*/
	var util = Object.create(requireUtil$2());
	util.inherits = requireInherits_browser();
	/*</replacement>*/

	/*<replacement>*/
	var debugUtil = require$$0$6;
	var debug = void 0;
	if (debugUtil && debugUtil.debuglog) {
	  debug = debugUtil.debuglog('stream');
	} else {
	  debug = function () {};
	}
	/*</replacement>*/

	var BufferList = requireBufferList();
	var destroyImpl = requireDestroy$1();
	var StringDecoder;

	util.inherits(Readable, Stream);

	var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];

	function prependListener(emitter, event, fn) {
	  // Sadly this is not cacheable as some libraries bundle their own
	  // event emitter implementation with them.
	  if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);

	  // This is a hack to make sure that our error handler is attached before any
	  // userland ones.  NEVER DO THIS. This is here only because this code needs
	  // to continue to work with older versions of Node.js that do not include
	  // the prependListener() method. The goal is to eventually remove this hack.
	  if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
	}

	function ReadableState(options, stream) {
	  Duplex = Duplex || require_stream_duplex$1();

	  options = options || {};

	  // Duplex streams are both readable and writable, but share
	  // the same options object.
	  // However, some cases require setting options to different
	  // values for the readable and the writable sides of the duplex stream.
	  // These options can be provided separately as readableXXX and writableXXX.
	  var isDuplex = stream instanceof Duplex;

	  // object stream flag. Used to make read(n) ignore n and to
	  // make all the buffer merging and length checks go away
	  this.objectMode = !!options.objectMode;

	  if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;

	  // the point at which it stops calling _read() to fill the buffer
	  // Note: 0 is a valid value, means "don't call _read preemptively ever"
	  var hwm = options.highWaterMark;
	  var readableHwm = options.readableHighWaterMark;
	  var defaultHwm = this.objectMode ? 16 : 16 * 1024;

	  if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;

	  // cast to ints.
	  this.highWaterMark = Math.floor(this.highWaterMark);

	  // A linked list is used to store data chunks instead of an array because the
	  // linked list can remove elements from the beginning faster than
	  // array.shift()
	  this.buffer = new BufferList();
	  this.length = 0;
	  this.pipes = null;
	  this.pipesCount = 0;
	  this.flowing = null;
	  this.ended = false;
	  this.endEmitted = false;
	  this.reading = false;

	  // a flag to be able to tell if the event 'readable'/'data' is emitted
	  // immediately, or on a later tick.  We set this to true at first, because
	  // any actions that shouldn't happen until "later" should generally also
	  // not happen before the first read call.
	  this.sync = true;

	  // whenever we return null, then we set a flag to say
	  // that we're awaiting a 'readable' event emission.
	  this.needReadable = false;
	  this.emittedReadable = false;
	  this.readableListening = false;
	  this.resumeScheduled = false;

	  // has it been destroyed
	  this.destroyed = false;

	  // Crypto is kind of old and crusty.  Historically, its default string
	  // encoding is 'binary' so we have to make this configurable.
	  // Everything else in the universe uses 'utf8', though.
	  this.defaultEncoding = options.defaultEncoding || 'utf8';

	  // the number of writers that are awaiting a drain event in .pipe()s
	  this.awaitDrain = 0;

	  // if true, a maybeReadMore has been scheduled
	  this.readingMore = false;

	  this.decoder = null;
	  this.encoding = null;
	  if (options.encoding) {
	    if (!StringDecoder) StringDecoder = requireString_decoder$1().StringDecoder;
	    this.decoder = new StringDecoder(options.encoding);
	    this.encoding = options.encoding;
	  }
	}

	function Readable(options) {
	  Duplex = Duplex || require_stream_duplex$1();

	  if (!(this instanceof Readable)) return new Readable(options);

	  this._readableState = new ReadableState(options, this);

	  // legacy
	  this.readable = true;

	  if (options) {
	    if (typeof options.read === 'function') this._read = options.read;

	    if (typeof options.destroy === 'function') this._destroy = options.destroy;
	  }

	  Stream.call(this);
	}

	Object.defineProperty(Readable.prototype, 'destroyed', {
	  get: function () {
	    if (this._readableState === undefined) {
	      return false;
	    }
	    return this._readableState.destroyed;
	  },
	  set: function (value) {
	    // we ignore the value if the stream
	    // has not been initialized yet
	    if (!this._readableState) {
	      return;
	    }

	    // backward compatibility, the user is explicitly
	    // managing destroyed
	    this._readableState.destroyed = value;
	  }
	});

	Readable.prototype.destroy = destroyImpl.destroy;
	Readable.prototype._undestroy = destroyImpl.undestroy;
	Readable.prototype._destroy = function (err, cb) {
	  this.push(null);
	  cb(err);
	};

	// Manually shove something into the read() buffer.
	// This returns true if the highWaterMark has not been hit yet,
	// similar to how Writable.write() returns true if you should
	// write() some more.
	Readable.prototype.push = function (chunk, encoding) {
	  var state = this._readableState;
	  var skipChunkCheck;

	  if (!state.objectMode) {
	    if (typeof chunk === 'string') {
	      encoding = encoding || state.defaultEncoding;
	      if (encoding !== state.encoding) {
	        chunk = Buffer.from(chunk, encoding);
	        encoding = '';
	      }
	      skipChunkCheck = true;
	    }
	  } else {
	    skipChunkCheck = true;
	  }

	  return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
	};

	// Unshift should *always* be something directly out of read()
	Readable.prototype.unshift = function (chunk) {
	  return readableAddChunk(this, chunk, null, true, false);
	};

	function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
	  var state = stream._readableState;
	  if (chunk === null) {
	    state.reading = false;
	    onEofChunk(stream, state);
	  } else {
	    var er;
	    if (!skipChunkCheck) er = chunkInvalid(state, chunk);
	    if (er) {
	      stream.emit('error', er);
	    } else if (state.objectMode || chunk && chunk.length > 0) {
	      if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
	        chunk = _uint8ArrayToBuffer(chunk);
	      }

	      if (addToFront) {
	        if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
	      } else if (state.ended) {
	        stream.emit('error', new Error('stream.push() after EOF'));
	      } else {
	        state.reading = false;
	        if (state.decoder && !encoding) {
	          chunk = state.decoder.write(chunk);
	          if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
	        } else {
	          addChunk(stream, state, chunk, false);
	        }
	      }
	    } else if (!addToFront) {
	      state.reading = false;
	    }
	  }

	  return needMoreData(state);
	}

	function addChunk(stream, state, chunk, addToFront) {
	  if (state.flowing && state.length === 0 && !state.sync) {
	    stream.emit('data', chunk);
	    stream.read(0);
	  } else {
	    // update the buffer info.
	    state.length += state.objectMode ? 1 : chunk.length;
	    if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);

	    if (state.needReadable) emitReadable(stream);
	  }
	  maybeReadMore(stream, state);
	}

	function chunkInvalid(state, chunk) {
	  var er;
	  if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
	    er = new TypeError('Invalid non-string/buffer chunk');
	  }
	  return er;
	}

	// if it's past the high water mark, we can push in some more.
	// Also, if we have no data yet, we can stand some
	// more bytes.  This is to work around cases where hwm=0,
	// such as the repl.  Also, if the push() triggered a
	// readable event, and the user called read(largeNumber) such that
	// needReadable was set, then we ought to push more, so that another
	// 'readable' event will be triggered.
	function needMoreData(state) {
	  return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
	}

	Readable.prototype.isPaused = function () {
	  return this._readableState.flowing === false;
	};

	// backwards compatibility.
	Readable.prototype.setEncoding = function (enc) {
	  if (!StringDecoder) StringDecoder = requireString_decoder$1().StringDecoder;
	  this._readableState.decoder = new StringDecoder(enc);
	  this._readableState.encoding = enc;
	  return this;
	};

	// Don't raise the hwm > 8MB
	var MAX_HWM = 0x800000;
	function computeNewHighWaterMark(n) {
	  if (n >= MAX_HWM) {
	    n = MAX_HWM;
	  } else {
	    // Get the next highest power of 2 to prevent increasing hwm excessively in
	    // tiny amounts
	    n--;
	    n |= n >>> 1;
	    n |= n >>> 2;
	    n |= n >>> 4;
	    n |= n >>> 8;
	    n |= n >>> 16;
	    n++;
	  }
	  return n;
	}

	// This function is designed to be inlinable, so please take care when making
	// changes to the function body.
	function howMuchToRead(n, state) {
	  if (n <= 0 || state.length === 0 && state.ended) return 0;
	  if (state.objectMode) return 1;
	  if (n !== n) {
	    // Only flow one buffer at a time
	    if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
	  }
	  // If we're asking for more than the current hwm, then raise the hwm.
	  if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
	  if (n <= state.length) return n;
	  // Don't have enough
	  if (!state.ended) {
	    state.needReadable = true;
	    return 0;
	  }
	  return state.length;
	}

	// you can override either this method, or the async _read(n) below.
	Readable.prototype.read = function (n) {
	  debug('read', n);
	  n = parseInt(n, 10);
	  var state = this._readableState;
	  var nOrig = n;

	  if (n !== 0) state.emittedReadable = false;

	  // if we're doing read(0) to trigger a readable event, but we
	  // already have a bunch of data in the buffer, then just trigger
	  // the 'readable' event and move on.
	  if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
	    debug('read: emitReadable', state.length, state.ended);
	    if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
	    return null;
	  }

	  n = howMuchToRead(n, state);

	  // if we've ended, and we're now clear, then finish it up.
	  if (n === 0 && state.ended) {
	    if (state.length === 0) endReadable(this);
	    return null;
	  }

	  // All the actual chunk generation logic needs to be
	  // *below* the call to _read.  The reason is that in certain
	  // synthetic stream cases, such as passthrough streams, _read
	  // may be a completely synchronous operation which may change
	  // the state of the read buffer, providing enough data when
	  // before there was *not* enough.
	  //
	  // So, the steps are:
	  // 1. Figure out what the state of things will be after we do
	  // a read from the buffer.
	  //
	  // 2. If that resulting state will trigger a _read, then call _read.
	  // Note that this may be asynchronous, or synchronous.  Yes, it is
	  // deeply ugly to write APIs this way, but that still doesn't mean
	  // that the Readable class should behave improperly, as streams are
	  // designed to be sync/async agnostic.
	  // Take note if the _read call is sync or async (ie, if the read call
	  // has returned yet), so that we know whether or not it's safe to emit
	  // 'readable' etc.
	  //
	  // 3. Actually pull the requested chunks out of the buffer and return.

	  // if we need a readable event, then we need to do some reading.
	  var doRead = state.needReadable;
	  debug('need readable', doRead);

	  // if we currently have less than the highWaterMark, then also read some
	  if (state.length === 0 || state.length - n < state.highWaterMark) {
	    doRead = true;
	    debug('length less than watermark', doRead);
	  }

	  // however, if we've ended, then there's no point, and if we're already
	  // reading, then it's unnecessary.
	  if (state.ended || state.reading) {
	    doRead = false;
	    debug('reading or ended', doRead);
	  } else if (doRead) {
	    debug('do read');
	    state.reading = true;
	    state.sync = true;
	    // if the length is currently zero, then we *need* a readable event.
	    if (state.length === 0) state.needReadable = true;
	    // call internal read method
	    this._read(state.highWaterMark);
	    state.sync = false;
	    // If _read pushed data synchronously, then `reading` will be false,
	    // and we need to re-evaluate how much data we can return to the user.
	    if (!state.reading) n = howMuchToRead(nOrig, state);
	  }

	  var ret;
	  if (n > 0) ret = fromList(n, state);else ret = null;

	  if (ret === null) {
	    state.needReadable = true;
	    n = 0;
	  } else {
	    state.length -= n;
	  }

	  if (state.length === 0) {
	    // If we have nothing in the buffer, then we want to know
	    // as soon as we *do* get something into the buffer.
	    if (!state.ended) state.needReadable = true;

	    // If we tried to read() past the EOF, then emit end on the next tick.
	    if (nOrig !== n && state.ended) endReadable(this);
	  }

	  if (ret !== null) this.emit('data', ret);

	  return ret;
	};

	function onEofChunk(stream, state) {
	  if (state.ended) return;
	  if (state.decoder) {
	    var chunk = state.decoder.end();
	    if (chunk && chunk.length) {
	      state.buffer.push(chunk);
	      state.length += state.objectMode ? 1 : chunk.length;
	    }
	  }
	  state.ended = true;

	  // emit 'readable' now to make sure it gets picked up.
	  emitReadable(stream);
	}

	// Don't emit readable right away in sync mode, because this can trigger
	// another read() call => stack overflow.  This way, it might trigger
	// a nextTick recursion warning, but that's not so bad.
	function emitReadable(stream) {
	  var state = stream._readableState;
	  state.needReadable = false;
	  if (!state.emittedReadable) {
	    debug('emitReadable', state.flowing);
	    state.emittedReadable = true;
	    if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
	  }
	}

	function emitReadable_(stream) {
	  debug('emit readable');
	  stream.emit('readable');
	  flow(stream);
	}

	// at this point, the user has presumably seen the 'readable' event,
	// and called read() to consume some data.  that may have triggered
	// in turn another _read(n) call, in which case reading = true if
	// it's in progress.
	// However, if we're not ended, or reading, and the length < hwm,
	// then go ahead and try to read some more preemptively.
	function maybeReadMore(stream, state) {
	  if (!state.readingMore) {
	    state.readingMore = true;
	    pna.nextTick(maybeReadMore_, stream, state);
	  }
	}

	function maybeReadMore_(stream, state) {
	  var len = state.length;
	  while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
	    debug('maybeReadMore read 0');
	    stream.read(0);
	    if (len === state.length)
	      // didn't get any data, stop spinning.
	      break;else len = state.length;
	  }
	  state.readingMore = false;
	}

	// abstract method.  to be overridden in specific implementation classes.
	// call cb(er, data) where data is <= n in length.
	// for virtual (non-string, non-buffer) streams, "length" is somewhat
	// arbitrary, and perhaps not very meaningful.
	Readable.prototype._read = function (n) {
	  this.emit('error', new Error('_read() is not implemented'));
	};

	Readable.prototype.pipe = function (dest, pipeOpts) {
	  var src = this;
	  var state = this._readableState;

	  switch (state.pipesCount) {
	    case 0:
	      state.pipes = dest;
	      break;
	    case 1:
	      state.pipes = [state.pipes, dest];
	      break;
	    default:
	      state.pipes.push(dest);
	      break;
	  }
	  state.pipesCount += 1;
	  debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);

	  var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;

	  var endFn = doEnd ? onend : unpipe;
	  if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);

	  dest.on('unpipe', onunpipe);
	  function onunpipe(readable, unpipeInfo) {
	    debug('onunpipe');
	    if (readable === src) {
	      if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
	        unpipeInfo.hasUnpiped = true;
	        cleanup();
	      }
	    }
	  }

	  function onend() {
	    debug('onend');
	    dest.end();
	  }

	  // when the dest drains, it reduces the awaitDrain counter
	  // on the source.  This would be more elegant with a .once()
	  // handler in flow(), but adding and removing repeatedly is
	  // too slow.
	  var ondrain = pipeOnDrain(src);
	  dest.on('drain', ondrain);

	  var cleanedUp = false;
	  function cleanup() {
	    debug('cleanup');
	    // cleanup event handlers once the pipe is broken
	    dest.removeListener('close', onclose);
	    dest.removeListener('finish', onfinish);
	    dest.removeListener('drain', ondrain);
	    dest.removeListener('error', onerror);
	    dest.removeListener('unpipe', onunpipe);
	    src.removeListener('end', onend);
	    src.removeListener('end', unpipe);
	    src.removeListener('data', ondata);

	    cleanedUp = true;

	    // if the reader is waiting for a drain event from this
	    // specific writer, then it would cause it to never start
	    // flowing again.
	    // So, if this is awaiting a drain, then we just call it now.
	    // If we don't know, then assume that we are waiting for one.
	    if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
	  }

	  // If the user pushes more data while we're writing to dest then we'll end up
	  // in ondata again. However, we only want to increase awaitDrain once because
	  // dest will only emit one 'drain' event for the multiple writes.
	  // => Introduce a guard on increasing awaitDrain.
	  var increasedAwaitDrain = false;
	  src.on('data', ondata);
	  function ondata(chunk) {
	    debug('ondata');
	    increasedAwaitDrain = false;
	    var ret = dest.write(chunk);
	    if (false === ret && !increasedAwaitDrain) {
	      // If the user unpiped during `dest.write()`, it is possible
	      // to get stuck in a permanently paused state if that write
	      // also returned false.
	      // => Check whether `dest` is still a piping destination.
	      if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
	        debug('false write response, pause', state.awaitDrain);
	        state.awaitDrain++;
	        increasedAwaitDrain = true;
	      }
	      src.pause();
	    }
	  }

	  // if the dest has an error, then stop piping into it.
	  // however, don't suppress the throwing behavior for this.
	  function onerror(er) {
	    debug('onerror', er);
	    unpipe();
	    dest.removeListener('error', onerror);
	    if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
	  }

	  // Make sure our error handler is attached before userland ones.
	  prependListener(dest, 'error', onerror);

	  // Both close and finish should trigger unpipe, but only once.
	  function onclose() {
	    dest.removeListener('finish', onfinish);
	    unpipe();
	  }
	  dest.once('close', onclose);
	  function onfinish() {
	    debug('onfinish');
	    dest.removeListener('close', onclose);
	    unpipe();
	  }
	  dest.once('finish', onfinish);

	  function unpipe() {
	    debug('unpipe');
	    src.unpipe(dest);
	  }

	  // tell the dest that it's being piped to
	  dest.emit('pipe', src);

	  // start the flow if it hasn't been started already.
	  if (!state.flowing) {
	    debug('pipe resume');
	    src.resume();
	  }

	  return dest;
	};

	function pipeOnDrain(src) {
	  return function () {
	    var state = src._readableState;
	    debug('pipeOnDrain', state.awaitDrain);
	    if (state.awaitDrain) state.awaitDrain--;
	    if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
	      state.flowing = true;
	      flow(src);
	    }
	  };
	}

	Readable.prototype.unpipe = function (dest) {
	  var state = this._readableState;
	  var unpipeInfo = { hasUnpiped: false };

	  // if we're not piping anywhere, then do nothing.
	  if (state.pipesCount === 0) return this;

	  // just one destination.  most common case.
	  if (state.pipesCount === 1) {
	    // passed in one, but it's not the right one.
	    if (dest && dest !== state.pipes) return this;

	    if (!dest) dest = state.pipes;

	    // got a match.
	    state.pipes = null;
	    state.pipesCount = 0;
	    state.flowing = false;
	    if (dest) dest.emit('unpipe', this, unpipeInfo);
	    return this;
	  }

	  // slow case. multiple pipe destinations.

	  if (!dest) {
	    // remove all.
	    var dests = state.pipes;
	    var len = state.pipesCount;
	    state.pipes = null;
	    state.pipesCount = 0;
	    state.flowing = false;

	    for (var i = 0; i < len; i++) {
	      dests[i].emit('unpipe', this, { hasUnpiped: false });
	    }return this;
	  }

	  // try to find the right one.
	  var index = indexOf(state.pipes, dest);
	  if (index === -1) return this;

	  state.pipes.splice(index, 1);
	  state.pipesCount -= 1;
	  if (state.pipesCount === 1) state.pipes = state.pipes[0];

	  dest.emit('unpipe', this, unpipeInfo);

	  return this;
	};

	// set up data events if they are asked for
	// Ensure readable listeners eventually get something
	Readable.prototype.on = function (ev, fn) {
	  var res = Stream.prototype.on.call(this, ev, fn);

	  if (ev === 'data') {
	    // Start flowing on next tick if stream isn't explicitly paused
	    if (this._readableState.flowing !== false) this.resume();
	  } else if (ev === 'readable') {
	    var state = this._readableState;
	    if (!state.endEmitted && !state.readableListening) {
	      state.readableListening = state.needReadable = true;
	      state.emittedReadable = false;
	      if (!state.reading) {
	        pna.nextTick(nReadingNextTick, this);
	      } else if (state.length) {
	        emitReadable(this);
	      }
	    }
	  }

	  return res;
	};
	Readable.prototype.addListener = Readable.prototype.on;

	function nReadingNextTick(self) {
	  debug('readable nexttick read 0');
	  self.read(0);
	}

	// pause() and resume() are remnants of the legacy readable stream API
	// If the user uses them, then switch into old mode.
	Readable.prototype.resume = function () {
	  var state = this._readableState;
	  if (!state.flowing) {
	    debug('resume');
	    state.flowing = true;
	    resume(this, state);
	  }
	  return this;
	};

	function resume(stream, state) {
	  if (!state.resumeScheduled) {
	    state.resumeScheduled = true;
	    pna.nextTick(resume_, stream, state);
	  }
	}

	function resume_(stream, state) {
	  if (!state.reading) {
	    debug('resume read 0');
	    stream.read(0);
	  }

	  state.resumeScheduled = false;
	  state.awaitDrain = 0;
	  stream.emit('resume');
	  flow(stream);
	  if (state.flowing && !state.reading) stream.read(0);
	}

	Readable.prototype.pause = function () {
	  debug('call pause flowing=%j', this._readableState.flowing);
	  if (false !== this._readableState.flowing) {
	    debug('pause');
	    this._readableState.flowing = false;
	    this.emit('pause');
	  }
	  return this;
	};

	function flow(stream) {
	  var state = stream._readableState;
	  debug('flow', state.flowing);
	  while (state.flowing && stream.read() !== null) {}
	}

	// wrap an old-style stream as the async data source.
	// This is *not* part of the readable stream interface.
	// It is an ugly unfortunate mess of history.
	Readable.prototype.wrap = function (stream) {
	  var _this = this;

	  var state = this._readableState;
	  var paused = false;

	  stream.on('end', function () {
	    debug('wrapped end');
	    if (state.decoder && !state.ended) {
	      var chunk = state.decoder.end();
	      if (chunk && chunk.length) _this.push(chunk);
	    }

	    _this.push(null);
	  });

	  stream.on('data', function (chunk) {
	    debug('wrapped data');
	    if (state.decoder) chunk = state.decoder.write(chunk);

	    // don't skip over falsy values in objectMode
	    if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;

	    var ret = _this.push(chunk);
	    if (!ret) {
	      paused = true;
	      stream.pause();
	    }
	  });

	  // proxy all the other methods.
	  // important when wrapping filters and duplexes.
	  for (var i in stream) {
	    if (this[i] === undefined && typeof stream[i] === 'function') {
	      this[i] = function (method) {
	        return function () {
	          return stream[method].apply(stream, arguments);
	        };
	      }(i);
	    }
	  }

	  // proxy certain important events.
	  for (var n = 0; n < kProxyEvents.length; n++) {
	    stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
	  }

	  // when we try to consume some more bytes, simply unpause the
	  // underlying stream.
	  this._read = function (n) {
	    debug('wrapped _read', n);
	    if (paused) {
	      paused = false;
	      stream.resume();
	    }
	  };

	  return this;
	};

	Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
	  // making it explicit this property is not enumerable
	  // because otherwise some prototype manipulation in
	  // userland will fail
	  enumerable: false,
	  get: function () {
	    return this._readableState.highWaterMark;
	  }
	});

	// exposed for testing purposes only.
	Readable._fromList = fromList;

	// Pluck off n bytes from an array of buffers.
	// Length is the combined lengths of all the buffers in the list.
	// This function is designed to be inlinable, so please take care when making
	// changes to the function body.
	function fromList(n, state) {
	  // nothing buffered
	  if (state.length === 0) return null;

	  var ret;
	  if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
	    // read it all, truncate the list
	    if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
	    state.buffer.clear();
	  } else {
	    // read part of list
	    ret = fromListPartial(n, state.buffer, state.decoder);
	  }

	  return ret;
	}

	// Extracts only enough buffered data to satisfy the amount requested.
	// This function is designed to be inlinable, so please take care when making
	// changes to the function body.
	function fromListPartial(n, list, hasStrings) {
	  var ret;
	  if (n < list.head.data.length) {
	    // slice is the same for buffers and strings
	    ret = list.head.data.slice(0, n);
	    list.head.data = list.head.data.slice(n);
	  } else if (n === list.head.data.length) {
	    // first chunk is a perfect match
	    ret = list.shift();
	  } else {
	    // result spans more than one buffer
	    ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
	  }
	  return ret;
	}

	// Copies a specified amount of characters from the list of buffered data
	// chunks.
	// This function is designed to be inlinable, so please take care when making
	// changes to the function body.
	function copyFromBufferString(n, list) {
	  var p = list.head;
	  var c = 1;
	  var ret = p.data;
	  n -= ret.length;
	  while (p = p.next) {
	    var str = p.data;
	    var nb = n > str.length ? str.length : n;
	    if (nb === str.length) ret += str;else ret += str.slice(0, n);
	    n -= nb;
	    if (n === 0) {
	      if (nb === str.length) {
	        ++c;
	        if (p.next) list.head = p.next;else list.head = list.tail = null;
	      } else {
	        list.head = p;
	        p.data = str.slice(nb);
	      }
	      break;
	    }
	    ++c;
	  }
	  list.length -= c;
	  return ret;
	}

	// Copies a specified amount of bytes from the list of buffered data chunks.
	// This function is designed to be inlinable, so please take care when making
	// changes to the function body.
	function copyFromBuffer(n, list) {
	  var ret = Buffer.allocUnsafe(n);
	  var p = list.head;
	  var c = 1;
	  p.data.copy(ret);
	  n -= p.data.length;
	  while (p = p.next) {
	    var buf = p.data;
	    var nb = n > buf.length ? buf.length : n;
	    buf.copy(ret, ret.length - n, 0, nb);
	    n -= nb;
	    if (n === 0) {
	      if (nb === buf.length) {
	        ++c;
	        if (p.next) list.head = p.next;else list.head = list.tail = null;
	      } else {
	        list.head = p;
	        p.data = buf.slice(nb);
	      }
	      break;
	    }
	    ++c;
	  }
	  list.length -= c;
	  return ret;
	}

	function endReadable(stream) {
	  var state = stream._readableState;

	  // If we get here before consuming all the bytes, then that is a
	  // bug in node.  Should never happen.
	  if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');

	  if (!state.endEmitted) {
	    state.ended = true;
	    pna.nextTick(endReadableNT, state, stream);
	  }
	}

	function endReadableNT(state, stream) {
	  // Check that we didn't get one last unshift.
	  if (!state.endEmitted && state.length === 0) {
	    state.endEmitted = true;
	    stream.readable = false;
	    stream.emit('end');
	  }
	}

	function indexOf(xs, x) {
	  for (var i = 0, l = xs.length; i < l; i++) {
	    if (xs[i] === x) return i;
	  }
	  return -1;
	}
	return _stream_readable$1;
}

var browser$4;
var hasRequiredBrowser$4;

function requireBrowser$4 () {
	if (hasRequiredBrowser$4) return browser$4;
	hasRequiredBrowser$4 = 1;
	/**
	 * Module exports.
	 */

	browser$4 = deprecate;

	/**
	 * Mark that a method should not be used.
	 * Returns a modified function which warns once by default.
	 *
	 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
	 *
	 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
	 * will throw an Error when invoked.
	 *
	 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
	 * will invoke `console.trace()` instead of `console.error()`.
	 *
	 * @param {Function} fn - the function to deprecate
	 * @param {String} msg - the string to print to the console when `fn` is invoked
	 * @returns {Function} a new "deprecated" version of `fn`
	 * @api public
	 */

	function deprecate (fn, msg) {
	  if (config('noDeprecation')) {
	    return fn;
	  }

	  var warned = false;
	  function deprecated() {
	    if (!warned) {
	      if (config('throwDeprecation')) {
	        throw new Error(msg);
	      } else if (config('traceDeprecation')) {
	        console.trace(msg);
	      } else {
	        console.warn(msg);
	      }
	      warned = true;
	    }
	    return fn.apply(this, arguments);
	  }

	  return deprecated;
	}

	/**
	 * Checks `localStorage` for boolean values for the given `name`.
	 *
	 * @param {String} name
	 * @returns {Boolean}
	 * @api private
	 */

	function config (name) {
	  // accessing global.localStorage can trigger a DOMException in sandboxed iframes
	  try {
	    if (!commonjsGlobal.localStorage) return false;
	  } catch (_) {
	    return false;
	  }
	  var val = commonjsGlobal.localStorage[name];
	  if (null == val) return false;
	  return String(val).toLowerCase() === 'true';
	}
	return browser$4;
}

var _stream_writable$1;
var hasRequired_stream_writable$1;

function require_stream_writable$1 () {
	if (hasRequired_stream_writable$1) return _stream_writable$1;
	hasRequired_stream_writable$1 = 1;

	/*<replacement>*/

	var pna = requireProcessNextickArgs();
	/*</replacement>*/

	_stream_writable$1 = Writable;

	// It seems a linked list but it is not
	// there will be only 2 of these for each stream
	function CorkedRequest(state) {
	  var _this = this;

	  this.next = null;
	  this.entry = null;
	  this.finish = function () {
	    onCorkedFinish(_this, state);
	  };
	}
	/* </replacement> */

	/*<replacement>*/
	var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
	/*</replacement>*/

	/*<replacement>*/
	var Duplex;
	/*</replacement>*/

	Writable.WritableState = WritableState;

	/*<replacement>*/
	var util = Object.create(requireUtil$2());
	util.inherits = requireInherits_browser();
	/*</replacement>*/

	/*<replacement>*/
	var internalUtil = {
	  deprecate: requireBrowser$4()
	};
	/*</replacement>*/

	/*<replacement>*/
	var Stream = requireStreamBrowser$1();
	/*</replacement>*/

	/*<replacement>*/

	var Buffer = requireSafeBuffer$1().Buffer;
	var OurUint8Array = (typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
	function _uint8ArrayToBuffer(chunk) {
	  return Buffer.from(chunk);
	}
	function _isUint8Array(obj) {
	  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
	}

	/*</replacement>*/

	var destroyImpl = requireDestroy$1();

	util.inherits(Writable, Stream);

	function nop() {}

	function WritableState(options, stream) {
	  Duplex = Duplex || require_stream_duplex$1();

	  options = options || {};

	  // Duplex streams are both readable and writable, but share
	  // the same options object.
	  // However, some cases require setting options to different
	  // values for the readable and the writable sides of the duplex stream.
	  // These options can be provided separately as readableXXX and writableXXX.
	  var isDuplex = stream instanceof Duplex;

	  // object stream flag to indicate whether or not this stream
	  // contains buffers or objects.
	  this.objectMode = !!options.objectMode;

	  if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;

	  // the point at which write() starts returning false
	  // Note: 0 is a valid value, means that we always return false if
	  // the entire buffer is not flushed immediately on write()
	  var hwm = options.highWaterMark;
	  var writableHwm = options.writableHighWaterMark;
	  var defaultHwm = this.objectMode ? 16 : 16 * 1024;

	  if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;

	  // cast to ints.
	  this.highWaterMark = Math.floor(this.highWaterMark);

	  // if _final has been called
	  this.finalCalled = false;

	  // drain event flag.
	  this.needDrain = false;
	  // at the start of calling end()
	  this.ending = false;
	  // when end() has been called, and returned
	  this.ended = false;
	  // when 'finish' is emitted
	  this.finished = false;

	  // has it been destroyed
	  this.destroyed = false;

	  // should we decode strings into buffers before passing to _write?
	  // this is here so that some node-core streams can optimize string
	  // handling at a lower level.
	  var noDecode = options.decodeStrings === false;
	  this.decodeStrings = !noDecode;

	  // Crypto is kind of old and crusty.  Historically, its default string
	  // encoding is 'binary' so we have to make this configurable.
	  // Everything else in the universe uses 'utf8', though.
	  this.defaultEncoding = options.defaultEncoding || 'utf8';

	  // not an actual buffer we keep track of, but a measurement
	  // of how much we're waiting to get pushed to some underlying
	  // socket or file.
	  this.length = 0;

	  // a flag to see when we're in the middle of a write.
	  this.writing = false;

	  // when true all writes will be buffered until .uncork() call
	  this.corked = 0;

	  // a flag to be able to tell if the onwrite cb is called immediately,
	  // or on a later tick.  We set this to true at first, because any
	  // actions that shouldn't happen until "later" should generally also
	  // not happen before the first write call.
	  this.sync = true;

	  // a flag to know if we're processing previously buffered items, which
	  // may call the _write() callback in the same tick, so that we don't
	  // end up in an overlapped onwrite situation.
	  this.bufferProcessing = false;

	  // the callback that's passed to _write(chunk,cb)
	  this.onwrite = function (er) {
	    onwrite(stream, er);
	  };

	  // the callback that the user supplies to write(chunk,encoding,cb)
	  this.writecb = null;

	  // the amount that is being written when _write is called.
	  this.writelen = 0;

	  this.bufferedRequest = null;
	  this.lastBufferedRequest = null;

	  // number of pending user-supplied write callbacks
	  // this must be 0 before 'finish' can be emitted
	  this.pendingcb = 0;

	  // emit prefinish if the only thing we're waiting for is _write cbs
	  // This is relevant for synchronous Transform streams
	  this.prefinished = false;

	  // True if the error was already emitted and should not be thrown again
	  this.errorEmitted = false;

	  // count buffered requests
	  this.bufferedRequestCount = 0;

	  // allocate the first CorkedRequest, there is always
	  // one allocated and free to use, and we maintain at most two
	  this.corkedRequestsFree = new CorkedRequest(this);
	}

	WritableState.prototype.getBuffer = function getBuffer() {
	  var current = this.bufferedRequest;
	  var out = [];
	  while (current) {
	    out.push(current);
	    current = current.next;
	  }
	  return out;
	};

	(function () {
	  try {
	    Object.defineProperty(WritableState.prototype, 'buffer', {
	      get: internalUtil.deprecate(function () {
	        return this.getBuffer();
	      }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
	    });
	  } catch (_) {}
	})();

	// Test _writableState for inheritance to account for Duplex streams,
	// whose prototype chain only points to Readable.
	var realHasInstance;
	if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
	  realHasInstance = Function.prototype[Symbol.hasInstance];
	  Object.defineProperty(Writable, Symbol.hasInstance, {
	    value: function (object) {
	      if (realHasInstance.call(this, object)) return true;
	      if (this !== Writable) return false;

	      return object && object._writableState instanceof WritableState;
	    }
	  });
	} else {
	  realHasInstance = function (object) {
	    return object instanceof this;
	  };
	}

	function Writable(options) {
	  Duplex = Duplex || require_stream_duplex$1();

	  // Writable ctor is applied to Duplexes, too.
	  // `realHasInstance` is necessary because using plain `instanceof`
	  // would return false, as no `_writableState` property is attached.

	  // Trying to use the custom `instanceof` for Writable here will also break the
	  // Node.js LazyTransform implementation, which has a non-trivial getter for
	  // `_writableState` that would lead to infinite recursion.
	  if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
	    return new Writable(options);
	  }

	  this._writableState = new WritableState(options, this);

	  // legacy.
	  this.writable = true;

	  if (options) {
	    if (typeof options.write === 'function') this._write = options.write;

	    if (typeof options.writev === 'function') this._writev = options.writev;

	    if (typeof options.destroy === 'function') this._destroy = options.destroy;

	    if (typeof options.final === 'function') this._final = options.final;
	  }

	  Stream.call(this);
	}

	// Otherwise people can pipe Writable streams, which is just wrong.
	Writable.prototype.pipe = function () {
	  this.emit('error', new Error('Cannot pipe, not readable'));
	};

	function writeAfterEnd(stream, cb) {
	  var er = new Error('write after end');
	  // TODO: defer error events consistently everywhere, not just the cb
	  stream.emit('error', er);
	  pna.nextTick(cb, er);
	}

	// Checks that a user-supplied chunk is valid, especially for the particular
	// mode the stream is in. Currently this means that `null` is never accepted
	// and undefined/non-string values are only allowed in object mode.
	function validChunk(stream, state, chunk, cb) {
	  var valid = true;
	  var er = false;

	  if (chunk === null) {
	    er = new TypeError('May not write null values to stream');
	  } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
	    er = new TypeError('Invalid non-string/buffer chunk');
	  }
	  if (er) {
	    stream.emit('error', er);
	    pna.nextTick(cb, er);
	    valid = false;
	  }
	  return valid;
	}

	Writable.prototype.write = function (chunk, encoding, cb) {
	  var state = this._writableState;
	  var ret = false;
	  var isBuf = !state.objectMode && _isUint8Array(chunk);

	  if (isBuf && !Buffer.isBuffer(chunk)) {
	    chunk = _uint8ArrayToBuffer(chunk);
	  }

	  if (typeof encoding === 'function') {
	    cb = encoding;
	    encoding = null;
	  }

	  if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;

	  if (typeof cb !== 'function') cb = nop;

	  if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
	    state.pendingcb++;
	    ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
	  }

	  return ret;
	};

	Writable.prototype.cork = function () {
	  var state = this._writableState;

	  state.corked++;
	};

	Writable.prototype.uncork = function () {
	  var state = this._writableState;

	  if (state.corked) {
	    state.corked--;

	    if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
	  }
	};

	Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
	  // node::ParseEncoding() requires lower case.
	  if (typeof encoding === 'string') encoding = encoding.toLowerCase();
	  if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
	  this._writableState.defaultEncoding = encoding;
	  return this;
	};

	function decodeChunk(state, chunk, encoding) {
	  if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
	    chunk = Buffer.from(chunk, encoding);
	  }
	  return chunk;
	}

	Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
	  // making it explicit this property is not enumerable
	  // because otherwise some prototype manipulation in
	  // userland will fail
	  enumerable: false,
	  get: function () {
	    return this._writableState.highWaterMark;
	  }
	});

	// if we're already writing something, then just put this
	// in the queue, and wait our turn.  Otherwise, call _write
	// If we return false, then we need a drain event, so set that flag.
	function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
	  if (!isBuf) {
	    var newChunk = decodeChunk(state, chunk, encoding);
	    if (chunk !== newChunk) {
	      isBuf = true;
	      encoding = 'buffer';
	      chunk = newChunk;
	    }
	  }
	  var len = state.objectMode ? 1 : chunk.length;

	  state.length += len;

	  var ret = state.length < state.highWaterMark;
	  // we must ensure that previous needDrain will not be reset to false.
	  if (!ret) state.needDrain = true;

	  if (state.writing || state.corked) {
	    var last = state.lastBufferedRequest;
	    state.lastBufferedRequest = {
	      chunk: chunk,
	      encoding: encoding,
	      isBuf: isBuf,
	      callback: cb,
	      next: null
	    };
	    if (last) {
	      last.next = state.lastBufferedRequest;
	    } else {
	      state.bufferedRequest = state.lastBufferedRequest;
	    }
	    state.bufferedRequestCount += 1;
	  } else {
	    doWrite(stream, state, false, len, chunk, encoding, cb);
	  }

	  return ret;
	}

	function doWrite(stream, state, writev, len, chunk, encoding, cb) {
	  state.writelen = len;
	  state.writecb = cb;
	  state.writing = true;
	  state.sync = true;
	  if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
	  state.sync = false;
	}

	function onwriteError(stream, state, sync, er, cb) {
	  --state.pendingcb;

	  if (sync) {
	    // defer the callback if we are being called synchronously
	    // to avoid piling up things on the stack
	    pna.nextTick(cb, er);
	    // this can emit finish, and it will always happen
	    // after error
	    pna.nextTick(finishMaybe, stream, state);
	    stream._writableState.errorEmitted = true;
	    stream.emit('error', er);
	  } else {
	    // the caller expect this to happen before if
	    // it is async
	    cb(er);
	    stream._writableState.errorEmitted = true;
	    stream.emit('error', er);
	    // this can emit finish, but finish must
	    // always follow error
	    finishMaybe(stream, state);
	  }
	}

	function onwriteStateUpdate(state) {
	  state.writing = false;
	  state.writecb = null;
	  state.length -= state.writelen;
	  state.writelen = 0;
	}

	function onwrite(stream, er) {
	  var state = stream._writableState;
	  var sync = state.sync;
	  var cb = state.writecb;

	  onwriteStateUpdate(state);

	  if (er) onwriteError(stream, state, sync, er, cb);else {
	    // Check if we're actually ready to finish, but don't emit yet
	    var finished = needFinish(state);

	    if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
	      clearBuffer(stream, state);
	    }

	    if (sync) {
	      /*<replacement>*/
	      asyncWrite(afterWrite, stream, state, finished, cb);
	      /*</replacement>*/
	    } else {
	      afterWrite(stream, state, finished, cb);
	    }
	  }
	}

	function afterWrite(stream, state, finished, cb) {
	  if (!finished) onwriteDrain(stream, state);
	  state.pendingcb--;
	  cb();
	  finishMaybe(stream, state);
	}

	// Must force callback to be called on nextTick, so that we don't
	// emit 'drain' before the write() consumer gets the 'false' return
	// value, and has a chance to attach a 'drain' listener.
	function onwriteDrain(stream, state) {
	  if (state.length === 0 && state.needDrain) {
	    state.needDrain = false;
	    stream.emit('drain');
	  }
	}

	// if there's something in the buffer waiting, then process it
	function clearBuffer(stream, state) {
	  state.bufferProcessing = true;
	  var entry = state.bufferedRequest;

	  if (stream._writev && entry && entry.next) {
	    // Fast case, write everything using _writev()
	    var l = state.bufferedRequestCount;
	    var buffer = new Array(l);
	    var holder = state.corkedRequestsFree;
	    holder.entry = entry;

	    var count = 0;
	    var allBuffers = true;
	    while (entry) {
	      buffer[count] = entry;
	      if (!entry.isBuf) allBuffers = false;
	      entry = entry.next;
	      count += 1;
	    }
	    buffer.allBuffers = allBuffers;

	    doWrite(stream, state, true, state.length, buffer, '', holder.finish);

	    // doWrite is almost always async, defer these to save a bit of time
	    // as the hot path ends with doWrite
	    state.pendingcb++;
	    state.lastBufferedRequest = null;
	    if (holder.next) {
	      state.corkedRequestsFree = holder.next;
	      holder.next = null;
	    } else {
	      state.corkedRequestsFree = new CorkedRequest(state);
	    }
	    state.bufferedRequestCount = 0;
	  } else {
	    // Slow case, write chunks one-by-one
	    while (entry) {
	      var chunk = entry.chunk;
	      var encoding = entry.encoding;
	      var cb = entry.callback;
	      var len = state.objectMode ? 1 : chunk.length;

	      doWrite(stream, state, false, len, chunk, encoding, cb);
	      entry = entry.next;
	      state.bufferedRequestCount--;
	      // if we didn't call the onwrite immediately, then
	      // it means that we need to wait until it does.
	      // also, that means that the chunk and cb are currently
	      // being processed, so move the buffer counter past them.
	      if (state.writing) {
	        break;
	      }
	    }

	    if (entry === null) state.lastBufferedRequest = null;
	  }

	  state.bufferedRequest = entry;
	  state.bufferProcessing = false;
	}

	Writable.prototype._write = function (chunk, encoding, cb) {
	  cb(new Error('_write() is not implemented'));
	};

	Writable.prototype._writev = null;

	Writable.prototype.end = function (chunk, encoding, cb) {
	  var state = this._writableState;

	  if (typeof chunk === 'function') {
	    cb = chunk;
	    chunk = null;
	    encoding = null;
	  } else if (typeof encoding === 'function') {
	    cb = encoding;
	    encoding = null;
	  }

	  if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);

	  // .end() fully uncorks
	  if (state.corked) {
	    state.corked = 1;
	    this.uncork();
	  }

	  // ignore unnecessary end() calls.
	  if (!state.ending) endWritable(this, state, cb);
	};

	function needFinish(state) {
	  return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
	}
	function callFinal(stream, state) {
	  stream._final(function (err) {
	    state.pendingcb--;
	    if (err) {
	      stream.emit('error', err);
	    }
	    state.prefinished = true;
	    stream.emit('prefinish');
	    finishMaybe(stream, state);
	  });
	}
	function prefinish(stream, state) {
	  if (!state.prefinished && !state.finalCalled) {
	    if (typeof stream._final === 'function') {
	      state.pendingcb++;
	      state.finalCalled = true;
	      pna.nextTick(callFinal, stream, state);
	    } else {
	      state.prefinished = true;
	      stream.emit('prefinish');
	    }
	  }
	}

	function finishMaybe(stream, state) {
	  var need = needFinish(state);
	  if (need) {
	    prefinish(stream, state);
	    if (state.pendingcb === 0) {
	      state.finished = true;
	      stream.emit('finish');
	    }
	  }
	  return need;
	}

	function endWritable(stream, state, cb) {
	  state.ending = true;
	  finishMaybe(stream, state);
	  if (cb) {
	    if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
	  }
	  state.ended = true;
	  stream.writable = false;
	}

	function onCorkedFinish(corkReq, state, err) {
	  var entry = corkReq.entry;
	  corkReq.entry = null;
	  while (entry) {
	    var cb = entry.callback;
	    state.pendingcb--;
	    cb(err);
	    entry = entry.next;
	  }

	  // reuse the free corkReq.
	  state.corkedRequestsFree.next = corkReq;
	}

	Object.defineProperty(Writable.prototype, 'destroyed', {
	  get: function () {
	    if (this._writableState === undefined) {
	      return false;
	    }
	    return this._writableState.destroyed;
	  },
	  set: function (value) {
	    // we ignore the value if the stream
	    // has not been initialized yet
	    if (!this._writableState) {
	      return;
	    }

	    // backward compatibility, the user is explicitly
	    // managing destroyed
	    this._writableState.destroyed = value;
	  }
	});

	Writable.prototype.destroy = destroyImpl.destroy;
	Writable.prototype._undestroy = destroyImpl.undestroy;
	Writable.prototype._destroy = function (err, cb) {
	  this.end();
	  cb(err);
	};
	return _stream_writable$1;
}

var _stream_duplex$1;
var hasRequired_stream_duplex$1;

function require_stream_duplex$1 () {
	if (hasRequired_stream_duplex$1) return _stream_duplex$1;
	hasRequired_stream_duplex$1 = 1;

	/*<replacement>*/

	var pna = requireProcessNextickArgs();
	/*</replacement>*/

	/*<replacement>*/
	var objectKeys = Object.keys || function (obj) {
	  var keys = [];
	  for (var key in obj) {
	    keys.push(key);
	  }return keys;
	};
	/*</replacement>*/

	_stream_duplex$1 = Duplex;

	/*<replacement>*/
	var util = Object.create(requireUtil$2());
	util.inherits = requireInherits_browser();
	/*</replacement>*/

	var Readable = require_stream_readable$1();
	var Writable = require_stream_writable$1();

	util.inherits(Duplex, Readable);

	{
	  // avoid scope creep, the keys array can then be collected
	  var keys = objectKeys(Writable.prototype);
	  for (var v = 0; v < keys.length; v++) {
	    var method = keys[v];
	    if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
	  }
	}

	function Duplex(options) {
	  if (!(this instanceof Duplex)) return new Duplex(options);

	  Readable.call(this, options);
	  Writable.call(this, options);

	  if (options && options.readable === false) this.readable = false;

	  if (options && options.writable === false) this.writable = false;

	  this.allowHalfOpen = true;
	  if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;

	  this.once('end', onend);
	}

	Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
	  // making it explicit this property is not enumerable
	  // because otherwise some prototype manipulation in
	  // userland will fail
	  enumerable: false,
	  get: function () {
	    return this._writableState.highWaterMark;
	  }
	});

	// the no-half-open enforcer
	function onend() {
	  // if we allow half-open state, or if the writable side ended,
	  // then we're ok.
	  if (this.allowHalfOpen || this._writableState.ended) return;

	  // no more data can be written.
	  // But allow more writes to happen in this tick.
	  pna.nextTick(onEndNT, this);
	}

	function onEndNT(self) {
	  self.end();
	}

	Object.defineProperty(Duplex.prototype, 'destroyed', {
	  get: function () {
	    if (this._readableState === undefined || this._writableState === undefined) {
	      return false;
	    }
	    return this._readableState.destroyed && this._writableState.destroyed;
	  },
	  set: function (value) {
	    // we ignore the value if the stream
	    // has not been initialized yet
	    if (this._readableState === undefined || this._writableState === undefined) {
	      return;
	    }

	    // backward compatibility, the user is explicitly
	    // managing destroyed
	    this._readableState.destroyed = value;
	    this._writableState.destroyed = value;
	  }
	});

	Duplex.prototype._destroy = function (err, cb) {
	  this.push(null);
	  this.end();

	  pna.nextTick(cb, err);
	};
	return _stream_duplex$1;
}

var duplexBrowser;
var hasRequiredDuplexBrowser;

function requireDuplexBrowser () {
	if (hasRequiredDuplexBrowser) return duplexBrowser;
	hasRequiredDuplexBrowser = 1;
	duplexBrowser = require_stream_duplex$1();
	return duplexBrowser;
}

var safeBuffer = {exports: {}};

/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */

var hasRequiredSafeBuffer;

function requireSafeBuffer () {
	if (hasRequiredSafeBuffer) return safeBuffer.exports;
	hasRequiredSafeBuffer = 1;
	(function (module, exports$1) {
		/* eslint-disable node/no-deprecated-api */
		var buffer = require$$0$4;
		var Buffer = buffer.Buffer;

		// alternative to using Object.keys for old browsers
		function copyProps (src, dst) {
		  for (var key in src) {
		    dst[key] = src[key];
		  }
		}
		if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
		  module.exports = buffer;
		} else {
		  // Copy properties from require('buffer')
		  copyProps(buffer, exports$1);
		  exports$1.Buffer = SafeBuffer;
		}

		function SafeBuffer (arg, encodingOrOffset, length) {
		  return Buffer(arg, encodingOrOffset, length)
		}

		SafeBuffer.prototype = Object.create(Buffer.prototype);

		// Copy static methods from Buffer
		copyProps(Buffer, SafeBuffer);

		SafeBuffer.from = function (arg, encodingOrOffset, length) {
		  if (typeof arg === 'number') {
		    throw new TypeError('Argument must not be a number')
		  }
		  return Buffer(arg, encodingOrOffset, length)
		};

		SafeBuffer.alloc = function (size, fill, encoding) {
		  if (typeof size !== 'number') {
		    throw new TypeError('Argument must be a number')
		  }
		  var buf = Buffer(size);
		  if (fill !== undefined) {
		    if (typeof encoding === 'string') {
		      buf.fill(fill, encoding);
		    } else {
		      buf.fill(fill);
		    }
		  } else {
		    buf.fill(0);
		  }
		  return buf
		};

		SafeBuffer.allocUnsafe = function (size) {
		  if (typeof size !== 'number') {
		    throw new TypeError('Argument must be a number')
		  }
		  return Buffer(size)
		};

		SafeBuffer.allocUnsafeSlow = function (size) {
		  if (typeof size !== 'number') {
		    throw new TypeError('Argument must be a number')
		  }
		  return buffer.SlowBuffer(size)
		}; 
	} (safeBuffer, safeBuffer.exports));
	return safeBuffer.exports;
}

var bl;
var hasRequiredBl;

function requireBl () {
	if (hasRequiredBl) return bl;
	hasRequiredBl = 1;
	var DuplexStream = requireDuplexBrowser()
	  , util         = require$$0$6
	  , Buffer       = requireSafeBuffer().Buffer;


	function BufferList (callback) {
	  if (!(this instanceof BufferList))
	    return new BufferList(callback)

	  this._bufs  = [];
	  this.length = 0;

	  if (typeof callback == 'function') {
	    this._callback = callback;

	    var piper = function piper (err) {
	      if (this._callback) {
	        this._callback(err);
	        this._callback = null;
	      }
	    }.bind(this);

	    this.on('pipe', function onPipe (src) {
	      src.on('error', piper);
	    });
	    this.on('unpipe', function onUnpipe (src) {
	      src.removeListener('error', piper);
	    });
	  } else {
	    this.append(callback);
	  }

	  DuplexStream.call(this);
	}


	util.inherits(BufferList, DuplexStream);


	BufferList.prototype._offset = function _offset (offset) {
	  var tot = 0, i = 0, _t;
	  if (offset === 0) return [ 0, 0 ]
	  for (; i < this._bufs.length; i++) {
	    _t = tot + this._bufs[i].length;
	    if (offset < _t || i == this._bufs.length - 1)
	      return [ i, offset - tot ]
	    tot = _t;
	  }
	};


	BufferList.prototype.append = function append (buf) {
	  var i = 0;

	  if (Buffer.isBuffer(buf)) {
	    this._appendBuffer(buf);
	  } else if (Array.isArray(buf)) {
	    for (; i < buf.length; i++)
	      this.append(buf[i]);
	  } else if (buf instanceof BufferList) {
	    // unwrap argument into individual BufferLists
	    for (; i < buf._bufs.length; i++)
	      this.append(buf._bufs[i]);
	  } else if (buf != null) {
	    // coerce number arguments to strings, since Buffer(number) does
	    // uninitialized memory allocation
	    if (typeof buf == 'number')
	      buf = buf.toString();

	    this._appendBuffer(Buffer.from(buf));
	  }

	  return this
	};


	BufferList.prototype._appendBuffer = function appendBuffer (buf) {
	  this._bufs.push(buf);
	  this.length += buf.length;
	};


	BufferList.prototype._write = function _write (buf, encoding, callback) {
	  this._appendBuffer(buf);

	  if (typeof callback == 'function')
	    callback();
	};


	BufferList.prototype._read = function _read (size) {
	  if (!this.length)
	    return this.push(null)

	  size = Math.min(size, this.length);
	  this.push(this.slice(0, size));
	  this.consume(size);
	};


	BufferList.prototype.end = function end (chunk) {
	  DuplexStream.prototype.end.call(this, chunk);

	  if (this._callback) {
	    this._callback(null, this.slice());
	    this._callback = null;
	  }
	};


	BufferList.prototype.get = function get (index) {
	  return this.slice(index, index + 1)[0]
	};


	BufferList.prototype.slice = function slice (start, end) {
	  if (typeof start == 'number' && start < 0)
	    start += this.length;
	  if (typeof end == 'number' && end < 0)
	    end += this.length;
	  return this.copy(null, 0, start, end)
	};


	BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {
	  if (typeof srcStart != 'number' || srcStart < 0)
	    srcStart = 0;
	  if (typeof srcEnd != 'number' || srcEnd > this.length)
	    srcEnd = this.length;
	  if (srcStart >= this.length)
	    return dst || Buffer.alloc(0)
	  if (srcEnd <= 0)
	    return dst || Buffer.alloc(0)

	  var copy   = !!dst
	    , off    = this._offset(srcStart)
	    , len    = srcEnd - srcStart
	    , bytes  = len
	    , bufoff = (copy && dstStart) || 0
	    , start  = off[1]
	    , l
	    , i;

	  // copy/slice everything
	  if (srcStart === 0 && srcEnd == this.length) {
	    if (!copy) { // slice, but full concat if multiple buffers
	      return this._bufs.length === 1
	        ? this._bufs[0]
	        : Buffer.concat(this._bufs, this.length)
	    }

	    // copy, need to copy individual buffers
	    for (i = 0; i < this._bufs.length; i++) {
	      this._bufs[i].copy(dst, bufoff);
	      bufoff += this._bufs[i].length;
	    }

	    return dst
	  }

	  // easy, cheap case where it's a subset of one of the buffers
	  if (bytes <= this._bufs[off[0]].length - start) {
	    return copy
	      ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)
	      : this._bufs[off[0]].slice(start, start + bytes)
	  }

	  if (!copy) // a slice, we need something to copy in to
	    dst = Buffer.allocUnsafe(len);

	  for (i = off[0]; i < this._bufs.length; i++) {
	    l = this._bufs[i].length - start;

	    if (bytes > l) {
	      this._bufs[i].copy(dst, bufoff, start);
	      bufoff += l;
	    } else {
	      this._bufs[i].copy(dst, bufoff, start, start + bytes);
	      bufoff += l;
	      break
	    }

	    bytes -= l;

	    if (start)
	      start = 0;
	  }

	  // safeguard so that we don't return uninitialized memory
	  if (dst.length > bufoff) return dst.slice(0, bufoff)

	  return dst
	};

	BufferList.prototype.shallowSlice = function shallowSlice (start, end) {
	  start = start || 0;
	  end = end || this.length;

	  if (start < 0)
	    start += this.length;
	  if (end < 0)
	    end += this.length;

	  var startOffset = this._offset(start)
	    , endOffset = this._offset(end)
	    , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1);

	  if (endOffset[1] == 0)
	    buffers.pop();
	  else
	    buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1]);

	  if (startOffset[1] != 0)
	    buffers[0] = buffers[0].slice(startOffset[1]);

	  return new BufferList(buffers)
	};

	BufferList.prototype.toString = function toString (encoding, start, end) {
	  return this.slice(start, end).toString(encoding)
	};

	BufferList.prototype.consume = function consume (bytes) {
	  // first, normalize the argument, in accordance with how Buffer does it
	  bytes = Math.trunc(bytes);
	  // do nothing if not a positive number
	  if (Number.isNaN(bytes) || bytes <= 0) return this

	  while (this._bufs.length) {
	    if (bytes >= this._bufs[0].length) {
	      bytes -= this._bufs[0].length;
	      this.length -= this._bufs[0].length;
	      this._bufs.shift();
	    } else {
	      this._bufs[0] = this._bufs[0].slice(bytes);
	      this.length -= bytes;
	      break
	    }
	  }
	  return this
	};


	BufferList.prototype.duplicate = function duplicate () {
	  var i = 0
	    , copy = new BufferList();

	  for (; i < this._bufs.length; i++)
	    copy.append(this._bufs[i]);

	  return copy
	};


	BufferList.prototype.destroy = function destroy () {
	  this._bufs.length = 0;
	  this.length = 0;
	  this.push(null);
	}


	;(function () {
	  var methods = {
	      'readDoubleBE' : 8
	    , 'readDoubleLE' : 8
	    , 'readFloatBE'  : 4
	    , 'readFloatLE'  : 4
	    , 'readInt32BE'  : 4
	    , 'readInt32LE'  : 4
	    , 'readUInt32BE' : 4
	    , 'readUInt32LE' : 4
	    , 'readInt16BE'  : 2
	    , 'readInt16LE'  : 2
	    , 'readUInt16BE' : 2
	    , 'readUInt16LE' : 2
	    , 'readInt8'     : 1
	    , 'readUInt8'    : 1
	  };

	  for (var m in methods) {
	    (function (m) {
	      BufferList.prototype[m] = function (offset) {
	        return this.slice(offset, offset + methods[m])[m](0)
	      };
	    }(m));
	  }
	}());


	bl = BufferList;
	return bl;
}

var immutable;
var hasRequiredImmutable;

function requireImmutable () {
	if (hasRequiredImmutable) return immutable;
	hasRequiredImmutable = 1;
	immutable = extend;

	var hasOwnProperty = Object.prototype.hasOwnProperty;

	function extend() {
	    var target = {};

	    for (var i = 0; i < arguments.length; i++) {
	        var source = arguments[i];

	        for (var key in source) {
	            if (hasOwnProperty.call(source, key)) {
	                target[key] = source[key];
	            }
	        }
	    }

	    return target
	}
	return immutable;
}

var headers = {};

var isarray;
var hasRequiredIsarray;

function requireIsarray () {
	if (hasRequiredIsarray) return isarray;
	hasRequiredIsarray = 1;
	var toString = {}.toString;

	isarray = Array.isArray || function (arr) {
	  return toString.call(arr) == '[object Array]';
	};
	return isarray;
}

var type$2;
var hasRequiredType;

function requireType () {
	if (hasRequiredType) return type$2;
	hasRequiredType = 1;

	/** @type {import('./type')} */
	type$2 = TypeError;
	return type$2;
}

var esObjectAtoms;
var hasRequiredEsObjectAtoms;

function requireEsObjectAtoms () {
	if (hasRequiredEsObjectAtoms) return esObjectAtoms;
	hasRequiredEsObjectAtoms = 1;

	/** @type {import('.')} */
	esObjectAtoms = Object;
	return esObjectAtoms;
}

var esErrors;
var hasRequiredEsErrors;

function requireEsErrors () {
	if (hasRequiredEsErrors) return esErrors;
	hasRequiredEsErrors = 1;

	/** @type {import('.')} */
	esErrors = Error;
	return esErrors;
}

var _eval;
var hasRequired_eval;

function require_eval () {
	if (hasRequired_eval) return _eval;
	hasRequired_eval = 1;

	/** @type {import('./eval')} */
	_eval = EvalError;
	return _eval;
}

var range;
var hasRequiredRange;

function requireRange () {
	if (hasRequiredRange) return range;
	hasRequiredRange = 1;

	/** @type {import('./range')} */
	range = RangeError;
	return range;
}

var ref$1;
var hasRequiredRef$1;

function requireRef$1 () {
	if (hasRequiredRef$1) return ref$1;
	hasRequiredRef$1 = 1;

	/** @type {import('./ref')} */
	ref$1 = ReferenceError;
	return ref$1;
}

var syntax;
var hasRequiredSyntax;

function requireSyntax () {
	if (hasRequiredSyntax) return syntax;
	hasRequiredSyntax = 1;

	/** @type {import('./syntax')} */
	syntax = SyntaxError;
	return syntax;
}

var uri$1;
var hasRequiredUri$1;

function requireUri$1 () {
	if (hasRequiredUri$1) return uri$1;
	hasRequiredUri$1 = 1;

	/** @type {import('./uri')} */
	uri$1 = URIError;
	return uri$1;
}

var abs;
var hasRequiredAbs;

function requireAbs () {
	if (hasRequiredAbs) return abs;
	hasRequiredAbs = 1;

	/** @type {import('./abs')} */
	abs = Math.abs;
	return abs;
}

var floor;
var hasRequiredFloor;

function requireFloor () {
	if (hasRequiredFloor) return floor;
	hasRequiredFloor = 1;

	/** @type {import('./floor')} */
	floor = Math.floor;
	return floor;
}

var max;
var hasRequiredMax;

function requireMax () {
	if (hasRequiredMax) return max;
	hasRequiredMax = 1;

	/** @type {import('./max')} */
	max = Math.max;
	return max;
}

var min;
var hasRequiredMin;

function requireMin () {
	if (hasRequiredMin) return min;
	hasRequiredMin = 1;

	/** @type {import('./min')} */
	min = Math.min;
	return min;
}

var pow;
var hasRequiredPow;

function requirePow () {
	if (hasRequiredPow) return pow;
	hasRequiredPow = 1;

	/** @type {import('./pow')} */
	pow = Math.pow;
	return pow;
}

var round;
var hasRequiredRound;

function requireRound () {
	if (hasRequiredRound) return round;
	hasRequiredRound = 1;

	/** @type {import('./round')} */
	round = Math.round;
	return round;
}

var _isNaN;
var hasRequired_isNaN;

function require_isNaN () {
	if (hasRequired_isNaN) return _isNaN;
	hasRequired_isNaN = 1;

	/** @type {import('./isNaN')} */
	_isNaN = Number.isNaN || function isNaN(a) {
		return a !== a;
	};
	return _isNaN;
}

var sign$1;
var hasRequiredSign;

function requireSign () {
	if (hasRequiredSign) return sign$1;
	hasRequiredSign = 1;

	var $isNaN = /*@__PURE__*/ require_isNaN();

	/** @type {import('./sign')} */
	sign$1 = function sign(number) {
		if ($isNaN(number) || number === 0) {
			return number;
		}
		return number < 0 ? -1 : 1;
	};
	return sign$1;
}

var gOPD;
var hasRequiredGOPD;

function requireGOPD () {
	if (hasRequiredGOPD) return gOPD;
	hasRequiredGOPD = 1;

	/** @type {import('./gOPD')} */
	gOPD = Object.getOwnPropertyDescriptor;
	return gOPD;
}

var gopd;
var hasRequiredGopd;

function requireGopd () {
	if (hasRequiredGopd) return gopd;
	hasRequiredGopd = 1;

	/** @type {import('.')} */
	var $gOPD = /*@__PURE__*/ requireGOPD();

	if ($gOPD) {
		try {
			$gOPD([], 'length');
		} catch (e) {
			// IE 8 has a broken gOPD
			$gOPD = null;
		}
	}

	gopd = $gOPD;
	return gopd;
}

var esDefineProperty;
var hasRequiredEsDefineProperty;

function requireEsDefineProperty () {
	if (hasRequiredEsDefineProperty) return esDefineProperty;
	hasRequiredEsDefineProperty = 1;

	/** @type {import('.')} */
	var $defineProperty = Object.defineProperty || false;
	if ($defineProperty) {
		try {
			$defineProperty({}, 'a', { value: 1 });
		} catch (e) {
			// IE 8 has a broken defineProperty
			$defineProperty = false;
		}
	}

	esDefineProperty = $defineProperty;
	return esDefineProperty;
}

var shams$1;
var hasRequiredShams$1;

function requireShams$1 () {
	if (hasRequiredShams$1) return shams$1;
	hasRequiredShams$1 = 1;

	/** @type {import('./shams')} */
	/* eslint complexity: [2, 18], max-statements: [2, 33] */
	shams$1 = function hasSymbols() {
		if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
		if (typeof Symbol.iterator === 'symbol') { return true; }

		/** @type {{ [k in symbol]?: unknown }} */
		var obj = {};
		var sym = Symbol('test');
		var symObj = Object(sym);
		if (typeof sym === 'string') { return false; }

		if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
		if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }

		// temp disabled per https://github.com/ljharb/object.assign/issues/17
		// if (sym instanceof Symbol) { return false; }
		// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
		// if (!(symObj instanceof Symbol)) { return false; }

		// if (typeof Symbol.prototype.toString !== 'function') { return false; }
		// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }

		var symVal = 42;
		obj[sym] = symVal;
		for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
		if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }

		if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }

		var syms = Object.getOwnPropertySymbols(obj);
		if (syms.length !== 1 || syms[0] !== sym) { return false; }

		if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }

		if (typeof Object.getOwnPropertyDescriptor === 'function') {
			// eslint-disable-next-line no-extra-parens
			var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym));
			if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
		}

		return true;
	};
	return shams$1;
}

var hasSymbols;
var hasRequiredHasSymbols;

function requireHasSymbols () {
	if (hasRequiredHasSymbols) return hasSymbols;
	hasRequiredHasSymbols = 1;

	var origSymbol = typeof Symbol !== 'undefined' && Symbol;
	var hasSymbolSham = requireShams$1();

	/** @type {import('.')} */
	hasSymbols = function hasNativeSymbols() {
		if (typeof origSymbol !== 'function') { return false; }
		if (typeof Symbol !== 'function') { return false; }
		if (typeof origSymbol('foo') !== 'symbol') { return false; }
		if (typeof Symbol('bar') !== 'symbol') { return false; }

		return hasSymbolSham();
	};
	return hasSymbols;
}

var Reflect_getPrototypeOf;
var hasRequiredReflect_getPrototypeOf;

function requireReflect_getPrototypeOf () {
	if (hasRequiredReflect_getPrototypeOf) return Reflect_getPrototypeOf;
	hasRequiredReflect_getPrototypeOf = 1;

	/** @type {import('./Reflect.getPrototypeOf')} */
	Reflect_getPrototypeOf = (typeof Reflect !== 'undefined' && Reflect.getPrototypeOf) || null;
	return Reflect_getPrototypeOf;
}

var Object_getPrototypeOf;
var hasRequiredObject_getPrototypeOf;

function requireObject_getPrototypeOf () {
	if (hasRequiredObject_getPrototypeOf) return Object_getPrototypeOf;
	hasRequiredObject_getPrototypeOf = 1;

	var $Object = /*@__PURE__*/ requireEsObjectAtoms();

	/** @type {import('./Object.getPrototypeOf')} */
	Object_getPrototypeOf = $Object.getPrototypeOf || null;
	return Object_getPrototypeOf;
}

var implementation;
var hasRequiredImplementation;

function requireImplementation () {
	if (hasRequiredImplementation) return implementation;
	hasRequiredImplementation = 1;

	/* eslint no-invalid-this: 1 */

	var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
	var toStr = Object.prototype.toString;
	var max = Math.max;
	var funcType = '[object Function]';

	var concatty = function concatty(a, b) {
	    var arr = [];

	    for (var i = 0; i < a.length; i += 1) {
	        arr[i] = a[i];
	    }
	    for (var j = 0; j < b.length; j += 1) {
	        arr[j + a.length] = b[j];
	    }

	    return arr;
	};

	var slicy = function slicy(arrLike, offset) {
	    var arr = [];
	    for (var i = offset, j = 0; i < arrLike.length; i += 1, j += 1) {
	        arr[j] = arrLike[i];
	    }
	    return arr;
	};

	var joiny = function (arr, joiner) {
	    var str = '';
	    for (var i = 0; i < arr.length; i += 1) {
	        str += arr[i];
	        if (i + 1 < arr.length) {
	            str += joiner;
	        }
	    }
	    return str;
	};

	implementation = function bind(that) {
	    var target = this;
	    if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
	        throw new TypeError(ERROR_MESSAGE + target);
	    }
	    var args = slicy(arguments, 1);

	    var bound;
	    var binder = function () {
	        if (this instanceof bound) {
	            var result = target.apply(
	                this,
	                concatty(args, arguments)
	            );
	            if (Object(result) === result) {
	                return result;
	            }
	            return this;
	        }
	        return target.apply(
	            that,
	            concatty(args, arguments)
	        );

	    };

	    var boundLength = max(0, target.length - args.length);
	    var boundArgs = [];
	    for (var i = 0; i < boundLength; i++) {
	        boundArgs[i] = '$' + i;
	    }

	    bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);

	    if (target.prototype) {
	        var Empty = function Empty() {};
	        Empty.prototype = target.prototype;
	        bound.prototype = new Empty();
	        Empty.prototype = null;
	    }

	    return bound;
	};
	return implementation;
}

var functionBind;
var hasRequiredFunctionBind;

function requireFunctionBind () {
	if (hasRequiredFunctionBind) return functionBind;
	hasRequiredFunctionBind = 1;

	var implementation = requireImplementation();

	functionBind = Function.prototype.bind || implementation;
	return functionBind;
}

var functionCall;
var hasRequiredFunctionCall;

function requireFunctionCall () {
	if (hasRequiredFunctionCall) return functionCall;
	hasRequiredFunctionCall = 1;

	/** @type {import('./functionCall')} */
	functionCall = Function.prototype.call;
	return functionCall;
}

var functionApply;
var hasRequiredFunctionApply;

function requireFunctionApply () {
	if (hasRequiredFunctionApply) return functionApply;
	hasRequiredFunctionApply = 1;

	/** @type {import('./functionApply')} */
	functionApply = Function.prototype.apply;
	return functionApply;
}

var reflectApply;
var hasRequiredReflectApply;

function requireReflectApply () {
	if (hasRequiredReflectApply) return reflectApply;
	hasRequiredReflectApply = 1;

	/** @type {import('./reflectApply')} */
	reflectApply = typeof Reflect !== 'undefined' && Reflect && Reflect.apply;
	return reflectApply;
}

var actualApply;
var hasRequiredActualApply;

function requireActualApply () {
	if (hasRequiredActualApply) return actualApply;
	hasRequiredActualApply = 1;

	var bind = requireFunctionBind();

	var $apply = requireFunctionApply();
	var $call = requireFunctionCall();
	var $reflectApply = requireReflectApply();

	/** @type {import('./actualApply')} */
	actualApply = $reflectApply || bind.call($call, $apply);
	return actualApply;
}

var callBindApplyHelpers;
var hasRequiredCallBindApplyHelpers;

function requireCallBindApplyHelpers () {
	if (hasRequiredCallBindApplyHelpers) return callBindApplyHelpers;
	hasRequiredCallBindApplyHelpers = 1;

	var bind = requireFunctionBind();
	var $TypeError = /*@__PURE__*/ requireType();

	var $call = requireFunctionCall();
	var $actualApply = requireActualApply();

	/** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */
	callBindApplyHelpers = function callBindBasic(args) {
		if (args.length < 1 || typeof args[0] !== 'function') {
			throw new $TypeError('a function is required');
		}
		return $actualApply(bind, $call, args);
	};
	return callBindApplyHelpers;
}

var get;
var hasRequiredGet;

function requireGet () {
	if (hasRequiredGet) return get;
	hasRequiredGet = 1;

	var callBind = requireCallBindApplyHelpers();
	var gOPD = /*@__PURE__*/ requireGopd();

	var hasProtoAccessor;
	try {
		// eslint-disable-next-line no-extra-parens, no-proto
		hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype;
	} catch (e) {
		if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') {
			throw e;
		}
	}

	// eslint-disable-next-line no-extra-parens
	var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__'));

	var $Object = Object;
	var $getPrototypeOf = $Object.getPrototypeOf;

	/** @type {import('./get')} */
	get = desc && typeof desc.get === 'function'
		? callBind([desc.get])
		: typeof $getPrototypeOf === 'function'
			? /** @type {import('./get')} */ function getDunder(value) {
				// eslint-disable-next-line eqeqeq
				return $getPrototypeOf(value == null ? value : $Object(value));
			}
			: false;
	return get;
}

var getProto;
var hasRequiredGetProto;

function requireGetProto () {
	if (hasRequiredGetProto) return getProto;
	hasRequiredGetProto = 1;

	var reflectGetProto = requireReflect_getPrototypeOf();
	var originalGetProto = requireObject_getPrototypeOf();

	var getDunderProto = /*@__PURE__*/ requireGet();

	/** @type {import('.')} */
	getProto = reflectGetProto
		? function getProto(O) {
			// @ts-expect-error TS can't narrow inside a closure, for some reason
			return reflectGetProto(O);
		}
		: originalGetProto
			? function getProto(O) {
				if (!O || (typeof O !== 'object' && typeof O !== 'function')) {
					throw new TypeError('getProto: not an object');
				}
				// @ts-expect-error TS can't narrow inside a closure, for some reason
				return originalGetProto(O);
			}
			: getDunderProto
				? function getProto(O) {
					// @ts-expect-error TS can't narrow inside a closure, for some reason
					return getDunderProto(O);
				}
				: null;
	return getProto;
}

var hasown;
var hasRequiredHasown;

function requireHasown () {
	if (hasRequiredHasown) return hasown;
	hasRequiredHasown = 1;

	var call = Function.prototype.call;
	var $hasOwn = Object.prototype.hasOwnProperty;
	var bind = requireFunctionBind();

	/** @type {import('.')} */
	hasown = bind.call(call, $hasOwn);
	return hasown;
}

var getIntrinsic;
var hasRequiredGetIntrinsic;

function requireGetIntrinsic () {
	if (hasRequiredGetIntrinsic) return getIntrinsic;
	hasRequiredGetIntrinsic = 1;

	var undefined$1;

	var $Object = /*@__PURE__*/ requireEsObjectAtoms();

	var $Error = /*@__PURE__*/ requireEsErrors();
	var $EvalError = /*@__PURE__*/ require_eval();
	var $RangeError = /*@__PURE__*/ requireRange();
	var $ReferenceError = /*@__PURE__*/ requireRef$1();
	var $SyntaxError = /*@__PURE__*/ requireSyntax();
	var $TypeError = /*@__PURE__*/ requireType();
	var $URIError = /*@__PURE__*/ requireUri$1();

	var abs = /*@__PURE__*/ requireAbs();
	var floor = /*@__PURE__*/ requireFloor();
	var max = /*@__PURE__*/ requireMax();
	var min = /*@__PURE__*/ requireMin();
	var pow = /*@__PURE__*/ requirePow();
	var round = /*@__PURE__*/ requireRound();
	var sign = /*@__PURE__*/ requireSign();

	var $Function = Function;

	// eslint-disable-next-line consistent-return
	var getEvalledConstructor = function (expressionSyntax) {
		try {
			return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
		} catch (e) {}
	};

	var $gOPD = /*@__PURE__*/ requireGopd();
	var $defineProperty = /*@__PURE__*/ requireEsDefineProperty();

	var throwTypeError = function () {
		throw new $TypeError();
	};
	var ThrowTypeError = $gOPD
		? (function () {
			try {
				// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
				arguments.callee; // IE 8 does not throw here
				return throwTypeError;
			} catch (calleeThrows) {
				try {
					// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
					return $gOPD(arguments, 'callee').get;
				} catch (gOPDthrows) {
					return throwTypeError;
				}
			}
		}())
		: throwTypeError;

	var hasSymbols = requireHasSymbols()();

	var getProto = requireGetProto();
	var $ObjectGPO = requireObject_getPrototypeOf();
	var $ReflectGPO = requireReflect_getPrototypeOf();

	var $apply = requireFunctionApply();
	var $call = requireFunctionCall();

	var needsEval = {};

	var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined$1 : getProto(Uint8Array);

	var INTRINSICS = {
		__proto__: null,
		'%AggregateError%': typeof AggregateError === 'undefined' ? undefined$1 : AggregateError,
		'%Array%': Array,
		'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer,
		'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined$1,
		'%AsyncFromSyncIteratorPrototype%': undefined$1,
		'%AsyncFunction%': needsEval,
		'%AsyncGenerator%': needsEval,
		'%AsyncGeneratorFunction%': needsEval,
		'%AsyncIteratorPrototype%': needsEval,
		'%Atomics%': typeof Atomics === 'undefined' ? undefined$1 : Atomics,
		'%BigInt%': typeof BigInt === 'undefined' ? undefined$1 : BigInt,
		'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined$1 : BigInt64Array,
		'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined$1 : BigUint64Array,
		'%Boolean%': Boolean,
		'%DataView%': typeof DataView === 'undefined' ? undefined$1 : DataView,
		'%Date%': Date,
		'%decodeURI%': decodeURI,
		'%decodeURIComponent%': decodeURIComponent,
		'%encodeURI%': encodeURI,
		'%encodeURIComponent%': encodeURIComponent,
		'%Error%': $Error,
		'%eval%': eval, // eslint-disable-line no-eval
		'%EvalError%': $EvalError,
		'%Float16Array%': typeof Float16Array === 'undefined' ? undefined$1 : Float16Array,
		'%Float32Array%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array,
		'%Float64Array%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array,
		'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined$1 : FinalizationRegistry,
		'%Function%': $Function,
		'%GeneratorFunction%': needsEval,
		'%Int8Array%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array,
		'%Int16Array%': typeof Int16Array === 'undefined' ? undefined$1 : Int16Array,
		'%Int32Array%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array,
		'%isFinite%': isFinite,
		'%isNaN%': isNaN,
		'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined$1,
		'%JSON%': typeof JSON === 'object' ? JSON : undefined$1,
		'%Map%': typeof Map === 'undefined' ? undefined$1 : Map,
		'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined$1 : getProto(new Map()[Symbol.iterator]()),
		'%Math%': Math,
		'%Number%': Number,
		'%Object%': $Object,
		'%Object.getOwnPropertyDescriptor%': $gOPD,
		'%parseFloat%': parseFloat,
		'%parseInt%': parseInt,
		'%Promise%': typeof Promise === 'undefined' ? undefined$1 : Promise,
		'%Proxy%': typeof Proxy === 'undefined' ? undefined$1 : Proxy,
		'%RangeError%': $RangeError,
		'%ReferenceError%': $ReferenceError,
		'%Reflect%': typeof Reflect === 'undefined' ? undefined$1 : Reflect,
		'%RegExp%': RegExp,
		'%Set%': typeof Set === 'undefined' ? undefined$1 : Set,
		'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined$1 : getProto(new Set()[Symbol.iterator]()),
		'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer,
		'%String%': String,
		'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined$1,
		'%Symbol%': hasSymbols ? Symbol : undefined$1,
		'%SyntaxError%': $SyntaxError,
		'%ThrowTypeError%': ThrowTypeError,
		'%TypedArray%': TypedArray,
		'%TypeError%': $TypeError,
		'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array,
		'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray,
		'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array,
		'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array,
		'%URIError%': $URIError,
		'%WeakMap%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap,
		'%WeakRef%': typeof WeakRef === 'undefined' ? undefined$1 : WeakRef,
		'%WeakSet%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet,

		'%Function.prototype.call%': $call,
		'%Function.prototype.apply%': $apply,
		'%Object.defineProperty%': $defineProperty,
		'%Object.getPrototypeOf%': $ObjectGPO,
		'%Math.abs%': abs,
		'%Math.floor%': floor,
		'%Math.max%': max,
		'%Math.min%': min,
		'%Math.pow%': pow,
		'%Math.round%': round,
		'%Math.sign%': sign,
		'%Reflect.getPrototypeOf%': $ReflectGPO
	};

	if (getProto) {
		try {
			null.error; // eslint-disable-line no-unused-expressions
		} catch (e) {
			// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
			var errorProto = getProto(getProto(e));
			INTRINSICS['%Error.prototype%'] = errorProto;
		}
	}

	var doEval = function doEval(name) {
		var value;
		if (name === '%AsyncFunction%') {
			value = getEvalledConstructor('async function () {}');
		} else if (name === '%GeneratorFunction%') {
			value = getEvalledConstructor('function* () {}');
		} else if (name === '%AsyncGeneratorFunction%') {
			value = getEvalledConstructor('async function* () {}');
		} else if (name === '%AsyncGenerator%') {
			var fn = doEval('%AsyncGeneratorFunction%');
			if (fn) {
				value = fn.prototype;
			}
		} else if (name === '%AsyncIteratorPrototype%') {
			var gen = doEval('%AsyncGenerator%');
			if (gen && getProto) {
				value = getProto(gen.prototype);
			}
		}

		INTRINSICS[name] = value;

		return value;
	};

	var LEGACY_ALIASES = {
		__proto__: null,
		'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
		'%ArrayPrototype%': ['Array', 'prototype'],
		'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
		'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
		'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
		'%ArrayProto_values%': ['Array', 'prototype', 'values'],
		'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
		'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
		'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
		'%BooleanPrototype%': ['Boolean', 'prototype'],
		'%DataViewPrototype%': ['DataView', 'prototype'],
		'%DatePrototype%': ['Date', 'prototype'],
		'%ErrorPrototype%': ['Error', 'prototype'],
		'%EvalErrorPrototype%': ['EvalError', 'prototype'],
		'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
		'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
		'%FunctionPrototype%': ['Function', 'prototype'],
		'%Generator%': ['GeneratorFunction', 'prototype'],
		'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
		'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
		'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
		'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
		'%JSONParse%': ['JSON', 'parse'],
		'%JSONStringify%': ['JSON', 'stringify'],
		'%MapPrototype%': ['Map', 'prototype'],
		'%NumberPrototype%': ['Number', 'prototype'],
		'%ObjectPrototype%': ['Object', 'prototype'],
		'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
		'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
		'%PromisePrototype%': ['Promise', 'prototype'],
		'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
		'%Promise_all%': ['Promise', 'all'],
		'%Promise_reject%': ['Promise', 'reject'],
		'%Promise_resolve%': ['Promise', 'resolve'],
		'%RangeErrorPrototype%': ['RangeError', 'prototype'],
		'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
		'%RegExpPrototype%': ['RegExp', 'prototype'],
		'%SetPrototype%': ['Set', 'prototype'],
		'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
		'%StringPrototype%': ['String', 'prototype'],
		'%SymbolPrototype%': ['Symbol', 'prototype'],
		'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
		'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
		'%TypeErrorPrototype%': ['TypeError', 'prototype'],
		'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
		'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
		'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
		'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
		'%URIErrorPrototype%': ['URIError', 'prototype'],
		'%WeakMapPrototype%': ['WeakMap', 'prototype'],
		'%WeakSetPrototype%': ['WeakSet', 'prototype']
	};

	var bind = requireFunctionBind();
	var hasOwn = /*@__PURE__*/ requireHasown();
	var $concat = bind.call($call, Array.prototype.concat);
	var $spliceApply = bind.call($apply, Array.prototype.splice);
	var $replace = bind.call($call, String.prototype.replace);
	var $strSlice = bind.call($call, String.prototype.slice);
	var $exec = bind.call($call, RegExp.prototype.exec);

	/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
	var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
	var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
	var stringToPath = function stringToPath(string) {
		var first = $strSlice(string, 0, 1);
		var last = $strSlice(string, -1);
		if (first === '%' && last !== '%') {
			throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
		} else if (last === '%' && first !== '%') {
			throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
		}
		var result = [];
		$replace(string, rePropName, function (match, number, quote, subString) {
			result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
		});
		return result;
	};
	/* end adaptation */

	var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
		var intrinsicName = name;
		var alias;
		if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
			alias = LEGACY_ALIASES[intrinsicName];
			intrinsicName = '%' + alias[0] + '%';
		}

		if (hasOwn(INTRINSICS, intrinsicName)) {
			var value = INTRINSICS[intrinsicName];
			if (value === needsEval) {
				value = doEval(intrinsicName);
			}
			if (typeof value === 'undefined' && !allowMissing) {
				throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
			}

			return {
				alias: alias,
				name: intrinsicName,
				value: value
			};
		}

		throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
	};

	getIntrinsic = function GetIntrinsic(name, allowMissing) {
		if (typeof name !== 'string' || name.length === 0) {
			throw new $TypeError('intrinsic name must be a non-empty string');
		}
		if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
			throw new $TypeError('"allowMissing" argument must be a boolean');
		}

		if ($exec(/^%?[^%]*%?$/, name) === null) {
			throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
		}
		var parts = stringToPath(name);
		var intrinsicBaseName = parts.length > 0 ? parts[0] : '';

		var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
		var intrinsicRealName = intrinsic.name;
		var value = intrinsic.value;
		var skipFurtherCaching = false;

		var alias = intrinsic.alias;
		if (alias) {
			intrinsicBaseName = alias[0];
			$spliceApply(parts, $concat([0, 1], alias));
		}

		for (var i = 1, isOwn = true; i < parts.length; i += 1) {
			var part = parts[i];
			var first = $strSlice(part, 0, 1);
			var last = $strSlice(part, -1);
			if (
				(
					(first === '"' || first === "'" || first === '`')
					|| (last === '"' || last === "'" || last === '`')
				)
				&& first !== last
			) {
				throw new $SyntaxError('property names with quotes must have matching quotes');
			}
			if (part === 'constructor' || !isOwn) {
				skipFurtherCaching = true;
			}

			intrinsicBaseName += '.' + part;
			intrinsicRealName = '%' + intrinsicBaseName + '%';

			if (hasOwn(INTRINSICS, intrinsicRealName)) {
				value = INTRINSICS[intrinsicRealName];
			} else if (value != null) {
				if (!(part in value)) {
					if (!allowMissing) {
						throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
					}
					return void undefined$1;
				}
				if ($gOPD && (i + 1) >= parts.length) {
					var desc = $gOPD(value, part);
					isOwn = !!desc;

					// By convention, when a data property is converted to an accessor
					// property to emulate a data property that does not suffer from
					// the override mistake, that accessor's getter is marked with
					// an `originalValue` property. Here, when we detect this, we
					// uphold the illusion by pretending to see that original data
					// property, i.e., returning the value rather than the getter
					// itself.
					if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
						value = desc.get;
					} else {
						value = value[part];
					}
				} else {
					isOwn = hasOwn(value, part);
					value = value[part];
				}

				if (isOwn && !skipFurtherCaching) {
					INTRINSICS[intrinsicRealName] = value;
				}
			}
		}
		return value;
	};
	return getIntrinsic;
}

var callBound;
var hasRequiredCallBound;

function requireCallBound () {
	if (hasRequiredCallBound) return callBound;
	hasRequiredCallBound = 1;

	var GetIntrinsic = /*@__PURE__*/ requireGetIntrinsic();

	var callBindBasic = requireCallBindApplyHelpers();

	/** @type {(thisArg: string, searchString: string, position?: number) => number} */
	var $indexOf = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]);

	/** @type {import('.')} */
	callBound = function callBoundIntrinsic(name, allowMissing) {
		/* eslint no-extra-parens: 0 */

		var intrinsic = /** @type {(this: unknown, ...args: unknown[]) => unknown} */ (GetIntrinsic(name, !!allowMissing));
		if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
			return callBindBasic(/** @type {const} */ ([intrinsic]));
		}
		return intrinsic;
	};
	return callBound;
}

var isCallable;
var hasRequiredIsCallable;

function requireIsCallable () {
	if (hasRequiredIsCallable) return isCallable;
	hasRequiredIsCallable = 1;

	var fnToStr = Function.prototype.toString;
	var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply;
	var badArrayLike;
	var isCallableMarker;
	if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') {
		try {
			badArrayLike = Object.defineProperty({}, 'length', {
				get: function () {
					throw isCallableMarker;
				}
			});
			isCallableMarker = {};
			// eslint-disable-next-line no-throw-literal
			reflectApply(function () { throw 42; }, null, badArrayLike);
		} catch (_) {
			if (_ !== isCallableMarker) {
				reflectApply = null;
			}
		}
	} else {
		reflectApply = null;
	}

	var constructorRegex = /^\s*class\b/;
	var isES6ClassFn = function isES6ClassFunction(value) {
		try {
			var fnStr = fnToStr.call(value);
			return constructorRegex.test(fnStr);
		} catch (e) {
			return false; // not a function
		}
	};

	var tryFunctionObject = function tryFunctionToStr(value) {
		try {
			if (isES6ClassFn(value)) { return false; }
			fnToStr.call(value);
			return true;
		} catch (e) {
			return false;
		}
	};
	var toStr = Object.prototype.toString;
	var objectClass = '[object Object]';
	var fnClass = '[object Function]';
	var genClass = '[object GeneratorFunction]';
	var ddaClass = '[object HTMLAllCollection]'; // IE 11
	var ddaClass2 = '[object HTML document.all class]';
	var ddaClass3 = '[object HTMLCollection]'; // IE 9-10
	var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag`

	var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing

	var isDDA = function isDocumentDotAll() { return false; };
	if (typeof document === 'object') {
		// Firefox 3 canonicalizes DDA to undefined when it's not accessed directly
		var all = document.all;
		if (toStr.call(all) === toStr.call(document.all)) {
			isDDA = function isDocumentDotAll(value) {
				/* globals document: false */
				// in IE 6-8, typeof document.all is "object" and it's truthy
				if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) {
					try {
						var str = toStr.call(value);
						return (
							str === ddaClass
							|| str === ddaClass2
							|| str === ddaClass3 // opera 12.16
							|| str === objectClass // IE 6-8
						) && value('') == null; // eslint-disable-line eqeqeq
					} catch (e) { /**/ }
				}
				return false;
			};
		}
	}

	isCallable = reflectApply
		? function isCallable(value) {
			if (isDDA(value)) { return true; }
			if (!value) { return false; }
			if (typeof value !== 'function' && typeof value !== 'object') { return false; }
			try {
				reflectApply(value, null, badArrayLike);
			} catch (e) {
				if (e !== isCallableMarker) { return false; }
			}
			return !isES6ClassFn(value) && tryFunctionObject(value);
		}
		: function isCallable(value) {
			if (isDDA(value)) { return true; }
			if (!value) { return false; }
			if (typeof value !== 'function' && typeof value !== 'object') { return false; }
			if (hasToStringTag) { return tryFunctionObject(value); }
			if (isES6ClassFn(value)) { return false; }
			var strClass = toStr.call(value);
			if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) { return false; }
			return tryFunctionObject(value);
		};
	return isCallable;
}

var forEach$1;
var hasRequiredForEach$1;

function requireForEach$1 () {
	if (hasRequiredForEach$1) return forEach$1;
	hasRequiredForEach$1 = 1;

	var isCallable = requireIsCallable();

	var toStr = Object.prototype.toString;
	var hasOwnProperty = Object.prototype.hasOwnProperty;

	/** @type {<This, A extends readonly unknown[]>(arr: A, iterator: (this: This | void, value: A[number], index: number, arr: A) => void, receiver: This | undefined) => void} */
	var forEachArray = function forEachArray(array, iterator, receiver) {
	    for (var i = 0, len = array.length; i < len; i++) {
	        if (hasOwnProperty.call(array, i)) {
	            if (receiver == null) {
	                iterator(array[i], i, array);
	            } else {
	                iterator.call(receiver, array[i], i, array);
	            }
	        }
	    }
	};

	/** @type {<This, S extends string>(string: S, iterator: (this: This | void, value: S[number], index: number, string: S) => void, receiver: This | undefined) => void} */
	var forEachString = function forEachString(string, iterator, receiver) {
	    for (var i = 0, len = string.length; i < len; i++) {
	        // no such thing as a sparse string.
	        if (receiver == null) {
	            iterator(string.charAt(i), i, string);
	        } else {
	            iterator.call(receiver, string.charAt(i), i, string);
	        }
	    }
	};

	/** @type {<This, O>(obj: O, iterator: (this: This | void, value: O[keyof O], index: keyof O, obj: O) => void, receiver: This | undefined) => void} */
	var forEachObject = function forEachObject(object, iterator, receiver) {
	    for (var k in object) {
	        if (hasOwnProperty.call(object, k)) {
	            if (receiver == null) {
	                iterator(object[k], k, object);
	            } else {
	                iterator.call(receiver, object[k], k, object);
	            }
	        }
	    }
	};

	/** @type {(x: unknown) => x is readonly unknown[]} */
	function isArray(x) {
	    return toStr.call(x) === '[object Array]';
	}

	/** @type {import('.')._internal} */
	forEach$1 = function forEach(list, iterator, thisArg) {
	    if (!isCallable(iterator)) {
	        throw new TypeError('iterator must be a function');
	    }

	    var receiver;
	    if (arguments.length >= 3) {
	        receiver = thisArg;
	    }

	    if (isArray(list)) {
	        forEachArray(list, iterator, receiver);
	    } else if (typeof list === 'string') {
	        forEachString(list, iterator, receiver);
	    } else {
	        forEachObject(list, iterator, receiver);
	    }
	};
	return forEach$1;
}

var possibleTypedArrayNames;
var hasRequiredPossibleTypedArrayNames;

function requirePossibleTypedArrayNames () {
	if (hasRequiredPossibleTypedArrayNames) return possibleTypedArrayNames;
	hasRequiredPossibleTypedArrayNames = 1;

	/** @type {import('.')} */
	possibleTypedArrayNames = [
		'Float16Array',
		'Float32Array',
		'Float64Array',
		'Int8Array',
		'Int16Array',
		'Int32Array',
		'Uint8Array',
		'Uint8ClampedArray',
		'Uint16Array',
		'Uint32Array',
		'BigInt64Array',
		'BigUint64Array'
	];
	return possibleTypedArrayNames;
}

var availableTypedArrays;
var hasRequiredAvailableTypedArrays;

function requireAvailableTypedArrays () {
	if (hasRequiredAvailableTypedArrays) return availableTypedArrays;
	hasRequiredAvailableTypedArrays = 1;

	var possibleNames = /*@__PURE__*/ requirePossibleTypedArrayNames();

	var g = typeof globalThis === 'undefined' ? commonjsGlobal : globalThis;

	/** @type {import('.')} */
	availableTypedArrays = function availableTypedArrays() {
		var /** @type {ReturnType<typeof availableTypedArrays>} */ out = [];
		for (var i = 0; i < possibleNames.length; i++) {
			if (typeof g[possibleNames[i]] === 'function') {
				// @ts-expect-error
				out[out.length] = possibleNames[i];
			}
		}
		return out;
	};
	return availableTypedArrays;
}

var callBind = {exports: {}};

var defineDataProperty;
var hasRequiredDefineDataProperty;

function requireDefineDataProperty () {
	if (hasRequiredDefineDataProperty) return defineDataProperty;
	hasRequiredDefineDataProperty = 1;

	var $defineProperty = /*@__PURE__*/ requireEsDefineProperty();

	var $SyntaxError = /*@__PURE__*/ requireSyntax();
	var $TypeError = /*@__PURE__*/ requireType();

	var gopd = /*@__PURE__*/ requireGopd();

	/** @type {import('.')} */
	defineDataProperty = function defineDataProperty(
		obj,
		property,
		value
	) {
		if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
			throw new $TypeError('`obj` must be an object or a function`');
		}
		if (typeof property !== 'string' && typeof property !== 'symbol') {
			throw new $TypeError('`property` must be a string or a symbol`');
		}
		if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) {
			throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null');
		}
		if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) {
			throw new $TypeError('`nonWritable`, if provided, must be a boolean or null');
		}
		if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) {
			throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null');
		}
		if (arguments.length > 6 && typeof arguments[6] !== 'boolean') {
			throw new $TypeError('`loose`, if provided, must be a boolean');
		}

		var nonEnumerable = arguments.length > 3 ? arguments[3] : null;
		var nonWritable = arguments.length > 4 ? arguments[4] : null;
		var nonConfigurable = arguments.length > 5 ? arguments[5] : null;
		var loose = arguments.length > 6 ? arguments[6] : false;

		/* @type {false | TypedPropertyDescriptor<unknown>} */
		var desc = !!gopd && gopd(obj, property);

		if ($defineProperty) {
			$defineProperty(obj, property, {
				configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable,
				enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable,
				value: value,
				writable: nonWritable === null && desc ? desc.writable : !nonWritable
			});
		} else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) {
			// must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable
			obj[property] = value; // eslint-disable-line no-param-reassign
		} else {
			throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.');
		}
	};
	return defineDataProperty;
}

var hasPropertyDescriptors_1;
var hasRequiredHasPropertyDescriptors;

function requireHasPropertyDescriptors () {
	if (hasRequiredHasPropertyDescriptors) return hasPropertyDescriptors_1;
	hasRequiredHasPropertyDescriptors = 1;

	var $defineProperty = /*@__PURE__*/ requireEsDefineProperty();

	var hasPropertyDescriptors = function hasPropertyDescriptors() {
		return !!$defineProperty;
	};

	hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() {
		// node v0.6 has a bug where array lengths can be Set but not Defined
		if (!$defineProperty) {
			return null;
		}
		try {
			return $defineProperty([], 'length', { value: 1 }).length !== 1;
		} catch (e) {
			// In Firefox 4-22, defining length on an array throws an exception.
			return true;
		}
	};

	hasPropertyDescriptors_1 = hasPropertyDescriptors;
	return hasPropertyDescriptors_1;
}

var setFunctionLength;
var hasRequiredSetFunctionLength;

function requireSetFunctionLength () {
	if (hasRequiredSetFunctionLength) return setFunctionLength;
	hasRequiredSetFunctionLength = 1;

	var GetIntrinsic = /*@__PURE__*/ requireGetIntrinsic();
	var define = /*@__PURE__*/ requireDefineDataProperty();
	var hasDescriptors = /*@__PURE__*/ requireHasPropertyDescriptors()();
	var gOPD = /*@__PURE__*/ requireGopd();

	var $TypeError = /*@__PURE__*/ requireType();
	var $floor = GetIntrinsic('%Math.floor%');

	/** @type {import('.')} */
	setFunctionLength = function setFunctionLength(fn, length) {
		if (typeof fn !== 'function') {
			throw new $TypeError('`fn` is not a function');
		}
		if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) {
			throw new $TypeError('`length` must be a positive 32-bit integer');
		}

		var loose = arguments.length > 2 && !!arguments[2];

		var functionLengthIsConfigurable = true;
		var functionLengthIsWritable = true;
		if ('length' in fn && gOPD) {
			var desc = gOPD(fn, 'length');
			if (desc && !desc.configurable) {
				functionLengthIsConfigurable = false;
			}
			if (desc && !desc.writable) {
				functionLengthIsWritable = false;
			}
		}

		if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) {
			if (hasDescriptors) {
				define(/** @type {Parameters<define>[0]} */ (fn), 'length', length, true, true);
			} else {
				define(/** @type {Parameters<define>[0]} */ (fn), 'length', length);
			}
		}
		return fn;
	};
	return setFunctionLength;
}

var applyBind;
var hasRequiredApplyBind;

function requireApplyBind () {
	if (hasRequiredApplyBind) return applyBind;
	hasRequiredApplyBind = 1;

	var bind = requireFunctionBind();
	var $apply = requireFunctionApply();
	var actualApply = requireActualApply();

	/** @type {import('./applyBind')} */
	applyBind = function applyBind() {
		return actualApply(bind, $apply, arguments);
	};
	return applyBind;
}

var hasRequiredCallBind;

function requireCallBind () {
	if (hasRequiredCallBind) return callBind.exports;
	hasRequiredCallBind = 1;
	(function (module) {

		var setFunctionLength = /*@__PURE__*/ requireSetFunctionLength();

		var $defineProperty = /*@__PURE__*/ requireEsDefineProperty();

		var callBindBasic = requireCallBindApplyHelpers();
		var applyBind = requireApplyBind();

		module.exports = function callBind(originalFunction) {
			var func = callBindBasic(arguments);
			var adjustedLength = originalFunction.length - (arguments.length - 1);
			return setFunctionLength(
				func,
				1 + (adjustedLength > 0 ? adjustedLength : 0),
				true
			);
		};

		if ($defineProperty) {
			$defineProperty(module.exports, 'apply', { value: applyBind });
		} else {
			module.exports.apply = applyBind;
		} 
	} (callBind));
	return callBind.exports;
}

var shams;
var hasRequiredShams;

function requireShams () {
	if (hasRequiredShams) return shams;
	hasRequiredShams = 1;

	var hasSymbols = requireShams$1();

	/** @type {import('.')} */
	shams = function hasToStringTagShams() {
		return hasSymbols() && !!Symbol.toStringTag;
	};
	return shams;
}

var whichTypedArray;
var hasRequiredWhichTypedArray;

function requireWhichTypedArray () {
	if (hasRequiredWhichTypedArray) return whichTypedArray;
	hasRequiredWhichTypedArray = 1;

	var forEach = requireForEach$1();
	var availableTypedArrays = /*@__PURE__*/ requireAvailableTypedArrays();
	var callBind = requireCallBind();
	var callBound = /*@__PURE__*/ requireCallBound();
	var gOPD = /*@__PURE__*/ requireGopd();
	var getProto = requireGetProto();

	var $toString = callBound('Object.prototype.toString');
	var hasToStringTag = requireShams()();

	var g = typeof globalThis === 'undefined' ? commonjsGlobal : globalThis;
	var typedArrays = availableTypedArrays();

	var $slice = callBound('String.prototype.slice');

	/** @type {<T = unknown>(array: readonly T[], value: unknown) => number} */
	var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) {
		for (var i = 0; i < array.length; i += 1) {
			if (array[i] === value) {
				return i;
			}
		}
		return -1;
	};

	/** @typedef {import('./types').Getter} Getter */
	/** @type {import('./types').Cache} */
	var cache = { __proto__: null };
	if (hasToStringTag && gOPD && getProto) {
		forEach(typedArrays, function (typedArray) {
			var arr = new g[typedArray]();
			if (Symbol.toStringTag in arr && getProto) {
				var proto = getProto(arr);
				// @ts-expect-error TS won't narrow inside a closure
				var descriptor = gOPD(proto, Symbol.toStringTag);
				if (!descriptor && proto) {
					var superProto = getProto(proto);
					// @ts-expect-error TS won't narrow inside a closure
					descriptor = gOPD(superProto, Symbol.toStringTag);
				}
				// @ts-expect-error TODO: fix
				cache['$' + typedArray] = callBind(descriptor.get);
			}
		});
	} else {
		forEach(typedArrays, function (typedArray) {
			var arr = new g[typedArray]();
			var fn = arr.slice || arr.set;
			if (fn) {
				cache[
					/** @type {`$${import('.').TypedArrayName}`} */ ('$' + typedArray)
				] = /** @type {import('./types').BoundSlice | import('./types').BoundSet} */ (
					// @ts-expect-error TODO FIXME
					callBind(fn)
				);
			}
		});
	}

	/** @type {(value: object) => false | import('.').TypedArrayName} */
	var tryTypedArrays = function tryAllTypedArrays(value) {
		/** @type {ReturnType<typeof tryAllTypedArrays>} */ var found = false;
		forEach(
			/** @type {Record<`\$${import('.').TypedArrayName}`, Getter>} */ (cache),
			/** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */
			function (getter, typedArray) {
				if (!found) {
					try {
						// @ts-expect-error a throw is fine here
						if ('$' + getter(value) === typedArray) {
							found = /** @type {import('.').TypedArrayName} */ ($slice(typedArray, 1));
						}
					} catch (e) { /**/ }
				}
			}
		);
		return found;
	};

	/** @type {(value: object) => false | import('.').TypedArrayName} */
	var trySlices = function tryAllSlices(value) {
		/** @type {ReturnType<typeof tryAllSlices>} */ var found = false;
		forEach(
			/** @type {Record<`\$${import('.').TypedArrayName}`, Getter>} */(cache),
			/** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */ function (getter, name) {
				if (!found) {
					try {
						// @ts-expect-error a throw is fine here
						getter(value);
						found = /** @type {import('.').TypedArrayName} */ ($slice(name, 1));
					} catch (e) { /**/ }
				}
			}
		);
		return found;
	};

	/** @type {import('.')} */
	whichTypedArray = function whichTypedArray(value) {
		if (!value || typeof value !== 'object') { return false; }
		if (!hasToStringTag) {
			/** @type {string} */
			var tag = $slice($toString(value), 8, -1);
			if ($indexOf(typedArrays, tag) > -1) {
				return tag;
			}
			if (tag !== 'Object') {
				return false;
			}
			// node < 0.6 hits here on real Typed Arrays
			return trySlices(value);
		}
		if (!gOPD) { return null; } // unknown engine
		return tryTypedArrays(value);
	};
	return whichTypedArray;
}

var isTypedArray;
var hasRequiredIsTypedArray;

function requireIsTypedArray () {
	if (hasRequiredIsTypedArray) return isTypedArray;
	hasRequiredIsTypedArray = 1;

	var whichTypedArray = /*@__PURE__*/ requireWhichTypedArray();

	/** @type {import('.')} */
	isTypedArray = function isTypedArray(value) {
		return !!whichTypedArray(value);
	};
	return isTypedArray;
}

var typedArrayBuffer;
var hasRequiredTypedArrayBuffer;

function requireTypedArrayBuffer () {
	if (hasRequiredTypedArrayBuffer) return typedArrayBuffer;
	hasRequiredTypedArrayBuffer = 1;

	var $TypeError = /*@__PURE__*/ requireType();

	var callBound = /*@__PURE__*/ requireCallBound();

	/** @type {undefined | ((thisArg: import('.').TypedArray) => Buffer<ArrayBufferLike>)} */
	var $typedArrayBuffer = callBound('TypedArray.prototype.buffer', true);

	var isTypedArray = /*@__PURE__*/ requireIsTypedArray();

	/** @type {import('.')} */
	// node <= 0.10, < 0.11.4 has a nonconfigurable own property instead of a prototype getter
	typedArrayBuffer = $typedArrayBuffer || function typedArrayBuffer(x) {
		if (!isTypedArray(x)) {
			throw new $TypeError('Not a Typed Array');
		}
		return x.buffer;
	};
	return typedArrayBuffer;
}

var toBuffer$1;
var hasRequiredToBuffer;

function requireToBuffer () {
	if (hasRequiredToBuffer) return toBuffer$1;
	hasRequiredToBuffer = 1;

	var Buffer = requireSafeBuffer().Buffer;
	var isArray = requireIsarray();
	var typedArrayBuffer = /*@__PURE__*/ requireTypedArrayBuffer();

	var isView = ArrayBuffer.isView || function isView(obj) {
		try {
			typedArrayBuffer(obj);
			return true;
		} catch (e) {
			return false;
		}
	};

	var useUint8Array = typeof Uint8Array !== 'undefined';
	var useArrayBuffer = typeof ArrayBuffer !== 'undefined'
		&& typeof Uint8Array !== 'undefined';
	var useFromArrayBuffer = useArrayBuffer && (Buffer.prototype instanceof Uint8Array || Buffer.TYPED_ARRAY_SUPPORT);

	toBuffer$1 = function toBuffer(data, encoding) {
		if (Buffer.isBuffer(data)) {
			if (data.constructor && !('isBuffer' in data)) {
				// probably a SlowBuffer
				return Buffer.from(data);
			}
			return data;
		}

		if (typeof data === 'string') {
			return Buffer.from(data, encoding);
		}

		/*
		 * Wrap any TypedArray instances and DataViews
		 * Makes sense only on engines with full TypedArray support -- let Buffer detect that
		 */
		if (useArrayBuffer && isView(data)) {
			// Bug in Node.js <6.3.1, which treats this as out-of-bounds
			if (data.byteLength === 0) {
				return Buffer.alloc(0);
			}

			// When Buffer is based on Uint8Array, we can just construct it from ArrayBuffer
			if (useFromArrayBuffer) {
				var res = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
				/*
				 * Recheck result size, as offset/length doesn't work on Node.js <5.10
				 * We just go to Uint8Array case if this fails
				 */
				if (res.byteLength === data.byteLength) {
					return res;
				}
			}

			// Convert to Uint8Array bytes and then to Buffer
			var uint8 = data instanceof Uint8Array ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
			var result = Buffer.from(uint8);

			/*
			 * Let's recheck that conversion succeeded
			 * We have .length but not .byteLength when useFromArrayBuffer is false
			 */
			if (result.length === data.byteLength) {
				return result;
			}
		}

		/*
		 * Uint8Array in engines where Buffer.from might not work with ArrayBuffer, just copy over
		 * Doesn't make sense with other TypedArray instances
		 */
		if (useUint8Array && data instanceof Uint8Array) {
			return Buffer.from(data);
		}

		var isArr = isArray(data);
		if (isArr) {
			for (var i = 0; i < data.length; i += 1) {
				var x = data[i];
				if (
					typeof x !== 'number'
					|| x < 0
					|| x > 255
					|| ~~x !== x // NaN and integer check
				) {
					throw new RangeError('Array items must be numbers in the range 0-255.');
				}
			}
		}

		/*
		 * Old Buffer polyfill on an engine that doesn't have TypedArray support
		 * Also, this is from a different Buffer polyfill implementation then we have, as instanceof check failed
		 * Convert to our current Buffer implementation
		 */
		if (
			isArr || (
				Buffer.isBuffer(data)
				&& data.constructor
				&& typeof data.constructor.isBuffer === 'function'
				&& data.constructor.isBuffer(data)
			)
		) {
			return Buffer.from(data);
		}

		throw new TypeError('The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.');
	};
	return toBuffer$1;
}

/* Node.js 6.4.0 and up has full support */

var bufferFill;
var hasRequiredBufferFill;

function requireBufferFill () {
	if (hasRequiredBufferFill) return bufferFill;
	hasRequiredBufferFill = 1;
	var hasFullSupport = (function () {
	  try {
	    if (!Buffer.isEncoding('latin1')) {
	      return false
	    }

	    var buf = Buffer.alloc ? Buffer.alloc(4) : new Buffer(4);

	    buf.fill('ab', 'ucs2');

	    return (buf.toString('hex') === '61006200')
	  } catch (_) {
	    return false
	  }
	}());

	function isSingleByte (val) {
	  return (val.length === 1 && val.charCodeAt(0) < 256)
	}

	function fillWithNumber (buffer, val, start, end) {
	  if (start < 0 || end > buffer.length) {
	    throw new RangeError('Out of range index')
	  }

	  start = start >>> 0;
	  end = end === undefined ? buffer.length : end >>> 0;

	  if (end > start) {
	    buffer.fill(val, start, end);
	  }

	  return buffer
	}

	function fillWithBuffer (buffer, val, start, end) {
	  if (start < 0 || end > buffer.length) {
	    throw new RangeError('Out of range index')
	  }

	  if (end <= start) {
	    return buffer
	  }

	  start = start >>> 0;
	  end = end === undefined ? buffer.length : end >>> 0;

	  var pos = start;
	  var len = val.length;
	  while (pos <= (end - len)) {
	    val.copy(buffer, pos);
	    pos += len;
	  }

	  if (pos !== end) {
	    val.copy(buffer, pos, 0, end - pos);
	  }

	  return buffer
	}

	function fill (buffer, val, start, end, encoding) {
	  if (hasFullSupport) {
	    return buffer.fill(val, start, end, encoding)
	  }

	  if (typeof val === 'number') {
	    return fillWithNumber(buffer, val, start, end)
	  }

	  if (typeof val === 'string') {
	    if (typeof start === 'string') {
	      encoding = start;
	      start = 0;
	      end = buffer.length;
	    } else if (typeof end === 'string') {
	      encoding = end;
	      end = buffer.length;
	    }

	    if (encoding !== undefined && typeof encoding !== 'string') {
	      throw new TypeError('encoding must be a string')
	    }

	    if (encoding === 'latin1') {
	      encoding = 'binary';
	    }

	    if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
	      throw new TypeError('Unknown encoding: ' + encoding)
	    }

	    if (val === '') {
	      return fillWithNumber(buffer, 0, start, end)
	    }

	    if (isSingleByte(val)) {
	      return fillWithNumber(buffer, val.charCodeAt(0), start, end)
	    }

	    val = new Buffer(val, encoding);
	  }

	  if (Buffer.isBuffer(val)) {
	    return fillWithBuffer(buffer, val, start, end)
	  }

	  // Other values (e.g. undefined, boolean, object) results in zero-fill
	  return fillWithNumber(buffer, 0, start, end)
	}

	bufferFill = fill;
	return bufferFill;
}

var bufferAllocUnsafe;
var hasRequiredBufferAllocUnsafe;

function requireBufferAllocUnsafe () {
	if (hasRequiredBufferAllocUnsafe) return bufferAllocUnsafe;
	hasRequiredBufferAllocUnsafe = 1;
	function allocUnsafe (size) {
	  if (typeof size !== 'number') {
	    throw new TypeError('"size" argument must be a number')
	  }

	  if (size < 0) {
	    throw new RangeError('"size" argument must not be negative')
	  }

	  if (Buffer.allocUnsafe) {
	    return Buffer.allocUnsafe(size)
	  } else {
	    return new Buffer(size)
	  }
	}

	bufferAllocUnsafe = allocUnsafe;
	return bufferAllocUnsafe;
}

var bufferAlloc;
var hasRequiredBufferAlloc;

function requireBufferAlloc () {
	if (hasRequiredBufferAlloc) return bufferAlloc;
	hasRequiredBufferAlloc = 1;
	var bufferFill = requireBufferFill();
	var allocUnsafe = requireBufferAllocUnsafe();

	bufferAlloc = function alloc (size, fill, encoding) {
	  if (typeof size !== 'number') {
	    throw new TypeError('"size" argument must be a number')
	  }

	  if (size < 0) {
	    throw new RangeError('"size" argument must not be negative')
	  }

	  if (Buffer.alloc) {
	    return Buffer.alloc(size, fill, encoding)
	  }

	  var buffer = allocUnsafe(size);

	  if (size === 0) {
	    return buffer
	  }

	  if (fill === undefined) {
	    return bufferFill(buffer, 0)
	  }

	  if (typeof encoding !== 'string') {
	    encoding = undefined;
	  }

	  return bufferFill(buffer, fill, encoding)
	};
	return bufferAlloc;
}

var hasRequiredHeaders;

function requireHeaders () {
	if (hasRequiredHeaders) return headers;
	hasRequiredHeaders = 1;
	var toBuffer = /*@__PURE__*/ requireToBuffer();
	var alloc = requireBufferAlloc();

	var ZEROS = '0000000000000000000';
	var SEVENS = '7777777777777777777';
	var ZERO_OFFSET = '0'.charCodeAt(0);
	var USTAR = 'ustar\x0000';
	var MASK = parseInt('7777', 8);

	var clamp = function (index, len, defaultValue) {
	  if (typeof index !== 'number') return defaultValue
	  index = ~~index; // Coerce to integer.
	  if (index >= len) return len
	  if (index >= 0) return index
	  index += len;
	  if (index >= 0) return index
	  return 0
	};

	var toType = function (flag) {
	  switch (flag) {
	    case 0:
	      return 'file'
	    case 1:
	      return 'link'
	    case 2:
	      return 'symlink'
	    case 3:
	      return 'character-device'
	    case 4:
	      return 'block-device'
	    case 5:
	      return 'directory'
	    case 6:
	      return 'fifo'
	    case 7:
	      return 'contiguous-file'
	    case 72:
	      return 'pax-header'
	    case 55:
	      return 'pax-global-header'
	    case 27:
	      return 'gnu-long-link-path'
	    case 28:
	    case 30:
	      return 'gnu-long-path'
	  }

	  return null
	};

	var toTypeflag = function (flag) {
	  switch (flag) {
	    case 'file':
	      return 0
	    case 'link':
	      return 1
	    case 'symlink':
	      return 2
	    case 'character-device':
	      return 3
	    case 'block-device':
	      return 4
	    case 'directory':
	      return 5
	    case 'fifo':
	      return 6
	    case 'contiguous-file':
	      return 7
	    case 'pax-header':
	      return 72
	  }

	  return 0
	};

	var indexOf = function (block, num, offset, end) {
	  for (; offset < end; offset++) {
	    if (block[offset] === num) return offset
	  }
	  return end
	};

	var cksum = function (block) {
	  var sum = 8 * 32;
	  for (var i = 0; i < 148; i++) sum += block[i];
	  for (var j = 156; j < 512; j++) sum += block[j];
	  return sum
	};

	var encodeOct = function (val, n) {
	  val = val.toString(8);
	  if (val.length > n) return SEVENS.slice(0, n) + ' '
	  else return ZEROS.slice(0, n - val.length) + val + ' '
	};

	/* Copied from the node-tar repo and modified to meet
	 * tar-stream coding standard.
	 *
	 * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349
	 */
	function parse256 (buf) {
	  // first byte MUST be either 80 or FF
	  // 80 for positive, FF for 2's comp
	  var positive;
	  if (buf[0] === 0x80) positive = true;
	  else if (buf[0] === 0xFF) positive = false;
	  else return null
	  var tuple = [];
	  for (var i = buf.length - 1; i > 0; i--) {
	    var byte = buf[i];
	    if (positive) tuple.push(byte);
	    else tuple.push(0xFF - byte);
	  }

	  var sum = 0;
	  var l = tuple.length;
	  for (i = 0; i < l; i++) {
	    sum += tuple[i] * Math.pow(256, i);
	  }

	  return positive ? sum : -1 * sum
	}

	var decodeOct = function (val, offset, length) {
	  val = val.slice(offset, offset + length);
	  offset = 0;

	  // If prefixed with 0x80 then parse as a base-256 integer
	  if (val[offset] & 0x80) {
	    return parse256(val)
	  } else {
	    // Older versions of tar can prefix with spaces
	    while (offset < val.length && val[offset] === 32) offset++;
	    var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length);
	    while (offset < end && val[offset] === 0) offset++;
	    if (end === offset) return 0
	    return parseInt(val.slice(offset, end).toString(), 8)
	  }
	};

	var decodeStr = function (val, offset, length, encoding) {
	  return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString(encoding)
	};

	var addLength = function (str) {
	  var len = Buffer.byteLength(str);
	  var digits = Math.floor(Math.log(len) / Math.log(10)) + 1;
	  if (len + digits >= Math.pow(10, digits)) digits++;

	  return (len + digits) + str
	};

	headers.decodeLongPath = function (buf, encoding) {
	  return decodeStr(buf, 0, buf.length, encoding)
	};

	headers.encodePax = function (opts) { // TODO: encode more stuff in pax
	  var result = '';
	  if (opts.name) result += addLength(' path=' + opts.name + '\n');
	  if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\n');
	  var pax = opts.pax;
	  if (pax) {
	    for (var key in pax) {
	      result += addLength(' ' + key + '=' + pax[key] + '\n');
	    }
	  }
	  return toBuffer(result)
	};

	headers.decodePax = function (buf) {
	  var result = {};

	  while (buf.length) {
	    var i = 0;
	    while (i < buf.length && buf[i] !== 32) i++;
	    var len = parseInt(buf.slice(0, i).toString(), 10);
	    if (!len) return result

	    var b = buf.slice(i + 1, len - 1).toString();
	    var keyIndex = b.indexOf('=');
	    if (keyIndex === -1) return result
	    result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1);

	    buf = buf.slice(len);
	  }

	  return result
	};

	headers.encode = function (opts) {
	  var buf = alloc(512);
	  var name = opts.name;
	  var prefix = '';

	  if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/';
	  if (Buffer.byteLength(name) !== name.length) return null // utf-8

	  while (Buffer.byteLength(name) > 100) {
	    var i = name.indexOf('/');
	    if (i === -1) return null
	    prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i);
	    name = name.slice(i + 1);
	  }

	  if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null
	  if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null

	  buf.write(name);
	  buf.write(encodeOct(opts.mode & MASK, 6), 100);
	  buf.write(encodeOct(opts.uid, 6), 108);
	  buf.write(encodeOct(opts.gid, 6), 116);
	  buf.write(encodeOct(opts.size, 11), 124);
	  buf.write(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136);

	  buf[156] = ZERO_OFFSET + toTypeflag(opts.type);

	  if (opts.linkname) buf.write(opts.linkname, 157);

	  buf.write(USTAR, 257);
	  if (opts.uname) buf.write(opts.uname, 265);
	  if (opts.gname) buf.write(opts.gname, 297);
	  buf.write(encodeOct(opts.devmajor || 0, 6), 329);
	  buf.write(encodeOct(opts.devminor || 0, 6), 337);

	  if (prefix) buf.write(prefix, 345);

	  buf.write(encodeOct(cksum(buf), 6), 148);

	  return buf
	};

	headers.decode = function (buf, filenameEncoding) {
	  var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET;

	  var name = decodeStr(buf, 0, 100, filenameEncoding);
	  var mode = decodeOct(buf, 100, 8);
	  var uid = decodeOct(buf, 108, 8);
	  var gid = decodeOct(buf, 116, 8);
	  var size = decodeOct(buf, 124, 12);
	  var mtime = decodeOct(buf, 136, 12);
	  var type = toType(typeflag);
	  var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding);
	  var uname = decodeStr(buf, 265, 32);
	  var gname = decodeStr(buf, 297, 32);
	  var devmajor = decodeOct(buf, 329, 8);
	  var devminor = decodeOct(buf, 337, 8);

	  if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name;

	  // to support old tar versions that use trailing / to indicate dirs
	  if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5;

	  var c = cksum(buf);

	  // checksum is still initial value if header was null.
	  if (c === 8 * 32) return null

	  // valid checksum
	  if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?')

	  return {
	    name: name,
	    mode: mode,
	    uid: uid,
	    gid: gid,
	    size: size,
	    mtime: new Date(1000 * mtime),
	    type: type,
	    linkname: linkname,
	    uname: uname,
	    gname: gname,
	    devmajor: devmajor,
	    devminor: devminor
	  }
	};
	return headers;
}

var readableBrowser$1 = {exports: {}};

var _stream_transform$1;
var hasRequired_stream_transform$1;

function require_stream_transform$1 () {
	if (hasRequired_stream_transform$1) return _stream_transform$1;
	hasRequired_stream_transform$1 = 1;

	_stream_transform$1 = Transform;

	var Duplex = require_stream_duplex$1();

	/*<replacement>*/
	var util = Object.create(requireUtil$2());
	util.inherits = requireInherits_browser();
	/*</replacement>*/

	util.inherits(Transform, Duplex);

	function afterTransform(er, data) {
	  var ts = this._transformState;
	  ts.transforming = false;

	  var cb = ts.writecb;

	  if (!cb) {
	    return this.emit('error', new Error('write callback called multiple times'));
	  }

	  ts.writechunk = null;
	  ts.writecb = null;

	  if (data != null) // single equals check for both `null` and `undefined`
	    this.push(data);

	  cb(er);

	  var rs = this._readableState;
	  rs.reading = false;
	  if (rs.needReadable || rs.length < rs.highWaterMark) {
	    this._read(rs.highWaterMark);
	  }
	}

	function Transform(options) {
	  if (!(this instanceof Transform)) return new Transform(options);

	  Duplex.call(this, options);

	  this._transformState = {
	    afterTransform: afterTransform.bind(this),
	    needTransform: false,
	    transforming: false,
	    writecb: null,
	    writechunk: null,
	    writeencoding: null
	  };

	  // start out asking for a readable event once data is transformed.
	  this._readableState.needReadable = true;

	  // we have implemented the _read method, and done the other things
	  // that Readable wants before the first _read call, so unset the
	  // sync guard flag.
	  this._readableState.sync = false;

	  if (options) {
	    if (typeof options.transform === 'function') this._transform = options.transform;

	    if (typeof options.flush === 'function') this._flush = options.flush;
	  }

	  // When the writable side finishes, then flush out anything remaining.
	  this.on('prefinish', prefinish);
	}

	function prefinish() {
	  var _this = this;

	  if (typeof this._flush === 'function') {
	    this._flush(function (er, data) {
	      done(_this, er, data);
	    });
	  } else {
	    done(this, null, null);
	  }
	}

	Transform.prototype.push = function (chunk, encoding) {
	  this._transformState.needTransform = false;
	  return Duplex.prototype.push.call(this, chunk, encoding);
	};

	// This is the part where you do stuff!
	// override this function in implementation classes.
	// 'chunk' is an input chunk.
	//
	// Call `push(newChunk)` to pass along transformed output
	// to the readable side.  You may call 'push' zero or more times.
	//
	// Call `cb(err)` when you are done with this chunk.  If you pass
	// an error, then that'll put the hurt on the whole operation.  If you
	// never call cb(), then you'll never get another chunk.
	Transform.prototype._transform = function (chunk, encoding, cb) {
	  throw new Error('_transform() is not implemented');
	};

	Transform.prototype._write = function (chunk, encoding, cb) {
	  var ts = this._transformState;
	  ts.writecb = cb;
	  ts.writechunk = chunk;
	  ts.writeencoding = encoding;
	  if (!ts.transforming) {
	    var rs = this._readableState;
	    if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
	  }
	};

	// Doesn't matter what the args are here.
	// _transform does all the work.
	// That we got here means that the readable side wants more data.
	Transform.prototype._read = function (n) {
	  var ts = this._transformState;

	  if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
	    ts.transforming = true;
	    this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
	  } else {
	    // mark that we need a transform, so that any data that comes in
	    // will get processed, now that we've asked for it.
	    ts.needTransform = true;
	  }
	};

	Transform.prototype._destroy = function (err, cb) {
	  var _this2 = this;

	  Duplex.prototype._destroy.call(this, err, function (err2) {
	    cb(err2);
	    _this2.emit('close');
	  });
	};

	function done(stream, er, data) {
	  if (er) return stream.emit('error', er);

	  if (data != null) // single equals check for both `null` and `undefined`
	    stream.push(data);

	  // if there's nothing in the write buffer, then that means
	  // that nothing more will ever be provided
	  if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');

	  if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');

	  return stream.push(null);
	}
	return _stream_transform$1;
}

var _stream_passthrough$1;
var hasRequired_stream_passthrough$1;

function require_stream_passthrough$1 () {
	if (hasRequired_stream_passthrough$1) return _stream_passthrough$1;
	hasRequired_stream_passthrough$1 = 1;

	_stream_passthrough$1 = PassThrough;

	var Transform = require_stream_transform$1();

	/*<replacement>*/
	var util = Object.create(requireUtil$2());
	util.inherits = requireInherits_browser();
	/*</replacement>*/

	util.inherits(PassThrough, Transform);

	function PassThrough(options) {
	  if (!(this instanceof PassThrough)) return new PassThrough(options);

	  Transform.call(this, options);
	}

	PassThrough.prototype._transform = function (chunk, encoding, cb) {
	  cb(null, chunk);
	};
	return _stream_passthrough$1;
}

var hasRequiredReadableBrowser$1;

function requireReadableBrowser$1 () {
	if (hasRequiredReadableBrowser$1) return readableBrowser$1.exports;
	hasRequiredReadableBrowser$1 = 1;
	(function (module, exports$1) {
		exports$1 = module.exports = require_stream_readable$1();
		exports$1.Stream = exports$1;
		exports$1.Readable = exports$1;
		exports$1.Writable = require_stream_writable$1();
		exports$1.Duplex = require_stream_duplex$1();
		exports$1.Transform = require_stream_transform$1();
		exports$1.PassThrough = require_stream_passthrough$1(); 
	} (readableBrowser$1, readableBrowser$1.exports));
	return readableBrowser$1.exports;
}

var extract;
var hasRequiredExtract;

function requireExtract () {
	if (hasRequiredExtract) return extract;
	hasRequiredExtract = 1;
	var util = require$$0$6;
	var bl = requireBl();
	var xtend = requireImmutable();
	var headers = requireHeaders();

	var Writable = requireReadableBrowser$1().Writable;
	var PassThrough = requireReadableBrowser$1().PassThrough;

	var noop = function () {};

	var overflow = function (size) {
	  size &= 511;
	  return size && 512 - size
	};

	var emptyStream = function (self, offset) {
	  var s = new Source(self, offset);
	  s.end();
	  return s
	};

	var mixinPax = function (header, pax) {
	  if (pax.path) header.name = pax.path;
	  if (pax.linkpath) header.linkname = pax.linkpath;
	  if (pax.size) header.size = parseInt(pax.size, 10);
	  header.pax = pax;
	  return header
	};

	var Source = function (self, offset) {
	  this._parent = self;
	  this.offset = offset;
	  PassThrough.call(this);
	};

	util.inherits(Source, PassThrough);

	Source.prototype.destroy = function (err) {
	  this._parent.destroy(err);
	};

	var Extract = function (opts) {
	  if (!(this instanceof Extract)) return new Extract(opts)
	  Writable.call(this, opts);

	  opts = opts || {};

	  this._offset = 0;
	  this._buffer = bl();
	  this._missing = 0;
	  this._partial = false;
	  this._onparse = noop;
	  this._header = null;
	  this._stream = null;
	  this._overflow = null;
	  this._cb = null;
	  this._locked = false;
	  this._destroyed = false;
	  this._pax = null;
	  this._paxGlobal = null;
	  this._gnuLongPath = null;
	  this._gnuLongLinkPath = null;

	  var self = this;
	  var b = self._buffer;

	  var oncontinue = function () {
	    self._continue();
	  };

	  var onunlock = function (err) {
	    self._locked = false;
	    if (err) return self.destroy(err)
	    if (!self._stream) oncontinue();
	  };

	  var onstreamend = function () {
	    self._stream = null;
	    var drain = overflow(self._header.size);
	    if (drain) self._parse(drain, ondrain);
	    else self._parse(512, onheader);
	    if (!self._locked) oncontinue();
	  };

	  var ondrain = function () {
	    self._buffer.consume(overflow(self._header.size));
	    self._parse(512, onheader);
	    oncontinue();
	  };

	  var onpaxglobalheader = function () {
	    var size = self._header.size;
	    self._paxGlobal = headers.decodePax(b.slice(0, size));
	    b.consume(size);
	    onstreamend();
	  };

	  var onpaxheader = function () {
	    var size = self._header.size;
	    self._pax = headers.decodePax(b.slice(0, size));
	    if (self._paxGlobal) self._pax = xtend(self._paxGlobal, self._pax);
	    b.consume(size);
	    onstreamend();
	  };

	  var ongnulongpath = function () {
	    var size = self._header.size;
	    this._gnuLongPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding);
	    b.consume(size);
	    onstreamend();
	  };

	  var ongnulonglinkpath = function () {
	    var size = self._header.size;
	    this._gnuLongLinkPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding);
	    b.consume(size);
	    onstreamend();
	  };

	  var onheader = function () {
	    var offset = self._offset;
	    var header;
	    try {
	      header = self._header = headers.decode(b.slice(0, 512), opts.filenameEncoding);
	    } catch (err) {
	      self.emit('error', err);
	    }
	    b.consume(512);

	    if (!header) {
	      self._parse(512, onheader);
	      oncontinue();
	      return
	    }
	    if (header.type === 'gnu-long-path') {
	      self._parse(header.size, ongnulongpath);
	      oncontinue();
	      return
	    }
	    if (header.type === 'gnu-long-link-path') {
	      self._parse(header.size, ongnulonglinkpath);
	      oncontinue();
	      return
	    }
	    if (header.type === 'pax-global-header') {
	      self._parse(header.size, onpaxglobalheader);
	      oncontinue();
	      return
	    }
	    if (header.type === 'pax-header') {
	      self._parse(header.size, onpaxheader);
	      oncontinue();
	      return
	    }

	    if (self._gnuLongPath) {
	      header.name = self._gnuLongPath;
	      self._gnuLongPath = null;
	    }

	    if (self._gnuLongLinkPath) {
	      header.linkname = self._gnuLongLinkPath;
	      self._gnuLongLinkPath = null;
	    }

	    if (self._pax) {
	      self._header = header = mixinPax(header, self._pax);
	      self._pax = null;
	    }

	    self._locked = true;

	    if (!header.size || header.type === 'directory') {
	      self._parse(512, onheader);
	      self.emit('entry', header, emptyStream(self, offset), onunlock);
	      return
	    }

	    self._stream = new Source(self, offset);

	    self.emit('entry', header, self._stream, onunlock);
	    self._parse(header.size, onstreamend);
	    oncontinue();
	  };

	  this._onheader = onheader;
	  this._parse(512, onheader);
	};

	util.inherits(Extract, Writable);

	Extract.prototype.destroy = function (err) {
	  if (this._destroyed) return
	  this._destroyed = true;

	  if (err) this.emit('error', err);
	  this.emit('close');
	  if (this._stream) this._stream.emit('close');
	};

	Extract.prototype._parse = function (size, onparse) {
	  if (this._destroyed) return
	  this._offset += size;
	  this._missing = size;
	  if (onparse === this._onheader) this._partial = false;
	  this._onparse = onparse;
	};

	Extract.prototype._continue = function () {
	  if (this._destroyed) return
	  var cb = this._cb;
	  this._cb = noop;
	  if (this._overflow) this._write(this._overflow, undefined, cb);
	  else cb();
	};

	Extract.prototype._write = function (data, enc, cb) {
	  if (this._destroyed) return

	  var s = this._stream;
	  var b = this._buffer;
	  var missing = this._missing;
	  if (data.length) this._partial = true;

	  // we do not reach end-of-chunk now. just forward it

	  if (data.length < missing) {
	    this._missing -= data.length;
	    this._overflow = null;
	    if (s) return s.write(data, cb)
	    b.append(data);
	    return cb()
	  }

	  // end-of-chunk. the parser should call cb.

	  this._cb = cb;
	  this._missing = 0;

	  var overflow = null;
	  if (data.length > missing) {
	    overflow = data.slice(missing);
	    data = data.slice(0, missing);
	  }

	  if (s) s.end(data);
	  else b.append(data);

	  this._overflow = overflow;
	  this._onparse();
	};

	Extract.prototype._final = function (cb) {
	  if (this._partial) return this.destroy(new Error('Unexpected end of data'))
	  cb();
	};

	extract = Extract;
	return extract;
}

var browser$3;
var hasRequiredBrowser$3;

function requireBrowser$3 () {
	if (hasRequiredBrowser$3) return browser$3;
	hasRequiredBrowser$3 = 1;
	browser$3 = require$$0$7;
	return browser$3;
}

var pack;
var hasRequiredPack;

function requirePack () {
	if (hasRequiredPack) return pack;
	hasRequiredPack = 1;
	var constants = requireBrowser$3();
	var eos = requireEndOfStream$1();
	var util = require$$0$6;
	var alloc = requireBufferAlloc();
	var toBuffer = /*@__PURE__*/ requireToBuffer();

	var Readable = requireReadableBrowser$1().Readable;
	var Writable = requireReadableBrowser$1().Writable;
	var StringDecoder = require$$1$3.StringDecoder;

	var headers = requireHeaders();

	var DMODE = parseInt('755', 8);
	var FMODE = parseInt('644', 8);

	var END_OF_TAR = alloc(1024);

	var noop = function () {};

	var overflow = function (self, size) {
	  size &= 511;
	  if (size) self.push(END_OF_TAR.slice(0, 512 - size));
	};

	function modeToType (mode) {
	  switch (mode & constants.S_IFMT) {
	    case constants.S_IFBLK: return 'block-device'
	    case constants.S_IFCHR: return 'character-device'
	    case constants.S_IFDIR: return 'directory'
	    case constants.S_IFIFO: return 'fifo'
	    case constants.S_IFLNK: return 'symlink'
	  }

	  return 'file'
	}

	var Sink = function (to) {
	  Writable.call(this);
	  this.written = 0;
	  this._to = to;
	  this._destroyed = false;
	};

	util.inherits(Sink, Writable);

	Sink.prototype._write = function (data, enc, cb) {
	  this.written += data.length;
	  if (this._to.push(data)) return cb()
	  this._to._drain = cb;
	};

	Sink.prototype.destroy = function () {
	  if (this._destroyed) return
	  this._destroyed = true;
	  this.emit('close');
	};

	var LinkSink = function () {
	  Writable.call(this);
	  this.linkname = '';
	  this._decoder = new StringDecoder('utf-8');
	  this._destroyed = false;
	};

	util.inherits(LinkSink, Writable);

	LinkSink.prototype._write = function (data, enc, cb) {
	  this.linkname += this._decoder.write(data);
	  cb();
	};

	LinkSink.prototype.destroy = function () {
	  if (this._destroyed) return
	  this._destroyed = true;
	  this.emit('close');
	};

	var Void = function () {
	  Writable.call(this);
	  this._destroyed = false;
	};

	util.inherits(Void, Writable);

	Void.prototype._write = function (data, enc, cb) {
	  cb(new Error('No body allowed for this entry'));
	};

	Void.prototype.destroy = function () {
	  if (this._destroyed) return
	  this._destroyed = true;
	  this.emit('close');
	};

	var Pack = function (opts) {
	  if (!(this instanceof Pack)) return new Pack(opts)
	  Readable.call(this, opts);

	  this._drain = noop;
	  this._finalized = false;
	  this._finalizing = false;
	  this._destroyed = false;
	  this._stream = null;
	};

	util.inherits(Pack, Readable);

	Pack.prototype.entry = function (header, buffer, callback) {
	  if (this._stream) throw new Error('already piping an entry')
	  if (this._finalized || this._destroyed) return

	  if (typeof buffer === 'function') {
	    callback = buffer;
	    buffer = null;
	  }

	  if (!callback) callback = noop;

	  var self = this;

	  if (!header.size || header.type === 'symlink') header.size = 0;
	  if (!header.type) header.type = modeToType(header.mode);
	  if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE;
	  if (!header.uid) header.uid = 0;
	  if (!header.gid) header.gid = 0;
	  if (!header.mtime) header.mtime = new Date();

	  if (typeof buffer === 'string') buffer = toBuffer(buffer);
	  if (Buffer.isBuffer(buffer)) {
	    header.size = buffer.length;
	    this._encode(header);
	    this.push(buffer);
	    overflow(self, header.size);
	    process.nextTick(callback);
	    return new Void()
	  }

	  if (header.type === 'symlink' && !header.linkname) {
	    var linkSink = new LinkSink();
	    eos(linkSink, function (err) {
	      if (err) { // stream was closed
	        self.destroy();
	        return callback(err)
	      }

	      header.linkname = linkSink.linkname;
	      self._encode(header);
	      callback();
	    });

	    return linkSink
	  }

	  this._encode(header);

	  if (header.type !== 'file' && header.type !== 'contiguous-file') {
	    process.nextTick(callback);
	    return new Void()
	  }

	  var sink = new Sink(this);

	  this._stream = sink;

	  eos(sink, function (err) {
	    self._stream = null;

	    if (err) { // stream was closed
	      self.destroy();
	      return callback(err)
	    }

	    if (sink.written !== header.size) { // corrupting tar
	      self.destroy();
	      return callback(new Error('size mismatch'))
	    }

	    overflow(self, header.size);
	    if (self._finalizing) self.finalize();
	    callback();
	  });

	  return sink
	};

	Pack.prototype.finalize = function () {
	  if (this._stream) {
	    this._finalizing = true;
	    return
	  }

	  if (this._finalized) return
	  this._finalized = true;
	  this.push(END_OF_TAR);
	  this.push(null);
	};

	Pack.prototype.destroy = function (err) {
	  if (this._destroyed) return
	  this._destroyed = true;

	  if (err) this.emit('error', err);
	  this.emit('close');
	  if (this._stream && this._stream.destroy) this._stream.destroy();
	};

	Pack.prototype._encode = function (header) {
	  if (!header.pax) {
	    var buf = headers.encode(header);
	    if (buf) {
	      this.push(buf);
	      return
	    }
	  }
	  this._encodePax(header);
	};

	Pack.prototype._encodePax = function (header) {
	  var paxHeader = headers.encodePax({
	    name: header.name,
	    linkname: header.linkname,
	    pax: header.pax
	  });

	  var newHeader = {
	    name: 'PaxHeader',
	    mode: header.mode,
	    uid: header.uid,
	    gid: header.gid,
	    size: paxHeader.length,
	    mtime: header.mtime,
	    type: 'pax-header',
	    linkname: header.linkname && 'PaxHeader',
	    uname: header.uname,
	    gname: header.gname,
	    devmajor: header.devmajor,
	    devminor: header.devminor
	  };

	  this.push(headers.encode(newHeader));
	  this.push(paxHeader);
	  overflow(this, paxHeader.length);

	  newHeader.size = header.size;
	  newHeader.type = header.type;
	  this.push(headers.encode(newHeader));
	};

	Pack.prototype._read = function (n) {
	  var drain = this._drain;
	  this._drain = noop;
	  drain();
	};

	pack = Pack;
	return pack;
}

var hasRequiredTarStream;

function requireTarStream () {
	if (hasRequiredTarStream) return tarStream;
	hasRequiredTarStream = 1;
	tarStream.extract = requireExtract();
	tarStream.pack = requirePack();
	return tarStream;
}

var base_stream;
var hasRequiredBase_stream;

function requireBase_stream () {
	if (hasRequiredBase_stream) return base_stream;
	hasRequiredBase_stream = 1;

	const stream = require$$1$1;

	class BaseStream extends stream.Readable {
	  addEntry(/* entry, opts */) {
	    throw new Error('.addEntry not implemented in sub class!');
	  }

	  _read() {}

	  emit(event, data) {
	    if (event === 'error') {
	      const error = data;
	      if (error.name === 'Error') {
	        error.name = this.constructor.name + 'Error';
	      }
	    }
	    super.emit(event, data);
	  }
	}

	base_stream = BaseStream;
	return base_stream;
}

var stream_1;
var hasRequiredStream$3;

function requireStream$3 () {
	if (hasRequiredStream$3) return stream_1;
	hasRequiredStream$3 = 1;

	const fs = fs__default;
	const path = path__default;
	const stream = require$$1$1;
	const tar = requireTarStream();
	const utils = requireUtils$2();
	const BaseStream = requireBase_stream();

	class TarStream extends BaseStream {
	  constructor(opts) {
	    super(opts);

	    this._waitingEntries = [];
	    this._processing = false;
	    this._init(opts);
	  }

	  _init() {
	    const pack = this._pack = tar.pack();
	    pack.on('end', () => this.push(null));
	    pack.on('data', chunk => this.push(chunk));
	    pack.on('error', err => this.emit('error', err));
	  }

	  addEntry(entry, opts) {
	    if (this._processing) {
	      return this._waitingEntries.push([ entry, opts ]);
	    }

	    opts = opts || {};
	    this._processing = true;

	    const entryType = utils.entryType(entry);
	    if (!entryType) return; // TODO

	    if (entryType === 'fileOrDir') {
	      this._addFileOrDirEntry(entry, opts);
	    } else if (entryType === 'buffer') {
	      this._addBufferEntry(entry, opts);
	    } else { // stream
	      this._addStreamEntry(entry, opts);
	    }

	  }

	  _addFileOrDirEntry(entry, opts) {
	    fs.stat(entry, (err, stat) => {
	      if (err) return this.emit('error', err);
	      if (stat.isDirectory()) return this._addDirEntry(entry, opts);
	      if (stat.isFile()) return this._addFileEntry(entry, opts);

	      const illigalEntryError = new Error('Type is not supported, must be a file path, directory path, file buffer, or a readable stream');
	      illigalEntryError.name = 'IlligalEntryError';
	      this.emit('error', illigalEntryError);
	    });
	  }

	  _addFileEntry(entry, opts) {
	    // stat file to get file size
	    fs.stat(entry, (err, stat) => {
	      if (err) return this.emit('error', err);
	      const entryStream = this._pack.entry({ name: opts.relativePath || path.basename(entry), size: stat.size, mode: stat.mode & 0o777 }, this._onEntryFinish.bind(this));
	      const stream = fs.createReadStream(entry, opts.fs);
	      stream.on('error', err => this.emit('error', err));
	      stream.pipe(entryStream);
	    });
	  }

	  _addDirEntry(entry, opts) {
	    fs.readdir(entry, (err, files) => {
	      if (err) return this.emit('error', err);

	      const relativePath = opts.relativePath || '';
	      files.forEach(fileOrDir => {
	        const newOpts = utils.clone(opts);
	        if (opts.ignoreBase) {
	          newOpts.relativePath = path.posix.join(relativePath, fileOrDir);
	        } else {
	          newOpts.relativePath = path.posix.join(relativePath, path.basename(entry), fileOrDir);
	        }
	        newOpts.ignoreBase = true;
	        this.addEntry(path.posix.join(entry, fileOrDir), newOpts);
	      });
	      this._onEntryFinish();
	    });
	  }

	  _addBufferEntry(entry, opts) {
	    if (!opts.relativePath) return this.emit('error', 'opts.relativePath is required if entry is a buffer');
	    this._pack.entry({ name: opts.relativePath }, entry, this._onEntryFinish.bind(this));
	  }

	  _addStreamEntry(entry, opts) {
	    entry.on('error', err => this.emit('error', err));

	    if (!opts.relativePath) return this.emit('error', new Error('opts.relativePath is required'));

	    if (opts.size) {
	      const entryStream = this._pack.entry({ name: opts.relativePath, size: opts.size }, this._onEntryFinish.bind(this));
	      entry.pipe(entryStream);
	    } else {
	      if (!opts.suppressSizeWarning) {
	        console.warn('You should specify the size of streamming data by opts.size to prevent all streaming data from loading into memory. If you are sure about memory cost, pass opts.suppressSizeWarning: true to suppress this warning');
	      }
	      const buf = [];
	      const collectStream = new stream.Writable({
	        write(chunk, _, callback) {
	          buf.push(chunk);
	          callback();
	        },
	      });
	      collectStream.on('error', err => this.emit('error', err));
	      collectStream.on('finish', () => {
	        this._pack.entry({ name: opts.relativePath }, Buffer.concat(buf), this._onEntryFinish.bind(this));
	      });
	      entry.pipe(collectStream);
	    }
	  }

	  _read() {}

	  _onEntryFinish(err) {
	    if (err) return this.emit('error', err);

	    this._processing = false;
	    const waitingEntry = this._waitingEntries.shift();
	    if (waitingEntry) {
	      this.addEntry.apply(this, waitingEntry);
	    } else {
	      this._finalize();
	    }
	  }

	  _finalize() {
	    this._pack.finalize();
	  }
	}

	stream_1 = TarStream;
	return stream_1;
}

var stream$2;
var hasRequiredStream$2;

function requireStream$2 () {
	if (hasRequiredStream$2) return stream$2;
	hasRequiredStream$2 = 1;

	const path = path__default;
	const yazl = requireYazl();
	const TarStream = requireStream$3();

	class ZipStream extends TarStream {
	  _init() {
	    const zipfile = this._zipfile = new yazl.ZipFile();
	    const stream = zipfile.outputStream;
	    stream.on('end', () => this.push(null));
	    stream.on('data', chunk => this.push(chunk));
	    stream.on('error', err => this.emit('error', err));
	  }

	  _addFileEntry(entry, opts) {
	    this._zipfile.addFile(entry, opts.relativePath || path.basename(entry), opts);
	    this._onEntryFinish();
	  }

	  _addBufferEntry(entry, opts) {
	    if (!opts.relativePath) return this.emit('error', new Error('opts.relativePath is required if entry is a buffer'));
	    this._zipfile.addBuffer(entry, opts.relativePath, opts);
	    this._onEntryFinish();
	  }

	  _addStreamEntry(entry, opts) {
	    if (!opts.relativePath) return this.emit('error', new Error('opts.relativePath is required if entry is a stream'));

	    entry.on('error', err => this.emit('error', err));
	    this._zipfile.addReadStream(entry, opts.relativePath, opts);
	    this._onEntryFinish();
	  }

	  _finalize() {
	    this._zipfile.end();
	  }
	}

	stream$2 = ZipStream;
	return stream$2;
}

var getReady = {exports: {}};

var hasRequiredGetReady;

function requireGetReady () {
	if (hasRequiredGetReady) return getReady.exports;
	hasRequiredGetReady = 1;

	function ready(flagOrFunction) {
	  this._ready = !!this._ready;
	  this._readyCallbacks = this._readyCallbacks || [];

	  if (arguments.length === 0) {
	    // return a promise
	    // support `this.ready().then(onready);` and `yield this.ready()`;
	    return new Promise(function (resolve) {
	      if (this._ready) {
	        return resolve();
	      }
	      this._readyCallbacks.push(resolve);
	    }.bind(this));
	  } else if (typeof flagOrFunction === 'function') {
	    this._readyCallbacks.push(flagOrFunction);
	  } else {
	    this._ready = !!flagOrFunction;
	  }

	  if (this._ready) {
	    this._readyCallbacks.splice(0, Infinity).forEach(function(callback) {
	      process.nextTick(callback);
	    });
	  }
	}

	function mixin(object) {
	  object.ready = ready;
	}

	getReady.exports = mixin;
	getReady.exports.mixin = mixin;
	return getReady.exports;
}

var file_stream$3;
var hasRequiredFile_stream$3;

function requireFile_stream$3 () {
	if (hasRequiredFile_stream$3) return file_stream$3;
	hasRequiredFile_stream$3 = 1;

	const path = path__default;
	const yazl = requireYazl();
	const assert = require$$2$2;
	const stream = require$$1$1;
	const utils = requireUtils$2();
	const ready = requireGetReady();

	class ZipFileStream extends stream.Transform {
	  constructor(opts) {
	    super(opts);

	    const sourceType = utils.sourceType(opts.source);

	    const zipfile = new yazl.ZipFile();
	    const zipStream = zipfile.outputStream;
	    zipStream.on('data', data => this.push(data));
	    zipStream.on('end', () => this.ready(true));
	    zipfile.on('error', err => this.emit('error', err));

	    if (sourceType !== 'file') {
	      assert(opts.relativePath, 'opts.relativePath is required when compressing a buffer, or a stream');
	    }

	    if (sourceType) {
	      this.end();
	    }

	    if (sourceType === 'file') {
	      zipfile.addFile(opts.source, opts.relativePath || path.basename(opts.source), opts.yazl);
	    } else if (sourceType === 'buffer') {
	      zipfile.addBuffer(opts.source, opts.relativePath, opts.yazl);
	    } else if (sourceType === 'stream') {
	      zipfile.addReadStream(opts.source, opts.relativePath, opts.yazl);
	    } else { // undefined
	      const passThrough = this._passThrough = new stream.PassThrough();
	      this.on('finish', () => passThrough.end());
	      zipfile.addReadStream(passThrough, opts.relativePath, opts.yazl);
	    }
	    zipfile.end(opts.yazl);
	  }

	  _transform(chunk, encoding, callback) {
	    if (this._passThrough) {
	      this._passThrough.write(chunk, encoding, callback);
	    }
	  }

	  _flush(callback) {
	    this.ready(callback);
	  }
	}

	ready.mixin(ZipFileStream.prototype);
	file_stream$3 = ZipFileStream;
	return file_stream$3;
}

var yauzl = {};

var fdSlicer2 = {};

var pend;
var hasRequiredPend;

function requirePend () {
	if (hasRequiredPend) return pend;
	hasRequiredPend = 1;
	pend = Pend;

	function Pend() {
	  this.pending = 0;
	  this.max = Infinity;
	  this.listeners = [];
	  this.waiting = [];
	  this.error = null;
	}

	Pend.prototype.go = function(fn) {
	  if (this.pending < this.max) {
	    pendGo(this, fn);
	  } else {
	    this.waiting.push(fn);
	  }
	};

	Pend.prototype.wait = function(cb) {
	  if (this.pending === 0) {
	    cb(this.error);
	  } else {
	    this.listeners.push(cb);
	  }
	};

	Pend.prototype.hold = function() {
	  return pendHold(this);
	};

	function pendHold(self) {
	  self.pending += 1;
	  var called = false;
	  return onCb;
	  function onCb(err) {
	    if (called) throw new Error("callback called twice");
	    called = true;
	    self.error = self.error || err;
	    self.pending -= 1;
	    if (self.waiting.length > 0 && self.pending < self.max) {
	      pendGo(self, self.waiting.shift());
	    } else if (self.pending === 0) {
	      var listeners = self.listeners;
	      self.listeners = [];
	      listeners.forEach(cbListener);
	    }
	  }
	  function cbListener(listener) {
	    listener(self.error);
	  }
	}

	function pendGo(self, fn) {
	  fn(pendHold(self));
	}
	return pend;
}

var hasRequiredFdSlicer2;

function requireFdSlicer2 () {
	if (hasRequiredFdSlicer2) return fdSlicer2;
	hasRequiredFdSlicer2 = 1;
	const fs = fs__default;
	const { Readable, Writable, PassThrough } = require$$1$1;
	const Pend = requirePend();
	const { EventEmitter } = require$$0$5;

	class FdSlicer extends EventEmitter {
	  constructor(fd, options = {}) {
	    super();

	    this.fd = fd;
	    this.pend = new Pend();
	    this.pend.max = 1;
	    this.refCount = 0;
	    this.autoClose = !!options.autoClose;
	  }

	  read(buffer, offset, length, position, callback) {
	    this.pend.go(cb => {
	      fs.read(this.fd, buffer, offset, length, position, (err, bytesRead, buffer) => {
	        cb();
	        callback(err, bytesRead, buffer);
	      });
	    });
	  }

	  write(buffer, offset, length, position, callback) {
	    this.pend.go(cb => {
	      fs.write(this.fd, buffer, offset, length, position, (err, written, buffer) => {
	        cb();
	        callback(err, written, buffer);
	      });
	    });
	  }

	  createReadStream(options) {
	    return new ReadStream(this, options);
	  }

	  createWriteStream(options) {
	    return new WriteStream(this, options);
	  }

	  ref() {
	    this.refCount += 1;
	  }

	  unref() {
	    this.refCount -= 1;

	    if (this.refCount > 0) return;
	    if (this.refCount < 0) throw new Error("invalid unref");

	    if (this.autoClose) {
	      fs.close(this.fd, err => {
	        if (err) {
	          this.emit('error', err);
	        } else {
	          this.emit('close');
	        }
	      });
	    }
	  }
	}

	class ReadStream extends Readable {
	  constructor(context, options = {}) {
	    super(options);

	    this.context = context;
	    this.context.ref();

	    this.start = options.start || 0;
	    this.endOffset = options.end;
	    this.pos = this.start;
	    this.destroyed = false;
	  }

	  _read(n) {
	    if (this.destroyed) return;

	    let toRead = Math.min(this._readableState.highWaterMark, n);
	    if (this.endOffset != null) {
	      toRead = Math.min(toRead, this.endOffset - this.pos);
	    }
	    if (toRead <= 0) {
	      this.destroyed = true;
	      this.push(null);
	      this.context.unref();
	      return;
	    }
	    this.context.pend.go(cb => {
	      if (this.destroyed) return cb();
	      const buffer = Buffer.alloc(toRead);
	      fs.read(this.context.fd, buffer, 0, toRead, this.pos, (err, bytesRead) => {
	        if (err) {
	          this.destroy(err);
	        } else if (bytesRead === 0) {
	          this.destroyed = true;
	          this.push(null);
	          this.context.unref();
	        } else {
	          this.pos += bytesRead;
	          this.push(buffer.slice(0, bytesRead));
	        }
	        cb();
	      });
	    });
	  }

	  destroy(err) {
	    if (this.destroyed) return;
	    err = err || new Error("stream destroyed");
	    this.destroyed = true;
	    this.emit('error', err);
	    this.context.unref();
	  }
	}

	class WriteStream extends Writable {
	  constructor(context, options = {}) {
	    super(options);

	    this.context = context;
	    this.context.ref();

	    this.start = options.start || 0;
	    this.endOffset = (options.end == null) ? Infinity : +options.end;
	    this.bytesWritten = 0;
	    this.pos = this.start;
	    this.destroyed = false;

	    this.on('finish', this.destroy.bind(this));
	  }

	  _write(buffer, _encoding, callback) {
	    if (this.destroyed) return;

	    if (this.pos + buffer.length > this.endOffset) {
	      const err = new Error("maximum file length exceeded");
	      err.code = 'ETOOBIG';
	      this.destroy();
	      callback(err);
	      return;
	    }
	    this.context.pend.go(cb => {
	      if (this.destroyed) return cb();
	      fs.write(this.context.fd, buffer, 0, buffer.length, this.pos, (err, bytes) => {
	        if (err) {
	          this.destroy();
	          cb();
	          callback(err);
	        } else {
	          this.bytesWritten += bytes;
	          this.pos += bytes;
	          this.emit('progress');
	          cb();
	          callback();
	        }
	      });
	    });
	  }

	  destroy() {
	    if (this.destroyed) return;
	    this.destroyed = true;
	    this.context.unref();
	  }
	}

	const { MAX_SAFE_INTEGER } = Number;

	class BufferSlicer extends EventEmitter {
	  constructor(buffer, options) {
	    super();

	    options = options || {};
	    this.refCount = 0;
	    this.buffer = buffer;
	    this.maxChunkSize = options.maxChunkSize || MAX_SAFE_INTEGER;
	  }

	  read(buffer, offset, length, position, callback) {
	    const end = position + length;
	    const delta = end - this.buffer.length;
	    const written = (delta > 0) ? delta : length;
	    this.buffer.copy(buffer, offset, position, end);
	    setImmediate(() => {
	      callback(null, written);
	    });
	  }

	  write(buffer, offset, length, position, callback) {
	    buffer.copy(this.buffer, position, offset, offset + length);
	    setImmediate(() => {
	      callback(null, length, buffer);
	    });
	  }

	  createReadStream(options = {}) {
	    const readStream = new PassThrough(options);
	    readStream.destroyed = false;
	    readStream.start = options.start || 0;
	    readStream.endOffset = options.end;
	    // by the time this function returns, we'll be done.
	    readStream.pos = readStream.endOffset || this.buffer.length;

	    // respect the maxChunkSize option to slice up the chunk into smaller pieces.
	    const entireSlice = this.buffer.slice(readStream.start, readStream.pos);
	    let offset = 0;
	    while (true) {
	      const nextOffset = offset + this.maxChunkSize;
	      if (nextOffset >= entireSlice.length) {
	        // last chunk
	        if (offset < entireSlice.length) {
	          readStream.write(entireSlice.slice(offset, entireSlice.length));
	        }
	        break;
	      }
	      readStream.write(entireSlice.slice(offset, nextOffset));
	      offset = nextOffset;
	    }

	    readStream.end();
	    readStream.destroy = () => {
	      readStream.destroyed = true;
	    };
	    return readStream;
	  }

	  createWriteStream(options) {
	    const bufferSlicer = this;
	    options = options || {};
	    const writeStream = new Writable(options);
	    writeStream.start = options.start || 0;
	    writeStream.endOffset = (options.end == null) ? this.buffer.length : +options.end;
	    writeStream.bytesWritten = 0;
	    writeStream.pos = writeStream.start;
	    writeStream.destroyed = false;
	    writeStream._write = (buffer, encoding, callback) => {
	      if (writeStream.destroyed) return;

	      const end = writeStream.pos + buffer.length;
	      if (end > writeStream.endOffset) {
	        const err = new Error("maximum file length exceeded");
	        err.code = 'ETOOBIG';
	        writeStream.destroyed = true;
	        callback(err);
	        return;
	      }
	      buffer.copy(bufferSlicer.buffer, writeStream.pos, 0, buffer.length);

	      writeStream.bytesWritten += buffer.length;
	      writeStream.pos = end;
	      writeStream.emit('progress');
	      callback();
	    };
	    writeStream.destroy = () => {
	      writeStream.destroyed = true;
	    };
	    return writeStream;
	  }

	  ref() {
	    this.refCount += 1;
	  }

	  unref() {
	    this.refCount -= 1;

	    if (this.refCount < 0) {
	      throw new Error("invalid unref");
	    }
	  }
	}

	function createFromBuffer(buffer, options) {
	  return new BufferSlicer(buffer, options);
	}

	function createFromFd(fd, options) {
	  return new FdSlicer(fd, options);
	}

	fdSlicer2.createFromBuffer = createFromBuffer;
	fdSlicer2.createFromFd = createFromFd;
	fdSlicer2.BufferSlicer = BufferSlicer;
	fdSlicer2.FdSlicer = FdSlicer;
	return fdSlicer2;
}

var hasRequiredYauzl;

function requireYauzl () {
	if (hasRequiredYauzl) return yauzl;
	hasRequiredYauzl = 1;
	var fs = fs__default;
	var zlib = require$$1$2;
	var fd_slicer = requireFdSlicer2();
	var crc32 = requireBufferCrc32();
	var util = require$$0$6;
	var EventEmitter = require$$0$5.EventEmitter;
	var Transform = require$$1$1.Transform;
	var PassThrough = require$$1$1.PassThrough;
	var Writable = require$$1$1.Writable;

	yauzl.open = open;
	yauzl.fromFd = fromFd;
	yauzl.fromBuffer = fromBuffer;
	yauzl.fromRandomAccessReader = fromRandomAccessReader;
	yauzl.dosDateTimeToDate = dosDateTimeToDate;
	yauzl.validateFileName = validateFileName;
	yauzl.ZipFile = ZipFile;
	yauzl.Entry = Entry;
	yauzl.RandomAccessReader = RandomAccessReader;

	function open(path, options, callback) {
	  if (typeof options === "function") {
	    callback = options;
	    options = null;
	  }
	  if (options == null) options = {};
	  if (options.autoClose == null) options.autoClose = true;
	  if (options.lazyEntries == null) options.lazyEntries = false;
	  if (options.decodeStrings == null) options.decodeStrings = true;
	  if (options.validateEntrySizes == null) options.validateEntrySizes = true;
	  if (options.strictFileNames == null) options.strictFileNames = false;
	  if (callback == null) callback = defaultCallback;
	  fs.open(path, "r", function(err, fd) {
	    if (err) return callback(err);
	    fromFd(fd, options, function(err, zipfile) {
	      if (err) fs.close(fd, defaultCallback);
	      callback(err, zipfile);
	    });
	  });
	}

	function fromFd(fd, options, callback) {
	  if (typeof options === "function") {
	    callback = options;
	    options = null;
	  }
	  if (options == null) options = {};
	  if (options.autoClose == null) options.autoClose = false;
	  if (options.lazyEntries == null) options.lazyEntries = false;
	  if (options.decodeStrings == null) options.decodeStrings = true;
	  if (options.validateEntrySizes == null) options.validateEntrySizes = true;
	  if (options.strictFileNames == null) options.strictFileNames = false;
	  if (callback == null) callback = defaultCallback;
	  fs.fstat(fd, function(err, stats) {
	    if (err) return callback(err);
	    var reader = fd_slicer.createFromFd(fd, {autoClose: true});
	    fromRandomAccessReader(reader, stats.size, options, callback);
	  });
	}

	function fromBuffer(buffer, options, callback) {
	  if (typeof options === "function") {
	    callback = options;
	    options = null;
	  }
	  if (options == null) options = {};
	  options.autoClose = false;
	  if (options.lazyEntries == null) options.lazyEntries = false;
	  if (options.decodeStrings == null) options.decodeStrings = true;
	  if (options.validateEntrySizes == null) options.validateEntrySizes = true;
	  if (options.strictFileNames == null) options.strictFileNames = false;
	  // limit the max chunk size. see https://github.com/thejoshwolfe/yauzl/issues/87
	  var reader = fd_slicer.createFromBuffer(buffer, {maxChunkSize: 0x10000});
	  fromRandomAccessReader(reader, buffer.length, options, callback);
	}

	function fromRandomAccessReader(reader, totalSize, options, callback) {
	  if (typeof options === "function") {
	    callback = options;
	    options = null;
	  }
	  if (options == null) options = {};
	  if (options.autoClose == null) options.autoClose = true;
	  if (options.lazyEntries == null) options.lazyEntries = false;
	  if (options.decodeStrings == null) options.decodeStrings = true;
	  var decodeStrings = !!options.decodeStrings;
	  if (options.validateEntrySizes == null) options.validateEntrySizes = true;
	  if (options.strictFileNames == null) options.strictFileNames = false;
	  if (callback == null) callback = defaultCallback;
	  if (typeof totalSize !== "number") throw new Error("expected totalSize parameter to be a number");
	  if (totalSize > Number.MAX_SAFE_INTEGER) {
	    throw new 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.");
	  }

	  // the matching unref() call is in zipfile.close()
	  reader.ref();

	  // eocdr means End of Central Directory Record.
	  // search backwards for the eocdr signature.
	  // the last field of the eocdr is a variable-length comment.
	  // the comment size is encoded in a 2-byte field in the eocdr, which we can't find without trudging backwards through the comment to find it.
	  // as a consequence of this design decision, it's possible to have ambiguous zip file metadata if a coherent eocdr was in the comment.
	  // we search backwards for a eocdr signature, and hope that whoever made the zip file was smart enough to forbid the eocdr signature in the comment.
	  var eocdrWithoutCommentSize = 22;
	  var maxCommentSize = 0xffff; // 2-byte size
	  var bufferSize = Math.min(eocdrWithoutCommentSize + maxCommentSize, totalSize);
	  var buffer = newBuffer(bufferSize);
	  var bufferReadStart = totalSize - buffer.length;
	  readAndAssertNoEof(reader, buffer, 0, bufferSize, bufferReadStart, function(err) {
	    if (err) return callback(err);
	    for (var i = bufferSize - eocdrWithoutCommentSize; i >= 0; i -= 1) {
	      if (buffer.readUInt32LE(i) !== 0x06054b50) continue;
	      // found eocdr
	      var eocdrBuffer = buffer.slice(i);

	      // 0 - End of central directory signature = 0x06054b50
	      // 4 - Number of this disk
	      var diskNumber = eocdrBuffer.readUInt16LE(4);
	      if (diskNumber !== 0) {
	        return callback(new Error("multi-disk zip files are not supported: found disk number: " + diskNumber));
	      }
	      // 6 - Disk where central directory starts
	      // 8 - Number of central directory records on this disk
	      // 10 - Total number of central directory records
	      var entryCount = eocdrBuffer.readUInt16LE(10);
	      // 12 - Size of central directory (bytes)
	      // 16 - Offset of start of central directory, relative to start of archive
	      var centralDirectoryOffset = eocdrBuffer.readUInt32LE(16);
	      // 20 - Comment length
	      var commentLength = eocdrBuffer.readUInt16LE(20);
	      var expectedCommentLength = eocdrBuffer.length - eocdrWithoutCommentSize;
	      if (commentLength !== expectedCommentLength) {
	        return callback(new Error("invalid comment length. expected: " + expectedCommentLength + ". found: " + commentLength));
	      }
	      // 22 - Comment
	      // the encoding is always cp437.
	      var comment = decodeStrings ? decodeBuffer(eocdrBuffer, 22, eocdrBuffer.length, false)
	                                  : eocdrBuffer.slice(22);

	      if (!(entryCount === 0xffff || centralDirectoryOffset === 0xffffffff)) {
	        return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames));
	      }

	      // ZIP64 format

	      // ZIP64 Zip64 end of central directory locator
	      var zip64EocdlBuffer = newBuffer(20);
	      var zip64EocdlOffset = bufferReadStart + i - zip64EocdlBuffer.length;
	      readAndAssertNoEof(reader, zip64EocdlBuffer, 0, zip64EocdlBuffer.length, zip64EocdlOffset, function(err) {
	        if (err) return callback(err);

	        // 0 - zip64 end of central dir locator signature = 0x07064b50
	        if (zip64EocdlBuffer.readUInt32LE(0) !== 0x07064b50) {
	          return callback(new Error("invalid zip64 end of central directory locator signature"));
	        }
	        // 4 - number of the disk with the start of the zip64 end of central directory
	        // 8 - relative offset of the zip64 end of central directory record
	        var zip64EocdrOffset = readUInt64LE(zip64EocdlBuffer, 8);
	        // 16 - total number of disks

	        // ZIP64 end of central directory record
	        var zip64EocdrBuffer = newBuffer(56);
	        readAndAssertNoEof(reader, zip64EocdrBuffer, 0, zip64EocdrBuffer.length, zip64EocdrOffset, function(err) {
	          if (err) return callback(err);

	          // 0 - zip64 end of central dir signature                           4 bytes  (0x06064b50)
	          if (zip64EocdrBuffer.readUInt32LE(0) !== 0x06064b50) {
	            return callback(new Error("invalid zip64 end of central directory record signature"));
	          }
	          // 4 - size of zip64 end of central directory record                8 bytes
	          // 12 - version made by                                             2 bytes
	          // 14 - version needed to extract                                   2 bytes
	          // 16 - number of this disk                                         4 bytes
	          // 20 - number of the disk with the start of the central directory  4 bytes
	          // 24 - total number of entries in the central directory on this disk         8 bytes
	          // 32 - total number of entries in the central directory            8 bytes
	          entryCount = readUInt64LE(zip64EocdrBuffer, 32);
	          // 40 - size of the central directory                               8 bytes
	          // 48 - offset of start of central directory with respect to the starting disk number     8 bytes
	          centralDirectoryOffset = readUInt64LE(zip64EocdrBuffer, 48);
	          // 56 - zip64 extensible data sector                                (variable size)
	          return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames));
	        });
	      });
	      return;
	    }
	    callback(new Error("end of central directory record signature not found"));
	  });
	}

	util.inherits(ZipFile, EventEmitter);
	function ZipFile(reader, centralDirectoryOffset, fileSize, entryCount, comment, autoClose, lazyEntries, decodeStrings, validateEntrySizes, strictFileNames) {
	  var self = this;
	  EventEmitter.call(self);
	  self.reader = reader;
	  // forward close events
	  self.reader.on("error", function(err) {
	    // error closing the fd
	    emitError(self, err);
	  });
	  self.reader.once("close", function() {
	    self.emit("close");
	  });
	  self.readEntryCursor = centralDirectoryOffset;
	  self.fileSize = fileSize;
	  self.entryCount = entryCount;
	  self.comment = comment;
	  self.entriesRead = 0;
	  self.autoClose = !!autoClose;
	  self.lazyEntries = !!lazyEntries;
	  self.decodeStrings = !!decodeStrings;
	  self.validateEntrySizes = !!validateEntrySizes;
	  self.strictFileNames = !!strictFileNames;
	  self.isOpen = true;
	  self.emittedError = false;

	  if (!self.lazyEntries) self._readEntry();
	}
	ZipFile.prototype.close = function() {
	  if (!this.isOpen) return;
	  this.isOpen = false;
	  this.reader.unref();
	};

	function emitErrorAndAutoClose(self, err) {
	  if (self.autoClose) self.close();
	  emitError(self, err);
	}
	function emitError(self, err) {
	  if (self.emittedError) return;
	  self.emittedError = true;
	  self.emit("error", err);
	}

	ZipFile.prototype.readEntry = function() {
	  if (!this.lazyEntries) throw new Error("readEntry() called without lazyEntries:true");
	  this._readEntry();
	};
	ZipFile.prototype._readEntry = function() {
	  var self = this;
	  if (self.entryCount === self.entriesRead) {
	    // done with metadata
	    setImmediate(function() {
	      if (self.autoClose) self.close();
	      if (self.emittedError) return;
	      self.emit("end");
	    });
	    return;
	  }
	  if (self.emittedError) return;
	  var buffer = newBuffer(46);
	  readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) {
	    if (err) return emitErrorAndAutoClose(self, err);
	    if (self.emittedError) return;
	    var entry = new Entry();
	    // 0 - Central directory file header signature
	    var signature = buffer.readUInt32LE(0);
	    if (signature !== 0x02014b50) return emitErrorAndAutoClose(self, new Error("invalid central directory file header signature: 0x" + signature.toString(16)));
	    // 4 - Version made by
	    entry.versionMadeBy = buffer.readUInt16LE(4);
	    // 6 - Version needed to extract (minimum)
	    entry.versionNeededToExtract = buffer.readUInt16LE(6);
	    // 8 - General purpose bit flag
	    entry.generalPurposeBitFlag = buffer.readUInt16LE(8);
	    // 10 - Compression method
	    entry.compressionMethod = buffer.readUInt16LE(10);
	    // 12 - File last modification time
	    entry.lastModFileTime = buffer.readUInt16LE(12);
	    // 14 - File last modification date
	    entry.lastModFileDate = buffer.readUInt16LE(14);
	    // 16 - CRC-32
	    entry.crc32 = buffer.readUInt32LE(16);
	    // 20 - Compressed size
	    entry.compressedSize = buffer.readUInt32LE(20);
	    // 24 - Uncompressed size
	    entry.uncompressedSize = buffer.readUInt32LE(24);
	    // 28 - File name length (n)
	    entry.fileNameLength = buffer.readUInt16LE(28);
	    // 30 - Extra field length (m)
	    entry.extraFieldLength = buffer.readUInt16LE(30);
	    // 32 - File comment length (k)
	    entry.fileCommentLength = buffer.readUInt16LE(32);
	    // 34 - Disk number where file starts
	    // 36 - Internal file attributes
	    entry.internalFileAttributes = buffer.readUInt16LE(36);
	    // 38 - External file attributes
	    entry.externalFileAttributes = buffer.readUInt32LE(38);
	    // 42 - Relative offset of local file header
	    entry.relativeOffsetOfLocalHeader = buffer.readUInt32LE(42);

	    if (entry.generalPurposeBitFlag & 0x40) return emitErrorAndAutoClose(self, new Error("strong encryption is not supported"));

	    self.readEntryCursor += 46;

	    buffer = newBuffer(entry.fileNameLength + entry.extraFieldLength + entry.fileCommentLength);
	    readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) {
	      if (err) return emitErrorAndAutoClose(self, err);
	      if (self.emittedError) return;
	      // 46 - File name
	      var isUtf8 = (entry.generalPurposeBitFlag & 0x800) !== 0;
	      entry.fileName = self.decodeStrings ? decodeBuffer(buffer, 0, entry.fileNameLength, isUtf8)
	                                          : buffer.slice(0, entry.fileNameLength);

	      // 46+n - Extra field
	      var fileCommentStart = entry.fileNameLength + entry.extraFieldLength;
	      var extraFieldBuffer = buffer.slice(entry.fileNameLength, fileCommentStart);
	      entry.extraFields = [];
	      var i = 0;
	      while (i < extraFieldBuffer.length - 3) {
	        var headerId = extraFieldBuffer.readUInt16LE(i + 0);
	        var dataSize = extraFieldBuffer.readUInt16LE(i + 2);
	        var dataStart = i + 4;
	        var dataEnd = dataStart + dataSize;
	        if (dataEnd > extraFieldBuffer.length) return emitErrorAndAutoClose(self, new Error("extra field length exceeds extra field buffer size"));
	        var dataBuffer = newBuffer(dataSize);
	        extraFieldBuffer.copy(dataBuffer, 0, dataStart, dataEnd);
	        entry.extraFields.push({
	          id: headerId,
	          data: dataBuffer,
	        });
	        i = dataEnd;
	      }

	      // 46+n+m - File comment
	      entry.fileComment = self.decodeStrings ? decodeBuffer(buffer, fileCommentStart, fileCommentStart + entry.fileCommentLength, isUtf8)
	                                             : buffer.slice(fileCommentStart, fileCommentStart + entry.fileCommentLength);
	      // compatibility hack for https://github.com/thejoshwolfe/yauzl/issues/47
	      entry.comment = entry.fileComment;

	      self.readEntryCursor += buffer.length;
	      self.entriesRead += 1;

	      if (entry.uncompressedSize            === 0xffffffff ||
	          entry.compressedSize              === 0xffffffff ||
	          entry.relativeOffsetOfLocalHeader === 0xffffffff) {
	        // ZIP64 format
	        // find the Zip64 Extended Information Extra Field
	        var zip64EiefBuffer = null;
	        for (var i = 0; i < entry.extraFields.length; i++) {
	          var extraField = entry.extraFields[i];
	          if (extraField.id === 0x0001) {
	            zip64EiefBuffer = extraField.data;
	            break;
	          }
	        }
	        if (zip64EiefBuffer == null) {
	          return emitErrorAndAutoClose(self, new Error("expected zip64 extended information extra field"));
	        }
	        var index = 0;
	        // 0 - Original Size          8 bytes
	        if (entry.uncompressedSize === 0xffffffff) {
	          if (index + 8 > zip64EiefBuffer.length) {
	            return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include uncompressed size"));
	          }
	          entry.uncompressedSize = readUInt64LE(zip64EiefBuffer, index);
	          index += 8;
	        }
	        // 8 - Compressed Size        8 bytes
	        if (entry.compressedSize === 0xffffffff) {
	          if (index + 8 > zip64EiefBuffer.length) {
	            return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include compressed size"));
	          }
	          entry.compressedSize = readUInt64LE(zip64EiefBuffer, index);
	          index += 8;
	        }
	        // 16 - Relative Header Offset 8 bytes
	        if (entry.relativeOffsetOfLocalHeader === 0xffffffff) {
	          if (index + 8 > zip64EiefBuffer.length) {
	            return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include relative header offset"));
	          }
	          entry.relativeOffsetOfLocalHeader = readUInt64LE(zip64EiefBuffer, index);
	          index += 8;
	        }
	        // 24 - Disk Start Number      4 bytes
	      }

	      // check for Info-ZIP Unicode Path Extra Field (0x7075)
	      // see https://github.com/thejoshwolfe/yauzl/issues/33
	      if (self.decodeStrings) {
	        for (var i = 0; i < entry.extraFields.length; i++) {
	          var extraField = entry.extraFields[i];
	          if (extraField.id === 0x7075) {
	            if (extraField.data.length < 6) {
	              // too short to be meaningful
	              continue;
	            }
	            // Version       1 byte      version of this extra field, currently 1
	            if (extraField.data.readUInt8(0) !== 1) {
	              // > Changes may not be backward compatible so this extra
	              // > field should not be used if the version is not recognized.
	              continue;
	            }
	            // NameCRC32     4 bytes     File Name Field CRC32 Checksum
	            var oldNameCrc32 = extraField.data.readUInt32LE(1);
	            if (crc32.unsigned(buffer.slice(0, entry.fileNameLength)) !== oldNameCrc32) {
	              // > If the CRC check fails, this UTF-8 Path Extra Field should be
	              // > ignored and the File Name field in the header should be used instead.
	              continue;
	            }
	            // UnicodeName   Variable    UTF-8 version of the entry File Name
	            entry.fileName = decodeBuffer(extraField.data, 5, extraField.data.length, true);
	            break;
	          }
	        }
	      }

	      // validate file size
	      if (self.validateEntrySizes && entry.compressionMethod === 0) {
	        var expectedCompressedSize = entry.uncompressedSize;
	        if (entry.isEncrypted()) {
	          // traditional encryption prefixes the file data with a header
	          expectedCompressedSize += 12;
	        }
	        if (entry.compressedSize !== expectedCompressedSize) {
	          var msg = "compressed/uncompressed size mismatch for stored file: " + entry.compressedSize + " != " + entry.uncompressedSize;
	          return emitErrorAndAutoClose(self, new Error(msg));
	        }
	      }

	      if (self.decodeStrings) {
	        if (!self.strictFileNames) {
	          // allow backslash
	          entry.fileName = entry.fileName.replace(/\\/g, "/");
	        }
	        var errorMessage = validateFileName(entry.fileName, self.validateFileNameOptions);
	        if (errorMessage != null) return emitErrorAndAutoClose(self, new Error(errorMessage));
	      }
	      self.emit("entry", entry);

	      if (!self.lazyEntries) self._readEntry();
	    });
	  });
	};

	ZipFile.prototype.openReadStream = function(entry, options, callback) {
	  var self = this;
	  // parameter validation
	  var relativeStart = 0;
	  var relativeEnd = entry.compressedSize;
	  if (callback == null) {
	    callback = options;
	    options = {};
	  } else {
	    // validate options that the caller has no excuse to get wrong
	    if (options.decrypt != null) {
	      if (!entry.isEncrypted()) {
	        throw new Error("options.decrypt can only be specified for encrypted entries");
	      }
	      if (options.decrypt !== false) throw new Error("invalid options.decrypt value: " + options.decrypt);
	      if (entry.isCompressed()) {
	        if (options.decompress !== false) throw new Error("entry is encrypted and compressed, and options.decompress !== false");
	      }
	    }
	    if (options.decompress != null) {
	      if (!entry.isCompressed()) {
	        throw new Error("options.decompress can only be specified for compressed entries");
	      }
	      if (!(options.decompress === false || options.decompress === true)) {
	        throw new Error("invalid options.decompress value: " + options.decompress);
	      }
	    }
	    if (options.start != null || options.end != null) {
	      if (entry.isCompressed() && options.decompress !== false) {
	        throw new Error("start/end range not allowed for compressed entry without options.decompress === false");
	      }
	      if (entry.isEncrypted() && options.decrypt !== false) {
	        throw new Error("start/end range not allowed for encrypted entry without options.decrypt === false");
	      }
	    }
	    if (options.start != null) {
	      relativeStart = options.start;
	      if (relativeStart < 0) throw new Error("options.start < 0");
	      if (relativeStart > entry.compressedSize) throw new Error("options.start > entry.compressedSize");
	    }
	    if (options.end != null) {
	      relativeEnd = options.end;
	      if (relativeEnd < 0) throw new Error("options.end < 0");
	      if (relativeEnd > entry.compressedSize) throw new Error("options.end > entry.compressedSize");
	      if (relativeEnd < relativeStart) throw new Error("options.end < options.start");
	    }
	  }
	  // any further errors can either be caused by the zipfile,
	  // or were introduced in a minor version of yauzl,
	  // so should be passed to the client rather than thrown.
	  if (!self.isOpen) return callback(new Error("closed"));
	  if (entry.isEncrypted()) {
	    if (options.decrypt !== false) return callback(new Error("entry is encrypted, and options.decrypt !== false"));
	  }
	  // make sure we don't lose the fd before we open the actual read stream
	  self.reader.ref();
	  var buffer = newBuffer(30);
	  readAndAssertNoEof(self.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader, function(err) {
	    try {
	      if (err) return callback(err);
	      // 0 - Local file header signature = 0x04034b50
	      var signature = buffer.readUInt32LE(0);
	      if (signature !== 0x04034b50) {
	        return callback(new Error("invalid local file header signature: 0x" + signature.toString(16)));
	      }
	      // all this should be redundant
	      // 4 - Version needed to extract (minimum)
	      // 6 - General purpose bit flag
	      // 8 - Compression method
	      // 10 - File last modification time
	      // 12 - File last modification date
	      // 14 - CRC-32
	      // 18 - Compressed size
	      // 22 - Uncompressed size
	      // 26 - File name length (n)
	      var fileNameLength = buffer.readUInt16LE(26);
	      // 28 - Extra field length (m)
	      var extraFieldLength = buffer.readUInt16LE(28);
	      // 30 - File name
	      // 30+n - Extra field
	      var localFileHeaderEnd = entry.relativeOffsetOfLocalHeader + buffer.length + fileNameLength + extraFieldLength;
	      var decompress;
	      if (entry.compressionMethod === 0) {
	        // 0 - The file is stored (no compression)
	        decompress = false;
	      } else if (entry.compressionMethod === 8) {
	        // 8 - The file is Deflated
	        decompress = options.decompress != null ? options.decompress : true;
	      } else {
	        return callback(new Error("unsupported compression method: " + entry.compressionMethod));
	      }
	      var fileDataStart = localFileHeaderEnd;
	      var fileDataEnd = fileDataStart + entry.compressedSize;
	      if (entry.compressedSize !== 0) {
	        // bounds check now, because the read streams will probably not complain loud enough.
	        // since we're dealing with an unsigned offset plus an unsigned size,
	        // we only have 1 thing to check for.
	        if (fileDataEnd > self.fileSize) {
	          return callback(new Error("file data overflows file bounds: " +
	              fileDataStart + " + " + entry.compressedSize + " > " + self.fileSize));
	        }
	      }
	      var readStream = self.reader.createReadStream({
	        start: fileDataStart + relativeStart,
	        end: fileDataStart + relativeEnd,
	      });
	      var endpointStream = readStream;
	      if (decompress) {
	        var destroyed = false;
	        var inflateFilter = zlib.createInflateRaw();
	        readStream.on("error", function(err) {
	          // setImmediate here because errors can be emitted during the first call to pipe()
	          setImmediate(function() {
	            if (!destroyed) inflateFilter.emit("error", err);
	          });
	        });
	        readStream.pipe(inflateFilter);

	        if (self.validateEntrySizes) {
	          endpointStream = new AssertByteCountStream(entry.uncompressedSize);
	          inflateFilter.on("error", function(err) {
	            // forward zlib errors to the client-visible stream
	            setImmediate(function() {
	              if (!destroyed) endpointStream.emit("error", err);
	            });
	          });
	          inflateFilter.pipe(endpointStream);
	        } else {
	          // the zlib filter is the client-visible stream
	          endpointStream = inflateFilter;
	        }
	        // this is part of yauzl's API, so implement this function on the client-visible stream
	        endpointStream.destroy = function() {
	          destroyed = true;
	          if (inflateFilter !== endpointStream) inflateFilter.unpipe(endpointStream);
	          readStream.unpipe(inflateFilter);
	          // TODO: the inflateFilter may cause a memory leak. see Issue #27.
	          readStream.destroy();
	        };
	      }
	      callback(null, endpointStream);
	    } finally {
	      self.reader.unref();
	    }
	  });
	};

	function Entry() {
	}
	Entry.prototype.getLastModDate = function() {
	  return dosDateTimeToDate(this.lastModFileDate, this.lastModFileTime);
	};
	Entry.prototype.isEncrypted = function() {
	  return (this.generalPurposeBitFlag & 0x1) !== 0;
	};
	Entry.prototype.isCompressed = function() {
	  return this.compressionMethod === 8;
	};

	function dosDateTimeToDate(date, time) {
	  var day = date & 0x1f; // 1-31
	  var month = (date >> 5 & 0xf) - 1; // 1-12, 0-11
	  var year = (date >> 9 & 0x7f) + 1980; // 0-128, 1980-2108

	  var millisecond = 0;
	  var second = (time & 0x1f) * 2; // 0-29, 0-58 (even numbers)
	  var minute = time >> 5 & 0x3f; // 0-59
	  var hour = time >> 11 & 0x1f; // 0-23

	  return new Date(year, month, day, hour, minute, second, millisecond);
	}

	function validateFileName(fileName) {
	  if (fileName.indexOf("\\") !== -1) {
	    return "invalid characters in fileName: " + fileName;
	  }
	  if (/^[a-zA-Z]:/.test(fileName) || /^\//.test(fileName)) {
	    return "absolute path: " + fileName;
	  }
	  if (fileName.split("/").indexOf("..") !== -1) {
	    return "invalid relative path: " + fileName;
	  }
	  // all good
	  return null;
	}

	function readAndAssertNoEof(reader, buffer, offset, length, position, callback) {
	  if (length === 0) {
	    // fs.read will throw an out-of-bounds error if you try to read 0 bytes from a 0 byte file
	    return setImmediate(function() { callback(null, newBuffer(0)); });
	  }
	  reader.read(buffer, offset, length, position, function(err, bytesRead) {
	    if (err) return callback(err);
	    if (bytesRead < length) {
	      return callback(new Error("unexpected EOF"));
	    }
	    callback();
	  });
	}

	util.inherits(AssertByteCountStream, Transform);
	function AssertByteCountStream(byteCount) {
	  Transform.call(this);
	  this.actualByteCount = 0;
	  this.expectedByteCount = byteCount;
	}
	AssertByteCountStream.prototype._transform = function(chunk, encoding, cb) {
	  this.actualByteCount += chunk.length;
	  if (this.actualByteCount > this.expectedByteCount) {
	    var msg = "too many bytes in the stream. expected " + this.expectedByteCount + ". got at least " + this.actualByteCount;
	    return cb(new Error(msg));
	  }
	  cb(null, chunk);
	};
	AssertByteCountStream.prototype._flush = function(cb) {
	  if (this.actualByteCount < this.expectedByteCount) {
	    var msg = "not enough bytes in the stream. expected " + this.expectedByteCount + ". got only " + this.actualByteCount;
	    return cb(new Error(msg));
	  }
	  cb();
	};

	util.inherits(RandomAccessReader, EventEmitter);
	function RandomAccessReader() {
	  EventEmitter.call(this);
	  this.refCount = 0;
	}
	RandomAccessReader.prototype.ref = function() {
	  this.refCount += 1;
	};
	RandomAccessReader.prototype.unref = function() {
	  var self = this;
	  self.refCount -= 1;

	  if (self.refCount > 0) return;
	  if (self.refCount < 0) throw new Error("invalid unref");

	  self.close(onCloseDone);

	  function onCloseDone(err) {
	    if (err) return self.emit('error', err);
	    self.emit('close');
	  }
	};
	RandomAccessReader.prototype.createReadStream = function(options) {
	  var start = options.start;
	  var end = options.end;
	  if (start === end) {
	    var emptyStream = new PassThrough();
	    setImmediate(function() {
	      emptyStream.end();
	    });
	    return emptyStream;
	  }
	  var stream = this._readStreamForRange(start, end);

	  var destroyed = false;
	  var refUnrefFilter = new RefUnrefFilter(this);
	  stream.on("error", function(err) {
	    setImmediate(function() {
	      if (!destroyed) refUnrefFilter.emit("error", err);
	    });
	  });
	  refUnrefFilter.destroy = function() {
	    stream.unpipe(refUnrefFilter);
	    refUnrefFilter.unref();
	    stream.destroy();
	  };

	  var byteCounter = new AssertByteCountStream(end - start);
	  refUnrefFilter.on("error", function(err) {
	    setImmediate(function() {
	      if (!destroyed) byteCounter.emit("error", err);
	    });
	  });
	  byteCounter.destroy = function() {
	    destroyed = true;
	    refUnrefFilter.unpipe(byteCounter);
	    refUnrefFilter.destroy();
	  };

	  return stream.pipe(refUnrefFilter).pipe(byteCounter);
	};
	RandomAccessReader.prototype._readStreamForRange = function(start, end) {
	  throw new Error("not implemented");
	};
	RandomAccessReader.prototype.read = function(buffer, offset, length, position, callback) {
	  var readStream = this.createReadStream({start: position, end: position + length});
	  var writeStream = new Writable();
	  var written = 0;
	  writeStream._write = function(chunk, encoding, cb) {
	    chunk.copy(buffer, offset + written, 0, chunk.length);
	    written += chunk.length;
	    cb();
	  };
	  writeStream.on("finish", callback);
	  readStream.on("error", function(error) {
	    callback(error);
	  });
	  readStream.pipe(writeStream);
	};
	RandomAccessReader.prototype.close = function(callback) {
	  setImmediate(callback);
	};

	util.inherits(RefUnrefFilter, PassThrough);
	function RefUnrefFilter(context) {
	  PassThrough.call(this);
	  this.context = context;
	  this.context.ref();
	  this.unreffedYet = false;
	}
	RefUnrefFilter.prototype._flush = function(cb) {
	  this.unref();
	  cb();
	};
	RefUnrefFilter.prototype.unref = function(cb) {
	  if (this.unreffedYet) return;
	  this.unreffedYet = true;
	  this.context.unref();
	};

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

	function readUInt64LE(buffer, offset) {
	  // there is no native function for this, because we can't actually store 64-bit integers precisely.
	  // after 53 bits, JavaScript's Number type (IEEE 754 double) can't store individual integers anymore.
	  // but since 53 bits is a whole lot more than 32 bits, we do our best anyway.
	  var lower32 = buffer.readUInt32LE(offset);
	  var upper32 = buffer.readUInt32LE(offset + 4);
	  // we can't use bitshifting here, because JavaScript bitshifting only works on 32-bit integers.
	  return upper32 * 0x100000000 + lower32;
	  // as long as we're bounds checking the result of this function against the total file size,
	  // we'll catch any overflow errors, because we already made sure the total file size was within reason.
	}

	// Node 10 deprecated new Buffer().
	var newBuffer;
	if (typeof Buffer.allocUnsafe === "function") {
	  newBuffer = function(len) {
	    return Buffer.allocUnsafe(len);
	  };
	} else {
	  newBuffer = function(len) {
	    return new Buffer(len);
	  };
	}

	function defaultCallback(err) {
	  if (err) throw err;
	}
	return yauzl;
}

var base_write_stream;
var hasRequiredBase_write_stream;

function requireBase_write_stream () {
	if (hasRequiredBase_write_stream) return base_write_stream;
	hasRequiredBase_write_stream = 1;

	const stream = require$$1$1;

	class UncompressBaseStream extends stream.Writable {
	  emit(event, data) {
	    if (event === 'error') {
	      const error = data;
	      if (error.name === 'Error') {
	        error.name = this.constructor.name + 'Error';
	      }
	    }
	    super.emit.apply(this, arguments);
	  }
	}

	base_write_stream = UncompressBaseStream;
	return base_write_stream;
}

var lib$4 = {exports: {}};

/* eslint-disable node/no-deprecated-api */

var safer_1;
var hasRequiredSafer;

function requireSafer () {
	if (hasRequiredSafer) return safer_1;
	hasRequiredSafer = 1;

	var buffer = require$$0$4;
	var Buffer = buffer.Buffer;

	var safer = {};

	var key;

	for (key in buffer) {
	  if (!buffer.hasOwnProperty(key)) continue
	  if (key === 'SlowBuffer' || key === 'Buffer') continue
	  safer[key] = buffer[key];
	}

	var Safer = safer.Buffer = {};
	for (key in Buffer) {
	  if (!Buffer.hasOwnProperty(key)) continue
	  if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue
	  Safer[key] = Buffer[key];
	}

	safer.Buffer.prototype = Buffer.prototype;

	if (!Safer.from || Safer.from === Uint8Array.from) {
	  Safer.from = function (value, encodingOrOffset, length) {
	    if (typeof value === 'number') {
	      throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value)
	    }
	    if (value && typeof value.length === 'undefined') {
	      throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value)
	    }
	    return Buffer(value, encodingOrOffset, length)
	  };
	}

	if (!Safer.alloc) {
	  Safer.alloc = function (size, fill, encoding) {
	    if (typeof size !== 'number') {
	      throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size)
	    }
	    if (size < 0 || size >= 2 * (1 << 30)) {
	      throw new RangeError('The value "' + size + '" is invalid for option "size"')
	    }
	    var buf = Buffer(size);
	    if (!fill || fill.length === 0) {
	      buf.fill(0);
	    } else if (typeof encoding === 'string') {
	      buf.fill(fill, encoding);
	    } else {
	      buf.fill(fill);
	    }
	    return buf
	  };
	}

	if (!safer.kStringMaxLength) {
	  try {
	    safer.kStringMaxLength = process.binding('buffer').kStringMaxLength;
	  } catch (e) {
	    // we can't determine kStringMaxLength in environments where process.binding
	    // is unsupported, so let's not set it
	  }
	}

	if (!safer.constants) {
	  safer.constants = {
	    MAX_LENGTH: safer.kMaxLength
	  };
	  if (safer.kStringMaxLength) {
	    safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength;
	  }
	}

	safer_1 = safer;
	return safer_1;
}

var bomHandling = {};

var hasRequiredBomHandling;

function requireBomHandling () {
	if (hasRequiredBomHandling) return bomHandling;
	hasRequiredBomHandling = 1;

	var BOMChar = '\uFEFF';

	bomHandling.PrependBOM = PrependBOMWrapper;
	function PrependBOMWrapper(encoder, options) {
	    this.encoder = encoder;
	    this.addBOM = true;
	}

	PrependBOMWrapper.prototype.write = function(str) {
	    if (this.addBOM) {
	        str = BOMChar + str;
	        this.addBOM = false;
	    }

	    return this.encoder.write(str);
	};

	PrependBOMWrapper.prototype.end = function() {
	    return this.encoder.end();
	};


	//------------------------------------------------------------------------------

	bomHandling.StripBOM = StripBOMWrapper;
	function StripBOMWrapper(decoder, options) {
	    this.decoder = decoder;
	    this.pass = false;
	    this.options = options || {};
	}

	StripBOMWrapper.prototype.write = function(buf) {
	    var res = this.decoder.write(buf);
	    if (this.pass || !res)
	        return res;

	    if (res[0] === BOMChar) {
	        res = res.slice(1);
	        if (typeof this.options.stripBOM === 'function')
	            this.options.stripBOM();
	    }

	    this.pass = true;
	    return res;
	};

	StripBOMWrapper.prototype.end = function() {
	    return this.decoder.end();
	};
	return bomHandling;
}

var encodings = {};

var internal;
var hasRequiredInternal;

function requireInternal () {
	if (hasRequiredInternal) return internal;
	hasRequiredInternal = 1;
	var Buffer = requireSafer().Buffer;

	// Export Node.js internal encodings.

	internal = {
	    // Encodings
	    utf8:   { type: "_internal", bomAware: true},
	    cesu8:  { type: "_internal", bomAware: true},
	    unicode11utf8: "utf8",

	    ucs2:   { type: "_internal", bomAware: true},
	    utf16le: "ucs2",

	    binary: { type: "_internal" },
	    base64: { type: "_internal" },
	    hex:    { type: "_internal" },

	    // Codec.
	    _internal: InternalCodec,
	};

	//------------------------------------------------------------------------------

	function InternalCodec(codecOptions, iconv) {
	    this.enc = codecOptions.encodingName;
	    this.bomAware = codecOptions.bomAware;

	    if (this.enc === "base64")
	        this.encoder = InternalEncoderBase64;
	    else if (this.enc === "cesu8") {
	        this.enc = "utf8"; // Use utf8 for decoding.
	        this.encoder = InternalEncoderCesu8;

	        // Add decoder for versions of Node not supporting CESU-8
	        if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') {
	            this.decoder = InternalDecoderCesu8;
	            this.defaultCharUnicode = iconv.defaultCharUnicode;
	        }
	    }
	}

	InternalCodec.prototype.encoder = InternalEncoder;
	InternalCodec.prototype.decoder = InternalDecoder;

	//------------------------------------------------------------------------------

	// We use node.js internal decoder. Its signature is the same as ours.
	var StringDecoder = require$$1$3.StringDecoder;

	if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method.
	    StringDecoder.prototype.end = function() {};


	function InternalDecoder(options, codec) {
	    StringDecoder.call(this, codec.enc);
	}

	InternalDecoder.prototype = StringDecoder.prototype;


	//------------------------------------------------------------------------------
	// Encoder is mostly trivial

	function InternalEncoder(options, codec) {
	    this.enc = codec.enc;
	}

	InternalEncoder.prototype.write = function(str) {
	    return Buffer.from(str, this.enc);
	};

	InternalEncoder.prototype.end = function() {
	};


	//------------------------------------------------------------------------------
	// Except base64 encoder, which must keep its state.

	function InternalEncoderBase64(options, codec) {
	    this.prevStr = '';
	}

	InternalEncoderBase64.prototype.write = function(str) {
	    str = this.prevStr + str;
	    var completeQuads = str.length - (str.length % 4);
	    this.prevStr = str.slice(completeQuads);
	    str = str.slice(0, completeQuads);

	    return Buffer.from(str, "base64");
	};

	InternalEncoderBase64.prototype.end = function() {
	    return Buffer.from(this.prevStr, "base64");
	};


	//------------------------------------------------------------------------------
	// CESU-8 encoder is also special.

	function InternalEncoderCesu8(options, codec) {
	}

	InternalEncoderCesu8.prototype.write = function(str) {
	    var buf = Buffer.alloc(str.length * 3), bufIdx = 0;
	    for (var i = 0; i < str.length; i++) {
	        var charCode = str.charCodeAt(i);
	        // Naive implementation, but it works because CESU-8 is especially easy
	        // to convert from UTF-16 (which all JS strings are encoded in).
	        if (charCode < 0x80)
	            buf[bufIdx++] = charCode;
	        else if (charCode < 0x800) {
	            buf[bufIdx++] = 0xC0 + (charCode >>> 6);
	            buf[bufIdx++] = 0x80 + (charCode & 0x3f);
	        }
	        else { // charCode will always be < 0x10000 in javascript.
	            buf[bufIdx++] = 0xE0 + (charCode >>> 12);
	            buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f);
	            buf[bufIdx++] = 0x80 + (charCode & 0x3f);
	        }
	    }
	    return buf.slice(0, bufIdx);
	};

	InternalEncoderCesu8.prototype.end = function() {
	};

	//------------------------------------------------------------------------------
	// CESU-8 decoder is not implemented in Node v4.0+

	function InternalDecoderCesu8(options, codec) {
	    this.acc = 0;
	    this.contBytes = 0;
	    this.accBytes = 0;
	    this.defaultCharUnicode = codec.defaultCharUnicode;
	}

	InternalDecoderCesu8.prototype.write = function(buf) {
	    var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, 
	        res = '';
	    for (var i = 0; i < buf.length; i++) {
	        var curByte = buf[i];
	        if ((curByte & 0xC0) !== 0x80) { // Leading byte
	            if (contBytes > 0) { // Previous code is invalid
	                res += this.defaultCharUnicode;
	                contBytes = 0;
	            }

	            if (curByte < 0x80) { // Single-byte code
	                res += String.fromCharCode(curByte);
	            } else if (curByte < 0xE0) { // Two-byte code
	                acc = curByte & 0x1F;
	                contBytes = 1; accBytes = 1;
	            } else if (curByte < 0xF0) { // Three-byte code
	                acc = curByte & 0x0F;
	                contBytes = 2; accBytes = 1;
	            } else { // Four or more are not supported for CESU-8.
	                res += this.defaultCharUnicode;
	            }
	        } else { // Continuation byte
	            if (contBytes > 0) { // We're waiting for it.
	                acc = (acc << 6) | (curByte & 0x3f);
	                contBytes--; accBytes++;
	                if (contBytes === 0) {
	                    // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80)
	                    if (accBytes === 2 && acc < 0x80 && acc > 0)
	                        res += this.defaultCharUnicode;
	                    else if (accBytes === 3 && acc < 0x800)
	                        res += this.defaultCharUnicode;
	                    else
	                        // Actually add character.
	                        res += String.fromCharCode(acc);
	                }
	            } else { // Unexpected continuation byte
	                res += this.defaultCharUnicode;
	            }
	        }
	    }
	    this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes;
	    return res;
	};

	InternalDecoderCesu8.prototype.end = function() {
	    var res = 0;
	    if (this.contBytes > 0)
	        res += this.defaultCharUnicode;
	    return res;
	};
	return internal;
}

var utf32 = {};

var hasRequiredUtf32;

function requireUtf32 () {
	if (hasRequiredUtf32) return utf32;
	hasRequiredUtf32 = 1;

	var Buffer = requireSafer().Buffer;

	// == UTF32-LE/BE codec. ==========================================================

	utf32._utf32 = Utf32Codec;

	function Utf32Codec(codecOptions, iconv) {
	    this.iconv = iconv;
	    this.bomAware = true;
	    this.isLE = codecOptions.isLE;
	}

	utf32.utf32le = { type: '_utf32', isLE: true };
	utf32.utf32be = { type: '_utf32', isLE: false };

	// Aliases
	utf32.ucs4le = 'utf32le';
	utf32.ucs4be = 'utf32be';

	Utf32Codec.prototype.encoder = Utf32Encoder;
	Utf32Codec.prototype.decoder = Utf32Decoder;

	// -- Encoding

	function Utf32Encoder(options, codec) {
	    this.isLE = codec.isLE;
	    this.highSurrogate = 0;
	}

	Utf32Encoder.prototype.write = function(str) {
	    var src = Buffer.from(str, 'ucs2');
	    var dst = Buffer.alloc(src.length * 2);
	    var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE;
	    var offset = 0;

	    for (var i = 0; i < src.length; i += 2) {
	        var code = src.readUInt16LE(i);
	        var isHighSurrogate = (0xD800 <= code && code < 0xDC00);
	        var isLowSurrogate = (0xDC00 <= code && code < 0xE000);

	        if (this.highSurrogate) {
	            if (isHighSurrogate || !isLowSurrogate) {
	                // There shouldn't be two high surrogates in a row, nor a high surrogate which isn't followed by a low
	                // surrogate. If this happens, keep the pending high surrogate as a stand-alone semi-invalid character
	                // (technically wrong, but expected by some applications, like Windows file names).
	                write32.call(dst, this.highSurrogate, offset);
	                offset += 4;
	            }
	            else {
	                // Create 32-bit value from high and low surrogates;
	                var codepoint = (((this.highSurrogate - 0xD800) << 10) | (code - 0xDC00)) + 0x10000;

	                write32.call(dst, codepoint, offset);
	                offset += 4;
	                this.highSurrogate = 0;

	                continue;
	            }
	        }

	        if (isHighSurrogate)
	            this.highSurrogate = code;
	        else {
	            // Even if the current character is a low surrogate, with no previous high surrogate, we'll
	            // encode it as a semi-invalid stand-alone character for the same reasons expressed above for
	            // unpaired high surrogates.
	            write32.call(dst, code, offset);
	            offset += 4;
	            this.highSurrogate = 0;
	        }
	    }

	    if (offset < dst.length)
	        dst = dst.slice(0, offset);

	    return dst;
	};

	Utf32Encoder.prototype.end = function() {
	    // Treat any leftover high surrogate as a semi-valid independent character.
	    if (!this.highSurrogate)
	        return;

	    var buf = Buffer.alloc(4);

	    if (this.isLE)
	        buf.writeUInt32LE(this.highSurrogate, 0);
	    else
	        buf.writeUInt32BE(this.highSurrogate, 0);

	    this.highSurrogate = 0;

	    return buf;
	};

	// -- Decoding

	function Utf32Decoder(options, codec) {
	    this.isLE = codec.isLE;
	    this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0);
	    this.overflow = null;
	}

	Utf32Decoder.prototype.write = function(src) {
	    if (src.length === 0)
	        return '';

	    if (this.overflow)
	        src = Buffer.concat([this.overflow, src]);

	    var goodLength = src.length - src.length % 4;

	    if (src.length !== goodLength) {
	        this.overflow = src.slice(goodLength);
	        src = src.slice(0, goodLength);
	    }
	    else
	        this.overflow = null;

	    var dst = Buffer.alloc(goodLength);
	    var offset = 0;

	    for (var i = 0; i < goodLength; i += 4) {
	        var codepoint = this.isLE ? src.readUInt32LE(i) : src.readUInt32BE(i);

	        if (codepoint < 0x10000) {
	            // Simple 16-bit character
	            dst.writeUInt16LE(codepoint, offset);
	            offset += 2;
	        }
	        else {
	            if (codepoint > 0x10FFFF) {
	                // Not a valid Unicode codepoint
	                dst.writeUInt16LE(this.badChar, offset);
	                offset += 2;
	            }
	            else {
	                // Create high and low surrogates.
	                codepoint -= 0x10000;
	                var high = 0xD800 | (codepoint >> 10);
	                var low = 0xDC00 + (codepoint & 0x3FF);
	                dst.writeUInt16LE(high, offset);
	                offset += 2;
	                dst.writeUInt16LE(low, offset);
	                offset += 2;
	            }
	        }
	    }

	    return dst.slice(0, offset).toString('ucs2');
	};

	Utf32Decoder.prototype.end = function() {
	    this.overflow = null;
	};

	// == UTF-32 Auto codec =============================================================
	// Decoder chooses automatically from UTF-32LE and UTF-32BE using BOM and space-based heuristic.
	// Defaults to UTF-32LE. http://en.wikipedia.org/wiki/UTF-32
	// Encoder/decoder default can be changed: iconv.decode(buf, 'utf32', {defaultEncoding: 'utf-32be'});

	// Encoder prepends BOM (which can be overridden with (addBOM: false}).

	utf32.utf32 = Utf32AutoCodec;
	utf32.ucs4 = Utf32AutoCodec;

	function Utf32AutoCodec(options, iconv) {
	    this.iconv = iconv;
	}

	Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder;
	Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder;

	// -- Encoding

	function Utf32AutoEncoder(options, codec) {
	    options = options || {};

	    if (options.addBOM === undefined)
	        options.addBOM = true;

	    this.encoder = codec.iconv.getEncoder(options.defaultEncoding || 'utf-32le', options);
	}

	Utf32AutoEncoder.prototype.write = function(str) {
	    return this.encoder.write(str);
	};

	Utf32AutoEncoder.prototype.end = function() {
	    return this.encoder.end();
	};

	// -- Decoding

	function Utf32AutoDecoder(options, codec) {
	    this.decoder = null;
	    this.initialBytes = [];
	    this.initialBytesLen = 0;
	    this.options = options || {};
	    this.iconv = codec.iconv;
	}

	Utf32AutoDecoder.prototype.write = function(buf) {
	    if (!this.decoder) {
	        // Codec is not chosen yet. Accumulate initial bytes.
	        this.initialBytes.push(buf);
	        this.initialBytesLen += buf.length;

	        if (this.initialBytesLen < 32) // We need more bytes to use space heuristic (see below)
	            return '';

	        // We have enough bytes -> detect endianness.
	        var buf2 = Buffer.concat(this.initialBytes),
	            encoding = detectEncoding(buf2, this.options.defaultEncoding);
	        this.decoder = this.iconv.getDecoder(encoding, this.options);
	        this.initialBytes.length = this.initialBytesLen = 0;
	    }

	    return this.decoder.write(buf);
	};

	Utf32AutoDecoder.prototype.end = function() {
	    if (!this.decoder) {
	        var buf = Buffer.concat(this.initialBytes),
	            encoding = detectEncoding(buf, this.options.defaultEncoding);
	        this.decoder = this.iconv.getDecoder(encoding, this.options);

	        var res = this.decoder.write(buf),
	            trail = this.decoder.end();

	        return trail ? (res + trail) : res;
	    }

	    return this.decoder.end();
	};

	function detectEncoding(buf, defaultEncoding) {
	    var enc = defaultEncoding || 'utf-32le';

	    if (buf.length >= 4) {
	        // Check BOM.
	        if (buf.readUInt32BE(0) === 0xFEFF) // UTF-32LE BOM
	            enc = 'utf-32be';
	        else if (buf.readUInt32LE(0) === 0xFEFF) // UTF-32LE BOM
	            enc = 'utf-32le';
	        else {
	            // No BOM found. Try to deduce encoding from initial content.
	            // Using the wrong endian-ism for UTF-32 will very often result in codepoints that are beyond
	            // the valid Unicode limit of 0x10FFFF. That will be used as the primary determinant.
	            //
	            // Further, we can suppose the content is mostly plain ASCII chars (U+00**).
	            // So, we count ASCII as if it was LE or BE, and decide from that.
	            var invalidLE = 0, invalidBE = 0;
	            var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions
	                _len = Math.min(buf.length - (buf.length % 4), 128); // Len is always even.

	            for (var i = 0; i < _len; i += 4) {
	                var b0 = buf[i], b1  = buf[i + 1], b2 = buf[i + 2], b3 = buf[i + 3];

	                if (b0 !== 0 || b1 > 0x10) ++invalidBE;
	                if (b3 !== 0 || b2 > 0x10) ++invalidLE;

	                if (b0 === 0 && b1 === 0 && b2 === 0 && b3 !== 0) asciiCharsBE++;
	                if (b0 !== 0 && b1 === 0 && b2 === 0 && b3 === 0) asciiCharsLE++;
	            }

	            if (invalidBE < invalidLE)
	                enc = 'utf-32be';
	            else if (invalidLE < invalidBE)
	                enc = 'utf-32le';
	            if (asciiCharsBE > asciiCharsLE)
	                enc = 'utf-32be';
	            else if (asciiCharsBE < asciiCharsLE)
	                enc = 'utf-32le';
	        }
	    }

	    return enc;
	}
	return utf32;
}

var utf16 = {};

var hasRequiredUtf16;

function requireUtf16 () {
	if (hasRequiredUtf16) return utf16;
	hasRequiredUtf16 = 1;
	var Buffer = requireSafer().Buffer;

	// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js

	// == UTF16-BE codec. ==========================================================

	utf16.utf16be = Utf16BECodec;
	function Utf16BECodec() {
	}

	Utf16BECodec.prototype.encoder = Utf16BEEncoder;
	Utf16BECodec.prototype.decoder = Utf16BEDecoder;
	Utf16BECodec.prototype.bomAware = true;


	// -- Encoding

	function Utf16BEEncoder() {
	}

	Utf16BEEncoder.prototype.write = function(str) {
	    var buf = Buffer.from(str, 'ucs2');
	    for (var i = 0; i < buf.length; i += 2) {
	        var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp;
	    }
	    return buf;
	};

	Utf16BEEncoder.prototype.end = function() {
	};


	// -- Decoding

	function Utf16BEDecoder() {
	    this.overflowByte = -1;
	}

	Utf16BEDecoder.prototype.write = function(buf) {
	    if (buf.length == 0)
	        return '';

	    var buf2 = Buffer.alloc(buf.length + 1),
	        i = 0, j = 0;

	    if (this.overflowByte !== -1) {
	        buf2[0] = buf[0];
	        buf2[1] = this.overflowByte;
	        i = 1; j = 2;
	    }

	    for (; i < buf.length-1; i += 2, j+= 2) {
	        buf2[j] = buf[i+1];
	        buf2[j+1] = buf[i];
	    }

	    this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1;

	    return buf2.slice(0, j).toString('ucs2');
	};

	Utf16BEDecoder.prototype.end = function() {
	};


	// == UTF-16 codec =============================================================
	// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic.
	// Defaults to UTF-16LE, as it's prevalent and default in Node.
	// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le
	// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'});

	// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false).

	utf16.utf16 = Utf16Codec;
	function Utf16Codec(codecOptions, iconv) {
	    this.iconv = iconv;
	}

	Utf16Codec.prototype.encoder = Utf16Encoder;
	Utf16Codec.prototype.decoder = Utf16Decoder;


	// -- Encoding (pass-through)

	function Utf16Encoder(options, codec) {
	    options = options || {};
	    if (options.addBOM === undefined)
	        options.addBOM = true;
	    this.encoder = codec.iconv.getEncoder('utf-16le', options);
	}

	Utf16Encoder.prototype.write = function(str) {
	    return this.encoder.write(str);
	};

	Utf16Encoder.prototype.end = function() {
	    return this.encoder.end();
	};


	// -- Decoding

	function Utf16Decoder(options, codec) {
	    this.decoder = null;
	    this.initialBytes = [];
	    this.initialBytesLen = 0;

	    this.options = options || {};
	    this.iconv = codec.iconv;
	}

	Utf16Decoder.prototype.write = function(buf) {
	    if (!this.decoder) {
	        // Codec is not chosen yet. Accumulate initial bytes.
	        this.initialBytes.push(buf);
	        this.initialBytesLen += buf.length;
	        
	        if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below)
	            return '';

	        // We have enough bytes -> detect endianness.
	        var buf = Buffer.concat(this.initialBytes),
	            encoding = detectEncoding(buf, this.options.defaultEncoding);
	        this.decoder = this.iconv.getDecoder(encoding, this.options);
	        this.initialBytes.length = this.initialBytesLen = 0;
	    }

	    return this.decoder.write(buf);
	};

	Utf16Decoder.prototype.end = function() {
	    if (!this.decoder) {
	        var buf = Buffer.concat(this.initialBytes),
	            encoding = detectEncoding(buf, this.options.defaultEncoding);
	        this.decoder = this.iconv.getDecoder(encoding, this.options);

	        var res = this.decoder.write(buf),
	            trail = this.decoder.end();

	        return trail ? (res + trail) : res;
	    }
	    return this.decoder.end();
	};

	function detectEncoding(buf, defaultEncoding) {
	    var enc = defaultEncoding || 'utf-16le';

	    if (buf.length >= 2) {
	        // Check BOM.
	        if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM
	            enc = 'utf-16be';
	        else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM
	            enc = 'utf-16le';
	        else {
	            // No BOM found. Try to deduce encoding from initial content.
	            // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon.
	            // So, we count ASCII as if it was LE or BE, and decide from that.
	            var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions
	                _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even.

	            for (var i = 0; i < _len; i += 2) {
	                if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++;
	                if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++;
	            }

	            if (asciiCharsBE > asciiCharsLE)
	                enc = 'utf-16be';
	            else if (asciiCharsBE < asciiCharsLE)
	                enc = 'utf-16le';
	        }
	    }

	    return enc;
	}
	return utf16;
}

var utf7 = {};

var hasRequiredUtf7;

function requireUtf7 () {
	if (hasRequiredUtf7) return utf7;
	hasRequiredUtf7 = 1;
	var Buffer = requireSafer().Buffer;

	// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152
	// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3

	utf7.utf7 = Utf7Codec;
	utf7.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7
	function Utf7Codec(codecOptions, iconv) {
	    this.iconv = iconv;
	}
	Utf7Codec.prototype.encoder = Utf7Encoder;
	Utf7Codec.prototype.decoder = Utf7Decoder;
	Utf7Codec.prototype.bomAware = true;


	// -- Encoding

	var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g;

	function Utf7Encoder(options, codec) {
	    this.iconv = codec.iconv;
	}

	Utf7Encoder.prototype.write = function(str) {
	    // Naive implementation.
	    // Non-direct chars are encoded as "+<base64>-"; single "+" char is encoded as "+-".
	    return Buffer.from(str.replace(nonDirectChars, function(chunk) {
	        return "+" + (chunk === '+' ? '' : 
	            this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) 
	            + "-";
	    }.bind(this)));
	};

	Utf7Encoder.prototype.end = function() {
	};


	// -- Decoding

	function Utf7Decoder(options, codec) {
	    this.iconv = codec.iconv;
	    this.inBase64 = false;
	    this.base64Accum = '';
	}

	var base64Regex = /[A-Za-z0-9\/+]/;
	var base64Chars = [];
	for (var i = 0; i < 256; i++)
	    base64Chars[i] = base64Regex.test(String.fromCharCode(i));

	var plusChar = '+'.charCodeAt(0), 
	    minusChar = '-'.charCodeAt(0),
	    andChar = '&'.charCodeAt(0);

	Utf7Decoder.prototype.write = function(buf) {
	    var res = "", lastI = 0,
	        inBase64 = this.inBase64,
	        base64Accum = this.base64Accum;

	    // The decoder is more involved as we must handle chunks in stream.

	    for (var i = 0; i < buf.length; i++) {
	        if (!inBase64) { // We're in direct mode.
	            // Write direct chars until '+'
	            if (buf[i] == plusChar) {
	                res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars.
	                lastI = i+1;
	                inBase64 = true;
	            }
	        } else { // We decode base64.
	            if (!base64Chars[buf[i]]) { // Base64 ended.
	                if (i == lastI && buf[i] == minusChar) {// "+-" -> "+"
	                    res += "+";
	                } else {
	                    var b64str = base64Accum + buf.slice(lastI, i).toString();
	                    res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
	                }

	                if (buf[i] != minusChar) // Minus is absorbed after base64.
	                    i--;

	                lastI = i+1;
	                inBase64 = false;
	                base64Accum = '';
	            }
	        }
	    }

	    if (!inBase64) {
	        res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars.
	    } else {
	        var b64str = base64Accum + buf.slice(lastI).toString();

	        var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.
	        base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.
	        b64str = b64str.slice(0, canBeDecoded);

	        res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
	    }

	    this.inBase64 = inBase64;
	    this.base64Accum = base64Accum;

	    return res;
	};

	Utf7Decoder.prototype.end = function() {
	    var res = "";
	    if (this.inBase64 && this.base64Accum.length > 0)
	        res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be");

	    this.inBase64 = false;
	    this.base64Accum = '';
	    return res;
	};


	// UTF-7-IMAP codec.
	// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3)
	// Differences:
	//  * Base64 part is started by "&" instead of "+"
	//  * Direct characters are 0x20-0x7E, except "&" (0x26)
	//  * In Base64, "," is used instead of "/"
	//  * Base64 must not be used to represent direct characters.
	//  * No implicit shift back from Base64 (should always end with '-')
	//  * String must end in non-shifted position.
	//  * "-&" while in base64 is not allowed.


	utf7.utf7imap = Utf7IMAPCodec;
	function Utf7IMAPCodec(codecOptions, iconv) {
	    this.iconv = iconv;
	}
	Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder;
	Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder;
	Utf7IMAPCodec.prototype.bomAware = true;


	// -- Encoding

	function Utf7IMAPEncoder(options, codec) {
	    this.iconv = codec.iconv;
	    this.inBase64 = false;
	    this.base64Accum = Buffer.alloc(6);
	    this.base64AccumIdx = 0;
	}

	Utf7IMAPEncoder.prototype.write = function(str) {
	    var inBase64 = this.inBase64,
	        base64Accum = this.base64Accum,
	        base64AccumIdx = this.base64AccumIdx,
	        buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0;

	    for (var i = 0; i < str.length; i++) {
	        var uChar = str.charCodeAt(i);
	        if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'.
	            if (inBase64) {
	                if (base64AccumIdx > 0) {
	                    bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx);
	                    base64AccumIdx = 0;
	                }

	                buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.
	                inBase64 = false;
	            }

	            if (!inBase64) {
	                buf[bufIdx++] = uChar; // Write direct character

	                if (uChar === andChar)  // Ampersand -> '&-'
	                    buf[bufIdx++] = minusChar;
	            }

	        } else { // Non-direct character
	            if (!inBase64) {
	                buf[bufIdx++] = andChar; // Write '&', then go to base64 mode.
	                inBase64 = true;
	            }
	            if (inBase64) {
	                base64Accum[base64AccumIdx++] = uChar >> 8;
	                base64Accum[base64AccumIdx++] = uChar & 0xFF;

	                if (base64AccumIdx == base64Accum.length) {
	                    bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx);
	                    base64AccumIdx = 0;
	                }
	            }
	        }
	    }

	    this.inBase64 = inBase64;
	    this.base64AccumIdx = base64AccumIdx;

	    return buf.slice(0, bufIdx);
	};

	Utf7IMAPEncoder.prototype.end = function() {
	    var buf = Buffer.alloc(10), bufIdx = 0;
	    if (this.inBase64) {
	        if (this.base64AccumIdx > 0) {
	            bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx);
	            this.base64AccumIdx = 0;
	        }

	        buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.
	        this.inBase64 = false;
	    }

	    return buf.slice(0, bufIdx);
	};


	// -- Decoding

	function Utf7IMAPDecoder(options, codec) {
	    this.iconv = codec.iconv;
	    this.inBase64 = false;
	    this.base64Accum = '';
	}

	var base64IMAPChars = base64Chars.slice();
	base64IMAPChars[','.charCodeAt(0)] = true;

	Utf7IMAPDecoder.prototype.write = function(buf) {
	    var res = "", lastI = 0,
	        inBase64 = this.inBase64,
	        base64Accum = this.base64Accum;

	    // The decoder is more involved as we must handle chunks in stream.
	    // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end).

	    for (var i = 0; i < buf.length; i++) {
	        if (!inBase64) { // We're in direct mode.
	            // Write direct chars until '&'
	            if (buf[i] == andChar) {
	                res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars.
	                lastI = i+1;
	                inBase64 = true;
	            }
	        } else { // We decode base64.
	            if (!base64IMAPChars[buf[i]]) { // Base64 ended.
	                if (i == lastI && buf[i] == minusChar) { // "&-" -> "&"
	                    res += "&";
	                } else {
	                    var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/');
	                    res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
	                }

	                if (buf[i] != minusChar) // Minus may be absorbed after base64.
	                    i--;

	                lastI = i+1;
	                inBase64 = false;
	                base64Accum = '';
	            }
	        }
	    }

	    if (!inBase64) {
	        res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars.
	    } else {
	        var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/');

	        var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.
	        base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.
	        b64str = b64str.slice(0, canBeDecoded);

	        res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
	    }

	    this.inBase64 = inBase64;
	    this.base64Accum = base64Accum;

	    return res;
	};

	Utf7IMAPDecoder.prototype.end = function() {
	    var res = "";
	    if (this.inBase64 && this.base64Accum.length > 0)
	        res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be");

	    this.inBase64 = false;
	    this.base64Accum = '';
	    return res;
	};
	return utf7;
}

var sbcsCodec = {};

var hasRequiredSbcsCodec;

function requireSbcsCodec () {
	if (hasRequiredSbcsCodec) return sbcsCodec;
	hasRequiredSbcsCodec = 1;
	var Buffer = requireSafer().Buffer;

	// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that
	// correspond to encoded bytes (if 128 - then lower half is ASCII). 

	sbcsCodec._sbcs = SBCSCodec;
	function SBCSCodec(codecOptions, iconv) {
	    if (!codecOptions)
	        throw new Error("SBCS codec is called without the data.")
	    
	    // Prepare char buffer for decoding.
	    if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256))
	        throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)");
	    
	    if (codecOptions.chars.length === 128) {
	        var asciiString = "";
	        for (var i = 0; i < 128; i++)
	            asciiString += String.fromCharCode(i);
	        codecOptions.chars = asciiString + codecOptions.chars;
	    }

	    this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2');
	    
	    // Encoding buffer.
	    var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0));

	    for (var i = 0; i < codecOptions.chars.length; i++)
	        encodeBuf[codecOptions.chars.charCodeAt(i)] = i;

	    this.encodeBuf = encodeBuf;
	}

	SBCSCodec.prototype.encoder = SBCSEncoder;
	SBCSCodec.prototype.decoder = SBCSDecoder;


	function SBCSEncoder(options, codec) {
	    this.encodeBuf = codec.encodeBuf;
	}

	SBCSEncoder.prototype.write = function(str) {
	    var buf = Buffer.alloc(str.length);
	    for (var i = 0; i < str.length; i++)
	        buf[i] = this.encodeBuf[str.charCodeAt(i)];
	    
	    return buf;
	};

	SBCSEncoder.prototype.end = function() {
	};


	function SBCSDecoder(options, codec) {
	    this.decodeBuf = codec.decodeBuf;
	}

	SBCSDecoder.prototype.write = function(buf) {
	    // Strings are immutable in JS -> we use ucs2 buffer to speed up computations.
	    var decodeBuf = this.decodeBuf;
	    var newBuf = Buffer.alloc(buf.length*2);
	    var idx1 = 0, idx2 = 0;
	    for (var i = 0; i < buf.length; i++) {
	        idx1 = buf[i]*2; idx2 = i*2;
	        newBuf[idx2] = decodeBuf[idx1];
	        newBuf[idx2+1] = decodeBuf[idx1+1];
	    }
	    return newBuf.toString('ucs2');
	};

	SBCSDecoder.prototype.end = function() {
	};
	return sbcsCodec;
}

var sbcsData;
var hasRequiredSbcsData;

function requireSbcsData () {
	if (hasRequiredSbcsData) return sbcsData;
	hasRequiredSbcsData = 1;

	// Manually added data to be used by sbcs codec in addition to generated one.

	sbcsData = {
	    // Not supported by iconv, not sure why.
	    "10029": "maccenteuro",
	    "maccenteuro": {
	        "type": "_sbcs",
	        "chars": "ÄĀāÉĄÖÜáąČäčĆćéŹźĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņŃ¬√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ"
	    },

	    "808": "cp808",
	    "ibm808": "cp808",
	    "cp808": {
	        "type": "_sbcs",
	        "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ "
	    },

	    "mik": {
	        "type": "_sbcs",
	        "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
	    },

	    "cp720": {
	        "type": "_sbcs",
	        "chars": "\x80\x81éâ\x84à\x86çêëèïî\x8d\x8e\x8f\x90\u0651\u0652ô¤ـûùءآأؤ£إئابةتثجحخدذرزسشص«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ضطظعغفµقكلمنهوىي≡\u064b\u064c\u064d\u064e\u064f\u0650≈°∙·√ⁿ²■\u00a0"
	    },

	    // Aliases of generated encodings.
	    "ascii8bit": "ascii",
	    "usascii": "ascii",
	    "ansix34": "ascii",
	    "ansix341968": "ascii",
	    "ansix341986": "ascii",
	    "csascii": "ascii",
	    "cp367": "ascii",
	    "ibm367": "ascii",
	    "isoir6": "ascii",
	    "iso646us": "ascii",
	    "iso646irv": "ascii",
	    "us": "ascii",

	    "latin1": "iso88591",
	    "latin2": "iso88592",
	    "latin3": "iso88593",
	    "latin4": "iso88594",
	    "latin5": "iso88599",
	    "latin6": "iso885910",
	    "latin7": "iso885913",
	    "latin8": "iso885914",
	    "latin9": "iso885915",
	    "latin10": "iso885916",

	    "csisolatin1": "iso88591",
	    "csisolatin2": "iso88592",
	    "csisolatin3": "iso88593",
	    "csisolatin4": "iso88594",
	    "csisolatincyrillic": "iso88595",
	    "csisolatinarabic": "iso88596",
	    "csisolatingreek" : "iso88597",
	    "csisolatinhebrew": "iso88598",
	    "csisolatin5": "iso88599",
	    "csisolatin6": "iso885910",

	    "l1": "iso88591",
	    "l2": "iso88592",
	    "l3": "iso88593",
	    "l4": "iso88594",
	    "l5": "iso88599",
	    "l6": "iso885910",
	    "l7": "iso885913",
	    "l8": "iso885914",
	    "l9": "iso885915",
	    "l10": "iso885916",

	    "isoir14": "iso646jp",
	    "isoir57": "iso646cn",
	    "isoir100": "iso88591",
	    "isoir101": "iso88592",
	    "isoir109": "iso88593",
	    "isoir110": "iso88594",
	    "isoir144": "iso88595",
	    "isoir127": "iso88596",
	    "isoir126": "iso88597",
	    "isoir138": "iso88598",
	    "isoir148": "iso88599",
	    "isoir157": "iso885910",
	    "isoir166": "tis620",
	    "isoir179": "iso885913",
	    "isoir199": "iso885914",
	    "isoir203": "iso885915",
	    "isoir226": "iso885916",

	    "cp819": "iso88591",
	    "ibm819": "iso88591",

	    "cyrillic": "iso88595",

	    "arabic": "iso88596",
	    "arabic8": "iso88596",
	    "ecma114": "iso88596",
	    "asmo708": "iso88596",

	    "greek" : "iso88597",
	    "greek8" : "iso88597",
	    "ecma118" : "iso88597",
	    "elot928" : "iso88597",

	    "hebrew": "iso88598",
	    "hebrew8": "iso88598",

	    "turkish": "iso88599",
	    "turkish8": "iso88599",

	    "thai": "iso885911",
	    "thai8": "iso885911",

	    "celtic": "iso885914",
	    "celtic8": "iso885914",
	    "isoceltic": "iso885914",

	    "tis6200": "tis620",
	    "tis62025291": "tis620",
	    "tis62025330": "tis620",

	    "10000": "macroman",
	    "10006": "macgreek",
	    "10007": "maccyrillic",
	    "10079": "maciceland",
	    "10081": "macturkish",

	    "cspc8codepage437": "cp437",
	    "cspc775baltic": "cp775",
	    "cspc850multilingual": "cp850",
	    "cspcp852": "cp852",
	    "cspc862latinhebrew": "cp862",
	    "cpgr": "cp869",

	    "msee": "cp1250",
	    "mscyrl": "cp1251",
	    "msansi": "cp1252",
	    "msgreek": "cp1253",
	    "msturk": "cp1254",
	    "mshebr": "cp1255",
	    "msarab": "cp1256",
	    "winbaltrim": "cp1257",

	    "cp20866": "koi8r",
	    "20866": "koi8r",
	    "ibm878": "koi8r",
	    "cskoi8r": "koi8r",

	    "cp21866": "koi8u",
	    "21866": "koi8u",
	    "ibm1168": "koi8u",

	    "strk10482002": "rk1048",

	    "tcvn5712": "tcvn",
	    "tcvn57121": "tcvn",

	    "gb198880": "iso646cn",
	    "cn": "iso646cn",

	    "csiso14jisc6220ro": "iso646jp",
	    "jisc62201969ro": "iso646jp",
	    "jp": "iso646jp",

	    "cshproman8": "hproman8",
	    "r8": "hproman8",
	    "roman8": "hproman8",
	    "xroman8": "hproman8",
	    "ibm1051": "hproman8",

	    "mac": "macintosh",
	    "csmacintosh": "macintosh",
	};
	return sbcsData;
}

var sbcsDataGenerated;
var hasRequiredSbcsDataGenerated;

function requireSbcsDataGenerated () {
	if (hasRequiredSbcsDataGenerated) return sbcsDataGenerated;
	hasRequiredSbcsDataGenerated = 1;

	// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script.
	sbcsDataGenerated = {
	  "437": "cp437",
	  "737": "cp737",
	  "775": "cp775",
	  "850": "cp850",
	  "852": "cp852",
	  "855": "cp855",
	  "856": "cp856",
	  "857": "cp857",
	  "858": "cp858",
	  "860": "cp860",
	  "861": "cp861",
	  "862": "cp862",
	  "863": "cp863",
	  "864": "cp864",
	  "865": "cp865",
	  "866": "cp866",
	  "869": "cp869",
	  "874": "windows874",
	  "922": "cp922",
	  "1046": "cp1046",
	  "1124": "cp1124",
	  "1125": "cp1125",
	  "1129": "cp1129",
	  "1133": "cp1133",
	  "1161": "cp1161",
	  "1162": "cp1162",
	  "1163": "cp1163",
	  "1250": "windows1250",
	  "1251": "windows1251",
	  "1252": "windows1252",
	  "1253": "windows1253",
	  "1254": "windows1254",
	  "1255": "windows1255",
	  "1256": "windows1256",
	  "1257": "windows1257",
	  "1258": "windows1258",
	  "28591": "iso88591",
	  "28592": "iso88592",
	  "28593": "iso88593",
	  "28594": "iso88594",
	  "28595": "iso88595",
	  "28596": "iso88596",
	  "28597": "iso88597",
	  "28598": "iso88598",
	  "28599": "iso88599",
	  "28600": "iso885910",
	  "28601": "iso885911",
	  "28603": "iso885913",
	  "28604": "iso885914",
	  "28605": "iso885915",
	  "28606": "iso885916",
	  "windows874": {
	    "type": "_sbcs",
	    "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
	  },
	  "win874": "windows874",
	  "cp874": "windows874",
	  "windows1250": {
	    "type": "_sbcs",
	    "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"
	  },
	  "win1250": "windows1250",
	  "cp1250": "windows1250",
	  "windows1251": {
	    "type": "_sbcs",
	    "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
	  },
	  "win1251": "windows1251",
	  "cp1251": "windows1251",
	  "windows1252": {
	    "type": "_sbcs",
	    "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
	  },
	  "win1252": "windows1252",
	  "cp1252": "windows1252",
	  "windows1253": {
	    "type": "_sbcs",
	    "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"
	  },
	  "win1253": "windows1253",
	  "cp1253": "windows1253",
	  "windows1254": {
	    "type": "_sbcs",
	    "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"
	  },
	  "win1254": "windows1254",
	  "cp1254": "windows1254",
	  "windows1255": {
	    "type": "_sbcs",
	    "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�"
	  },
	  "win1255": "windows1255",
	  "cp1255": "windows1255",
	  "windows1256": {
	    "type": "_sbcs",
	    "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے"
	  },
	  "win1256": "windows1256",
	  "cp1256": "windows1256",
	  "windows1257": {
	    "type": "_sbcs",
	    "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙"
	  },
	  "win1257": "windows1257",
	  "cp1257": "windows1257",
	  "windows1258": {
	    "type": "_sbcs",
	    "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
	  },
	  "win1258": "windows1258",
	  "cp1258": "windows1258",
	  "iso88591": {
	    "type": "_sbcs",
	    "chars": " ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
	  },
	  "cp28591": "iso88591",
	  "iso88592": {
	    "type": "_sbcs",
	    "chars": " Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"
	  },
	  "cp28592": "iso88592",
	  "iso88593": {
	    "type": "_sbcs",
	    "chars": " Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙"
	  },
	  "cp28593": "iso88593",
	  "iso88594": {
	    "type": "_sbcs",
	    "chars": " ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙"
	  },
	  "cp28594": "iso88594",
	  "iso88595": {
	    "type": "_sbcs",
	    "chars": " ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ"
	  },
	  "cp28595": "iso88595",
	  "iso88596": {
	    "type": "_sbcs",
	    "chars": " ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������"
	  },
	  "cp28596": "iso88596",
	  "iso88597": {
	    "type": "_sbcs",
	    "chars": " ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"
	  },
	  "cp28597": "iso88597",
	  "iso88598": {
	    "type": "_sbcs",
	    "chars": " �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�"
	  },
	  "cp28598": "iso88598",
	  "iso88599": {
	    "type": "_sbcs",
	    "chars": " ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"
	  },
	  "cp28599": "iso88599",
	  "iso885910": {
	    "type": "_sbcs",
	    "chars": " ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ"
	  },
	  "cp28600": "iso885910",
	  "iso885911": {
	    "type": "_sbcs",
	    "chars": " กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
	  },
	  "cp28601": "iso885911",
	  "iso885913": {
	    "type": "_sbcs",
	    "chars": " ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’"
	  },
	  "cp28603": "iso885913",
	  "iso885914": {
	    "type": "_sbcs",
	    "chars": " Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ"
	  },
	  "cp28604": "iso885914",
	  "iso885915": {
	    "type": "_sbcs",
	    "chars": " ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
	  },
	  "cp28605": "iso885915",
	  "iso885916": {
	    "type": "_sbcs",
	    "chars": " ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ"
	  },
	  "cp28606": "iso885916",
	  "cp437": {
	    "type": "_sbcs",
	    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñÑªº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
	  },
	  "ibm437": "cp437",
	  "csibm437": "cp437",
	  "cp737": {
	    "type": "_sbcs",
	    "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ "
	  },
	  "ibm737": "cp737",
	  "csibm737": "cp737",
	  "cp775": {
	    "type": "_sbcs",
	    "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ "
	  },
	  "ibm775": "cp775",
	  "csibm775": "cp775",
	  "cp850": {
	    "type": "_sbcs",
	    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñÑªº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýÝ¯´­±‗¾¶§÷¸°¨·¹³²■ "
	  },
	  "ibm850": "cp850",
	  "csibm850": "cp850",
	  "cp852": {
	    "type": "_sbcs",
	    "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘę¬źČş«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ "
	  },
	  "ibm852": "cp852",
	  "csibm852": "cp852",
	  "cp855": {
	    "type": "_sbcs",
	    "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ "
	  },
	  "ibm855": "cp855",
	  "csibm855": "cp855",
	  "cp856": {
	    "type": "_sbcs",
	    "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ "
	  },
	  "ibm856": "cp856",
	  "csibm856": "cp856",
	  "cp857": {
	    "type": "_sbcs",
	    "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞğ¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ "
	  },
	  "ibm857": "cp857",
	  "csibm857": "cp857",
	  "cp858": {
	    "type": "_sbcs",
	    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñÑªº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýÝ¯´­±‗¾¶§÷¸°¨·¹³²■ "
	  },
	  "ibm858": "cp858",
	  "csibm858": "cp858",
	  "cp860": {
	    "type": "_sbcs",
	    "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñÑªº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
	  },
	  "ibm860": "cp860",
	  "csibm860": "cp860",
	  "cp861": {
	    "type": "_sbcs",
	    "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
	  },
	  "ibm861": "cp861",
	  "csibm861": "cp861",
	  "cp862": {
	    "type": "_sbcs",
	    "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñÑªº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
	  },
	  "ibm862": "cp862",
	  "csibm862": "cp862",
	  "cp863": {
	    "type": "_sbcs",
	    "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
	  },
	  "ibm863": "cp863",
	  "csibm863": "cp863",
	  "cp864": {
	    "type": "_sbcs",
	    "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�"
	  },
	  "ibm864": "cp864",
	  "csibm864": "cp864",
	  "cp865": {
	    "type": "_sbcs",
	    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñÑªº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
	  },
	  "ibm865": "cp865",
	  "csibm865": "cp865",
	  "cp866": {
	    "type": "_sbcs",
	    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ "
	  },
	  "ibm866": "cp866",
	  "csibm866": "cp866",
	  "cp869": {
	    "type": "_sbcs",
	    "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ "
	  },
	  "ibm869": "cp869",
	  "csibm869": "cp869",
	  "cp922": {
	    "type": "_sbcs",
	    "chars": " ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ"
	  },
	  "ibm922": "cp922",
	  "csibm922": "cp922",
	  "cp1046": {
	    "type": "_sbcs",
	    "chars": "ﺈ×÷ﹱ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�"
	  },
	  "ibm1046": "cp1046",
	  "csibm1046": "cp1046",
	  "cp1124": {
	    "type": "_sbcs",
	    "chars": " ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ"
	  },
	  "ibm1124": "cp1124",
	  "csibm1124": "cp1124",
	  "cp1125": {
	    "type": "_sbcs",
	    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ "
	  },
	  "ibm1125": "cp1125",
	  "csibm1125": "cp1125",
	  "cp1129": {
	    "type": "_sbcs",
	    "chars": " ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
	  },
	  "ibm1129": "cp1129",
	  "csibm1129": "cp1129",
	  "cp1133": {
	    "type": "_sbcs",
	    "chars": " ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�"
	  },
	  "ibm1133": "cp1133",
	  "csibm1133": "cp1133",
	  "cp1161": {
	    "type": "_sbcs",
	    "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ "
	  },
	  "ibm1161": "cp1161",
	  "csibm1161": "cp1161",
	  "cp1162": {
	    "type": "_sbcs",
	    "chars": "€…‘’“”•–— กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
	  },
	  "ibm1162": "cp1162",
	  "csibm1162": "cp1162",
	  "cp1163": {
	    "type": "_sbcs",
	    "chars": " ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
	  },
	  "ibm1163": "cp1163",
	  "csibm1163": "cp1163",
	  "maccroatian": {
	    "type": "_sbcs",
	    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ"
	  },
	  "maccyrillic": {
	    "type": "_sbcs",
	    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"
	  },
	  "macgreek": {
	    "type": "_sbcs",
	    "chars": "Ä¹²É³ÖÜ΅àâä΄¨çéèêë£™îï•½‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�"
	  },
	  "maciceland": {
	    "type": "_sbcs",
	    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
	  },
	  "macroman": {
	    "type": "_sbcs",
	    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›ﬁﬂ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
	  },
	  "macromania": {
	    "type": "_sbcs",
	    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
	  },
	  "macthai": {
	    "type": "_sbcs",
	    "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู﻿​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����"
	  },
	  "macturkish": {
	    "type": "_sbcs",
	    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ"
	  },
	  "macukraine": {
	    "type": "_sbcs",
	    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"
	  },
	  "koi8r": {
	    "type": "_sbcs",
	    "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
	  },
	  "koi8u": {
	    "type": "_sbcs",
	    "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
	  },
	  "koi8ru": {
	    "type": "_sbcs",
	    "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
	  },
	  "koi8t": {
	    "type": "_sbcs",
	    "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
	  },
	  "armscii8": {
	    "type": "_sbcs",
	    "chars": " �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�"
	  },
	  "rk1048": {
	    "type": "_sbcs",
	    "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
	  },
	  "tcvn": {
	    "type": "_sbcs",
	    "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ"
	  },
	  "georgianacademy": {
	    "type": "_sbcs",
	    "chars": "‚ƒ„…†‡ˆ‰Š‹Œ‘’“”•–—˜™š›œŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
	  },
	  "georgianps": {
	    "type": "_sbcs",
	    "chars": "‚ƒ„…†‡ˆ‰Š‹Œ‘’“”•–—˜™š›œŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
	  },
	  "pt154": {
	    "type": "_sbcs",
	    "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
	  },
	  "viscii": {
	    "type": "_sbcs",
	    "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ"
	  },
	  "iso646cn": {
	    "type": "_sbcs",
	    "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������"
	  },
	  "iso646jp": {
	    "type": "_sbcs",
	    "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������"
	  },
	  "hproman8": {
	    "type": "_sbcs",
	    "chars": " ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�"
	  },
	  "macintosh": {
	    "type": "_sbcs",
	    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›ﬁﬂ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
	  },
	  "ascii": {
	    "type": "_sbcs",
	    "chars": "��������������������������������������������������������������������������������������������������������������������������������"
	  },
	  "tis620": {
	    "type": "_sbcs",
	    "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
	  }
	};
	return sbcsDataGenerated;
}

var dbcsCodec = {};

var hasRequiredDbcsCodec;

function requireDbcsCodec () {
	if (hasRequiredDbcsCodec) return dbcsCodec;
	hasRequiredDbcsCodec = 1;
	var Buffer = requireSafer().Buffer;

	// Multibyte codec. In this scheme, a character is represented by 1 or more bytes.
	// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences.
	// To save memory and loading time, we read table files only when requested.

	dbcsCodec._dbcs = DBCSCodec;

	var UNASSIGNED = -1,
	    GB18030_CODE = -2,
	    SEQ_START  = -10,
	    NODE_START = -1e3,
	    UNASSIGNED_NODE = new Array(0x100),
	    DEF_CHAR = -1;

	for (var i = 0; i < 0x100; i++)
	    UNASSIGNED_NODE[i] = UNASSIGNED;


	// Class DBCSCodec reads and initializes mapping tables.
	function DBCSCodec(codecOptions, iconv) {
	    this.encodingName = codecOptions.encodingName;
	    if (!codecOptions)
	        throw new Error("DBCS codec is called without the data.")
	    if (!codecOptions.table)
	        throw new Error("Encoding '" + this.encodingName + "' has no data.");

	    // Load tables.
	    var mappingTable = codecOptions.table();


	    // Decode tables: MBCS -> Unicode.

	    // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256.
	    // Trie root is decodeTables[0].
	    // Values: >=  0 -> unicode character code. can be > 0xFFFF
	    //         == UNASSIGNED -> unknown/unassigned sequence.
	    //         == GB18030_CODE -> this is the end of a GB18030 4-byte sequence.
	    //         <= NODE_START -> index of the next node in our trie to process next byte.
	    //         <= SEQ_START  -> index of the start of a character code sequence, in decodeTableSeq.
	    this.decodeTables = [];
	    this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node.

	    // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. 
	    this.decodeTableSeq = [];

	    // Actual mapping tables consist of chunks. Use them to fill up decode tables.
	    for (var i = 0; i < mappingTable.length; i++)
	        this._addDecodeChunk(mappingTable[i]);

	    this.defaultCharUnicode = iconv.defaultCharUnicode;

	    
	    // Encode tables: Unicode -> DBCS.

	    // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance.
	    // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null.
	    // Values: >=  0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.).
	    //         == UNASSIGNED -> no conversion found. Output a default char.
	    //         <= SEQ_START  -> it's an index in encodeTableSeq, see below. The character starts a sequence.
	    this.encodeTable = [];
	    
	    // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of
	    // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key
	    // means end of sequence (needed when one sequence is a strict subsequence of another).
	    // Objects are kept separately from encodeTable to increase performance.
	    this.encodeTableSeq = [];

	    // Some chars can be decoded, but need not be encoded.
	    var skipEncodeChars = {};
	    if (codecOptions.encodeSkipVals)
	        for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) {
	            var val = codecOptions.encodeSkipVals[i];
	            if (typeof val === 'number')
	                skipEncodeChars[val] = true;
	            else
	                for (var j = val.from; j <= val.to; j++)
	                    skipEncodeChars[j] = true;
	        }
	        
	    // Use decode trie to recursively fill out encode tables.
	    this._fillEncodeTable(0, 0, skipEncodeChars);

	    // Add more encoding pairs when needed.
	    if (codecOptions.encodeAdd) {
	        for (var uChar in codecOptions.encodeAdd)
	            if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar))
	                this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]);
	    }

	    this.defCharSB  = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)];
	    if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?'];
	    if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0);


	    // Load & create GB18030 tables when needed.
	    if (typeof codecOptions.gb18030 === 'function') {
	        this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges.

	        // Add GB18030 decode tables.
	        var thirdByteNodeIdx = this.decodeTables.length;
	        var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0);

	        var fourthByteNodeIdx = this.decodeTables.length;
	        var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0);

	        for (var i = 0x81; i <= 0xFE; i++) {
	            var secondByteNodeIdx = NODE_START - this.decodeTables[0][i];
	            var secondByteNode = this.decodeTables[secondByteNodeIdx];
	            for (var j = 0x30; j <= 0x39; j++)
	                secondByteNode[j] = NODE_START - thirdByteNodeIdx;
	        }
	        for (var i = 0x81; i <= 0xFE; i++)
	            thirdByteNode[i] = NODE_START - fourthByteNodeIdx;
	        for (var i = 0x30; i <= 0x39; i++)
	            fourthByteNode[i] = GB18030_CODE;
	    }        
	}

	DBCSCodec.prototype.encoder = DBCSEncoder;
	DBCSCodec.prototype.decoder = DBCSDecoder;

	// Decoder helpers
	DBCSCodec.prototype._getDecodeTrieNode = function(addr) {
	    var bytes = [];
	    for (; addr > 0; addr >>= 8)
	        bytes.push(addr & 0xFF);
	    if (bytes.length == 0)
	        bytes.push(0);

	    var node = this.decodeTables[0];
	    for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie.
	        var val = node[bytes[i]];

	        if (val == UNASSIGNED) { // Create new node.
	            node[bytes[i]] = NODE_START - this.decodeTables.length;
	            this.decodeTables.push(node = UNASSIGNED_NODE.slice(0));
	        }
	        else if (val <= NODE_START) { // Existing node.
	            node = this.decodeTables[NODE_START - val];
	        }
	        else
	            throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16));
	    }
	    return node;
	};


	DBCSCodec.prototype._addDecodeChunk = function(chunk) {
	    // First element of chunk is the hex mbcs code where we start.
	    var curAddr = parseInt(chunk[0], 16);

	    // Choose the decoding node where we'll write our chars.
	    var writeTable = this._getDecodeTrieNode(curAddr);
	    curAddr = curAddr & 0xFF;

	    // Write all other elements of the chunk to the table.
	    for (var k = 1; k < chunk.length; k++) {
	        var part = chunk[k];
	        if (typeof part === "string") { // String, write as-is.
	            for (var l = 0; l < part.length;) {
	                var code = part.charCodeAt(l++);
	                if (0xD800 <= code && code < 0xDC00) { // Decode surrogate
	                    var codeTrail = part.charCodeAt(l++);
	                    if (0xDC00 <= codeTrail && codeTrail < 0xE000)
	                        writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00);
	                    else
	                        throw new Error("Incorrect surrogate pair in "  + this.encodingName + " at chunk " + chunk[0]);
	                }
	                else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used)
	                    var len = 0xFFF - code + 2;
	                    var seq = [];
	                    for (var m = 0; m < len; m++)
	                        seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq.

	                    writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length;
	                    this.decodeTableSeq.push(seq);
	                }
	                else
	                    writeTable[curAddr++] = code; // Basic char
	            }
	        } 
	        else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character.
	            var charCode = writeTable[curAddr - 1] + 1;
	            for (var l = 0; l < part; l++)
	                writeTable[curAddr++] = charCode++;
	        }
	        else
	            throw new Error("Incorrect type '" + typeof part + "' given in "  + this.encodingName + " at chunk " + chunk[0]);
	    }
	    if (curAddr > 0xFF)
	        throw new Error("Incorrect chunk in "  + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr);
	};

	// Encoder helpers
	DBCSCodec.prototype._getEncodeBucket = function(uCode) {
	    var high = uCode >> 8; // This could be > 0xFF because of astral characters.
	    if (this.encodeTable[high] === undefined)
	        this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand.
	    return this.encodeTable[high];
	};

	DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) {
	    var bucket = this._getEncodeBucket(uCode);
	    var low = uCode & 0xFF;
	    if (bucket[low] <= SEQ_START)
	        this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it.
	    else if (bucket[low] == UNASSIGNED)
	        bucket[low] = dbcsCode;
	};

	DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) {
	    
	    // Get the root of character tree according to first character of the sequence.
	    var uCode = seq[0];
	    var bucket = this._getEncodeBucket(uCode);
	    var low = uCode & 0xFF;

	    var node;
	    if (bucket[low] <= SEQ_START) {
	        // There's already a sequence with  - use it.
	        node = this.encodeTableSeq[SEQ_START-bucket[low]];
	    }
	    else {
	        // There was no sequence object - allocate a new one.
	        node = {};
	        if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence.
	        bucket[low] = SEQ_START - this.encodeTableSeq.length;
	        this.encodeTableSeq.push(node);
	    }

	    // Traverse the character tree, allocating new nodes as needed.
	    for (var j = 1; j < seq.length-1; j++) {
	        var oldVal = node[uCode];
	        if (typeof oldVal === 'object')
	            node = oldVal;
	        else {
	            node = node[uCode] = {};
	            if (oldVal !== undefined)
	                node[DEF_CHAR] = oldVal;
	        }
	    }

	    // Set the leaf to given dbcsCode.
	    uCode = seq[seq.length-1];
	    node[uCode] = dbcsCode;
	};

	DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) {
	    var node = this.decodeTables[nodeIdx];
	    for (var i = 0; i < 0x100; i++) {
	        var uCode = node[i];
	        var mbCode = prefix + i;
	        if (skipEncodeChars[mbCode])
	            continue;

	        if (uCode >= 0)
	            this._setEncodeChar(uCode, mbCode);
	        else if (uCode <= NODE_START)
	            this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars);
	        else if (uCode <= SEQ_START)
	            this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode);
	    }
	};



	// == Encoder ==================================================================

	function DBCSEncoder(options, codec) {
	    // Encoder state
	    this.leadSurrogate = -1;
	    this.seqObj = undefined;
	    
	    // Static data
	    this.encodeTable = codec.encodeTable;
	    this.encodeTableSeq = codec.encodeTableSeq;
	    this.defaultCharSingleByte = codec.defCharSB;
	    this.gb18030 = codec.gb18030;
	}

	DBCSEncoder.prototype.write = function(str) {
	    var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)),
	        leadSurrogate = this.leadSurrogate,
	        seqObj = this.seqObj, nextChar = -1,
	        i = 0, j = 0;

	    while (true) {
	        // 0. Get next character.
	        if (nextChar === -1) {
	            if (i == str.length) break;
	            var uCode = str.charCodeAt(i++);
	        }
	        else {
	            var uCode = nextChar;
	            nextChar = -1;    
	        }

	        // 1. Handle surrogates.
	        if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates.
	            if (uCode < 0xDC00) { // We've got lead surrogate.
	                if (leadSurrogate === -1) {
	                    leadSurrogate = uCode;
	                    continue;
	                } else {
	                    leadSurrogate = uCode;
	                    // Double lead surrogate found.
	                    uCode = UNASSIGNED;
	                }
	            } else { // We've got trail surrogate.
	                if (leadSurrogate !== -1) {
	                    uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00);
	                    leadSurrogate = -1;
	                } else {
	                    // Incomplete surrogate pair - only trail surrogate found.
	                    uCode = UNASSIGNED;
	                }
	                
	            }
	        }
	        else if (leadSurrogate !== -1) {
	            // Incomplete surrogate pair - only lead surrogate found.
	            nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char.
	            leadSurrogate = -1;
	        }

	        // 2. Convert uCode character.
	        var dbcsCode = UNASSIGNED;
	        if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence
	            var resCode = seqObj[uCode];
	            if (typeof resCode === 'object') { // Sequence continues.
	                seqObj = resCode;
	                continue;

	            } else if (typeof resCode == 'number') { // Sequence finished. Write it.
	                dbcsCode = resCode;

	            } else if (resCode == undefined) { // Current character is not part of the sequence.

	                // Try default character for this sequence
	                resCode = seqObj[DEF_CHAR];
	                if (resCode !== undefined) {
	                    dbcsCode = resCode; // Found. Write it.
	                    nextChar = uCode; // Current character will be written too in the next iteration.

	                }
	            }
	            seqObj = undefined;
	        }
	        else if (uCode >= 0) {  // Regular character
	            var subtable = this.encodeTable[uCode >> 8];
	            if (subtable !== undefined)
	                dbcsCode = subtable[uCode & 0xFF];
	            
	            if (dbcsCode <= SEQ_START) { // Sequence start
	                seqObj = this.encodeTableSeq[SEQ_START-dbcsCode];
	                continue;
	            }

	            if (dbcsCode == UNASSIGNED && this.gb18030) {
	                // Use GB18030 algorithm to find character(s) to write.
	                var idx = findIdx(this.gb18030.uChars, uCode);
	                if (idx != -1) {
	                    var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]);
	                    newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600;
	                    newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260;
	                    newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10;
	                    newBuf[j++] = 0x30 + dbcsCode;
	                    continue;
	                }
	            }
	        }

	        // 3. Write dbcsCode character.
	        if (dbcsCode === UNASSIGNED)
	            dbcsCode = this.defaultCharSingleByte;
	        
	        if (dbcsCode < 0x100) {
	            newBuf[j++] = dbcsCode;
	        }
	        else if (dbcsCode < 0x10000) {
	            newBuf[j++] = dbcsCode >> 8;   // high byte
	            newBuf[j++] = dbcsCode & 0xFF; // low byte
	        }
	        else {
	            newBuf[j++] = dbcsCode >> 16;
	            newBuf[j++] = (dbcsCode >> 8) & 0xFF;
	            newBuf[j++] = dbcsCode & 0xFF;
	        }
	    }

	    this.seqObj = seqObj;
	    this.leadSurrogate = leadSurrogate;
	    return newBuf.slice(0, j);
	};

	DBCSEncoder.prototype.end = function() {
	    if (this.leadSurrogate === -1 && this.seqObj === undefined)
	        return; // All clean. Most often case.

	    var newBuf = Buffer.alloc(10), j = 0;

	    if (this.seqObj) { // We're in the sequence.
	        var dbcsCode = this.seqObj[DEF_CHAR];
	        if (dbcsCode !== undefined) { // Write beginning of the sequence.
	            if (dbcsCode < 0x100) {
	                newBuf[j++] = dbcsCode;
	            }
	            else {
	                newBuf[j++] = dbcsCode >> 8;   // high byte
	                newBuf[j++] = dbcsCode & 0xFF; // low byte
	            }
	        }
	        this.seqObj = undefined;
	    }

	    if (this.leadSurrogate !== -1) {
	        // Incomplete surrogate pair - only lead surrogate found.
	        newBuf[j++] = this.defaultCharSingleByte;
	        this.leadSurrogate = -1;
	    }
	    
	    return newBuf.slice(0, j);
	};

	// Export for testing
	DBCSEncoder.prototype.findIdx = findIdx;


	// == Decoder ==================================================================

	function DBCSDecoder(options, codec) {
	    // Decoder state
	    this.nodeIdx = 0;
	    this.prevBuf = Buffer.alloc(0);

	    // Static data
	    this.decodeTables = codec.decodeTables;
	    this.decodeTableSeq = codec.decodeTableSeq;
	    this.defaultCharUnicode = codec.defaultCharUnicode;
	    this.gb18030 = codec.gb18030;
	}

	DBCSDecoder.prototype.write = function(buf) {
	    var newBuf = Buffer.alloc(buf.length*2),
	        nodeIdx = this.nodeIdx, 
	        prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length,
	        seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence.
	        uCode;

	    if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later.
	        prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]);
	    
	    for (var i = 0, j = 0; i < buf.length; i++) {
	        var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset];

	        // Lookup in current trie node.
	        var uCode = this.decodeTables[nodeIdx][curByte];

	        if (uCode >= 0) ;
	        else if (uCode === UNASSIGNED) { // Unknown char.
	            // TODO: Callback with seq.
	            //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset);
	            i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle).
	            uCode = this.defaultCharUnicode.charCodeAt(0);
	        }
	        else if (uCode === GB18030_CODE) {
	            var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset);
	            var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30);
	            var idx = findIdx(this.gb18030.gbChars, ptr);
	            uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx];
	        }
	        else if (uCode <= NODE_START) { // Go to next trie node.
	            nodeIdx = NODE_START - uCode;
	            continue;
	        }
	        else if (uCode <= SEQ_START) { // Output a sequence of chars.
	            var seq = this.decodeTableSeq[SEQ_START - uCode];
	            for (var k = 0; k < seq.length - 1; k++) {
	                uCode = seq[k];
	                newBuf[j++] = uCode & 0xFF;
	                newBuf[j++] = uCode >> 8;
	            }
	            uCode = seq[seq.length-1];
	        }
	        else
	            throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte);

	        // Write the character to buffer, handling higher planes using surrogate pair.
	        if (uCode > 0xFFFF) { 
	            uCode -= 0x10000;
	            var uCodeLead = 0xD800 + Math.floor(uCode / 0x400);
	            newBuf[j++] = uCodeLead & 0xFF;
	            newBuf[j++] = uCodeLead >> 8;

	            uCode = 0xDC00 + uCode % 0x400;
	        }
	        newBuf[j++] = uCode & 0xFF;
	        newBuf[j++] = uCode >> 8;

	        // Reset trie node.
	        nodeIdx = 0; seqStart = i+1;
	    }

	    this.nodeIdx = nodeIdx;
	    this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset);
	    return newBuf.slice(0, j).toString('ucs2');
	};

	DBCSDecoder.prototype.end = function() {
	    var ret = '';

	    // Try to parse all remaining chars.
	    while (this.prevBuf.length > 0) {
	        // Skip 1 character in the buffer.
	        ret += this.defaultCharUnicode;
	        var buf = this.prevBuf.slice(1);

	        // Parse remaining as usual.
	        this.prevBuf = Buffer.alloc(0);
	        this.nodeIdx = 0;
	        if (buf.length > 0)
	            ret += this.write(buf);
	    }

	    this.nodeIdx = 0;
	    return ret;
	};

	// Binary search for GB18030. Returns largest i such that table[i] <= val.
	function findIdx(table, val) {
	    if (table[0] > val)
	        return -1;

	    var l = 0, r = table.length;
	    while (l < r-1) { // always table[l] <= val < table[r]
	        var mid = l + Math.floor((r-l+1)/2);
	        if (table[mid] <= val)
	            l = mid;
	        else
	            r = mid;
	    }
	    return l;
	}
	return dbcsCodec;
}

const require$$0$3 = [
	[
		"0",
		"\u0000",
		128
	],
	[
		"a1",
		"｡",
		62
	],
	[
		"8140",
		"　、。，．・：；？！゛゜´｀¨＾￣＿ヽヾゝゞ〃仝々〆〇ー―‐／＼～∥｜…‥‘’“”（）〔〕［］｛｝〈",
		9,
		"＋－±×"
	],
	[
		"8180",
		"÷＝≠＜＞≦≧∞∴♂♀°′″℃￥＄￠￡％＃＆＊＠§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"
	],
	[
		"81b8",
		"∈∋⊆⊇⊂⊃∪∩"
	],
	[
		"81c8",
		"∧∨￢⇒⇔∀∃"
	],
	[
		"81da",
		"∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"
	],
	[
		"81f0",
		"Å‰♯♭♪†‡¶"
	],
	[
		"81fc",
		"◯"
	],
	[
		"824f",
		"０",
		9
	],
	[
		"8260",
		"Ａ",
		25
	],
	[
		"8281",
		"ａ",
		25
	],
	[
		"829f",
		"ぁ",
		82
	],
	[
		"8340",
		"ァ",
		62
	],
	[
		"8380",
		"ム",
		22
	],
	[
		"839f",
		"Α",
		16,
		"Σ",
		6
	],
	[
		"83bf",
		"α",
		16,
		"σ",
		6
	],
	[
		"8440",
		"А",
		5,
		"ЁЖ",
		25
	],
	[
		"8470",
		"а",
		5,
		"ёж",
		7
	],
	[
		"8480",
		"о",
		17
	],
	[
		"849f",
		"─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"
	],
	[
		"8740",
		"①",
		19,
		"Ⅰ",
		9
	],
	[
		"875f",
		"㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"
	],
	[
		"877e",
		"㍻"
	],
	[
		"8780",
		"〝〟№㏍℡㊤",
		4,
		"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"
	],
	[
		"889f",
		"亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"
	],
	[
		"8940",
		"院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"
	],
	[
		"8980",
		"園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"
	],
	[
		"8a40",
		"魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"
	],
	[
		"8a80",
		"橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"
	],
	[
		"8b40",
		"機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"
	],
	[
		"8b80",
		"朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"
	],
	[
		"8c40",
		"掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"
	],
	[
		"8c80",
		"劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"
	],
	[
		"8d40",
		"后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"
	],
	[
		"8d80",
		"項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"
	],
	[
		"8e40",
		"察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"
	],
	[
		"8e80",
		"死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"
	],
	[
		"8f40",
		"宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"
	],
	[
		"8f80",
		"準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"
	],
	[
		"9040",
		"拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"
	],
	[
		"9080",
		"逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"
	],
	[
		"9140",
		"繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"
	],
	[
		"9180",
		"操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"
	],
	[
		"9240",
		"叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"
	],
	[
		"9280",
		"逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"
	],
	[
		"9340",
		"邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"
	],
	[
		"9380",
		"凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"
	],
	[
		"9440",
		"如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"
	],
	[
		"9480",
		"楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"
	],
	[
		"9540",
		"鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"
	],
	[
		"9580",
		"斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"
	],
	[
		"9640",
		"法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"
	],
	[
		"9680",
		"摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"
	],
	[
		"9740",
		"諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"
	],
	[
		"9780",
		"沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"
	],
	[
		"9840",
		"蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"
	],
	[
		"989f",
		"弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"
	],
	[
		"9940",
		"僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"
	],
	[
		"9980",
		"凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"
	],
	[
		"9a40",
		"咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"
	],
	[
		"9a80",
		"噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"
	],
	[
		"9b40",
		"奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"
	],
	[
		"9b80",
		"它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"
	],
	[
		"9c40",
		"廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"
	],
	[
		"9c80",
		"怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"
	],
	[
		"9d40",
		"戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"
	],
	[
		"9d80",
		"捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"
	],
	[
		"9e40",
		"曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"
	],
	[
		"9e80",
		"梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"
	],
	[
		"9f40",
		"檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"
	],
	[
		"9f80",
		"麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"
	],
	[
		"e040",
		"漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"
	],
	[
		"e080",
		"烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"
	],
	[
		"e140",
		"瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"
	],
	[
		"e180",
		"痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"
	],
	[
		"e240",
		"磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"
	],
	[
		"e280",
		"窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"
	],
	[
		"e340",
		"紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"
	],
	[
		"e380",
		"縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"
	],
	[
		"e440",
		"隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"
	],
	[
		"e480",
		"艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"
	],
	[
		"e540",
		"蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"
	],
	[
		"e580",
		"蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"
	],
	[
		"e640",
		"襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"
	],
	[
		"e680",
		"諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"
	],
	[
		"e740",
		"蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"
	],
	[
		"e780",
		"轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"
	],
	[
		"e840",
		"錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"
	],
	[
		"e880",
		"閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"
	],
	[
		"e940",
		"顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"
	],
	[
		"e980",
		"騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"
	],
	[
		"ea40",
		"鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"
	],
	[
		"ea80",
		"黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"
	],
	[
		"ed40",
		"纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"
	],
	[
		"ed80",
		"塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"
	],
	[
		"ee40",
		"犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"
	],
	[
		"ee80",
		"蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"
	],
	[
		"eeef",
		"ⅰ",
		9,
		"￢￤＇＂"
	],
	[
		"f040",
		"",
		62
	],
	[
		"f080",
		"",
		124
	],
	[
		"f140",
		"",
		62
	],
	[
		"f180",
		"",
		124
	],
	[
		"f240",
		"",
		62
	],
	[
		"f280",
		"",
		124
	],
	[
		"f340",
		"",
		62
	],
	[
		"f380",
		"",
		124
	],
	[
		"f440",
		"",
		62
	],
	[
		"f480",
		"",
		124
	],
	[
		"f540",
		"",
		62
	],
	[
		"f580",
		"",
		124
	],
	[
		"f640",
		"",
		62
	],
	[
		"f680",
		"",
		124
	],
	[
		"f740",
		"",
		62
	],
	[
		"f780",
		"",
		124
	],
	[
		"f840",
		"",
		62
	],
	[
		"f880",
		"",
		124
	],
	[
		"f940",
		""
	],
	[
		"fa40",
		"ⅰ",
		9,
		"Ⅰ",
		9,
		"￢￤＇＂㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"
	],
	[
		"fa80",
		"兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"
	],
	[
		"fb40",
		"涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"
	],
	[
		"fb80",
		"祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"
	],
	[
		"fc40",
		"髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"
	]
];

const require$$1 = /* #__PURE__ */ JSON.parse("[[\"0\",\"\\u0000\",127],[\"8ea1\",\"｡\",62],[\"a1a1\",\"　、。，．・：；？！゛゜´｀¨＾￣＿ヽヾゝゞ〃仝々〆〇ー―‐／＼～∥｜…‥‘’“”（）〔〕［］｛｝〈\",9,\"＋－±×÷＝≠＜＞≦≧∞∴♂♀°′″℃￥＄￠￡％＃＆＊＠§☆★○●◎◇\"],[\"a2a1\",\"◆□■△▲▽▼※〒→←↑↓〓\"],[\"a2ba\",\"∈∋⊆⊇⊂⊃∪∩\"],[\"a2ca\",\"∧∨￢⇒⇔∀∃\"],[\"a2dc\",\"∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬\"],[\"a2f2\",\"Å‰♯♭♪†‡¶\"],[\"a2fe\",\"◯\"],[\"a3b0\",\"０\",9],[\"a3c1\",\"Ａ\",25],[\"a3e1\",\"ａ\",25],[\"a4a1\",\"ぁ\",82],[\"a5a1\",\"ァ\",85],[\"a6a1\",\"Α\",16,\"Σ\",6],[\"a6c1\",\"α\",16,\"σ\",6],[\"a7a1\",\"А\",5,\"ЁЖ\",25],[\"a7d1\",\"а\",5,\"ёж\",25],[\"a8a1\",\"─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂\"],[\"ada1\",\"①\",19,\"Ⅰ\",9],[\"adc0\",\"㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡\"],[\"addf\",\"㍻〝〟№㏍℡㊤\",4,\"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪\"],[\"b0a1\",\"亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭\"],[\"b1a1\",\"院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応\"],[\"b2a1\",\"押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改\"],[\"b3a1\",\"魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱\"],[\"b4a1\",\"粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄\"],[\"b5a1\",\"機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京\"],[\"b6a1\",\"供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈\"],[\"b7a1\",\"掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲\"],[\"b8a1\",\"検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向\"],[\"b9a1\",\"后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込\"],[\"baa1\",\"此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷\"],[\"bba1\",\"察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時\"],[\"bca1\",\"次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周\"],[\"bda1\",\"宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償\"],[\"bea1\",\"勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾\"],[\"bfa1\",\"拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾\"],[\"c0a1\",\"澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線\"],[\"c1a1\",\"繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎\"],[\"c2a1\",\"臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只\"],[\"c3a1\",\"叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵\"],[\"c4a1\",\"帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓\"],[\"c5a1\",\"邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到\"],[\"c6a1\",\"董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入\"],[\"c7a1\",\"如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦\"],[\"c8a1\",\"函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美\"],[\"c9a1\",\"鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服\"],[\"caa1\",\"福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋\"],[\"cba1\",\"法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満\"],[\"cca1\",\"漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒\"],[\"cda1\",\"諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃\"],[\"cea1\",\"痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯\"],[\"cfa1\",\"蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕\"],[\"d0a1\",\"弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲\"],[\"d1a1\",\"僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨\"],[\"d2a1\",\"辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨\"],[\"d3a1\",\"咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉\"],[\"d4a1\",\"圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩\"],[\"d5a1\",\"奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓\"],[\"d6a1\",\"屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏\"],[\"d7a1\",\"廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚\"],[\"d8a1\",\"悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛\"],[\"d9a1\",\"戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼\"],[\"daa1\",\"據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼\"],[\"dba1\",\"曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍\"],[\"dca1\",\"棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣\"],[\"dda1\",\"檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾\"],[\"dea1\",\"沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌\"],[\"dfa1\",\"漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼\"],[\"e0a1\",\"燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱\"],[\"e1a1\",\"瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰\"],[\"e2a1\",\"癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬\"],[\"e3a1\",\"磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐\"],[\"e4a1\",\"筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆\"],[\"e5a1\",\"紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺\"],[\"e6a1\",\"罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋\"],[\"e7a1\",\"隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙\"],[\"e8a1\",\"茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈\"],[\"e9a1\",\"蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙\"],[\"eaa1\",\"蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞\"],[\"eba1\",\"襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫\"],[\"eca1\",\"譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊\"],[\"eda1\",\"蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸\"],[\"eea1\",\"遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮\"],[\"efa1\",\"錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞\"],[\"f0a1\",\"陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰\"],[\"f1a1\",\"顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷\"],[\"f2a1\",\"髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈\"],[\"f3a1\",\"鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠\"],[\"f4a1\",\"堯槇遙瑤凜熙\"],[\"f9a1\",\"纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德\"],[\"faa1\",\"忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱\"],[\"fba1\",\"犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚\"],[\"fca1\",\"釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑\"],[\"fcf1\",\"ⅰ\",9,\"￢￤＇＂\"],[\"8fa2af\",\"˘ˇ¸˙˝¯˛˚～΄΅\"],[\"8fa2c2\",\"¡¦¿\"],[\"8fa2eb\",\"ºª©®™¤№\"],[\"8fa6e1\",\"ΆΈΉΊΪ\"],[\"8fa6e7\",\"Ό\"],[\"8fa6e9\",\"ΎΫ\"],[\"8fa6ec\",\"Ώ\"],[\"8fa6f1\",\"άέήίϊΐόςύϋΰώ\"],[\"8fa7c2\",\"Ђ\",10,\"ЎЏ\"],[\"8fa7f2\",\"ђ\",10,\"ўџ\"],[\"8fa9a1\",\"ÆĐ\"],[\"8fa9a4\",\"Ħ\"],[\"8fa9a6\",\"Ĳ\"],[\"8fa9a8\",\"ŁĿ\"],[\"8fa9ab\",\"ŊØŒ\"],[\"8fa9af\",\"ŦÞ\"],[\"8fa9c1\",\"æđðħıĳĸłŀŉŋøœßŧþ\"],[\"8faaa1\",\"ÁÀÄÂĂǍĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ\"],[\"8faaba\",\"ĜĞĢĠĤÍÌÏÎǏİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑŐŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴÝŸŶŹŽŻ\"],[\"8faba1\",\"áàäâăǎāąåãćĉčçċďéèëêěėēęǵĝğ\"],[\"8fabbd\",\"ġĥíìïîǐ\"],[\"8fabc5\",\"īįĩĵķĺľļńňņñóòöôǒőōõŕřŗśŝšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż\"],[\"8fb0a1\",\"丂丄丅丌丒丟丣两丨丫丮丯丰丵乀乁乄乇乑乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾侁侂侄\"],[\"8fb1a1\",\"侅侉侊侌侎侐侒侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀俁俅俆俈俉俋俌俍俏俒俜俠俢俰俲俼俽俿倀倁倄倇倊倌倎倐倓倗倘倛倜倝倞倢倧倮倰倲倳倵偀偁偂偅偆偊偌偎偑偒偓偗偙偟偠偢偣偦偧偪偭偰偱倻傁傃傄傆傊傎傏傐\"],[\"8fb2a1\",\"傒傓傔傖傛傜傞\",4,\"傪傯傰傹傺傽僀僃僄僇僌僎僐僓僔僘僜僝僟僢僤僦僨僩僯僱僶僺僾儃儆儇儈儋儌儍儎僲儐儗儙儛儜儝儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊兏兓兕兗兘兟兤兦兾冃冄冋冎冘冝冡冣冭冸冺冼冾冿凂\"],[\"8fb3a1\",\"凈减凑凒凓凕凘凞凢凥凮凲凳凴凷刁刂刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌勏勑勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋\"],[\"8fb4a1\",\"匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾卂卌卋卙卛卡卣卥卬卭卲卹卾厃厇厈厎厓厔厙厝厡厤厪厫厯厲厴厵厷厸厺厽叀叅叏叒叓叕叚叝叞叠另叧叵吂吓吚吡吧吨吪启吱吴吵呃呄呇呍呏呞呢呤呦呧呩呫呭呮呴呿\"],[\"8fb5a1\",\"咁咃咅咈咉咍咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊响哎哠哪哬哯哶哼哾哿唀唁唅唈唉唌唍唎唕唪唫唲唵唶唻唼唽啁啇啉啊啍啐啑啘啚啛啞啠啡啤啦啿喁喂喆喈喎喏喑喒喓喔喗喣喤喭喲喿嗁嗃嗆嗉嗋嗌嗎嗑嗒\"],[\"8fb6a1\",\"嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊嘍\",5,\"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀噁噃噄噆噉噋噍噏噔噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚嚝嚞嚟嚦嚧嚨嚩嚫嚬嚭嚱嚳嚷嚾囅囉囊囋囏囐囌囍囙囜囝囟囡囤\",4,\"囱囫园\"],[\"8fb7a1\",\"囶囷圁圂圇圊圌圑圕圚圛圝圠圢圣圤圥圩圪圬圮圯圳圴圽圾圿坅坆坌坍坒坢坥坧坨坫坭\",4,\"坳坴坵坷坹坺坻坼坾垁垃垌垔垗垙垚垜垝垞垟垡垕垧垨垩垬垸垽埇埈埌埏埕埝埞埤埦埧埩埭埰埵埶埸埽埾埿堃堄堈堉埡\"],[\"8fb8a1\",\"堌堍堛堞堟堠堦堧堭堲堹堿塉塌塍塏塐塕塟塡塤塧塨塸塼塿墀墁墇墈墉墊墌墍墏墐墔墖墝墠墡墢墦墩墱墲壄墼壂壈壍壎壐壒壔壖壚壝壡壢壩壳夅夆夋夌夒夓夔虁夝夡夣夤夨夯夰夳夵夶夿奃奆奒奓奙奛奝奞奟奡奣奫奭\"],[\"8fb9a1\",\"奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼姁姃姄姈姊姍姒姝姞姟姣姤姧姮姯姱姲姴姷娀娄娌娍娎娒娓娞娣娤娧娨娪娭娰婄婅婇婈婌婐婕婞婣婥婧婭婷婺婻婾媋媐媓媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿\"],[\"8fbaa1\",\"嫄嫆嫈嫏嫚嫜嫠嫥嫪嫮嫵嫶嫽嬀嬁嬈嬗嬴嬙嬛嬝嬡嬥嬭嬸孁孋孌孒孖孞孨孮孯孼孽孾孿宁宄宆宊宎宐宑宓宔宖宨宩宬宭宯宱宲宷宺宼寀寁寍寏寖\",4,\"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩\"],[\"8fbba1\",\"屭屰屴屵屺屻屼屽岇岈岊岏岒岝岟岠岢岣岦岪岲岴岵岺峉峋峒峝峗峮峱峲峴崁崆崍崒崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿嶁嶃嶈嶊嶒嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋巐巎巘巙巠巤\"],[\"8fbca1\",\"巩巸巹帀帇帍帒帔帕帘帟帠帮帨帲帵帾幋幐幉幑幖幘幛幜幞幨幪\",4,\"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜弝弡弢弣弤弨弫弬弮弰弴弶弻弽弿彀彄彅彇彍彐彔彘彛彠彣彤彧\"],[\"8fbda1\",\"彯彲彴彵彸彺彽彾徉徍徏徖徜徝徢徧徫徤徬徯徰徱徸忄忇忈忉忋忐\",4,\"忞忡忢忨忩忪忬忭忮忯忲忳忶忺忼怇怊怍怓怔怗怘怚怟怤怭怳怵恀恇恈恉恌恑恔恖恗恝恡恧恱恾恿悂悆悈悊悎悑悓悕悘悝悞悢悤悥您悰悱悷\"],[\"8fbea1\",\"悻悾惂惄惈惉惊惋惎惏惔惕惙惛惝惞惢惥惲惵惸惼惽愂愇愊愌愐\",4,\"愖愗愙愜愞愢愪愫愰愱愵愶愷愹慁慅慆慉慞慠慬慲慸慻慼慿憀憁憃憄憋憍憒憓憗憘憜憝憟憠憥憨憪憭憸憹憼懀懁懂懎懏懕懜懝懞懟懡懢懧懩懥\"],[\"8fbfa1\",\"懬懭懯戁戃戄戇戓戕戜戠戢戣戧戩戫戹戽扂扃扄扆扌扐扑扒扔扖扚扜扤扭扯扳扺扽抍抎抏抐抦抨抳抶抷抺抾抿拄拎拕拖拚拪拲拴拼拽挃挄挊挋挍挐挓挖挘挩挪挭挵挶挹挼捁捂捃捄捆捊捋捎捒捓捔捘捛捥捦捬捭捱捴捵\"],[\"8fc0a1\",\"捸捼捽捿掂掄掇掊掐掔掕掙掚掞掤掦掭掮掯掽揁揅揈揎揑揓揔揕揜揠揥揪揬揲揳揵揸揹搉搊搐搒搔搘搞搠搢搤搥搩搪搯搰搵搽搿摋摏摑摒摓摔摚摛摜摝摟摠摡摣摭摳摴摻摽撅撇撏撐撑撘撙撛撝撟撡撣撦撨撬撳撽撾撿\"],[\"8fc1a1\",\"擄擉擊擋擌擎擐擑擕擗擤擥擩擪擭擰擵擷擻擿攁攄攈攉攊攏攓攔攖攙攛攞攟攢攦攩攮攱攺攼攽敃敇敉敐敒敔敟敠敧敫敺敽斁斅斊斒斕斘斝斠斣斦斮斲斳斴斿旂旈旉旎旐旔旖旘旟旰旲旴旵旹旾旿昀昄昈昉昍昑昒昕昖昝\"],[\"8fc2a1\",\"昞昡昢昣昤昦昩昪昫昬昮昰昱昳昹昷晀晅晆晊晌晑晎晗晘晙晛晜晠晡曻晪晫晬晾晳晵晿晷晸晹晻暀晼暋暌暍暐暒暙暚暛暜暟暠暤暭暱暲暵暻暿曀曂曃曈曌曎曏曔曛曟曨曫曬曮曺朅朇朎朓朙朜朠朢朳朾杅杇杈杌杔杕杝\"],[\"8fc3a1\",\"杦杬杮杴杶杻极构枎枏枑枓枖枘枙枛枰枱枲枵枻枼枽柹柀柂柃柅柈柉柒柗柙柜柡柦柰柲柶柷桒栔栙栝栟栨栧栬栭栯栰栱栳栻栿桄桅桊桌桕桗桘桛桫桮\",4,\"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌棏\"],[\"8fc4a1\",\"棐棑棓棖棙棜棝棥棨棪棫棬棭棰棱棵棶棻棼棽椆椉椊椐椑椓椖椗椱椳椵椸椻楂楅楉楎楗楛楣楤楥楦楨楩楬楰楱楲楺楻楿榀榍榒榖榘榡榥榦榨榫榭榯榷榸榺榼槅槈槑槖槗槢槥槮槯槱槳槵槾樀樁樃樏樑樕樚樝樠樤樨樰樲\"],[\"8fc5a1\",\"樴樷樻樾樿橅橆橉橊橎橐橑橒橕橖橛橤橧橪橱橳橾檁檃檆檇檉檋檑檛檝檞檟檥檫檯檰檱檴檽檾檿櫆櫉櫈櫌櫐櫔櫕櫖櫜櫝櫤櫧櫬櫰櫱櫲櫼櫽欂欃欆欇欉欏欐欑欗欛欞欤欨欫欬欯欵欶欻欿歆歊歍歒歖歘歝歠歧歫歮歰歵歽\"],[\"8fc6a1\",\"歾殂殅殗殛殟殠殢殣殨殩殬殭殮殰殸殹殽殾毃毄毉毌毖毚毡毣毦毧毮毱毷毹毿氂氄氅氉氍氎氐氒氙氟氦氧氨氬氮氳氵氶氺氻氿汊汋汍汏汒汔汙汛汜汫汭汯汴汶汸汹汻沅沆沇沉沔沕沗沘沜沟沰沲沴泂泆泍泏泐泑泒泔泖\"],[\"8fc7a1\",\"泚泜泠泧泩泫泬泮泲泴洄洇洊洎洏洑洓洚洦洧洨汧洮洯洱洹洼洿浗浞浟浡浥浧浯浰浼涂涇涑涒涔涖涗涘涪涬涴涷涹涽涿淄淈淊淎淏淖淛淝淟淠淢淥淩淯淰淴淶淼渀渄渞渢渧渲渶渹渻渼湄湅湈湉湋湏湑湒湓湔湗湜湝湞\"],[\"8fc8a1\",\"湢湣湨湳湻湽溍溓溙溠溧溭溮溱溳溻溿滀滁滃滇滈滊滍滎滏滫滭滮滹滻滽漄漈漊漌漍漖漘漚漛漦漩漪漯漰漳漶漻漼漭潏潑潒潓潗潙潚潝潞潡潢潨潬潽潾澃澇澈澋澌澍澐澒澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊\"],[\"8fc9a1\",\"濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇瀍瀗瀠瀣瀯瀴瀷瀹瀼灃灄灈灉灊灋灔灕灝灞灎灤灥灬灮灵灶灾炁炅炆炔\",4,\"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃\",4,\"焋焌焏焞焠焫焭焯焰焱焸煁煅煆煇煊煋煐煒煗煚煜煞煠\"],[\"8fcaa1\",\"煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀燁燄燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚爝爟爤爫爯爴爸爹牁牂牃牅牎牏牐牓牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉犍犎犓犛犨犭犮犱犴犾狁狇狉狌狕狖狘狟狥狳狴狺狻\"],[\"8fcba1\",\"狾猂猄猅猇猋猍猒猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽獃獍獐獒獖獘獝獞獟獠獦獧獩獫獬獮獯獱獷獹獼玀玁玃玅玆玎玐玓玕玗玘玜玞玟玠玢玥玦玪玫玭玵玷玹玼玽玿珅珆珉珋珌珏珒珓珖珙珝珡珣珦珧珩珴珵珷珹珺珻珽\"],[\"8fcca1\",\"珿琀琁琄琇琊琑琚琛琤琦琨\",9,\"琹瑀瑃瑄瑆瑇瑋瑍瑑瑒瑗瑝瑢瑦瑧瑨瑫瑭瑮瑱瑲璀璁璅璆璇璉璏璐璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌瓐瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆\"],[\"8fcda1\",\"甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎畐畒畗畞畟畡畯畱畹\",5,\"疁疅疐疒疓疕疙疜疢疤疴疺疿痀痁痄痆痌痎痏痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌瘏瘒瘓瘕瘖瘙瘛瘜瘝瘞瘣瘥瘦瘩瘭瘲瘳瘵瘸瘹\"],[\"8fcea1\",\"瘺瘼癊癀癁癃癄癅癉癋癕癙癟癤癥癭癮癯癱癴皁皅皌皍皕皛皜皝皟皠皢\",6,\"皪皭皽盁盅盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾睂睅睆睊睍睎睏睒睖睗睜睞睟睠睢\"],[\"8fcfa1\",\"睤睧睪睬睰睲睳睴睺睽瞀瞄瞌瞍瞔瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉砍砎砑砝砡砢砣砭砮砰砵砷硃硄硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊碏碔碘碡碝碞碟碤碨碬碭碰碱碲碳\"],[\"8fd0a1\",\"碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌礐礚礜礞礟礠礥礧礩礭礱礴礵礻礽礿祄祅祆祊祋祏祑祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊秏秔秖秚秝秞\"],[\"8fd1a1\",\"秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜穝穟穠穥穧穪穭穵穸穾窀窂窅窆窊窋窐窑窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰\"],[\"8fd2a1\",\"笱笴笽笿筀筁筇筎筕筠筤筦筩筪筭筯筲筳筷箄箉箎箐箑箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾簁簂簃簄簆簉簋簌簎簏簙簛簠簥簦簨簬簱簳簴簶簹簺籆籊籕籑籒籓籙\",5],[\"8fd3a1\",\"籡籣籧籩籭籮籰籲籹籼籽粆粇粏粔粞粠粦粰粶粷粺粻粼粿糄糇糈糉糍糏糓糔糕糗糙糚糝糦糩糫糵紃紇紈紉紏紑紒紓紖紝紞紣紦紪紭紱紼紽紾絀絁絇絈絍絑絓絗絙絚絜絝絥絧絪絰絸絺絻絿綁綂綃綅綆綈綋綌綍綑綖綗綝\"],[\"8fd4a1\",\"綞綦綧綪綳綶綷綹緂\",4,\"緌緍緎緗緙縀緢緥緦緪緫緭緱緵緶緹緺縈縐縑縕縗縜縝縠縧縨縬縭縯縳縶縿繄繅繇繎繐繒繘繟繡繢繥繫繮繯繳繸繾纁纆纇纊纍纑纕纘纚纝纞缼缻缽缾缿罃罄罇罏罒罓罛罜罝罡罣罤罥罦罭\"],[\"8fd5a1\",\"罱罽罾罿羀羋羍羏羐羑羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎翏翛翟翣翥翨翬翮翯翲翺翽翾翿耇耈耊耍耎耏耑耓耔耖耝耞耟耠耤耦耬耮耰耴耵耷耹耺耼耾聀聄聠聤聦聭聱聵肁肈肎肜肞肦肧肫肸肹胈胍胏胒胔胕胗胘胠胭胮\"],[\"8fd6a1\",\"胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷膁膐膄膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎臏臕臗臛臝臞臡臤臫臬臰臱臲臵臶臸臹臽臿舀舃舏舓舔舙舚舝舡舢舨舲舴舺艃艄艅艆\"],[\"8fd7a1\",\"艋艎艏艑艖艜艠艣艧艭艴艻艽艿芀芁芃芄芇芉芊芎芑芔芖芘芚芛芠芡芣芤芧芨芩芪芮芰芲芴芷芺芼芾芿苆苐苕苚苠苢苤苨苪苭苯苶苷苽苾茀茁茇茈茊茋荔茛茝茞茟茡茢茬茭茮茰茳茷茺茼茽荂荃荄荇荍荎荑荕荖荗荰荸\"],[\"8fd8a1\",\"荽荿莀莂莄莆莍莒莔莕莘莙莛莜莝莦莧莩莬莾莿菀菇菉菏菐菑菔菝荓菨菪菶菸菹菼萁萆萊萏萑萕萙莭萯萹葅葇葈葊葍葏葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽蒁蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌蓏蓓\"],[\"8fd9a1\",\"蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎蔐蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆蕏\",4,\"蕖蕙蕜\",6,\"蕤蕫蕯蕹蕺蕻蕽蕿薁薅薆薉薋薌薏薓薘薝薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼\"],[\"8fdaa1\",\"藿蘀蘄蘅蘍蘎蘐蘑蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙虝虠\",4,\"虩虬虯虵虶虷虺蚍蚑蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀蛁蛃蛅蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎蜏蜐蜓蜔蜙蜞蜟蜡蜣\"],[\"8fdba1\",\"蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾蝀蝃蝅蝍蝘蝝蝡蝤蝥蝯蝱蝲蝻螃\",6,\"螋螌螐螓螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿蟁蟈蟉蟊蟎蟕蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿蠁蠃蠆蠉蠊蠋蠐蠙蠒蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵\"],[\"8fdca1\",\"蠺蠼衁衃衅衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊\",4,\"裑裒裓裛裞裧裯裰裱裵裷褁褆褍褎褏褕褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉襏襒襗襚襛襜襡襢襣襫襮襰襳襵襺\"],[\"8fdda1\",\"襻襼襽覉覍覐覔覕覛覜覟覠覥覰覴覵覶覷覼觔\",4,\"觥觩觫觭觱觳觶觹觽觿訄訅訇訏訑訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉詍詎詓詖詗詘詜詝詡詥詧詵詶詷詹詺詻詾詿誀誃誆誋誏誐誒誖誗誙誟誧誩誮誯誳\"],[\"8fdea1\",\"誶誷誻誾諃諆諈諉諊諑諓諔諕諗諝諟諬諰諴諵諶諼諿謅謆謋謑謜謞謟謊謭謰謷謼譂\",4,\"譈譒譓譔譙譍譞譣譭譶譸譹譼譾讁讄讅讋讍讏讔讕讜讞讟谸谹谽谾豅豇豉豋豏豑豓豔豗豘豛豝豙豣豤豦豨豩豭豳豵豶豻豾貆\"],[\"8fdfa1\",\"貇貋貐貒貓貙貛貜貤貹貺賅賆賉賋賏賖賕賙賝賡賨賬賯賰賲賵賷賸賾賿贁贃贉贒贗贛赥赩赬赮赿趂趄趈趍趐趑趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽踁踄踅踆踋踑踔踖踠踡踢\"],[\"8fe0a1\",\"踣踦踧踱踳踶踷踸踹踽蹀蹁蹋蹍蹎蹏蹔蹛蹜蹝蹞蹡蹢蹩蹬蹭蹯蹰蹱蹹蹺蹻躂躃躉躐躒躕躚躛躝躞躢躧躩躭躮躳躵躺躻軀軁軃軄軇軏軑軔軜軨軮軰軱軷軹軺軭輀輂輇輈輏輐輖輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀轁\"],[\"8fe1a1\",\"轃轇轏轑\",4,\"轘轝轞轥辝辠辡辤辥辦辵辶辸达迀迁迆迊迋迍运迒迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿遃遄遌遛遝遢遦遧遬遰遴遹邅邈邋邌邎邐邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃\"],[\"8fe2a1\",\"郄郅郇郈郕郗郘郙郜郝郟郥郒郶郫郯郰郴郾郿鄀鄄鄅鄆鄈鄍鄐鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈酏酓酗酙酚酛酡酤酧酭酴酹酺酻醁醃醅醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿\"],[\"8fe3a1\",\"釂釃釅釓釔釗釙釚釞釤釥釩釪釬\",5,\"釷釹釻釽鈀鈁鈄鈅鈆鈇鈉鈊鈌鈐鈒鈓鈖鈘鈜鈝鈣鈤鈥鈦鈨鈮鈯鈰鈳鈵鈶鈸鈹鈺鈼鈾鉀鉂鉃鉆鉇鉊鉍鉎鉏鉑鉘鉙鉜鉝鉠鉡鉥鉧鉨鉩鉮鉯鉰鉵\",4,\"鉻鉼鉽鉿銈銉銊銍銎銒銗\"],[\"8fe4a1\",\"銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿\",4,\"鋅鋆鋇鋈鋋鋌鋍鋎鋐鋓鋕鋗鋘鋙鋜鋝鋟鋠鋡鋣鋥鋧鋨鋬鋮鋰鋹鋻鋿錀錂錈錍錑錔錕錜錝錞錟錡錤錥錧錩錪錳錴錶錷鍇鍈鍉鍐鍑鍒鍕鍗鍘鍚鍞鍤鍥鍧鍩鍪鍭鍯鍰鍱鍳鍴鍶\"],[\"8fe5a1\",\"鍺鍽鍿鎀鎁鎂鎈鎊鎋鎍鎏鎒鎕鎘鎛鎞鎡鎣鎤鎦鎨鎫鎴鎵鎶鎺鎩鏁鏄鏅鏆鏇鏉\",4,\"鏓鏙鏜鏞鏟鏢鏦鏧鏹鏷鏸鏺鏻鏽鐁鐂鐄鐈鐉鐍鐎鐏鐕鐖鐗鐟鐮鐯鐱鐲鐳鐴鐻鐿鐽鑃鑅鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹\"],[\"8fe6a1\",\"镾閄閈閌閍閎閝閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋闐闑闒闓闙闚闝闞闟闠闤闦阝阞阢阤阥阦阬阱阳阷阸阹阺阼阽陁陒陔陖陗陘陡陮陴陻陼陾陿隁隂隃隄隉隑隖隚隝隟隤隥隦隩隮隯隳隺雊雒嶲雘雚雝雞雟雩雯雱雺霂\"],[\"8fe7a1\",\"霃霅霉霚霛霝霡霢霣霨霱霳靁靃靊靎靏靕靗靘靚靛靣靧靪靮靳靶靷靸靻靽靿鞀鞉鞕鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿韁韄韅韇韉韊韌韍韎韐韑韔韗韘韙韝韞韠韛韡韤韯韱韴韷韸韺頇頊頙頍頎頔頖頜頞頠頣頦\"],[\"8fe8a1\",\"頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱\",4,\"餹餺餻餼饀饁饆饇饈饍饎饔饘饙饛饜饞饟饠馛馝馟馦馰馱馲馵\"],[\"8fe9a1\",\"馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌騐騑騖騞騠騢騣騤騧騭騮騳騵騶騸驇驁驄驊驋驌驎驑驔驖驝骪骬骮骯骲骴骵骶骹骻骾骿髁髃髆髈髎髐髒髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿\",4],[\"8feaa1\",\"鬄鬅鬈鬉鬋鬌鬍鬎鬐鬒鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪\",4,\"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋鮍鮏鮐鮔鮚鮝鮞鮦鮧鮩鮬鮰鮱鮲鮷鮸鮻鮼鮾鮿鯁鯇鯈鯎鯐鯗鯘鯝鯟鯥鯧鯪鯫鯯鯳鯷鯸\"],[\"8feba1\",\"鯹鯺鯽鯿鰀鰂鰋鰏鰑鰖鰘鰙鰚鰜鰞鰢鰣鰦\",4,\"鰱鰵鰶鰷鰽鱁鱃鱄鱅鱉鱊鱎鱏鱐鱓鱔鱖鱘鱛鱝鱞鱟鱣鱩鱪鱜鱫鱨鱮鱰鱲鱵鱷鱻鳦鳲鳷鳹鴋鴂鴑鴗鴘鴜鴝鴞鴯鴰鴲鴳鴴鴺鴼鵅鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻\"],[\"8feca1\",\"鵼鵾鶃鶄鶆鶊鶍鶎鶒鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎鸐鸑鸒鸕鸖鸙鸜鸝鹺鹻鹼麀麂麃麄麅麇麎麏麖麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵\"],[\"8feda1\",\"黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃\",4,\"齓齕齖齗齘齚齝齞齨齩齭\",4,\"齳齵齺齽龏龐龑龒龔龖龗龞龡龢龣龥\"]]");

const require$$2$1 = /* #__PURE__ */ JSON.parse("[[\"0\",\"\\u0000\",127,\"€\"],[\"8140\",\"丂丄丅丆丏丒丗丟丠両丣並丩丮丯丱丳丵丷丼乀乁乂乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪\",5,\"乲乴\",9,\"乿\",6,\"亇亊\"],[\"8180\",\"亐亖亗亙亜亝亞亣亪亯亰亱亴亶亷亸亹亼亽亾仈仌仏仐仒仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂\",6,\"伋伌伒\",4,\"伜伝伡伣伨伩伬伭伮伱伳伵伷伹伻伾\",4,\"佄佅佇\",5,\"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀侁侂侅來侇侊侌侎侐侒侓侕侖侘侙侚侜侞侟価侢\"],[\"8240\",\"侤侫侭侰\",4,\"侶\",8,\"俀俁係俆俇俈俉俋俌俍俒\",4,\"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿\",11],[\"8280\",\"個倎倐們倓倕倖倗倛倝倞倠倢倣値倧倫倯\",10,\"倻倽倿偀偁偂偄偅偆偉偊偋偍偐\",4,\"偖偗偘偙偛偝\",7,\"偦\",5,\"偭\",8,\"偸偹偺偼偽傁傂傃傄傆傇傉傊傋傌傎\",20,\"傤傦傪傫傭\",4,\"傳\",6,\"傼\"],[\"8340\",\"傽\",17,\"僐\",5,\"僗僘僙僛\",10,\"僨僩僪僫僯僰僱僲僴僶\",4,\"僼\",9,\"儈\"],[\"8380\",\"儉儊儌\",5,\"儓\",13,\"儢\",28,\"兂兇兊兌兎兏児兒兓兗兘兙兛兝\",4,\"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎冏冐冑冓冔冘冚冝冞冟冡冣冦\",4,\"冭冮冴冸冹冺冾冿凁凂凃凅凈凊凍凎凐凒\",5],[\"8440\",\"凘凙凚凜凞凟凢凣凥\",5,\"凬凮凱凲凴凷凾刄刅刉刋刌刏刐刓刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄\",5,\"剋剎剏剒剓剕剗剘\"],[\"8480\",\"剙剚剛剝剟剠剢剣剤剦剨剫剬剭剮剰剱剳\",9,\"剾劀劃\",4,\"劉\",6,\"劑劒劔\",6,\"劜劤劥劦劧劮劯劰労\",9,\"勀勁勂勄勅勆勈勊勌勍勎勏勑勓勔動勗務\",5,\"勠勡勢勣勥\",10,\"勱\",7,\"勻勼勽匁匂匃匄匇匉匊匋匌匎\"],[\"8540\",\"匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯\",9,\"匼匽區卂卄卆卋卌卍卐協単卙卛卝卥卨卪卬卭卲卶卹卻卼卽卾厀厁厃厇厈厊厎厏\"],[\"8580\",\"厐\",4,\"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯\",6,\"厷厸厹厺厼厽厾叀參\",4,\"収叏叐叒叓叕叚叜叝叞叡叢叧叴叺叾叿吀吂吅吇吋吔吘吙吚吜吢吤吥吪吰吳吶吷吺吽吿呁呂呄呅呇呉呌呍呎呏呑呚呝\",4,\"呣呥呧呩\",7,\"呴呹呺呾呿咁咃咅咇咈咉咊咍咑咓咗咘咜咞咟咠咡\"],[\"8640\",\"咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠\",4,\"哫哬哯哰哱哴\",5,\"哻哾唀唂唃唄唅唈唊\",4,\"唒唓唕\",5,\"唜唝唞唟唡唥唦\"],[\"8680\",\"唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋\",4,\"啑啒啓啔啗\",4,\"啝啞啟啠啢啣啨啩啫啯\",5,\"啹啺啽啿喅喆喌喍喎喐喒喓喕喖喗喚喛喞喠\",6,\"喨\",8,\"喲喴営喸喺喼喿\",4,\"嗆嗇嗈嗊嗋嗎嗏嗐嗕嗗\",4,\"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸\",4,\"嗿嘂嘃嘄嘅\"],[\"8740\",\"嘆嘇嘊嘋嘍嘐\",7,\"嘙嘚嘜嘝嘠嘡嘢嘥嘦嘨嘩嘪嘫嘮嘯嘰嘳嘵嘷嘸嘺嘼嘽嘾噀\",11,\"噏\",4,\"噕噖噚噛噝\",4],[\"8780\",\"噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽\",7,\"嚇\",6,\"嚐嚑嚒嚔\",14,\"嚤\",10,\"嚰\",6,\"嚸嚹嚺嚻嚽\",12,\"囋\",8,\"囕囖囘囙囜団囥\",5,\"囬囮囯囲図囶囷囸囻囼圀圁圂圅圇國\",6],[\"8840\",\"園\",9,\"圝圞圠圡圢圤圥圦圧圫圱圲圴\",4,\"圼圽圿坁坃坄坅坆坈坉坋坒\",4,\"坘坙坢坣坥坧坬坮坰坱坲坴坵坸坹坺坽坾坿垀\"],[\"8880\",\"垁垇垈垉垊垍\",4,\"垔\",6,\"垜垝垞垟垥垨垪垬垯垰垱垳垵垶垷垹\",8,\"埄\",6,\"埌埍埐埑埓埖埗埛埜埞埡埢埣埥\",7,\"埮埰埱埲埳埵埶執埻埼埾埿堁堃堄堅堈堉堊堌堎堏堐堒堓堔堖堗堘堚堛堜堝堟堢堣堥\",4,\"堫\",4,\"報堲堳場堶\",7],[\"8940\",\"堾\",5,\"塅\",6,\"塎塏塐塒塓塕塖塗塙\",4,\"塟\",5,\"塦\",4,\"塭\",16,\"塿墂墄墆墇墈墊墋墌\"],[\"8980\",\"墍\",4,\"墔\",4,\"墛墜墝墠\",7,\"墪\",17,\"墽墾墿壀壂壃壄壆\",10,\"壒壓壔壖\",13,\"壥\",5,\"壭壯壱売壴壵壷壸壺\",7,\"夃夅夆夈\",4,\"夎夐夑夒夓夗夘夛夝夞夠夡夢夣夦夨夬夰夲夳夵夶夻\"],[\"8a40\",\"夽夾夿奀奃奅奆奊奌奍奐奒奓奙奛\",4,\"奡奣奤奦\",12,\"奵奷奺奻奼奾奿妀妅妉妋妌妎妏妐妑妔妕妘妚妛妜妝妟妠妡妢妦\"],[\"8a80\",\"妧妬妭妰妱妳\",5,\"妺妼妽妿\",6,\"姇姈姉姌姍姎姏姕姖姙姛姞\",4,\"姤姦姧姩姪姫姭\",11,\"姺姼姽姾娀娂娊娋娍娎娏娐娒娔娕娖娗娙娚娛娝娞娡娢娤娦娧娨娪\",6,\"娳娵娷\",4,\"娽娾娿婁\",4,\"婇婈婋\",9,\"婖婗婘婙婛\",5],[\"8b40\",\"婡婣婤婥婦婨婩婫\",8,\"婸婹婻婼婽婾媀\",17,\"媓\",6,\"媜\",13,\"媫媬\"],[\"8b80\",\"媭\",4,\"媴媶媷媹\",4,\"媿嫀嫃\",5,\"嫊嫋嫍\",4,\"嫓嫕嫗嫙嫚嫛嫝嫞嫟嫢嫤嫥嫧嫨嫪嫬\",4,\"嫲\",22,\"嬊\",11,\"嬘\",25,\"嬳嬵嬶嬸\",7,\"孁\",6],[\"8c40\",\"孈\",7,\"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊宍宎宐宑宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀寁寃寈寉寊寋寍寎寏\"],[\"8c80\",\"寑寔\",8,\"寠寢寣實寧審\",4,\"寯寱\",6,\"寽対尀専尃尅將專尋尌對導尐尒尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌屍屒屓屔屖屗屘屚屛屜屝屟屢層屧\",6,\"屰屲\",6,\"屻屼屽屾岀岃\",4,\"岉岊岋岎岏岒岓岕岝\",4,\"岤\",4],[\"8d40\",\"岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅\",5,\"峌\",5,\"峓\",5,\"峚\",6,\"峢峣峧峩峫峬峮峯峱\",9,\"峼\",4],[\"8d80\",\"崁崄崅崈\",5,\"崏\",4,\"崕崗崘崙崚崜崝崟\",4,\"崥崨崪崫崬崯\",4,\"崵\",7,\"崿\",7,\"嵈嵉嵍\",10,\"嵙嵚嵜嵞\",10,\"嵪嵭嵮嵰嵱嵲嵳嵵\",12,\"嶃\",21,\"嶚嶛嶜嶞嶟嶠\"],[\"8e40\",\"嶡\",21,\"嶸\",12,\"巆\",6,\"巎\",12,\"巜巟巠巣巤巪巬巭\"],[\"8e80\",\"巰巵巶巸\",4,\"巿帀帄帇帉帊帋帍帎帒帓帗帞\",7,\"帨\",4,\"帯帰帲\",4,\"帹帺帾帿幀幁幃幆\",5,\"幍\",6,\"幖\",4,\"幜幝幟幠幣\",14,\"幵幷幹幾庁庂広庅庈庉庌庍庎庒庘庛庝庡庢庣庤庨\",4,\"庮\",4,\"庴庺庻庼庽庿\",6],[\"8f40\",\"廆廇廈廋\",5,\"廔廕廗廘廙廚廜\",11,\"廩廫\",8,\"廵廸廹廻廼廽弅弆弇弉弌弍弎弐弒弔弖弙弚弜弝弞弡弢弣弤\"],[\"8f80\",\"弨弫弬弮弰弲\",6,\"弻弽弾弿彁\",14,\"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆徍徎徏徑従徔徖徚徛徝從徟徠徢\",5,\"復徫徬徯\",5,\"徶徸徹徺徻徾\",4,\"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇\"],[\"9040\",\"怈怉怋怌怐怑怓怗怘怚怞怟怢怣怤怬怭怮怰\",4,\"怶\",4,\"怽怾恀恄\",6,\"恌恎恏恑恓恔恖恗恘恛恜恞恟恠恡恥恦恮恱恲恴恵恷恾悀\"],[\"9080\",\"悁悂悅悆悇悈悊悋悎悏悐悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽\",7,\"惇惈惉惌\",4,\"惒惓惔惖惗惙惛惞惡\",4,\"惪惱惲惵惷惸惻\",4,\"愂愃愄愅愇愊愋愌愐\",4,\"愖愗愘愙愛愜愝愞愡愢愥愨愩愪愬\",18,\"慀\",6],[\"9140\",\"慇慉態慍慏慐慒慓慔慖\",6,\"慞慟慠慡慣慤慥慦慩\",6,\"慱慲慳慴慶慸\",18,\"憌憍憏\",4,\"憕\"],[\"9180\",\"憖\",6,\"憞\",8,\"憪憫憭\",9,\"憸\",5,\"憿懀懁懃\",4,\"應懌\",4,\"懓懕\",16,\"懧\",13,\"懶\",8,\"戀\",5,\"戇戉戓戔戙戜戝戞戠戣戦戧戨戩戫戭戯戰戱戲戵戶戸\",4,\"扂扄扅扆扊\"],[\"9240\",\"扏扐払扖扗扙扚扜\",6,\"扤扥扨扱扲扴扵扷扸扺扻扽抁抂抃抅抆抇抈抋\",5,\"抔抙抜抝択抣抦抧抩抪抭抮抯抰抲抳抴抶抷抸抺抾拀拁\"],[\"9280\",\"拃拋拏拑拕拝拞拠拡拤拪拫拰拲拵拸拹拺拻挀挃挄挅挆挊挋挌挍挏挐挒挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳\",5,\"挻挼挾挿捀捁捄捇捈捊捑捒捓捔捖\",7,\"捠捤捥捦捨捪捫捬捯捰捲捳捴捵捸捹捼捽捾捿掁掃掄掅掆掋掍掑掓掔掕掗掙\",6,\"採掤掦掫掯掱掲掵掶掹掻掽掿揀\"],[\"9340\",\"揁揂揃揅揇揈揊揋揌揑揓揔揕揗\",6,\"揟揢揤\",4,\"揫揬揮揯揰揱揳揵揷揹揺揻揼揾搃搄搆\",4,\"損搎搑搒搕\",5,\"搝搟搢搣搤\"],[\"9380\",\"搥搧搨搩搫搮\",5,\"搵\",4,\"搻搼搾摀摂摃摉摋\",6,\"摓摕摖摗摙\",4,\"摟\",7,\"摨摪摫摬摮\",9,\"摻\",6,\"撃撆撈\",8,\"撓撔撗撘撚撛撜撝撟\",4,\"撥撦撧撨撪撫撯撱撲撳撴撶撹撻撽撾撿擁擃擄擆\",6,\"擏擑擓擔擕擖擙據\"],[\"9440\",\"擛擜擝擟擠擡擣擥擧\",24,\"攁\",7,\"攊\",7,\"攓\",4,\"攙\",8],[\"9480\",\"攢攣攤攦\",4,\"攬攭攰攱攲攳攷攺攼攽敀\",4,\"敆敇敊敋敍敎敐敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數\",14,\"斈斉斊斍斎斏斒斔斕斖斘斚斝斞斠斢斣斦斨斪斬斮斱\",7,\"斺斻斾斿旀旂旇旈旉旊旍旐旑旓旔旕旘\",7,\"旡旣旤旪旫\"],[\"9540\",\"旲旳旴旵旸旹旻\",4,\"昁昄昅昇昈昉昋昍昐昑昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷\",4,\"昽昿晀時晄\",6,\"晍晎晐晑晘\"],[\"9580\",\"晙晛晜晝晞晠晢晣晥晧晩\",4,\"晱晲晳晵晸晹晻晼晽晿暀暁暃暅暆暈暉暊暋暍暎暏暐暒暓暔暕暘\",4,\"暞\",8,\"暩\",4,\"暯\",4,\"暵暶暷暸暺暻暼暽暿\",25,\"曚曞\",7,\"曧曨曪\",5,\"曱曵曶書曺曻曽朁朂會\"],[\"9640\",\"朄朅朆朇朌朎朏朑朒朓朖朘朙朚朜朞朠\",5,\"朧朩朮朰朲朳朶朷朸朹朻朼朾朿杁杄杅杇杊杋杍杒杔杕杗\",4,\"杝杢杣杤杦杧杫杬杮東杴杶\"],[\"9680\",\"杸杹杺杻杽枀枂枃枅枆枈枊枌枍枎枏枑枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹\",7,\"柂柅\",9,\"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵\",7,\"柾栁栂栃栄栆栍栐栒栔栕栘\",4,\"栞栟栠栢\",6,\"栫\",6,\"栴栵栶栺栻栿桇桋桍桏桒桖\",5],[\"9740\",\"桜桝桞桟桪桬\",7,\"桵桸\",8,\"梂梄梇\",7,\"梐梑梒梔梕梖梘\",9,\"梣梤梥梩梪梫梬梮梱梲梴梶梷梸\"],[\"9780\",\"梹\",6,\"棁棃\",5,\"棊棌棎棏棐棑棓棔棖棗棙棛\",4,\"棡棢棤\",9,\"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆\",4,\"椌椏椑椓\",11,\"椡椢椣椥\",7,\"椮椯椱椲椳椵椶椷椸椺椻椼椾楀楁楃\",16,\"楕楖楘楙楛楜楟\"],[\"9840\",\"楡楢楤楥楧楨楩楪楬業楯楰楲\",4,\"楺楻楽楾楿榁榃榅榊榋榌榎\",5,\"榖榗榙榚榝\",9,\"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽\"],[\"9880\",\"榾榿槀槂\",7,\"構槍槏槑槒槓槕\",5,\"槜槝槞槡\",11,\"槮槯槰槱槳\",9,\"槾樀\",9,\"樋\",11,\"標\",5,\"樠樢\",5,\"権樫樬樭樮樰樲樳樴樶\",6,\"樿\",4,\"橅橆橈\",7,\"橑\",6,\"橚\"],[\"9940\",\"橜\",4,\"橢橣橤橦\",10,\"橲\",6,\"橺橻橽橾橿檁檂檃檅\",8,\"檏檒\",4,\"檘\",7,\"檡\",5],[\"9980\",\"檧檨檪檭\",114,\"欥欦欨\",6],[\"9a40\",\"欯欰欱欳欴欵欶欸欻欼欽欿歀歁歂歄歅歈歊歋歍\",11,\"歚\",7,\"歨歩歫\",13,\"歺歽歾歿殀殅殈\"],[\"9a80\",\"殌殎殏殐殑殔殕殗殘殙殜\",4,\"殢\",7,\"殫\",7,\"殶殸\",6,\"毀毃毄毆\",4,\"毌毎毐毑毘毚毜\",4,\"毢\",7,\"毬毭毮毰毱毲毴毶毷毸毺毻毼毾\",6,\"氈\",4,\"氎氒気氜氝氞氠氣氥氫氬氭氱氳氶氷氹氺氻氼氾氿汃汄汅汈汋\",4,\"汑汒汓汖汘\"],[\"9b40\",\"汙汚汢汣汥汦汧汫\",4,\"汱汳汵汷汸決汻汼汿沀沄沇沊沋沍沎沑沒沕沖沗沘沚沜沝沞沠沢沨沬沯沰沴沵沶沷沺泀況泂泃泆泇泈泋泍泎泏泑泒泘\"],[\"9b80\",\"泙泚泜泝泟泤泦泧泩泬泭泲泴泹泿洀洂洃洅洆洈洉洊洍洏洐洑洓洔洕洖洘洜洝洟\",5,\"洦洨洩洬洭洯洰洴洶洷洸洺洿浀浂浄浉浌浐浕浖浗浘浛浝浟浡浢浤浥浧浨浫浬浭浰浱浲浳浵浶浹浺浻浽\",4,\"涃涄涆涇涊涋涍涏涐涒涖\",4,\"涜涢涥涬涭涰涱涳涴涶涷涹\",5,\"淁淂淃淈淉淊\"],[\"9c40\",\"淍淎淏淐淒淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽\",7,\"渆渇済渉渋渏渒渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵\"],[\"9c80\",\"渶渷渹渻\",7,\"湅\",7,\"湏湐湑湒湕湗湙湚湜湝湞湠\",10,\"湬湭湯\",14,\"満溁溂溄溇溈溊\",4,\"溑\",6,\"溙溚溛溝溞溠溡溣溤溦溨溩溫溬溭溮溰溳溵溸溹溼溾溿滀滃滄滅滆滈滉滊滌滍滎滐滒滖滘滙滛滜滝滣滧滪\",5],[\"9d40\",\"滰滱滲滳滵滶滷滸滺\",7,\"漃漄漅漇漈漊\",4,\"漐漑漒漖\",9,\"漡漢漣漥漦漧漨漬漮漰漲漴漵漷\",6,\"漿潀潁潂\"],[\"9d80\",\"潃潄潅潈潉潊潌潎\",9,\"潙潚潛潝潟潠潡潣潤潥潧\",5,\"潯潰潱潳潵潶潷潹潻潽\",6,\"澅澆澇澊澋澏\",12,\"澝澞澟澠澢\",4,\"澨\",10,\"澴澵澷澸澺\",5,\"濁濃\",5,\"濊\",6,\"濓\",10,\"濟濢濣濤濥\"],[\"9e40\",\"濦\",7,\"濰\",32,\"瀒\",7,\"瀜\",6,\"瀤\",6],[\"9e80\",\"瀫\",9,\"瀶瀷瀸瀺\",17,\"灍灎灐\",13,\"灟\",11,\"灮灱灲灳灴灷灹灺灻災炁炂炃炄炆炇炈炋炌炍炏炐炑炓炗炘炚炛炞\",12,\"炰炲炴炵炶為炾炿烄烅烆烇烉烋\",12,\"烚\"],[\"9f40\",\"烜烝烞烠烡烢烣烥烪烮烰\",6,\"烸烺烻烼烾\",10,\"焋\",4,\"焑焒焔焗焛\",10,\"焧\",7,\"焲焳焴\"],[\"9f80\",\"焵焷\",13,\"煆煇煈煉煋煍煏\",12,\"煝煟\",4,\"煥煩\",4,\"煯煰煱煴煵煶煷煹煻煼煾\",5,\"熅\",4,\"熋熌熍熎熐熑熒熓熕熖熗熚\",4,\"熡\",6,\"熩熪熫熭\",5,\"熴熶熷熸熺\",8,\"燄\",9,\"燏\",4],[\"a040\",\"燖\",9,\"燡燢燣燤燦燨\",5,\"燯\",9,\"燺\",11,\"爇\",19],[\"a080\",\"爛爜爞\",9,\"爩爫爭爮爯爲爳爴爺爼爾牀\",6,\"牉牊牋牎牏牐牑牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅\",4,\"犌犎犐犑犓\",11,\"犠\",11,\"犮犱犲犳犵犺\",6,\"狅狆狇狉狊狋狌狏狑狓狔狕狖狘狚狛\"],[\"a1a1\",\"　、。·ˉˇ¨〃々—～‖…‘’“”〔〕〈\",7,\"〖〗【】±×÷∶∧∨∑∏∪∩∈∷√⊥∥∠⌒⊙∫∮≡≌≈∽∝≠≮≯≤≥∞∵∴♂♀°′″℃＄¤￠￡‰§№☆★○●◎◇◆□■△▲※→←↑↓〓\"],[\"a2a1\",\"ⅰ\",9],[\"a2b1\",\"⒈\",19,\"⑴\",19,\"①\",9],[\"a2e5\",\"㈠\",9],[\"a2f1\",\"Ⅰ\",11],[\"a3a1\",\"！＂＃￥％\",88,\"￣\"],[\"a4a1\",\"ぁ\",82],[\"a5a1\",\"ァ\",85],[\"a6a1\",\"Α\",16,\"Σ\",6],[\"a6c1\",\"α\",16,\"σ\",6],[\"a6e0\",\"︵︶︹︺︿﹀︽︾﹁﹂﹃﹄\"],[\"a6ee\",\"︻︼︷︸︱\"],[\"a6f4\",\"︳︴\"],[\"a7a1\",\"А\",5,\"ЁЖ\",25],[\"a7d1\",\"а\",5,\"ёж\",25],[\"a840\",\"ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿═\",35,\"▁\",6],[\"a880\",\"█\",7,\"▓▔▕▼▽◢◣◤◥☉⊕〒〝〞\"],[\"a8a1\",\"āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜüêɑ\"],[\"a8bd\",\"ńň\"],[\"a8c0\",\"ɡ\"],[\"a8c5\",\"ㄅ\",36],[\"a940\",\"〡\",8,\"㊣㎎㎏㎜㎝㎞㎡㏄㏎㏑㏒㏕︰￢￤\"],[\"a959\",\"℡㈱\"],[\"a95c\",\"‐\"],[\"a960\",\"ー゛゜ヽヾ〆ゝゞ﹉\",9,\"﹔﹕﹖﹗﹙\",8],[\"a980\",\"﹢\",4,\"﹨﹩﹪﹫\"],[\"a996\",\"〇\"],[\"a9a4\",\"─\",75],[\"aa40\",\"狜狝狟狢\",5,\"狪狫狵狶狹狽狾狿猀猂猄\",5,\"猋猌猍猏猐猑猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽獀\",8],[\"aa80\",\"獉獊獋獌獎獏獑獓獔獕獖獘\",7,\"獡\",10,\"獮獰獱\"],[\"ab40\",\"獲\",11,\"獿\",4,\"玅玆玈玊玌玍玏玐玒玓玔玕玗玘玙玚玜玝玞玠玡玣\",5,\"玪玬玭玱玴玵玶玸玹玼玽玾玿珁珃\",4],[\"ab80\",\"珋珌珎珒\",6,\"珚珛珜珝珟珡珢珣珤珦珨珪珫珬珮珯珰珱珳\",4],[\"ac40\",\"珸\",10,\"琄琇琈琋琌琍琎琑\",8,\"琜\",5,\"琣琤琧琩琫琭琯琱琲琷\",4,\"琽琾琿瑀瑂\",11],[\"ac80\",\"瑎\",6,\"瑖瑘瑝瑠\",12,\"瑮瑯瑱\",4,\"瑸瑹瑺\"],[\"ad40\",\"瑻瑼瑽瑿璂璄璅璆璈璉璊璌璍璏璑\",10,\"璝璟\",7,\"璪\",15,\"璻\",12],[\"ad80\",\"瓈\",9,\"瓓\",8,\"瓝瓟瓡瓥瓧\",6,\"瓰瓱瓲\"],[\"ae40\",\"瓳瓵瓸\",6,\"甀甁甂甃甅\",7,\"甎甐甒甔甕甖甗甛甝甞甠\",4,\"甦甧甪甮甴甶甹甼甽甿畁畂畃畄畆畇畉畊畍畐畑畒畓畕畖畗畘\"],[\"ae80\",\"畝\",7,\"畧畨畩畫\",6,\"畳畵當畷畺\",4,\"疀疁疂疄疅疇\"],[\"af40\",\"疈疉疊疌疍疎疐疓疕疘疛疜疞疢疦\",4,\"疭疶疷疺疻疿痀痁痆痋痌痎痏痐痑痓痗痙痚痜痝痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇\"],[\"af80\",\"瘈瘉瘋瘍瘎瘏瘑瘒瘓瘔瘖瘚瘜瘝瘞瘡瘣瘧瘨瘬瘮瘯瘱瘲瘶瘷瘹瘺瘻瘽癁療癄\"],[\"b040\",\"癅\",6,\"癎\",5,\"癕癗\",4,\"癝癟癠癡癢癤\",6,\"癬癭癮癰\",7,\"癹発發癿皀皁皃皅皉皊皌皍皏皐皒皔皕皗皘皚皛\"],[\"b080\",\"皜\",7,\"皥\",8,\"皯皰皳皵\",9,\"盀盁盃啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥\"],[\"b140\",\"盄盇盉盋盌盓盕盙盚盜盝盞盠\",4,\"盦\",7,\"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎\",10,\"眛眜眝眞眡眣眤眥眧眪眫\"],[\"b180\",\"眬眮眰\",4,\"眹眻眽眾眿睂睄睅睆睈\",7,\"睒\",7,\"睜薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳\"],[\"b240\",\"睝睞睟睠睤睧睩睪睭\",11,\"睺睻睼瞁瞂瞃瞆\",5,\"瞏瞐瞓\",11,\"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶\",4],[\"b280\",\"瞼瞾矀\",12,\"矎\",8,\"矘矙矚矝\",4,\"矤病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖\"],[\"b340\",\"矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃\",5,\"砊砋砎砏砐砓砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿硁硂硃硄硆硈硉硊硋硍硏硑硓硔硘硙硚\"],[\"b380\",\"硛硜硞\",11,\"硯\",7,\"硸硹硺硻硽\",6,\"场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚\"],[\"b440\",\"碄碅碆碈碊碋碏碐碒碔碕碖碙碝碞碠碢碤碦碨\",7,\"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌磍磎磏磑磒磓磖磗磘磚\",9],[\"b480\",\"磤磥磦磧磩磪磫磭\",4,\"磳磵磶磸磹磻\",5,\"礂礃礄礆\",6,\"础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮\"],[\"b540\",\"礍\",5,\"礔\",9,\"礟\",4,\"礥\",14,\"礵\",4,\"礽礿祂祃祄祅祇祊\",8,\"祔祕祘祙祡祣\"],[\"b580\",\"祤祦祩祪祫祬祮祰\",6,\"祹祻\",4,\"禂禃禆禇禈禉禋禌禍禎禐禑禒怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠\"],[\"b640\",\"禓\",6,\"禛\",11,\"禨\",10,\"禴\",4,\"禼禿秂秄秅秇秈秊秌秎秏秐秓秔秖秗秙\",5,\"秠秡秢秥秨秪\"],[\"b680\",\"秬秮秱\",6,\"秹秺秼秾秿稁稄稅稇稈稉稊稌稏\",4,\"稕稖稘稙稛稜丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二\"],[\"b740\",\"稝稟稡稢稤\",14,\"稴稵稶稸稺稾穀\",5,\"穇\",9,\"穒\",4,\"穘\",16],[\"b780\",\"穩\",6,\"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎窏窐窓窔窙窚窛窞窡窢贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服\"],[\"b840\",\"窣窤窧窩窪窫窮\",4,\"窴\",10,\"竀\",10,\"竌\",9,\"竗竘竚竛竜竝竡竢竤竧\",5,\"竮竰竱竲竳\"],[\"b880\",\"竴\",4,\"竻竼竾笀笁笂笅笇笉笌笍笎笐笒笓笖笗笘笚笜笝笟笡笢笣笧笩笭浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹\"],[\"b940\",\"笯笰笲笴笵笶笷笹笻笽笿\",5,\"筆筈筊筍筎筓筕筗筙筜筞筟筡筣\",10,\"筯筰筳筴筶筸筺筼筽筿箁箂箃箄箆\",6,\"箎箏\"],[\"b980\",\"箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹\",7,\"篂篃範埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈\"],[\"ba40\",\"篅篈築篊篋篍篎篏篐篒篔\",4,\"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲\",4,\"篸篹篺篻篽篿\",7,\"簈簉簊簍簎簐\",5,\"簗簘簙\"],[\"ba80\",\"簚\",4,\"簠\",5,\"簨簩簫\",12,\"簹\",5,\"籂骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖\"],[\"bb40\",\"籃\",9,\"籎\",36,\"籵\",5,\"籾\",9],[\"bb80\",\"粈粊\",6,\"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴\",4,\"粺粻弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕\"],[\"bc40\",\"粿糀糂糃糄糆糉糋糎\",6,\"糘糚糛糝糞糡\",6,\"糩\",5,\"糰\",7,\"糹糺糼\",13,\"紋\",5],[\"bc80\",\"紑\",14,\"紡紣紤紥紦紨紩紪紬紭紮細\",6,\"肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件\"],[\"bd40\",\"紷\",54,\"絯\",7],[\"bd80\",\"絸\",32,\"健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸\"],[\"be40\",\"継\",12,\"綧\",6,\"綯\",42],[\"be80\",\"線\",32,\"尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君峻\"],[\"bf40\",\"緻\",62],[\"bf80\",\"縺縼\",4,\"繂\",4,\"繈\",21,\"俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀\"],[\"c040\",\"繞\",35,\"纃\",23,\"纜纝纞\"],[\"c080\",\"纮纴纻纼绖绤绬绹缊缐缞缷缹缻\",6,\"罃罆\",9,\"罒罓馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐\"],[\"c140\",\"罖罙罛罜罝罞罠罣\",4,\"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂\",7,\"羋羍羏\",4,\"羕\",4,\"羛羜羠羢羣羥羦羨\",6,\"羱\"],[\"c180\",\"羳\",4,\"羺羻羾翀翂翃翄翆翇翈翉翋翍翏\",4,\"翖翗翙\",5,\"翢翣痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿\"],[\"c240\",\"翤翧翨翪翫翬翭翯翲翴\",6,\"翽翾翿耂耇耈耉耊耎耏耑耓耚耛耝耞耟耡耣耤耫\",5,\"耲耴耹耺耼耾聀聁聄聅聇聈聉聎聏聐聑聓聕聖聗\"],[\"c280\",\"聙聛\",13,\"聫\",5,\"聲\",11,\"隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫\"],[\"c340\",\"聾肁肂肅肈肊肍\",5,\"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇\",4,\"胏\",6,\"胘胟胠胢胣胦胮胵胷胹胻胾胿脀脁脃脄脅脇脈脋\"],[\"c380\",\"脌脕脗脙脛脜脝脟\",12,\"脭脮脰脳脴脵脷脹\",4,\"脿谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸\"],[\"c440\",\"腀\",5,\"腇腉腍腎腏腒腖腗腘腛\",4,\"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸膁膃\",4,\"膉膋膌膍膎膐膒\",5,\"膙膚膞\",4,\"膤膥\"],[\"c480\",\"膧膩膫\",7,\"膴\",5,\"膼膽膾膿臄臅臇臈臉臋臍\",6,\"摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁\"],[\"c540\",\"臔\",14,\"臤臥臦臨臩臫臮\",4,\"臵\",5,\"臽臿舃與\",4,\"舎舏舑舓舕\",5,\"舝舠舤舥舦舧舩舮舲舺舼舽舿\"],[\"c580\",\"艀艁艂艃艅艆艈艊艌艍艎艐\",7,\"艙艛艜艝艞艠\",7,\"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗\"],[\"c640\",\"艪艫艬艭艱艵艶艷艸艻艼芀芁芃芅芆芇芉芌芐芓芔芕芖芚芛芞芠芢芣芧芲芵芶芺芻芼芿苀苂苃苅苆苉苐苖苙苚苝苢苧苨苩苪苬苭苮苰苲苳苵苶苸\"],[\"c680\",\"苺苼\",4,\"茊茋茍茐茒茓茖茘茙茝\",9,\"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐\"],[\"c740\",\"茾茿荁荂荄荅荈荊\",4,\"荓荕\",4,\"荝荢荰\",6,\"荹荺荾\",6,\"莇莈莊莋莌莍莏莐莑莔莕莖莗莙莚莝莟莡\",6,\"莬莭莮\"],[\"c780\",\"莯莵莻莾莿菂菃菄菆菈菉菋菍菎菐菑菒菓菕菗菙菚菛菞菢菣菤菦菧菨菫菬菭恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠\"],[\"c840\",\"菮華菳\",4,\"菺菻菼菾菿萀萂萅萇萈萉萊萐萒\",5,\"萙萚萛萞\",5,\"萩\",7,\"萲\",5,\"萹萺萻萾\",7,\"葇葈葉\"],[\"c880\",\"葊\",6,\"葒\",4,\"葘葝葞葟葠葢葤\",4,\"葪葮葯葰葲葴葷葹葻葼取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁\"],[\"c940\",\"葽\",4,\"蒃蒄蒅蒆蒊蒍蒏\",7,\"蒘蒚蒛蒝蒞蒟蒠蒢\",12,\"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎蓏蓒蓔蓕蓗\"],[\"c980\",\"蓘\",4,\"蓞蓡蓢蓤蓧\",4,\"蓭蓮蓯蓱\",10,\"蓽蓾蔀蔁蔂伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳\"],[\"ca40\",\"蔃\",8,\"蔍蔎蔏蔐蔒蔔蔕蔖蔘蔙蔛蔜蔝蔞蔠蔢\",8,\"蔭\",9,\"蔾\",4,\"蕄蕅蕆蕇蕋\",10],[\"ca80\",\"蕗蕘蕚蕛蕜蕝蕟\",4,\"蕥蕦蕧蕩\",8,\"蕳蕵蕶蕷蕸蕼蕽蕿薀薁省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱\"],[\"cb40\",\"薂薃薆薈\",6,\"薐\",10,\"薝\",6,\"薥薦薧薩薫薬薭薱\",5,\"薸薺\",6,\"藂\",6,\"藊\",4,\"藑藒\"],[\"cb80\",\"藔藖\",5,\"藝\",6,\"藥藦藧藨藪\",14,\"恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔\"],[\"cc40\",\"藹藺藼藽藾蘀\",4,\"蘆\",10,\"蘒蘓蘔蘕蘗\",15,\"蘨蘪\",13,\"蘹蘺蘻蘽蘾蘿虀\"],[\"cc80\",\"虁\",11,\"虒虓處\",4,\"虛虜虝號虠虡虣\",7,\"獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃\"],[\"cd40\",\"虭虯虰虲\",6,\"蚃\",6,\"蚎\",4,\"蚔蚖\",5,\"蚞\",4,\"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻\",4,\"蛁蛂蛃蛅蛈蛌蛍蛒蛓蛕蛖蛗蛚蛜\"],[\"cd80\",\"蛝蛠蛡蛢蛣蛥蛦蛧蛨蛪蛫蛬蛯蛵蛶蛷蛺蛻蛼蛽蛿蜁蜄蜅蜆蜋蜌蜎蜏蜐蜑蜔蜖汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威\"],[\"ce40\",\"蜙蜛蜝蜟蜠蜤蜦蜧蜨蜪蜫蜬蜭蜯蜰蜲蜳蜵蜶蜸蜹蜺蜼蜽蝀\",6,\"蝊蝋蝍蝏蝐蝑蝒蝔蝕蝖蝘蝚\",5,\"蝡蝢蝦\",7,\"蝯蝱蝲蝳蝵\"],[\"ce80\",\"蝷蝸蝹蝺蝿螀螁螄螆螇螉螊螌螎\",4,\"螔螕螖螘\",6,\"螠\",4,\"巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺\"],[\"cf40\",\"螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿蟁\",4,\"蟇蟈蟉蟌\",4,\"蟔\",6,\"蟜蟝蟞蟟蟡蟢蟣蟤蟦蟧蟨蟩蟫蟬蟭蟯\",9],[\"cf80\",\"蟺蟻蟼蟽蟿蠀蠁蠂蠄\",5,\"蠋\",7,\"蠔蠗蠘蠙蠚蠜\",4,\"蠣稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓\"],[\"d040\",\"蠤\",13,\"蠳\",5,\"蠺蠻蠽蠾蠿衁衂衃衆\",5,\"衎\",5,\"衕衖衘衚\",6,\"衦衧衪衭衯衱衳衴衵衶衸衹衺\"],[\"d080\",\"衻衼袀袃袆袇袉袊袌袎袏袐袑袓袔袕袗\",4,\"袝\",4,\"袣袥\",5,\"小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄\"],[\"d140\",\"袬袮袯袰袲\",4,\"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌裍裏裐裑裓裖裗裚\",4,\"裠裡裦裧裩\",6,\"裲裵裶裷裺裻製裿褀褁褃\",5],[\"d180\",\"褉褋\",4,\"褑褔\",4,\"褜\",4,\"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶\"],[\"d240\",\"褸\",8,\"襂襃襅\",24,\"襠\",5,\"襧\",19,\"襼\"],[\"d280\",\"襽襾覀覂覄覅覇\",26,\"摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐\"],[\"d340\",\"覢\",30,\"觃觍觓觔觕觗觘觙觛觝觟觠觡觢觤觧觨觩觪觬觭觮觰觱觲觴\",6],[\"d380\",\"觻\",4,\"訁\",5,\"計\",21,\"印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉\"],[\"d440\",\"訞\",31,\"訿\",8,\"詉\",21],[\"d480\",\"詟\",25,\"詺\",6,\"浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧\"],[\"d540\",\"誁\",7,\"誋\",7,\"誔\",46],[\"d580\",\"諃\",32,\"铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政\"],[\"d640\",\"諤\",34,\"謈\",27],[\"d680\",\"謤謥謧\",30,\"帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑\"],[\"d740\",\"譆\",31,\"譧\",4,\"譭\",25],[\"d780\",\"讇\",24,\"讬讱讻诇诐诪谉谞住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座\"],[\"d840\",\"谸\",8,\"豂豃豄豅豈豊豋豍\",7,\"豖豗豘豙豛\",5,\"豣\",6,\"豬\",6,\"豴豵豶豷豻\",6,\"貃貄貆貇\"],[\"d880\",\"貈貋貍\",6,\"貕貖貗貙\",20,\"亍丌兀丐廿卅丕亘丞鬲孬噩丨禺丿匕乇夭爻卮氐囟胤馗毓睾鼗丶亟鼐乜乩亓芈孛啬嘏仄厍厝厣厥厮靥赝匚叵匦匮匾赜卦卣刂刈刎刭刳刿剀剌剞剡剜蒯剽劂劁劐劓冂罔亻仃仉仂仨仡仫仞伛仳伢佤仵伥伧伉伫佞佧攸佚佝\"],[\"d940\",\"貮\",62],[\"d980\",\"賭\",32,\"佟佗伲伽佶佴侑侉侃侏佾佻侪佼侬侔俦俨俪俅俚俣俜俑俟俸倩偌俳倬倏倮倭俾倜倌倥倨偾偃偕偈偎偬偻傥傧傩傺僖儆僭僬僦僮儇儋仝氽佘佥俎龠汆籴兮巽黉馘冁夔勹匍訇匐凫夙兕亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼\"],[\"da40\",\"贎\",14,\"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸\",8,\"趂趃趆趇趈趉趌\",4,\"趒趓趕\",9,\"趠趡\"],[\"da80\",\"趢趤\",12,\"趲趶趷趹趻趽跀跁跂跅跇跈跉跊跍跐跒跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋诏诎诒诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌谏谑谒谔谕谖谙谛谘谝谟谠谡谥谧谪谫谮谯谲谳谵谶卩卺阝阢阡阱阪阽阼陂陉陔陟陧陬陲陴隈隍隗隰邗邛邝邙邬邡邴邳邶邺\"],[\"db40\",\"跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾\",6,\"踆踇踈踋踍踎踐踑踒踓踕\",7,\"踠踡踤\",4,\"踫踭踰踲踳踴踶踷踸踻踼踾\"],[\"db80\",\"踿蹃蹅蹆蹌\",4,\"蹓\",5,\"蹚\",11,\"蹧蹨蹪蹫蹮蹱邸邰郏郅邾郐郄郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆刍奂劢劬劭劾哿勐勖勰叟燮矍廴凵凼鬯厶弁畚巯坌垩垡塾墼壅壑圩圬圪圳圹圮圯坜圻坂坩垅坫垆坼坻坨坭坶坳垭垤垌垲埏垧垴垓垠埕埘埚埙埒垸埴埯埸埤埝\"],[\"dc40\",\"蹳蹵蹷\",4,\"蹽蹾躀躂躃躄躆躈\",6,\"躑躒躓躕\",6,\"躝躟\",11,\"躭躮躰躱躳\",6,\"躻\",7],[\"dc80\",\"軃\",10,\"軏\",21,\"堋堍埽埭堀堞堙塄堠塥塬墁墉墚墀馨鼙懿艹艽艿芏芊芨芄芎芑芗芙芫芸芾芰苈苊苣芘芷芮苋苌苁芩芴芡芪芟苄苎芤苡茉苷苤茏茇苜苴苒苘茌苻苓茑茚茆茔茕苠苕茜荑荛荜茈莒茼茴茱莛荞茯荏荇荃荟荀茗荠茭茺茳荦荥\"],[\"dd40\",\"軥\",62],[\"dd80\",\"輤\",32,\"荨茛荩荬荪荭荮莰荸莳莴莠莪莓莜莅荼莶莩荽莸荻莘莞莨莺莼菁萁菥菘堇萘萋菝菽菖萜萸萑萆菔菟萏萃菸菹菪菅菀萦菰菡葜葑葚葙葳蒇蒈葺蒉葸萼葆葩葶蒌蒎萱葭蓁蓍蓐蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌甍蔸蓰蔹蔟蔺\"],[\"de40\",\"轅\",32,\"轪辀辌辒辝辠辡辢辤辥辦辧辪辬辭辮辯農辳辴辵辷辸辺辻込辿迀迃迆\"],[\"de80\",\"迉\",4,\"迏迒迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇薏蕹薮薜薅薹薷薰藓藁藜藿蘧蘅蘩蘖蘼廾弈夼奁耷奕奚奘匏尢尥尬尴扌扪抟抻拊拚拗拮挢拶挹捋捃掭揶捱捺掎掴捭掬掊捩掮掼揲揸揠揿揄揞揎摒揆掾摅摁搋搛搠搌搦搡摞撄摭撖\"],[\"df40\",\"這逜連逤逥逧\",5,\"逰\",4,\"逷逹逺逽逿遀遃遅遆遈\",4,\"過達違遖遙遚遜\",5,\"遤遦遧適遪遫遬遯\",4,\"遶\",6,\"遾邁\"],[\"df80\",\"還邅邆邇邉邊邌\",4,\"邒邔邖邘邚邜邞邟邠邤邥邧邨邩邫邭邲邷邼邽邿郀摺撷撸撙撺擀擐擗擤擢攉攥攮弋忒甙弑卟叱叽叩叨叻吒吖吆呋呒呓呔呖呃吡呗呙吣吲咂咔呷呱呤咚咛咄呶呦咝哐咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤哝哏哞唛哧唠哽唔哳唢唣唏唑唧唪啧喏喵啉啭啁啕唿啐唼\"],[\"e040\",\"郂郃郆郈郉郋郌郍郒郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀鄁鄃鄅\",19,\"鄚鄛鄜\"],[\"e080\",\"鄝鄟鄠鄡鄤\",10,\"鄰鄲\",6,\"鄺\",8,\"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈喁喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦嗝嗄嗯嗥嗲嗳嗌嗍嗨嗵嗤辔嘞嘈嘌嘁嘤嘣嗾嘀嘧嘭噘嘹噗嘬噍噢噙噜噌噔嚆噤噱噫噻噼嚅嚓嚯囔囗囝囡囵囫囹囿圄圊圉圜帏帙帔帑帱帻帼\"],[\"e140\",\"酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀\",4,\"醆醈醊醎醏醓\",6,\"醜\",5,\"醤\",5,\"醫醬醰醱醲醳醶醷醸醹醻\"],[\"e180\",\"醼\",10,\"釈釋釐釒\",9,\"針\",8,\"帷幄幔幛幞幡岌屺岍岐岖岈岘岙岑岚岜岵岢岽岬岫岱岣峁岷峄峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯嵝嵫嵋嵊嵩嵴嶂嶙嶝豳嶷巅彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃狁狎狍狒狨狯狩狲狴狷猁狳猃狺\"],[\"e240\",\"釦\",62],[\"e280\",\"鈥\",32,\"狻猗猓猡猊猞猝猕猢猹猥猬猸猱獐獍獗獠獬獯獾舛夥飧夤夂饣饧\",5,\"饴饷饽馀馄馇馊馍馐馑馓馔馕庀庑庋庖庥庠庹庵庾庳赓廒廑廛廨廪膺忄忉忖忏怃忮怄忡忤忾怅怆忪忭忸怙怵怦怛怏怍怩怫怊怿怡恸恹恻恺恂\"],[\"e340\",\"鉆\",45,\"鉵\",16],[\"e380\",\"銆\",7,\"銏\",24,\"恪恽悖悚悭悝悃悒悌悛惬悻悱惝惘惆惚悴愠愦愕愣惴愀愎愫慊慵憬憔憧憷懔懵忝隳闩闫闱闳闵闶闼闾阃阄阆阈阊阋阌阍阏阒阕阖阗阙阚丬爿戕氵汔汜汊沣沅沐沔沌汨汩汴汶沆沩泐泔沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾\"],[\"e440\",\"銨\",5,\"銯\",24,\"鋉\",31],[\"e480\",\"鋩\",32,\"洹洧洌浃浈洇洄洙洎洫浍洮洵洚浏浒浔洳涑浯涞涠浞涓涔浜浠浼浣渚淇淅淞渎涿淠渑淦淝淙渖涫渌涮渫湮湎湫溲湟溆湓湔渲渥湄滟溱溘滠漭滢溥溧溽溻溷滗溴滏溏滂溟潢潆潇漤漕滹漯漶潋潴漪漉漩澉澍澌潸潲潼潺濑\"],[\"e540\",\"錊\",51,\"錿\",10],[\"e580\",\"鍊\",31,\"鍫濉澧澹澶濂濡濮濞濠濯瀚瀣瀛瀹瀵灏灞宀宄宕宓宥宸甯骞搴寤寮褰寰蹇謇辶迓迕迥迮迤迩迦迳迨逅逄逋逦逑逍逖逡逵逶逭逯遄遑遒遐遨遘遢遛暹遴遽邂邈邃邋彐彗彖彘尻咫屐屙孱屣屦羼弪弩弭艴弼鬻屮妁妃妍妩妪妣\"],[\"e640\",\"鍬\",34,\"鎐\",27],[\"e680\",\"鎬\",29,\"鏋鏌鏍妗姊妫妞妤姒妲妯姗妾娅娆姝娈姣姘姹娌娉娲娴娑娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀骁骅骈骊骐骒骓骖骘骛骜骝骟骠骢骣骥骧纟纡纣纥纨纩\"],[\"e740\",\"鏎\",7,\"鏗\",54],[\"e780\",\"鐎\",32,\"纭纰纾绀绁绂绉绋绌绐绔绗绛绠绡绨绫绮绯绱绲缍绶绺绻绾缁缂缃缇缈缋缌缏缑缒缗缙缜缛缟缡\",6,\"缪缫缬缭缯\",4,\"缵幺畿巛甾邕玎玑玮玢玟珏珂珑玷玳珀珉珈珥珙顼琊珩珧珞玺珲琏琪瑛琦琥琨琰琮琬\"],[\"e840\",\"鐯\",14,\"鐿\",43,\"鑬鑭鑮鑯\"],[\"e880\",\"鑰\",20,\"钑钖钘铇铏铓铔铚铦铻锜锠琛琚瑁瑜瑗瑕瑙瑷瑭瑾璜璎璀璁璇璋璞璨璩璐璧瓒璺韪韫韬杌杓杞杈杩枥枇杪杳枘枧杵枨枞枭枋杷杼柰栉柘栊柩枰栌柙枵柚枳柝栀柃枸柢栎柁柽栲栳桠桡桎桢桄桤梃栝桕桦桁桧桀栾桊桉栩梵梏桴桷梓桫棂楮棼椟椠棹\"],[\"e940\",\"锧锳锽镃镈镋镕镚镠镮镴镵長\",7,\"門\",42],[\"e980\",\"閫\",32,\"椤棰椋椁楗棣椐楱椹楠楂楝榄楫榀榘楸椴槌榇榈槎榉楦楣楹榛榧榻榫榭槔榱槁槊槟榕槠榍槿樯槭樗樘橥槲橄樾檠橐橛樵檎橹樽樨橘橼檑檐檩檗檫猷獒殁殂殇殄殒殓殍殚殛殡殪轫轭轱轲轳轵轶轸轷轹轺轼轾辁辂辄辇辋\"],[\"ea40\",\"闌\",27,\"闬闿阇阓阘阛阞阠阣\",6,\"阫阬阭阯阰阷阸阹阺阾陁陃陊陎陏陑陒陓陖陗\"],[\"ea80\",\"陘陙陚陜陝陞陠陣陥陦陫陭\",4,\"陳陸\",12,\"隇隉隊辍辎辏辘辚軎戋戗戛戟戢戡戥戤戬臧瓯瓴瓿甏甑甓攴旮旯旰昊昙杲昃昕昀炅曷昝昴昱昶昵耆晟晔晁晏晖晡晗晷暄暌暧暝暾曛曜曦曩贲贳贶贻贽赀赅赆赈赉赇赍赕赙觇觊觋觌觎觏觐觑牮犟牝牦牯牾牿犄犋犍犏犒挈挲掰\"],[\"eb40\",\"隌階隑隒隓隕隖隚際隝\",9,\"隨\",7,\"隱隲隴隵隷隸隺隻隿雂雃雈雊雋雐雑雓雔雖\",9,\"雡\",6,\"雫\"],[\"eb80\",\"雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌霐霑霒霔霕霗\",4,\"霝霟霠搿擘耄毪毳毽毵毹氅氇氆氍氕氘氙氚氡氩氤氪氲攵敕敫牍牒牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙胍胗朐胝胫胱胴胭脍脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧塍媵膈膂膑滕膣膪臌朦臊膻\"],[\"ec40\",\"霡\",8,\"霫霬霮霯霱霳\",4,\"霺霻霼霽霿\",18,\"靔靕靗靘靚靜靝靟靣靤靦靧靨靪\",7],[\"ec80\",\"靲靵靷\",4,\"靽\",7,\"鞆\",4,\"鞌鞎鞏鞐鞓鞕鞖鞗鞙\",4,\"臁膦欤欷欹歃歆歙飑飒飓飕飙飚殳彀毂觳斐齑斓於旆旄旃旌旎旒旖炀炜炖炝炻烀炷炫炱烨烊焐焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹爝爨灬焘煦熹戾戽扃扈扉礻祀祆祉祛祜祓祚祢祗祠祯祧祺禅禊禚禧禳忑忐\"],[\"ed40\",\"鞞鞟鞡鞢鞤\",6,\"鞬鞮鞰鞱鞳鞵\",46],[\"ed80\",\"韤韥韨韮\",4,\"韴韷\",23,\"怼恝恚恧恁恙恣悫愆愍慝憩憝懋懑戆肀聿沓泶淼矶矸砀砉砗砘砑斫砭砜砝砹砺砻砟砼砥砬砣砩硎硭硖硗砦硐硇硌硪碛碓碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄眍盹眇眈眚眢眙眭眦眵眸睐睑睇睃睚睨\"],[\"ee40\",\"頏\",62],[\"ee80\",\"顎\",32,\"睢睥睿瞍睽瞀瞌瞑瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹羁罾盍盥蠲钅钆钇钋钊钌钍钏钐钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶\",4,\"钼钽钿铄铈\",6,\"铐铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪\"],[\"ef40\",\"顯\",5,\"颋颎颒颕颙颣風\",37,\"飏飐飔飖飗飛飜飝飠\",4],[\"ef80\",\"飥飦飩\",30,\"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊锍锎锏锒\",4,\"锘锛锝锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎镏镒镓镔镖镗镘镙镛镞镟镝镡镢镤\",8,\"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔\"],[\"f040\",\"餈\",4,\"餎餏餑\",28,\"餯\",26],[\"f080\",\"饊\",9,\"饖\",12,\"饤饦饳饸饹饻饾馂馃馉稹稷穑黏馥穰皈皎皓皙皤瓞瓠甬鸠鸢鸨\",4,\"鸲鸱鸶鸸鸷鸹鸺鸾鹁鹂鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦\",6,\"鹱鹭鹳疒疔疖疠疝疬疣疳疴疸痄疱疰痃痂痖痍痣痨痦痤痫痧瘃痱痼痿瘐瘀瘅瘌瘗瘊瘥瘘瘕瘙\"],[\"f140\",\"馌馎馚\",10,\"馦馧馩\",47],[\"f180\",\"駙\",32,\"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳癍癞癔癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶襁襦襻疋胥皲皴矜耒耔耖耜耠耢耥耦耧耩耨耱耋耵聃聆聍聒聩聱覃顸颀颃\"],[\"f240\",\"駺\",62],[\"f280\",\"騹\",32,\"颉颌颍颏颔颚颛颞颟颡颢颥颦虍虔虬虮虿虺虼虻蚨蚍蚋蚬蚝蚧蚣蚪蚓蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉蛏蚴蛩蛱蛲蛭蛳蛐蜓蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊蜍蜉蜣蜻蜞蜥蜮蜚蜾蝈蜴蜱蜩蜷蜿螂蜢蝽蝾蝻蝠蝰蝌蝮螋蝓蝣蝼蝤蝙蝥螓螯螨蟒\"],[\"f340\",\"驚\",17,\"驲骃骉骍骎骔骕骙骦骩\",6,\"骲骳骴骵骹骻骽骾骿髃髄髆\",4,\"髍髎髏髐髒體髕髖髗髙髚髛髜\"],[\"f380\",\"髝髞髠髢髣髤髥髧髨髩髪髬髮髰\",8,\"髺髼\",6,\"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅舐竺竽笈笃笄笕笊笫笏筇笸笪笙笮笱笠笥笤笳笾笞筘筚筅筵筌筝筠筮筻筢筲筱箐箦箧箸箬箝箨箅箪箜箢箫箴篑篁篌篝篚篥篦篪簌篾篼簏簖簋\"],[\"f440\",\"鬇鬉\",5,\"鬐鬑鬒鬔\",10,\"鬠鬡鬢鬤\",10,\"鬰鬱鬳\",7,\"鬽鬾鬿魀魆魊魋魌魎魐魒魓魕\",5],[\"f480\",\"魛\",32,\"簟簪簦簸籁籀臾舁舂舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋艏艚艟艨衾袅袈裘裟襞羝羟羧羯羰羲籼敉粑粝粜粞粢粲粼粽糁糇糌糍糈糅糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊酐酎酏酤\"],[\"f540\",\"魼\",62],[\"f580\",\"鮻\",32,\"酢酡酰酩酯酽酾酲酴酹醌醅醐醍醑醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎跏跛跆跬跷跸跣跹跻跤踉跽踔踝踟踬踮踣踯踺蹀踹踵踽踱蹉蹁蹂蹑蹒蹊蹰蹶蹼蹯蹴躅躏躔躐躜躞豸貂貊貅貘貔斛觖觞觚觜\"],[\"f640\",\"鯜\",62],[\"f680\",\"鰛\",32,\"觥觫觯訾謦靓雩雳雯霆霁霈霏霎霪霭霰霾龀龃龅\",5,\"龌黾鼋鼍隹隼隽雎雒瞿雠銎銮鋈錾鍪鏊鎏鐾鑫鱿鲂鲅鲆鲇鲈稣鲋鲎鲐鲑鲒鲔鲕鲚鲛鲞\",5,\"鲥\",4,\"鲫鲭鲮鲰\",7,\"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋\"],[\"f740\",\"鰼\",62],[\"f780\",\"鱻鱽鱾鲀鲃鲄鲉鲊鲌鲏鲓鲖鲗鲘鲙鲝鲪鲬鲯鲹鲾\",4,\"鳈鳉鳑鳒鳚鳛鳠鳡鳌\",4,\"鳓鳔鳕鳗鳘鳙鳜鳝鳟鳢靼鞅鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼髁髀髅髂髋髌髑魅魃魇魉魈魍魑飨餍餮饕饔髟髡髦髯髫髻髭髹鬈鬏鬓鬟鬣麽麾縻麂麇麈麋麒鏖麝麟黛黜黝黠黟黢黩黧黥黪黯鼢鼬鼯鼹鼷鼽鼾齄\"],[\"f840\",\"鳣\",62],[\"f880\",\"鴢\",32],[\"f940\",\"鵃\",62],[\"f980\",\"鶂\",32],[\"fa40\",\"鶣\",62],[\"fa80\",\"鷢\",32],[\"fb40\",\"鸃\",27,\"鸤鸧鸮鸰鸴鸻鸼鹀鹍鹐鹒鹓鹔鹖鹙鹝鹟鹠鹡鹢鹥鹮鹯鹲鹴\",9,\"麀\"],[\"fb80\",\"麁麃麄麅麆麉麊麌\",5,\"麔\",8,\"麞麠\",5,\"麧麨麩麪\"],[\"fc40\",\"麫\",8,\"麵麶麷麹麺麼麿\",4,\"黅黆黇黈黊黋黌黐黒黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰\",8,\"黺黽黿\",6],[\"fc80\",\"鼆\",4,\"鼌鼏鼑鼒鼔鼕鼖鼘鼚\",5,\"鼡鼣\",8,\"鼭鼮鼰鼱\"],[\"fd40\",\"鼲\",4,\"鼸鼺鼼鼿\",4,\"齅\",10,\"齒\",38],[\"fd80\",\"齹\",5,\"龁龂龍\",11,\"龜龝龞龡\",4,\"郎凉秊裏隣\"],[\"fe40\",\"兀嗀﨎﨏﨑﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩\"]]");

const require$$3$1 = [
	[
		"a140",
		"",
		62
	],
	[
		"a180",
		"",
		32
	],
	[
		"a240",
		"",
		62
	],
	[
		"a280",
		"",
		32
	],
	[
		"a2ab",
		"",
		5
	],
	[
		"a2e3",
		"€"
	],
	[
		"a2ef",
		""
	],
	[
		"a2fd",
		""
	],
	[
		"a340",
		"",
		62
	],
	[
		"a380",
		"",
		31,
		"　"
	],
	[
		"a440",
		"",
		62
	],
	[
		"a480",
		"",
		32
	],
	[
		"a4f4",
		"",
		10
	],
	[
		"a540",
		"",
		62
	],
	[
		"a580",
		"",
		32
	],
	[
		"a5f7",
		"",
		7
	],
	[
		"a640",
		"",
		62
	],
	[
		"a680",
		"",
		32
	],
	[
		"a6b9",
		"",
		7
	],
	[
		"a6d9",
		"",
		6
	],
	[
		"a6ec",
		""
	],
	[
		"a6f3",
		""
	],
	[
		"a6f6",
		"",
		8
	],
	[
		"a740",
		"",
		62
	],
	[
		"a780",
		"",
		32
	],
	[
		"a7c2",
		"",
		14
	],
	[
		"a7f2",
		"",
		12
	],
	[
		"a896",
		"",
		10
	],
	[
		"a8bc",
		""
	],
	[
		"a8bf",
		"ǹ"
	],
	[
		"a8c1",
		""
	],
	[
		"a8ea",
		"",
		20
	],
	[
		"a958",
		""
	],
	[
		"a95b",
		""
	],
	[
		"a95d",
		""
	],
	[
		"a989",
		"〾⿰",
		11
	],
	[
		"a997",
		"",
		12
	],
	[
		"a9f0",
		"",
		14
	],
	[
		"aaa1",
		"",
		93
	],
	[
		"aba1",
		"",
		93
	],
	[
		"aca1",
		"",
		93
	],
	[
		"ada1",
		"",
		93
	],
	[
		"aea1",
		"",
		93
	],
	[
		"afa1",
		"",
		93
	],
	[
		"d7fa",
		"",
		4
	],
	[
		"f8a1",
		"",
		93
	],
	[
		"f9a1",
		"",
		93
	],
	[
		"faa1",
		"",
		93
	],
	[
		"fba1",
		"",
		93
	],
	[
		"fca1",
		"",
		93
	],
	[
		"fda1",
		"",
		93
	],
	[
		"fe50",
		"⺁⺄㑳㑇⺈⺋㖞㘚㘎⺌⺗㥮㤘㧏㧟㩳㧐㭎㱮㳠⺧⺪䁖䅟⺮䌷⺳⺶⺷䎱䎬⺻䏝䓖䙡䙌"
	],
	[
		"fe80",
		"䜣䜩䝼䞍⻊䥇䥺䥽䦂䦃䦅䦆䦟䦛䦷䦶䲣䲟䲠䲡䱷䲢䴓",
		6,
		"䶮",
		93
	]
];

const uChars = [128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536];
const gbChars = [0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000];
const require$$4$1 = {
  uChars,
  gbChars,
};

const require$$5 = /* #__PURE__ */ JSON.parse("[[\"0\",\"\\u0000\",127],[\"8141\",\"갂갃갅갆갋\",4,\"갘갞갟갡갢갣갥\",6,\"갮갲갳갴\"],[\"8161\",\"갵갶갷갺갻갽갾갿걁\",9,\"걌걎\",5,\"걕\"],[\"8181\",\"걖걗걙걚걛걝\",18,\"걲걳걵걶걹걻\",4,\"겂겇겈겍겎겏겑겒겓겕\",6,\"겞겢\",5,\"겫겭겮겱\",6,\"겺겾겿곀곂곃곅곆곇곉곊곋곍\",7,\"곖곘\",7,\"곢곣곥곦곩곫곭곮곲곴곷\",4,\"곾곿괁괂괃괅괇\",4,\"괎괐괒괓\"],[\"8241\",\"괔괕괖괗괙괚괛괝괞괟괡\",7,\"괪괫괮\",5],[\"8261\",\"괶괷괹괺괻괽\",6,\"굆굈굊\",5,\"굑굒굓굕굖굗\"],[\"8281\",\"굙\",7,\"굢굤\",7,\"굮굯굱굲굷굸굹굺굾궀궃\",4,\"궊궋궍궎궏궑\",10,\"궞\",5,\"궥\",17,\"궸\",7,\"귂귃귅귆귇귉\",6,\"귒귔\",7,\"귝귞귟귡귢귣귥\",18],[\"8341\",\"귺귻귽귾긂\",5,\"긊긌긎\",5,\"긕\",7],[\"8361\",\"긝\",18,\"긲긳긵긶긹긻긼\"],[\"8381\",\"긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗\",4,\"깞깢깣깤깦깧깪깫깭깮깯깱\",6,\"깺깾\",5,\"꺆\",5,\"꺍\",46,\"꺿껁껂껃껅\",6,\"껎껒\",5,\"껚껛껝\",8],[\"8441\",\"껦껧껩껪껬껮\",5,\"껵껶껷껹껺껻껽\",8],[\"8461\",\"꼆꼉꼊꼋꼌꼎꼏꼑\",18],[\"8481\",\"꼤\",7,\"꼮꼯꼱꼳꼵\",6,\"꼾꽀꽄꽅꽆꽇꽊\",5,\"꽑\",10,\"꽞\",5,\"꽦\",18,\"꽺\",5,\"꾁꾂꾃꾅꾆꾇꾉\",6,\"꾒꾓꾔꾖\",5,\"꾝\",26,\"꾺꾻꾽꾾\"],[\"8541\",\"꾿꿁\",5,\"꿊꿌꿏\",4,\"꿕\",6,\"꿝\",4],[\"8561\",\"꿢\",5,\"꿪\",5,\"꿲꿳꿵꿶꿷꿹\",6,\"뀂뀃\"],[\"8581\",\"뀅\",6,\"뀍뀎뀏뀑뀒뀓뀕\",6,\"뀞\",9,\"뀩\",26,\"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞\",29,\"끾끿낁낂낃낅\",6,\"낎낐낒\",5,\"낛낝낞낣낤\"],[\"8641\",\"낥낦낧낪낰낲낶낷낹낺낻낽\",6,\"냆냊\",5,\"냒\"],[\"8661\",\"냓냕냖냗냙\",6,\"냡냢냣냤냦\",10],[\"8681\",\"냱\",22,\"넊넍넎넏넑넔넕넖넗넚넞\",4,\"넦넧넩넪넫넭\",6,\"넶넺\",5,\"녂녃녅녆녇녉\",6,\"녒녓녖녗녙녚녛녝녞녟녡\",22,\"녺녻녽녾녿놁놃\",4,\"놊놌놎놏놐놑놕놖놗놙놚놛놝\"],[\"8741\",\"놞\",9,\"놩\",15],[\"8761\",\"놹\",18,\"뇍뇎뇏뇑뇒뇓뇕\"],[\"8781\",\"뇖\",5,\"뇞뇠\",7,\"뇪뇫뇭뇮뇯뇱\",7,\"뇺뇼뇾\",5,\"눆눇눉눊눍\",6,\"눖눘눚\",5,\"눡\",18,\"눵\",6,\"눽\",26,\"뉙뉚뉛뉝뉞뉟뉡\",6,\"뉪\",4],[\"8841\",\"뉯\",4,\"뉶\",5,\"뉽\",6,\"늆늇늈늊\",4],[\"8861\",\"늏늒늓늕늖늗늛\",4,\"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷\"],[\"8881\",\"늸\",15,\"닊닋닍닎닏닑닓\",4,\"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉\",6,\"댒댖\",5,\"댝\",54,\"덗덙덚덝덠덡덢덣\"],[\"8941\",\"덦덨덪덬덭덯덲덳덵덶덷덹\",6,\"뎂뎆\",5,\"뎍\"],[\"8961\",\"뎎뎏뎑뎒뎓뎕\",10,\"뎢\",5,\"뎩뎪뎫뎭\"],[\"8981\",\"뎮\",21,\"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩\",18,\"돽\",18,\"됑\",6,\"됙됚됛됝됞됟됡\",6,\"됪됬\",7,\"됵\",15],[\"8a41\",\"둅\",10,\"둒둓둕둖둗둙\",6,\"둢둤둦\"],[\"8a61\",\"둧\",4,\"둭\",18,\"뒁뒂\"],[\"8a81\",\"뒃\",4,\"뒉\",19,\"뒞\",5,\"뒥뒦뒧뒩뒪뒫뒭\",7,\"뒶뒸뒺\",5,\"듁듂듃듅듆듇듉\",6,\"듑듒듓듔듖\",5,\"듞듟듡듢듥듧\",4,\"듮듰듲\",5,\"듹\",26,\"딖딗딙딚딝\"],[\"8b41\",\"딞\",5,\"딦딫\",4,\"딲딳딵딶딷딹\",6,\"땂땆\"],[\"8b61\",\"땇땈땉땊땎땏땑땒땓땕\",6,\"땞땢\",8],[\"8b81\",\"땫\",52,\"떢떣떥떦떧떩떬떭떮떯떲떶\",4,\"떾떿뗁뗂뗃뗅\",6,\"뗎뗒\",5,\"뗙\",18,\"뗭\",18],[\"8c41\",\"똀\",15,\"똒똓똕똖똗똙\",4],[\"8c61\",\"똞\",6,\"똦\",5,\"똭\",6,\"똵\",5],[\"8c81\",\"똻\",12,\"뙉\",26,\"뙥뙦뙧뙩\",50,\"뚞뚟뚡뚢뚣뚥\",5,\"뚭뚮뚯뚰뚲\",16],[\"8d41\",\"뛃\",16,\"뛕\",8],[\"8d61\",\"뛞\",17,\"뛱뛲뛳뛵뛶뛷뛹뛺\"],[\"8d81\",\"뛻\",4,\"뜂뜃뜄뜆\",33,\"뜪뜫뜭뜮뜱\",6,\"뜺뜼\",7,\"띅띆띇띉띊띋띍\",6,\"띖\",9,\"띡띢띣띥띦띧띩\",6,\"띲띴띶\",5,\"띾띿랁랂랃랅\",6,\"랎랓랔랕랚랛랝랞\"],[\"8e41\",\"랟랡\",6,\"랪랮\",5,\"랶랷랹\",8],[\"8e61\",\"럂\",4,\"럈럊\",19],[\"8e81\",\"럞\",13,\"럮럯럱럲럳럵\",6,\"럾렂\",4,\"렊렋렍렎렏렑\",6,\"렚렜렞\",5,\"렦렧렩렪렫렭\",6,\"렶렺\",5,\"롁롂롃롅\",11,\"롒롔\",7,\"롞롟롡롢롣롥\",6,\"롮롰롲\",5,\"롹롺롻롽\",7],[\"8f41\",\"뢅\",7,\"뢎\",17],[\"8f61\",\"뢠\",7,\"뢩\",6,\"뢱뢲뢳뢵뢶뢷뢹\",4],[\"8f81\",\"뢾뢿룂룄룆\",5,\"룍룎룏룑룒룓룕\",7,\"룞룠룢\",5,\"룪룫룭룮룯룱\",6,\"룺룼룾\",5,\"뤅\",18,\"뤙\",6,\"뤡\",26,\"뤾뤿륁륂륃륅\",6,\"륍륎륐륒\",5],[\"9041\",\"륚륛륝륞륟륡\",6,\"륪륬륮\",5,\"륶륷륹륺륻륽\"],[\"9061\",\"륾\",5,\"릆릈릋릌릏\",15],[\"9081\",\"릟\",12,\"릮릯릱릲릳릵\",6,\"릾맀맂\",5,\"맊맋맍맓\",4,\"맚맜맟맠맢맦맧맩맪맫맭\",6,\"맶맻\",4,\"먂\",5,\"먉\",11,\"먖\",33,\"먺먻먽먾먿멁멃멄멅멆\"],[\"9141\",\"멇멊멌멏멐멑멒멖멗멙멚멛멝\",6,\"멦멪\",5],[\"9161\",\"멲멳멵멶멷멹\",9,\"몆몈몉몊몋몍\",5],[\"9181\",\"몓\",20,\"몪몭몮몯몱몳\",4,\"몺몼몾\",5,\"뫅뫆뫇뫉\",14,\"뫚\",33,\"뫽뫾뫿묁묂묃묅\",7,\"묎묐묒\",5,\"묙묚묛묝묞묟묡\",6],[\"9241\",\"묨묪묬\",7,\"묷묹묺묿\",4,\"뭆뭈뭊뭋뭌뭎뭑뭒\"],[\"9261\",\"뭓뭕뭖뭗뭙\",7,\"뭢뭤\",7,\"뭭\",4],[\"9281\",\"뭲\",21,\"뮉뮊뮋뮍뮎뮏뮑\",18,\"뮥뮦뮧뮩뮪뮫뮭\",6,\"뮵뮶뮸\",7,\"믁믂믃믅믆믇믉\",6,\"믑믒믔\",35,\"믺믻믽믾밁\"],[\"9341\",\"밃\",4,\"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵\"],[\"9361\",\"밶밷밹\",6,\"뱂뱆뱇뱈뱊뱋뱎뱏뱑\",8],[\"9381\",\"뱚뱛뱜뱞\",37,\"벆벇벉벊벍벏\",4,\"벖벘벛\",4,\"벢벣벥벦벩\",6,\"벲벶\",5,\"벾벿볁볂볃볅\",7,\"볎볒볓볔볖볗볙볚볛볝\",22,\"볷볹볺볻볽\"],[\"9441\",\"볾\",5,\"봆봈봊\",5,\"봑봒봓봕\",8],[\"9461\",\"봞\",5,\"봥\",6,\"봭\",12],[\"9481\",\"봺\",5,\"뵁\",6,\"뵊뵋뵍뵎뵏뵑\",6,\"뵚\",9,\"뵥뵦뵧뵩\",22,\"붂붃붅붆붋\",4,\"붒붔붖붗붘붛붝\",6,\"붥\",10,\"붱\",6,\"붹\",24],[\"9541\",\"뷒뷓뷖뷗뷙뷚뷛뷝\",11,\"뷪\",5,\"뷱\"],[\"9561\",\"뷲뷳뷵뷶뷷뷹\",6,\"븁븂븄븆\",5,\"븎븏븑븒븓\"],[\"9581\",\"븕\",6,\"븞븠\",35,\"빆빇빉빊빋빍빏\",4,\"빖빘빜빝빞빟빢빣빥빦빧빩빫\",4,\"빲빶\",4,\"빾빿뺁뺂뺃뺅\",6,\"뺎뺒\",5,\"뺚\",13,\"뺩\",14],[\"9641\",\"뺸\",23,\"뻒뻓\"],[\"9661\",\"뻕뻖뻙\",6,\"뻡뻢뻦\",5,\"뻭\",8],[\"9681\",\"뻶\",10,\"뼂\",5,\"뼊\",13,\"뼚뼞\",33,\"뽂뽃뽅뽆뽇뽉\",6,\"뽒뽓뽔뽖\",44],[\"9741\",\"뾃\",16,\"뾕\",8],[\"9761\",\"뾞\",17,\"뾱\",7],[\"9781\",\"뾹\",11,\"뿆\",5,\"뿎뿏뿑뿒뿓뿕\",6,\"뿝뿞뿠뿢\",89,\"쀽쀾쀿\"],[\"9841\",\"쁀\",16,\"쁒\",5,\"쁙쁚쁛\"],[\"9861\",\"쁝쁞쁟쁡\",6,\"쁪\",15],[\"9881\",\"쁺\",21,\"삒삓삕삖삗삙\",6,\"삢삤삦\",5,\"삮삱삲삷\",4,\"삾샂샃샄샆샇샊샋샍샎샏샑\",6,\"샚샞\",5,\"샦샧샩샪샫샭\",6,\"샶샸샺\",5,\"섁섂섃섅섆섇섉\",6,\"섑섒섓섔섖\",5,\"섡섢섥섨섩섪섫섮\"],[\"9941\",\"섲섳섴섵섷섺섻섽섾섿셁\",6,\"셊셎\",5,\"셖셗\"],[\"9961\",\"셙셚셛셝\",6,\"셦셪\",5,\"셱셲셳셵셶셷셹셺셻\"],[\"9981\",\"셼\",8,\"솆\",5,\"솏솑솒솓솕솗\",4,\"솞솠솢솣솤솦솧솪솫솭솮솯솱\",11,\"솾\",5,\"쇅쇆쇇쇉쇊쇋쇍\",6,\"쇕쇖쇙\",6,\"쇡쇢쇣쇥쇦쇧쇩\",6,\"쇲쇴\",7,\"쇾쇿숁숂숃숅\",6,\"숎숐숒\",5,\"숚숛숝숞숡숢숣\"],[\"9a41\",\"숤숥숦숧숪숬숮숰숳숵\",16],[\"9a61\",\"쉆쉇쉉\",6,\"쉒쉓쉕쉖쉗쉙\",6,\"쉡쉢쉣쉤쉦\"],[\"9a81\",\"쉧\",4,\"쉮쉯쉱쉲쉳쉵\",6,\"쉾슀슂\",5,\"슊\",5,\"슑\",6,\"슙슚슜슞\",5,\"슦슧슩슪슫슮\",5,\"슶슸슺\",33,\"싞싟싡싢싥\",5,\"싮싰싲싳싴싵싷싺싽싾싿쌁\",6,\"쌊쌋쌎쌏\"],[\"9b41\",\"쌐쌑쌒쌖쌗쌙쌚쌛쌝\",6,\"쌦쌧쌪\",8],[\"9b61\",\"쌳\",17,\"썆\",7],[\"9b81\",\"썎\",25,\"썪썫썭썮썯썱썳\",4,\"썺썻썾\",5,\"쎅쎆쎇쎉쎊쎋쎍\",50,\"쏁\",22,\"쏚\"],[\"9c41\",\"쏛쏝쏞쏡쏣\",4,\"쏪쏫쏬쏮\",5,\"쏶쏷쏹\",5],[\"9c61\",\"쏿\",8,\"쐉\",6,\"쐑\",9],[\"9c81\",\"쐛\",8,\"쐥\",6,\"쐭쐮쐯쐱쐲쐳쐵\",6,\"쐾\",9,\"쑉\",26,\"쑦쑧쑩쑪쑫쑭\",6,\"쑶쑷쑸쑺\",5,\"쒁\",18,\"쒕\",6,\"쒝\",12],[\"9d41\",\"쒪\",13,\"쒹쒺쒻쒽\",8],[\"9d61\",\"쓆\",25],[\"9d81\",\"쓠\",8,\"쓪\",5,\"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂\",9,\"씍씎씏씑씒씓씕\",6,\"씝\",10,\"씪씫씭씮씯씱\",6,\"씺씼씾\",5,\"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩\",6,\"앲앶\",5,\"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔\"],[\"9e41\",\"얖얙얚얛얝얞얟얡\",7,\"얪\",9,\"얶\"],[\"9e61\",\"얷얺얿\",4,\"엋엍엏엒엓엕엖엗엙\",6,\"엢엤엦엧\"],[\"9e81\",\"엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑\",6,\"옚옝\",6,\"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉\",6,\"왒왖\",5,\"왞왟왡\",10,\"왭왮왰왲\",5,\"왺왻왽왾왿욁\",6,\"욊욌욎\",5,\"욖욗욙욚욛욝\",6,\"욦\"],[\"9f41\",\"욨욪\",5,\"욲욳욵욶욷욻\",4,\"웂웄웆\",5,\"웎\"],[\"9f61\",\"웏웑웒웓웕\",6,\"웞웟웢\",5,\"웪웫웭웮웯웱웲\"],[\"9f81\",\"웳\",4,\"웺웻웼웾\",5,\"윆윇윉윊윋윍\",6,\"윖윘윚\",5,\"윢윣윥윦윧윩\",6,\"윲윴윶윸윹윺윻윾윿읁읂읃읅\",4,\"읋읎읐읙읚읛읝읞읟읡\",6,\"읩읪읬\",7,\"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛\",4,\"잢잧\",4,\"잮잯잱잲잳잵잶잷\"],[\"a041\",\"잸잹잺잻잾쟂\",5,\"쟊쟋쟍쟏쟑\",6,\"쟙쟚쟛쟜\"],[\"a061\",\"쟞\",5,\"쟥쟦쟧쟩쟪쟫쟭\",13],[\"a081\",\"쟻\",4,\"젂젃젅젆젇젉젋\",4,\"젒젔젗\",4,\"젞젟젡젢젣젥\",6,\"젮젰젲\",5,\"젹젺젻젽젾젿졁\",6,\"졊졋졎\",5,\"졕\",26,\"졲졳졵졶졷졹졻\",4,\"좂좄좈좉좊좎\",5,\"좕\",7,\"좞좠좢좣좤\"],[\"a141\",\"좥좦좧좩\",18,\"좾좿죀죁\"],[\"a161\",\"죂죃죅죆죇죉죊죋죍\",6,\"죖죘죚\",5,\"죢죣죥\"],[\"a181\",\"죦\",14,\"죶\",5,\"죾죿줁줂줃줇\",4,\"줎　、。·‥…¨〃­―∥＼∼‘’“”〔〕〈\",9,\"±×÷≠≤≥∞∴°′″℃Å￠￡￥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨￢\"],[\"a241\",\"줐줒\",5,\"줙\",18],[\"a261\",\"줭\",6,\"줵\",18],[\"a281\",\"쥈\",7,\"쥒쥓쥕쥖쥗쥙\",6,\"쥢쥤\",7,\"쥭쥮쥯⇒⇔∀∃´～ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®\"],[\"a341\",\"쥱쥲쥳쥵\",6,\"쥽\",10,\"즊즋즍즎즏\"],[\"a361\",\"즑\",6,\"즚즜즞\",16],[\"a381\",\"즯\",16,\"짂짃짅짆짉짋\",4,\"짒짔짗짘짛！\",58,\"￦］\",32,\"￣\"],[\"a441\",\"짞짟짡짣짥짦짨짩짪짫짮짲\",5,\"짺짻짽짾짿쨁쨂쨃쨄\"],[\"a461\",\"쨅쨆쨇쨊쨎\",5,\"쨕쨖쨗쨙\",12],[\"a481\",\"쨦쨧쨨쨪\",28,\"ㄱ\",93],[\"a541\",\"쩇\",4,\"쩎쩏쩑쩒쩓쩕\",6,\"쩞쩢\",5,\"쩩쩪\"],[\"a561\",\"쩫\",17,\"쩾\",5,\"쪅쪆\"],[\"a581\",\"쪇\",16,\"쪙\",14,\"ⅰ\",9],[\"a5b0\",\"Ⅰ\",9],[\"a5c1\",\"Α\",16,\"Σ\",6],[\"a5e1\",\"α\",16,\"σ\",6],[\"a641\",\"쪨\",19,\"쪾쪿쫁쫂쫃쫅\"],[\"a661\",\"쫆\",5,\"쫎쫐쫒쫔쫕쫖쫗쫚\",5,\"쫡\",6],[\"a681\",\"쫨쫩쫪쫫쫭\",6,\"쫵\",18,\"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃\",7],[\"a741\",\"쬋\",4,\"쬑쬒쬓쬕쬖쬗쬙\",6,\"쬢\",7],[\"a761\",\"쬪\",22,\"쭂쭃쭄\"],[\"a781\",\"쭅쭆쭇쭊쭋쭍쭎쭏쭑\",6,\"쭚쭛쭜쭞\",5,\"쭥\",7,\"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙\",9,\"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰\",9,\"㎀\",4,\"㎺\",5,\"㎐\",4,\"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆\"],[\"a841\",\"쭭\",10,\"쭺\",14],[\"a861\",\"쮉\",18,\"쮝\",6],[\"a881\",\"쮤\",19,\"쮹\",11,\"ÆÐªĦ\"],[\"a8a6\",\"Ĳ\"],[\"a8a8\",\"ĿŁØŒºÞŦŊ\"],[\"a8b1\",\"㉠\",27,\"ⓐ\",25,\"①\",14,\"½⅓⅔¼¾⅛⅜⅝⅞\"],[\"a941\",\"쯅\",14,\"쯕\",10],[\"a961\",\"쯠쯡쯢쯣쯥쯦쯨쯪\",18],[\"a981\",\"쯽\",14,\"찎찏찑찒찓찕\",6,\"찞찟찠찣찤æđðħıĳĸŀłøœßþŧŋŉ㈀\",27,\"⒜\",25,\"⑴\",14,\"¹²³⁴ⁿ₁₂₃₄\"],[\"aa41\",\"찥찦찪찫찭찯찱\",6,\"찺찿\",4,\"챆챇챉챊챋챍챎\"],[\"aa61\",\"챏\",4,\"챖챚\",5,\"챡챢챣챥챧챩\",6,\"챱챲\"],[\"aa81\",\"챳챴챶\",29,\"ぁ\",82],[\"ab41\",\"첔첕첖첗첚첛첝첞첟첡\",6,\"첪첮\",5,\"첶첷첹\"],[\"ab61\",\"첺첻첽\",6,\"쳆쳈쳊\",5,\"쳑쳒쳓쳕\",5],[\"ab81\",\"쳛\",8,\"쳥\",6,\"쳭쳮쳯쳱\",12,\"ァ\",85],[\"ac41\",\"쳾쳿촀촂\",5,\"촊촋촍촎촏촑\",6,\"촚촜촞촟촠\"],[\"ac61\",\"촡촢촣촥촦촧촩촪촫촭\",11,\"촺\",4],[\"ac81\",\"촿\",28,\"쵝쵞쵟А\",5,\"ЁЖ\",25],[\"acd1\",\"а\",5,\"ёж\",25],[\"ad41\",\"쵡쵢쵣쵥\",6,\"쵮쵰쵲\",5,\"쵹\",7],[\"ad61\",\"춁\",6,\"춉\",10,\"춖춗춙춚춛춝춞춟\"],[\"ad81\",\"춠춡춢춣춦춨춪\",5,\"춱\",18,\"췅\"],[\"ae41\",\"췆\",5,\"췍췎췏췑\",16],[\"ae61\",\"췢\",5,\"췩췪췫췭췮췯췱\",6,\"췺췼췾\",4],[\"ae81\",\"츃츅츆츇츉츊츋츍\",6,\"츕츖츗츘츚\",5,\"츢츣츥츦츧츩츪츫\"],[\"af41\",\"츬츭츮츯츲츴츶\",19],[\"af61\",\"칊\",13,\"칚칛칝칞칢\",5,\"칪칬\"],[\"af81\",\"칮\",5,\"칶칷칹칺칻칽\",6,\"캆캈캊\",5,\"캒캓캕캖캗캙\"],[\"b041\",\"캚\",5,\"캢캦\",5,\"캮\",12],[\"b061\",\"캻\",5,\"컂\",19],[\"b081\",\"컖\",13,\"컦컧컩컪컭\",6,\"컶컺\",5,\"가각간갇갈갉갊감\",7,\"같\",4,\"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆\"],[\"b141\",\"켂켃켅켆켇켉\",6,\"켒켔켖\",5,\"켝켞켟켡켢켣\"],[\"b161\",\"켥\",6,\"켮켲\",5,\"켹\",11],[\"b181\",\"콅\",14,\"콖콗콙콚콛콝\",6,\"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸\"],[\"b241\",\"콭콮콯콲콳콵콶콷콹\",6,\"쾁쾂쾃쾄쾆\",5,\"쾍\"],[\"b261\",\"쾎\",18,\"쾢\",5,\"쾩\"],[\"b281\",\"쾪\",5,\"쾱\",18,\"쿅\",6,\"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙\"],[\"b341\",\"쿌\",19,\"쿢쿣쿥쿦쿧쿩\"],[\"b361\",\"쿪\",5,\"쿲쿴쿶\",5,\"쿽쿾쿿퀁퀂퀃퀅\",5],[\"b381\",\"퀋\",5,\"퀒\",5,\"퀙\",19,\"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫\",4,\"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝\"],[\"b441\",\"퀮\",5,\"퀶퀷퀹퀺퀻퀽\",6,\"큆큈큊\",5],[\"b461\",\"큑큒큓큕큖큗큙\",6,\"큡\",10,\"큮큯\"],[\"b481\",\"큱큲큳큵\",6,\"큾큿킀킂\",18,\"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫\",4,\"닳담답닷\",4,\"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥\"],[\"b541\",\"킕\",14,\"킦킧킩킪킫킭\",5],[\"b561\",\"킳킶킸킺\",5,\"탂탃탅탆탇탊\",5,\"탒탖\",4],[\"b581\",\"탛탞탟탡탢탣탥\",6,\"탮탲\",5,\"탹\",11,\"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸\"],[\"b641\",\"턅\",7,\"턎\",17],[\"b661\",\"턠\",15,\"턲턳턵턶턷턹턻턼턽턾\"],[\"b681\",\"턿텂텆\",5,\"텎텏텑텒텓텕\",6,\"텞텠텢\",5,\"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗\"],[\"b741\",\"텮\",13,\"텽\",6,\"톅톆톇톉톊\"],[\"b761\",\"톋\",20,\"톢톣톥톦톧\"],[\"b781\",\"톩\",6,\"톲톴톶톷톸톹톻톽톾톿퇁\",14,\"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩\"],[\"b841\",\"퇐\",7,\"퇙\",17],[\"b861\",\"퇫\",8,\"퇵퇶퇷퇹\",13],[\"b881\",\"툈툊\",5,\"툑\",24,\"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많\",4,\"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼\"],[\"b941\",\"툪툫툮툯툱툲툳툵\",6,\"툾퉀퉂\",5,\"퉉퉊퉋퉌\"],[\"b961\",\"퉍\",14,\"퉝\",6,\"퉥퉦퉧퉨\"],[\"b981\",\"퉩\",22,\"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바\",4,\"받\",4,\"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗\"],[\"ba41\",\"튍튎튏튒튓튔튖\",5,\"튝튞튟튡튢튣튥\",6,\"튭\"],[\"ba61\",\"튮튯튰튲\",5,\"튺튻튽튾틁틃\",4,\"틊틌\",5],[\"ba81\",\"틒틓틕틖틗틙틚틛틝\",6,\"틦\",9,\"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤\"],[\"bb41\",\"틻\",4,\"팂팄팆\",5,\"팏팑팒팓팕팗\",4,\"팞팢팣\"],[\"bb61\",\"팤팦팧팪팫팭팮팯팱\",6,\"팺팾\",5,\"퍆퍇퍈퍉\"],[\"bb81\",\"퍊\",31,\"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤\"],[\"bc41\",\"퍪\",17,\"퍾퍿펁펂펃펅펆펇\"],[\"bc61\",\"펈펉펊펋펎펒\",5,\"펚펛펝펞펟펡\",6,\"펪펬펮\"],[\"bc81\",\"펯\",4,\"펵펶펷펹펺펻펽\",6,\"폆폇폊\",5,\"폑\",5,\"샥샨샬샴샵샷샹섀섄섈섐섕서\",4,\"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭\"],[\"bd41\",\"폗폙\",7,\"폢폤\",7,\"폮폯폱폲폳폵폶폷\"],[\"bd61\",\"폸폹폺폻폾퐀퐂\",5,\"퐉\",13],[\"bd81\",\"퐗\",5,\"퐞\",25,\"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰\"],[\"be41\",\"퐸\",7,\"푁푂푃푅\",14],[\"be61\",\"푔\",7,\"푝푞푟푡푢푣푥\",7,\"푮푰푱푲\"],[\"be81\",\"푳\",4,\"푺푻푽푾풁풃\",4,\"풊풌풎\",5,\"풕\",8,\"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄\",6,\"엌엎\"],[\"bf41\",\"풞\",10,\"풪\",14],[\"bf61\",\"풹\",18,\"퓍퓎퓏퓑퓒퓓퓕\"],[\"bf81\",\"퓖\",5,\"퓝퓞퓠\",7,\"퓩퓪퓫퓭퓮퓯퓱\",6,\"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염\",5,\"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨\"],[\"c041\",\"퓾\",5,\"픅픆픇픉픊픋픍\",6,\"픖픘\",5],[\"c061\",\"픞\",25],[\"c081\",\"픸픹픺픻픾픿핁핂핃핅\",6,\"핎핐핒\",5,\"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응\",7,\"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊\"],[\"c141\",\"핤핦핧핪핬핮\",5,\"핶핷핹핺핻핽\",6,\"햆햊햋\"],[\"c161\",\"햌햍햎햏햑\",19,\"햦햧\"],[\"c181\",\"햨\",31,\"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓\"],[\"c241\",\"헊헋헍헎헏헑헓\",4,\"헚헜헞\",5,\"헦헧헩헪헫헭헮\"],[\"c261\",\"헯\",4,\"헶헸헺\",5,\"혂혃혅혆혇혉\",6,\"혒\"],[\"c281\",\"혖\",5,\"혝혞혟혡혢혣혥\",7,\"혮\",9,\"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻\"],[\"c341\",\"혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝\",4],[\"c361\",\"홢\",4,\"홨홪\",5,\"홲홳홵\",11],[\"c381\",\"횁횂횄횆\",5,\"횎횏횑횒횓횕\",7,\"횞횠횢\",5,\"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층\"],[\"c441\",\"횫횭횮횯횱\",7,\"횺횼\",7,\"훆훇훉훊훋\"],[\"c461\",\"훍훎훏훐훒훓훕훖훘훚\",5,\"훡훢훣훥훦훧훩\",4],[\"c481\",\"훮훯훱훲훳훴훶\",5,\"훾훿휁휂휃휅\",11,\"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼\"],[\"c541\",\"휕휖휗휚휛휝휞휟휡\",6,\"휪휬휮\",5,\"휶휷휹\"],[\"c561\",\"휺휻휽\",6,\"흅흆흈흊\",5,\"흒흓흕흚\",4],[\"c581\",\"흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵\",6,\"흾흿힀힂\",5,\"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜\"],[\"c641\",\"힍힎힏힑\",6,\"힚힜힞\",5],[\"c6a1\",\"퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁\"],[\"c7a1\",\"퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠\"],[\"c8a1\",\"혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝\"],[\"caa1\",\"伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕\"],[\"cba1\",\"匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢\"],[\"cca1\",\"瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械\"],[\"cda1\",\"棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜\"],[\"cea1\",\"科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾\"],[\"cfa1\",\"區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴\"],[\"d0a1\",\"鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣\"],[\"d1a1\",\"朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩\",5,\"那樂\",4,\"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉\"],[\"d2a1\",\"納臘蠟衲囊娘廊\",4,\"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧\",5,\"駑魯\",10,\"濃籠聾膿農惱牢磊腦賂雷尿壘\",7,\"嫩訥杻紐勒\",5,\"能菱陵尼泥匿溺多茶\"],[\"d3a1\",\"丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃\"],[\"d4a1\",\"棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅\"],[\"d5a1\",\"蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣\"],[\"d6a1\",\"煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼\"],[\"d7a1\",\"遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬\"],[\"d8a1\",\"立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅\"],[\"d9a1\",\"蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文\"],[\"daa1\",\"汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑\"],[\"dba1\",\"發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖\"],[\"dca1\",\"碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦\"],[\"dda1\",\"孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥\"],[\"dea1\",\"脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索\"],[\"dfa1\",\"傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署\"],[\"e0a1\",\"胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬\"],[\"e1a1\",\"聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁\"],[\"e2a1\",\"戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧\"],[\"e3a1\",\"嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁\"],[\"e4a1\",\"沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額\"],[\"e5a1\",\"櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬\"],[\"e6a1\",\"旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒\"],[\"e7a1\",\"簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳\"],[\"e8a1\",\"烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療\"],[\"e9a1\",\"窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓\"],[\"eaa1\",\"運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜\"],[\"eba1\",\"濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼\"],[\"eca1\",\"議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄\"],[\"eda1\",\"立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長\"],[\"eea1\",\"障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱\"],[\"efa1\",\"煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖\"],[\"f0a1\",\"靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫\"],[\"f1a1\",\"踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只\"],[\"f2a1\",\"咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯\"],[\"f3a1\",\"鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策\"],[\"f4a1\",\"責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢\"],[\"f5a1\",\"椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃\"],[\"f6a1\",\"贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託\"],[\"f7a1\",\"鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑\"],[\"f8a1\",\"阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃\"],[\"f9a1\",\"品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航\"],[\"faa1\",\"行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型\"],[\"fba1\",\"形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵\"],[\"fca1\",\"禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆\"],[\"fda1\",\"爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰\"]]");

const require$$6 = /* #__PURE__ */ JSON.parse("[[\"0\",\"\\u0000\",127],[\"a140\",\"　，、。．‧；：？！︰…‥﹐﹑﹒·﹔﹕﹖﹗｜–︱—︳╴︴﹏（）︵︶｛｝︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚\"],[\"a1a1\",\"﹛﹜﹝﹞‘’“”〝〞‵′＃＆＊※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯￣＿ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡＋－×÷±√＜＞＝≦≧≠∞≒≡﹢\",4,\"～∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣／\"],[\"a240\",\"＼∕﹨＄￥〒￠￡％＠℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁\",7,\"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭\"],[\"a2a1\",\"╮╰╯═╞╪╡◢◣◥◤╱╲╳０\",9,\"Ⅰ\",9,\"〡\",8,\"十卄卅Ａ\",25,\"ａ\",21],[\"a340\",\"ｗｘｙｚΑ\",16,\"Σ\",6,\"α\",16,\"σ\",6,\"ㄅ\",10],[\"a3a1\",\"ㄐ\",25,\"˙ˉˊˇˋ\"],[\"a3e1\",\"€\"],[\"a440\",\"一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才\"],[\"a4a1\",\"丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙\"],[\"a540\",\"世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外\"],[\"a5a1\",\"央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全\"],[\"a640\",\"共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年\"],[\"a6a1\",\"式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣\"],[\"a740\",\"作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍\"],[\"a7a1\",\"均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠\"],[\"a840\",\"杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒\"],[\"a8a1\",\"芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵\"],[\"a940\",\"咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居\"],[\"a9a1\",\"屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊\"],[\"aa40\",\"昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠\"],[\"aaa1\",\"炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附\"],[\"ab40\",\"陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品\"],[\"aba1\",\"哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷\"],[\"ac40\",\"拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗\"],[\"aca1\",\"活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄\"],[\"ad40\",\"耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥\"],[\"ada1\",\"迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪\"],[\"ae40\",\"哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙\"],[\"aea1\",\"恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓\"],[\"af40\",\"浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷\"],[\"afa1\",\"砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃\"],[\"b040\",\"虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡\"],[\"b0a1\",\"陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀\"],[\"b140\",\"娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽\"],[\"b1a1\",\"情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺\"],[\"b240\",\"毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶\"],[\"b2a1\",\"瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼\"],[\"b340\",\"莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途\"],[\"b3a1\",\"部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠\"],[\"b440\",\"婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍\"],[\"b4a1\",\"插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋\"],[\"b540\",\"溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘\"],[\"b5a1\",\"窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁\"],[\"b640\",\"詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑\"],[\"b6a1\",\"間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼\"],[\"b740\",\"媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業\"],[\"b7a1\",\"楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督\"],[\"b840\",\"睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫\"],[\"b8a1\",\"腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊\"],[\"b940\",\"辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴\"],[\"b9a1\",\"飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇\"],[\"ba40\",\"愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢\"],[\"baa1\",\"滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬\"],[\"bb40\",\"罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤\"],[\"bba1\",\"說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜\"],[\"bc40\",\"劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂\"],[\"bca1\",\"慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃\"],[\"bd40\",\"瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯\"],[\"bda1\",\"翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞\"],[\"be40\",\"輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉\"],[\"bea1\",\"鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡\"],[\"bf40\",\"濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊\"],[\"bfa1\",\"縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚\"],[\"c040\",\"錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇\"],[\"c0a1\",\"嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬\"],[\"c140\",\"瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪\"],[\"c1a1\",\"薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁\"],[\"c240\",\"駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘\"],[\"c2a1\",\"癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦\"],[\"c340\",\"鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸\"],[\"c3a1\",\"獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類\"],[\"c440\",\"願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼\"],[\"c4a1\",\"纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴\"],[\"c540\",\"護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬\"],[\"c5a1\",\"禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒\"],[\"c640\",\"讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲\"],[\"c940\",\"乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕\"],[\"c9a1\",\"氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋\"],[\"ca40\",\"汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘\"],[\"caa1\",\"吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇\"],[\"cb40\",\"杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓\"],[\"cba1\",\"芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢\"],[\"cc40\",\"坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋\"],[\"cca1\",\"怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲\"],[\"cd40\",\"泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺\"],[\"cda1\",\"矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏\"],[\"ce40\",\"哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛\"],[\"cea1\",\"峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺\"],[\"cf40\",\"柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂\"],[\"cfa1\",\"洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀\"],[\"d040\",\"穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪\"],[\"d0a1\",\"苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱\"],[\"d140\",\"唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧\"],[\"d1a1\",\"恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤\"],[\"d240\",\"毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸\"],[\"d2a1\",\"牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐\"],[\"d340\",\"笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢\"],[\"d3a1\",\"荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐\"],[\"d440\",\"酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅\"],[\"d4a1\",\"唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏\"],[\"d540\",\"崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟\"],[\"d5a1\",\"捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉\"],[\"d640\",\"淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏\"],[\"d6a1\",\"痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟\"],[\"d740\",\"耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷\"],[\"d7a1\",\"蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪\"],[\"d840\",\"釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷\"],[\"d8a1\",\"堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔\"],[\"d940\",\"惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒\"],[\"d9a1\",\"晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞\"],[\"da40\",\"湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖\"],[\"daa1\",\"琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥\"],[\"db40\",\"罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳\"],[\"dba1\",\"菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺\"],[\"dc40\",\"軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈\"],[\"dca1\",\"隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆\"],[\"dd40\",\"媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤\"],[\"dda1\",\"搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼\"],[\"de40\",\"毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓\"],[\"dea1\",\"煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓\"],[\"df40\",\"稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯\"],[\"dfa1\",\"腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤\"],[\"e040\",\"觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿\"],[\"e0a1\",\"遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠\"],[\"e140\",\"凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠\"],[\"e1a1\",\"寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉\"],[\"e240\",\"榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊\"],[\"e2a1\",\"漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓\"],[\"e340\",\"禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞\"],[\"e3a1\",\"耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻\"],[\"e440\",\"裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍\"],[\"e4a1\",\"銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘\"],[\"e540\",\"噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉\"],[\"e5a1\",\"憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒\"],[\"e640\",\"澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙\"],[\"e6a1\",\"獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟\"],[\"e740\",\"膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢\"],[\"e7a1\",\"蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧\"],[\"e840\",\"踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓\"],[\"e8a1\",\"銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮\"],[\"e940\",\"噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺\"],[\"e9a1\",\"憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸\"],[\"ea40\",\"澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙\"],[\"eaa1\",\"瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘\"],[\"eb40\",\"蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠\"],[\"eba1\",\"諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌\"],[\"ec40\",\"錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕\"],[\"eca1\",\"魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎\"],[\"ed40\",\"檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶\"],[\"eda1\",\"瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞\"],[\"ee40\",\"蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞\"],[\"eea1\",\"謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜\"],[\"ef40\",\"鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰\"],[\"efa1\",\"鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶\"],[\"f040\",\"璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒\"],[\"f0a1\",\"臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧\"],[\"f140\",\"蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪\"],[\"f1a1\",\"鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰\"],[\"f240\",\"徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛\"],[\"f2a1\",\"礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕\"],[\"f340\",\"譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦\"],[\"f3a1\",\"鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲\"],[\"f440\",\"嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩\"],[\"f4a1\",\"禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿\"],[\"f540\",\"鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛\"],[\"f5a1\",\"鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥\"],[\"f640\",\"蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺\"],[\"f6a1\",\"騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚\"],[\"f740\",\"糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊\"],[\"f7a1\",\"驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾\"],[\"f840\",\"讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏\"],[\"f8a1\",\"齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚\"],[\"f940\",\"纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊\"],[\"f9a1\",\"龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓\"]]");

const require$$7 = [
	[
		"8740",
		"䏰䰲䘃䖦䕸𧉧䵷䖳𧲱䳢𧳅㮕䜶䝄䱇䱀𤊿𣘗𧍒𦺋𧃒䱗𪍑䝏䗚䲅𧱬䴇䪤䚡𦬣爥𥩔𡩣𣸆𣽡晍囻"
	],
	[
		"8767",
		"綕夝𨮹㷴霴𧯯寛𡵞媤㘥𩺰嫑宷峼杮薓𩥅瑡璝㡵𡵓𣚞𦀡㻬"
	],
	[
		"87a1",
		"𥣞㫵竼龗𤅡𨤍𣇪𠪊𣉞䌊蒄龖鐯䤰蘓墖靊鈘秐稲晠権袝瑌篅枂稬剏遆㓦珄𥶹瓆鿇垳䤯呌䄱𣚎堘穲𧭥讏䚮𦺈䆁𥶙箮𢒼鿈𢓁𢓉𢓌鿉蔄𣖻䂴鿊䓡𪷿拁灮鿋"
	],
	[
		"8840",
		"㇀",
		4,
		"𠄌㇅𠃑𠃍㇆㇇𠃋𡿨㇈𠃊㇉㇊㇋㇌𠄎㇍㇎ĀÁǍÀĒÉĚÈŌÓǑÒ࿿Ê̄Ế࿿Ê̌ỀÊāáǎàɑēéěèīíǐìōóǒòūúǔùǖǘǚ"
	],
	[
		"88a1",
		"ǜü࿿ê̄ế࿿ê̌ềêɡ⏚⏛"
	],
	[
		"8940",
		"𪎩𡅅"
	],
	[
		"8943",
		"攊"
	],
	[
		"8946",
		"丽滝鵎釟"
	],
	[
		"894c",
		"𧜵撑会伨侨兖兴农凤务动医华发变团声处备夲头学实実岚庆总斉柾栄桥济炼电纤纬纺织经统缆缷艺苏药视设询车轧轮"
	],
	[
		"89a1",
		"琑糼緍楆竉刧"
	],
	[
		"89ab",
		"醌碸酞肼"
	],
	[
		"89b0",
		"贋胶𠧧"
	],
	[
		"89b5",
		"肟黇䳍鷉鸌䰾𩷶𧀎鸊𪄳㗁"
	],
	[
		"89c1",
		"溚舾甙"
	],
	[
		"89c5",
		"䤑马骏龙禇𨑬𡷊𠗐𢫦两亁亀亇亿仫伷㑌侽㹈倃傈㑽㒓㒥円夅凛凼刅争剹劐匧㗇厩㕑厰㕓参吣㕭㕲㚁咓咣咴咹哐哯唘唣唨㖘唿㖥㖿嗗㗅"
	],
	[
		"8a40",
		"𧶄唥"
	],
	[
		"8a43",
		"𠱂𠴕𥄫喐𢳆㧬𠍁蹆𤶸𩓥䁓𨂾睺𢰸㨴䟕𨅝𦧲𤷪擝𠵼𠾴𠳕𡃴撍蹾𠺖𠰋𠽤𢲩𨉖𤓓"
	],
	[
		"8a64",
		"𠵆𩩍𨃩䟴𤺧𢳂骲㩧𩗴㿭㔆𥋇𩟔𧣈𢵄鵮頕"
	],
	[
		"8a76",
		"䏙𦂥撴哣𢵌𢯊𡁷㧻𡁯"
	],
	[
		"8aa1",
		"𦛚𦜖𧦠擪𥁒𠱃蹨𢆡𨭌𠜱"
	],
	[
		"8aac",
		"䠋𠆩㿺塳𢶍"
	],
	[
		"8ab2",
		"𤗈𠓼𦂗𠽌𠶖啹䂻䎺"
	],
	[
		"8abb",
		"䪴𢩦𡂝膪飵𠶜捹㧾𢝵跀嚡摼㹃"
	],
	[
		"8ac9",
		"𪘁𠸉𢫏𢳉"
	],
	[
		"8ace",
		"𡃈𣧂㦒㨆𨊛㕸𥹉𢃇噒𠼱𢲲𩜠㒼氽𤸻"
	],
	[
		"8adf",
		"𧕴𢺋𢈈𪙛𨳍𠹺𠰴𦠜羓𡃏𢠃𢤹㗻𥇣𠺌𠾍𠺪㾓𠼰𠵇𡅏𠹌"
	],
	[
		"8af6",
		"𠺫𠮩𠵈𡃀𡄽㿹𢚖搲𠾭"
	],
	[
		"8b40",
		"𣏴𧘹𢯎𠵾𠵿𢱑𢱕㨘𠺘𡃇𠼮𪘲𦭐𨳒𨶙𨳊閪哌苄喹"
	],
	[
		"8b55",
		"𩻃鰦骶𧝞𢷮煀腭胬尜𦕲脴㞗卟𨂽醶𠻺𠸏𠹷𠻻㗝𤷫㘉𠳖嚯𢞵𡃉𠸐𠹸𡁸𡅈𨈇𡑕𠹹𤹐𢶤婔𡀝𡀞𡃵𡃶垜𠸑"
	],
	[
		"8ba1",
		"𧚔𨋍𠾵𠹻𥅾㜃𠾶𡆀𥋘𪊽𤧚𡠺𤅷𨉼墙剨㘚𥜽箲孨䠀䬬鼧䧧鰟鮍𥭴𣄽嗻㗲嚉丨夂𡯁屮靑𠂆乛亻㔾尣彑忄㣺扌攵歺氵氺灬爫丬犭𤣩罒礻糹罓𦉪㓁"
	],
	[
		"8bde",
		"𦍋耂肀𦘒𦥑卝衤见𧢲讠贝钅镸长门𨸏韦页风飞饣𩠐鱼鸟黄歯龜丷𠂇阝户钢"
	],
	[
		"8c40",
		"倻淾𩱳龦㷉袏𤅎灷峵䬠𥇍㕙𥴰愢𨨲辧釶熑朙玺𣊁𪄇㲋𡦀䬐磤琂冮𨜏䀉橣𪊺䈣蘏𠩯稪𩥇𨫪靕灍匤𢁾鏴盙𨧣龧矝亣俰傼丯众龨吴綋墒壐𡶶庒庙忂𢜒斋"
	],
	[
		"8ca1",
		"𣏹椙橃𣱣泿"
	],
	[
		"8ca7",
		"爀𤔅玌㻛𤨓嬕璹讃𥲤𥚕窓篬糃繬苸薗龩袐龪躹龫迏蕟駠鈡龬𨶹𡐿䁱䊢娚"
	],
	[
		"8cc9",
		"顨杫䉶圽"
	],
	[
		"8cce",
		"藖𤥻芿𧄍䲁𦵴嵻𦬕𦾾龭龮宖龯曧繛湗秊㶈䓃𣉖𢞖䎚䔶"
	],
	[
		"8ce6",
		"峕𣬚諹屸㴒𣕑嵸龲煗䕘𤃬𡸣䱷㥸㑊𠆤𦱁諌侴𠈹妿腬顖𩣺弻"
	],
	[
		"8d40",
		"𠮟"
	],
	[
		"8d42",
		"𢇁𨥭䄂䚻𩁹㼇龳𪆵䃸㟖䛷𦱆䅼𨚲𧏿䕭㣔𥒚䕡䔛䶉䱻䵶䗪㿈𤬏㙡䓞䒽䇭崾嵈嵖㷼㠏嶤嶹㠠㠸幂庽弥徃㤈㤔㤿㥍惗愽峥㦉憷憹懏㦸戬抐拥挘㧸嚱"
	],
	[
		"8da1",
		"㨃揢揻搇摚㩋擀崕嘡龟㪗斆㪽旿晓㫲暒㬢朖㭂枤栀㭘桊梄㭲㭱㭻椉楃牜楤榟榅㮼槖㯝橥橴橱檂㯬檙㯲檫檵櫔櫶殁毁毪汵沪㳋洂洆洦涁㳯涤涱渕渘温溆𨧀溻滢滚齿滨滩漤漴㵆𣽁澁澾㵪㵵熷岙㶊瀬㶑灐灔灯灿炉𠌥䏁㗱𠻘"
	],
	[
		"8e40",
		"𣻗垾𦻓焾𥟠㙎榢𨯩孴穉𥣡𩓙穥穽𥦬窻窰竂竃燑𦒍䇊竚竝竪䇯咲𥰁笋筕笩𥌎𥳾箢筯莜𥮴𦱿篐萡箒箸𥴠㶭𥱥蒒篺簆簵𥳁籄粃𤢂粦晽𤕸糉糇糦籴糳糵糎"
	],
	[
		"8ea1",
		"繧䔝𦹄絝𦻖璍綉綫焵綳緒𤁗𦀩緤㴓緵𡟹緥𨍭縝𦄡𦅚繮纒䌫鑬縧罀罁罇礶𦋐駡羗𦍑羣𡙡𠁨䕜𣝦䔃𨌺翺𦒉者耈耝耨耯𪂇𦳃耻耼聡𢜔䦉𦘦𣷣𦛨朥肧𨩈脇脚墰𢛶汿𦒘𤾸擧𡒊舘𡡞橓𤩥𤪕䑺舩𠬍𦩒𣵾俹𡓽蓢荢𦬊𤦧𣔰𡝳𣷸芪椛芳䇛"
	],
	[
		"8f40",
		"蕋苐茚𠸖𡞴㛁𣅽𣕚艻苢茘𣺋𦶣𦬅𦮗𣗎㶿茝嗬莅䔋𦶥莬菁菓㑾𦻔橗蕚㒖𦹂𢻯葘𥯤葱㷓䓤檧葊𣲵祘蒨𦮖𦹷𦹃蓞萏莑䒠蒓蓤𥲑䉀𥳀䕃蔴嫲𦺙䔧蕳䔖枿蘖"
	],
	[
		"8fa1",
		"𨘥𨘻藁𧂈蘂𡖂𧃍䕫䕪蘨㙈𡢢号𧎚虾蝱𪃸蟮𢰧螱蟚蠏噡虬桖䘏衅衆𧗠𣶹𧗤衞袜䙛袴袵揁装睷𧜏覇覊覦覩覧覼𨨥觧𧤤𧪽誜瞓釾誐𧩙竩𧬺𣾏䜓𧬸煼謌謟𥐰𥕥謿譌譍誩𤩺讐讛誯𡛟䘕衏貛𧵔𧶏貫㜥𧵓賖𧶘𧶽贒贃𡤐賛灜贑𤳉㻐起"
	],
	[
		"9040",
		"趩𨀂𡀔𤦊㭼𨆼𧄌竧躭躶軃鋔輙輭𨍥𨐒辥錃𪊟𠩐辳䤪𨧞𨔽𣶻廸𣉢迹𪀔𨚼𨔁𢌥㦀𦻗逷𨔼𧪾遡𨕬𨘋邨𨜓郄𨛦邮都酧㫰醩釄粬𨤳𡺉鈎沟鉁鉢𥖹銹𨫆𣲛𨬌𥗛"
	],
	[
		"90a1",
		"𠴱錬鍫𨫡𨯫炏嫃𨫢𨫥䥥鉄𨯬𨰹𨯿鍳鑛躼閅閦鐦閠濶䊹𢙺𨛘𡉼𣸮䧟氜陻隖䅬隣𦻕懚隶磵𨫠隽双䦡𦲸𠉴𦐐𩂯𩃥𤫑𡤕𣌊霱虂霶䨏䔽䖅𤫩灵孁霛靜𩇕靗孊𩇫靟鐥僐𣂷𣂼鞉鞟鞱鞾韀韒韠𥑬韮琜𩐳響韵𩐝𧥺䫑頴頳顋顦㬎𧅵㵑𠘰𤅜"
	],
	[
		"9140",
		"𥜆飊颷飈飇䫿𦴧𡛓喰飡飦飬鍸餹𤨩䭲𩡗𩤅駵騌騻騐驘𥜥㛄𩂱𩯕髠髢𩬅髴䰎鬔鬭𨘀倴鬴𦦨㣃𣁽魐魀𩴾婅𡡣鮎𤉋鰂鯿鰌𩹨鷔𩾷𪆒𪆫𪃡𪄣𪇟鵾鶃𪄴鸎梈"
	],
	[
		"91a1",
		"鷄𢅛𪆓𪈠𡤻𪈳鴹𪂹𪊴麐麕麞麢䴴麪麯𤍤黁㭠㧥㴝伲㞾𨰫鼂鼈䮖鐤𦶢鼗鼖鼹嚟嚊齅馸𩂋韲葿齢齩竜龎爖䮾𤥵𤦻煷𤧸𤍈𤩑玞𨯚𡣺禟𨥾𨸶鍩鏳𨩄鋬鎁鏋𨥬𤒹爗㻫睲穃烐𤑳𤏸煾𡟯炣𡢾𣖙㻇𡢅𥐯𡟸㜢𡛻𡠹㛡𡝴𡣑𥽋㜣𡛀坛𤨥𡏾𡊨"
	],
	[
		"9240",
		"𡏆𡒶蔃𣚦蔃葕𤦔𧅥𣸱𥕜𣻻𧁒䓴𣛮𩦝𦼦柹㜳㰕㷧塬𡤢栐䁗𣜿𤃡𤂋𤄏𦰡哋嚞𦚱嚒𠿟𠮨𠸍鏆𨬓鎜仸儫㠙𤐶亼𠑥𠍿佋侊𥙑婨𠆫𠏋㦙𠌊𠐔㐵伩𠋀𨺳𠉵諚𠈌亘"
	],
	[
		"92a1",
		"働儍侢伃𤨎𣺊佂倮偬傁俌俥偘僼兙兛兝兞湶𣖕𣸹𣺿浲𡢄𣺉冨凃𠗠䓝𠒣𠒒𠒑赺𨪜𠜎剙劤𠡳勡鍮䙺熌𤎌𠰠𤦬𡃤槑𠸝瑹㻞璙琔瑖玘䮎𤪼𤂍叐㖄爏𤃉喴𠍅响𠯆圝鉝雴鍦埝垍坿㘾壋媙𨩆𡛺𡝯𡜐娬妸銏婾嫏娒𥥆𡧳𡡡𤊕㛵洅瑃娡𥺃"
	],
	[
		"9340",
		"媁𨯗𠐓鏠璌𡌃焅䥲鐈𨧻鎽㞠尞岞幞幈𡦖𡥼𣫮廍孏𡤃𡤄㜁𡢠㛝𡛾㛓脪𨩇𡶺𣑲𨦨弌弎𡤧𡞫婫𡜻孄蘔𧗽衠恾𢡠𢘫忛㺸𢖯𢖾𩂈𦽳懀𠀾𠁆𢘛憙憘恵𢲛𢴇𤛔𩅍"
	],
	[
		"93a1",
		"摱𤙥𢭪㨩𢬢𣑐𩣪𢹸挷𪑛撶挱揑𤧣𢵧护𢲡搻敫楲㯴𣂎𣊭𤦉𣊫唍𣋠𡣙𩐿曎𣊉𣆳㫠䆐𥖄𨬢𥖏𡛼𥕛𥐥磮𣄃𡠪𣈴㑤𣈏𣆂𤋉暎𦴤晫䮓昰𧡰𡷫晣𣋒𣋡昞𥡲㣑𣠺𣞼㮙𣞢𣏾瓐㮖枏𤘪梶栞㯄檾㡣𣟕𤒇樳橒櫉欅𡤒攑梘橌㯗橺歗𣿀𣲚鎠鋲𨯪𨫋"
	],
	[
		"9440",
		"銉𨀞𨧜鑧涥漋𤧬浧𣽿㶏渄𤀼娽渊塇洤硂焻𤌚𤉶烱牐犇犔𤞏𤜥兹𤪤𠗫瑺𣻸𣙟𤩊𤤗𥿡㼆㺱𤫟𨰣𣼵悧㻳瓌琼鎇琷䒟𦷪䕑疃㽣𤳙𤴆㽘畕癳𪗆㬙瑨𨫌𤦫𤦎㫻"
	],
	[
		"94a1",
		"㷍𤩎㻿𤧅𤣳釺圲鍂𨫣𡡤僟𥈡𥇧睸𣈲眎眏睻𤚗𣞁㩞𤣰琸璛㺿𤪺𤫇䃈𤪖𦆮錇𥖁砞碍碈磒珐祙𧝁𥛣䄎禛蒖禥樭𣻺稺秴䅮𡛦䄲鈵秱𠵌𤦌𠊙𣶺𡝮㖗啫㕰㚪𠇔𠰍竢婙𢛵𥪯𥪜娍𠉛磰娪𥯆竾䇹籝籭䈑𥮳𥺼𥺦糍𤧹𡞰粎籼粮檲緜縇緓罎𦉡"
	],
	[
		"9540",
		"𦅜𧭈綗𥺂䉪𦭵𠤖柖𠁎𣗏埄𦐒𦏸𤥢翝笧𠠬𥫩𥵃笌𥸎駦虅驣樜𣐿㧢𤧷𦖭騟𦖠蒀𧄧𦳑䓪脷䐂胆脉腂𦞴飃𦩂艢艥𦩑葓𦶧蘐𧈛媆䅿𡡀嬫𡢡嫤𡣘蚠蜨𣶏蠭𧐢娂"
	],
	[
		"95a1",
		"衮佅袇袿裦襥襍𥚃襔𧞅𧞄𨯵𨯙𨮜𨧹㺭蒣䛵䛏㟲訽訜𩑈彍鈫𤊄旔焩烄𡡅鵭貟賩𧷜妚矃姰䍮㛔踪躧𤰉輰轊䋴汘澻𢌡䢛潹溋𡟚鯩㚵𤤯邻邗啱䤆醻鐄𨩋䁢𨫼鐧𨰝𨰻蓥訫閙閧閗閖𨴴瑅㻂𤣿𤩂𤏪㻧𣈥随𨻧𨹦𨹥㻌𤧭𤩸𣿮琒瑫㻼靁𩂰"
	],
	[
		"9640",
		"桇䨝𩂓𥟟靝鍨𨦉𨰦𨬯𦎾銺嬑譩䤼珹𤈛鞛靱餸𠼦巁𨯅𤪲頟𩓚鋶𩗗釥䓀𨭐𤩧𨭤飜𨩅㼀鈪䤥萔餻饍𧬆㷽馛䭯馪驜𨭥𥣈檏騡嫾騯𩣱䮐𩥈馼䮽䮗鍽塲𡌂堢𤦸"
	],
	[
		"96a1",
		"𡓨硄𢜟𣶸棅㵽鑘㤧慐𢞁𢥫愇鱏鱓鱻鰵鰐魿鯏𩸭鮟𪇵𪃾鴡䲮𤄄鸘䲰鴌𪆴𪃭𪃳𩤯鶥蒽𦸒𦿟𦮂藼䔳𦶤𦺄𦷰萠藮𦸀𣟗𦁤秢𣖜𣙀䤭𤧞㵢鏛銾鍈𠊿碹鉷鑍俤㑀遤𥕝砽硔碶硋𡝗𣇉𤥁㚚佲濚濙瀞瀞吔𤆵垻壳垊鴖埗焴㒯𤆬燫𦱀𤾗嬨𡞵𨩉"
	],
	[
		"9740",
		"愌嫎娋䊼𤒈㜬䭻𨧼鎻鎸𡣖𠼝葲𦳀𡐓𤋺𢰦𤏁妔𣶷𦝁綨𦅛𦂤𤦹𤦋𨧺鋥珢㻩璴𨭣𡢟㻡𤪳櫘珳珻㻖𤨾𤪔𡟙𤩦𠎧𡐤𤧥瑈𤤖炥𤥶銄珦鍟𠓾錱𨫎𨨖鎆𨯧𥗕䤵𨪂煫"
	],
	[
		"97a1",
		"𤥃𠳿嚤𠘚𠯫𠲸唂秄𡟺緾𡛂𤩐𡡒䔮鐁㜊𨫀𤦭妰𡢿𡢃𧒄媡㛢𣵛㚰鉟婹𨪁𡡢鍴㳍𠪴䪖㦊僴㵩㵌𡎜煵䋻𨈘渏𩃤䓫浗𧹏灧沯㳖𣿭𣸭渂漌㵯𠏵畑㚼㓈䚀㻚䡱姄鉮䤾轁𨰜𦯀堒埈㛖𡑒烾𤍢𤩱𢿣𡊰𢎽梹楧𡎘𣓥𧯴𣛟𨪃𣟖𣏺𤲟樚𣚭𦲷萾䓟䓎"
	],
	[
		"9840",
		"𦴦𦵑𦲂𦿞漗𧄉茽𡜺菭𦲀𧁓𡟛妉媂𡞳婡婱𡤅𤇼㜭姯𡜼㛇熎鎐暚𤊥婮娫𤊓樫𣻹𧜶𤑛𤋊焝𤉙𨧡侰𦴨峂𤓎𧹍𤎽樌𤉖𡌄炦焳𤏩㶥泟勇𤩏繥姫崯㷳彜𤩝𡟟綤萦"
	],
	[
		"98a1",
		"咅𣫺𣌀𠈔坾𠣕𠘙㿥𡾞𪊶瀃𩅛嵰玏糓𨩙𩐠俈翧狍猐𧫴猸猹𥛶獁獈㺩𧬘遬燵𤣲珡臶㻊県㻑沢国琙琞琟㻢㻰㻴㻺瓓㼎㽓畂畭畲疍㽼痈痜㿀癍㿗癴㿜発𤽜熈嘣覀塩䀝睃䀹条䁅㗛瞘䁪䁯属瞾矋売砘点砜䂨砹硇硑硦葈𥔵礳栃礲䄃"
	],
	[
		"9940",
		"䄉禑禙辻稆込䅧窑䆲窼艹䇄竏竛䇏両筢筬筻簒簛䉠䉺类粜䊌粸䊔糭输烀𠳏総緔緐緽羮羴犟䎗耠耥笹耮耱联㷌垴炠肷胩䏭脌猪脎脒畠脔䐁㬹腖腙腚"
	],
	[
		"99a1",
		"䐓堺腼膄䐥膓䐭膥埯臁臤艔䒏芦艶苊苘苿䒰荗险榊萅烵葤惣蒈䔄蒾蓡蓸蔐蔸蕒䔻蕯蕰藠䕷虲蚒蚲蛯际螋䘆䘗袮裿褤襇覑𧥧訩訸誔誴豑賔賲贜䞘塟跃䟭仮踺嗘坔蹱嗵躰䠷軎転軤軭軲辷迁迊迌逳駄䢭飠鈓䤞鈨鉘鉫銱銮銿"
	],
	[
		"9a40",
		"鋣鋫鋳鋴鋽鍃鎄鎭䥅䥑麿鐗匁鐝鐭鐾䥪鑔鑹锭関䦧间阳䧥枠䨤靀䨵鞲韂噔䫤惨颹䬙飱塄餎餙冴餜餷饂饝饢䭰駅䮝騼鬏窃魩鮁鯝鯱鯴䱭鰠㝯𡯂鵉鰺"
	],
	[
		"9aa1",
		"黾噐鶓鶽鷀鷼银辶鹻麬麱麽黆铜黢黱黸竈齄𠂔𠊷𠎠椚铃妬𠓗塀铁㞹𠗕𠘕𠙶𡚺块煳𠫂𠫍𠮿呪吆𠯋咞𠯻𠰻𠱓𠱥𠱼惧𠲍噺𠲵𠳝𠳭𠵯𠶲𠷈楕鰯螥𠸄𠸎𠻗𠾐𠼭𠹳尠𠾼帋𡁜𡁏𡁶朞𡁻𡂈𡂖㙇𡂿𡃓𡄯𡄻卤蒭𡋣𡍵𡌶讁𡕷𡘙𡟃𡟇乸炻𡠭𡥪"
	],
	[
		"9b40",
		"𡨭𡩅𡰪𡱰𡲬𡻈拃𡻕𡼕熘桕𢁅槩㛈𢉼𢏗𢏺𢜪𢡱𢥏苽𢥧𢦓𢫕覥𢫨辠𢬎鞸𢬿顇骽𢱌"
	],
	[
		"9b62",
		"𢲈𢲷𥯨𢴈𢴒𢶷𢶕𢹂𢽴𢿌𣀳𣁦𣌟𣏞徱晈暿𧩹𣕧𣗳爁𤦺矗𣘚𣜖纇𠍆墵朎"
	],
	[
		"9ba1",
		"椘𣪧𧙗𥿢𣸑𣺹𧗾𢂚䣐䪸𤄙𨪚𤋮𤌍𤀻𤌴𤎖𤩅𠗊凒𠘑妟𡺨㮾𣳿𤐄𤓖垈𤙴㦛𤜯𨗨𩧉㝢𢇃譞𨭎駖𤠒𤣻𤨕爉𤫀𠱸奥𤺥𤾆𠝹軚𥀬劏圿煱𥊙𥐙𣽊𤪧喼𥑆𥑮𦭒釔㑳𥔿𧘲𥕞䜘𥕢𥕦𥟇𤤿𥡝偦㓻𣏌惞𥤃䝼𨥈𥪮𥮉𥰆𡶐垡煑澶𦄂𧰒遖𦆲𤾚譢𦐂𦑊"
	],
	[
		"9c40",
		"嵛𦯷輶𦒄𡤜諪𤧶𦒈𣿯𦔒䯀𦖿𦚵𢜛鑥𥟡憕娧晉侻嚹𤔡𦛼乪𤤴陖涏𦲽㘘襷𦞙𦡮𦐑𦡞營𦣇筂𩃀𠨑𦤦鄄𦤹穅鷰𦧺騦𦨭㙟𦑩𠀡禃𦨴𦭛崬𣔙菏𦮝䛐𦲤画补𦶮墶"
	],
	[
		"9ca1",
		"㜜𢖍𧁋𧇍㱔𧊀𧊅銁𢅺𧊋錰𧋦𤧐氹钟𧑐𠻸蠧裵𢤦𨑳𡞱溸𤨪𡠠㦤㚹尐秣䔿暶𩲭𩢤襃𧟌𧡘囖䃟𡘊㦡𣜯𨃨𡏅熭荦𧧝𩆨婧䲷𧂯𨦫𧧽𧨊𧬋𧵦𤅺筃祾𨀉澵𪋟樃𨌘厢𦸇鎿栶靝𨅯𨀣𦦵𡏭𣈯𨁈嶅𨰰𨂃圕頣𨥉嶫𤦈斾槕叒𤪥𣾁㰑朶𨂐𨃴𨄮𡾡𨅏"
	],
	[
		"9d40",
		"𨆉𨆯𨈚𨌆𨌯𨎊㗊𨑨𨚪䣺揦𨥖砈鉕𨦸䏲𨧧䏟𨧨𨭆𨯔姸𨰉輋𨿅𩃬筑𩄐𩄼㷷𩅞𤫊运犏嚋𩓧𩗩𩖰𩖸𩜲𩣑𩥉𩥪𩧃𩨨𩬎𩵚𩶛纟𩻸𩼣䲤镇𪊓熢𪋿䶑递𪗋䶜𠲜达嗁"
	],
	[
		"9da1",
		"辺𢒰边𤪓䔉繿潖檱仪㓤𨬬𧢝㜺躀𡟵𨀤𨭬𨮙𧨾𦚯㷫𧙕𣲷𥘵𥥖亚𥺁𦉘嚿𠹭踎孭𣺈𤲞揞拐𡟶𡡻攰嘭𥱊吚𥌑㷆𩶘䱽嘢嘞罉𥻘奵𣵀蝰东𠿪𠵉𣚺脗鵞贘瘻鱅癎瞹鍅吲腈苷嘥脲萘肽嗪祢噃吖𠺝㗎嘅嗱曱𨋢㘭甴嗰喺咗啲𠱁𠲖廐𥅈𠹶𢱢"
	],
	[
		"9e40",
		"𠺢麫絚嗞𡁵抝靭咔賍燶酶揼掹揾啩𢭃鱲𢺳冚㓟𠶧冧呍唞唓癦踭𦢊疱肶蠄螆裇膶萜𡃁䓬猄𤜆宐茋𦢓噻𢛴𧴯𤆣𧵳𦻐𧊶酰𡇙鈈𣳼𪚩𠺬𠻹牦𡲢䝎𤿂𧿹𠿫䃺"
	],
	[
		"9ea1",
		"鱝攟𢶠䣳𤟠𩵼𠿬𠸊恢𧖣𠿭"
	],
	[
		"9ead",
		"𦁈𡆇熣纎鵐业丄㕷嬍沲卧㚬㧜卽㚥𤘘墚𤭮舭呋垪𥪕𠥹"
	],
	[
		"9ec5",
		"㩒𢑥獴𩺬䴉鯭𣳾𩼰䱛𤾩𩖞𩿞葜𣶶𧊲𦞳𣜠挮紥𣻷𣸬㨪逈勌㹴㙺䗩𠒎癀嫰𠺶硺𧼮墧䂿噼鮋嵴癔𪐴麅䳡痹㟻愙𣃚𤏲"
	],
	[
		"9ef5",
		"噝𡊩垧𤥣𩸆刴𧂮㖭汊鵼"
	],
	[
		"9f40",
		"籖鬹埞𡝬屓擓𩓐𦌵𧅤蚭𠴨𦴢𤫢𠵱"
	],
	[
		"9f4f",
		"凾𡼏嶎霃𡷑麁遌笟鬂峑箣扨挵髿篏鬪籾鬮籂粆鰕篼鬉鼗鰛𤤾齚啳寃俽麘俲剠㸆勑坧偖妷帒韈鶫轜呩鞴饀鞺匬愰"
	],
	[
		"9fa1",
		"椬叚鰊鴂䰻陁榀傦畆𡝭駚剳"
	],
	[
		"9fae",
		"酙隁酜"
	],
	[
		"9fb2",
		"酑𨺗捿𦴣櫊嘑醎畺抅𠏼獏籰𥰡𣳽"
	],
	[
		"9fc1",
		"𤤙盖鮝个𠳔莾衂"
	],
	[
		"9fc9",
		"届槀僭坺刟巵从氱𠇲伹咜哚劚趂㗾弌㗳"
	],
	[
		"9fdb",
		"歒酼龥鮗頮颴骺麨麄煺笔"
	],
	[
		"9fe7",
		"毺蠘罸"
	],
	[
		"9feb",
		"嘠𪙊蹷齓"
	],
	[
		"9ff0",
		"跔蹏鸜踁抂𨍽踨蹵竓𤩷稾磘泪詧瘇"
	],
	[
		"a040",
		"𨩚鼦泎蟖痃𪊲硓咢贌狢獱謭猂瓱賫𤪻蘯徺袠䒷"
	],
	[
		"a055",
		"𡠻𦸅"
	],
	[
		"a058",
		"詾𢔛"
	],
	[
		"a05b",
		"惽癧髗鵄鍮鮏蟵"
	],
	[
		"a063",
		"蠏賷猬霡鮰㗖犲䰇籑饊𦅙慙䰄麖慽"
	],
	[
		"a073",
		"坟慯抦戹拎㩜懢厪𣏵捤栂㗒"
	],
	[
		"a0a1",
		"嵗𨯂迚𨸹"
	],
	[
		"a0a6",
		"僙𡵆礆匲阸𠼻䁥"
	],
	[
		"a0ae",
		"矾"
	],
	[
		"a0b0",
		"糂𥼚糚稭聦聣絍甅瓲覔舚朌聢𧒆聛瓰脃眤覉𦟌畓𦻑螩蟎臈螌詉貭譃眫瓸蓚㘵榲趦"
	],
	[
		"a0d4",
		"覩瑨涹蟁𤀑瓧㷛煶悤憜㳑煢恷"
	],
	[
		"a0e2",
		"罱𨬭牐惩䭾删㰘𣳇𥻗𧙖𥔱𡥄𡋾𩤃𦷜𧂭峁𦆭𨨏𣙷𠃮𦡆𤼎䕢嬟𦍌齐麦𦉫"
	],
	[
		"a3c0",
		"␀",
		31,
		"␡"
	],
	[
		"c6a1",
		"①",
		9,
		"⑴",
		9,
		"ⅰ",
		9,
		"丶丿亅亠冂冖冫勹匸卩厶夊宀巛⼳广廴彐彡攴无疒癶辵隶¨ˆヽヾゝゞ〃仝々〆〇ー［］✽ぁ",
		23
	],
	[
		"c740",
		"す",
		58,
		"ァアィイ"
	],
	[
		"c7a1",
		"ゥ",
		81,
		"А",
		5,
		"ЁЖ",
		4
	],
	[
		"c840",
		"Л",
		26,
		"ёж",
		25,
		"⇧↸↹㇏𠃌乚𠂊刂䒑"
	],
	[
		"c8a1",
		"龰冈龱𧘇"
	],
	[
		"c8cd",
		"￢￤＇＂㈱№℡゛゜⺀⺄⺆⺇⺈⺊⺌⺍⺕⺜⺝⺥⺧⺪⺬⺮⺶⺼⺾⻆⻊⻌⻍⻏⻖⻗⻞⻣"
	],
	[
		"c8f5",
		"ʃɐɛɔɵœøŋʊɪ"
	],
	[
		"f9fe",
		"￭"
	],
	[
		"fa40",
		"𠕇鋛𠗟𣿅蕌䊵珯况㙉𤥂𨧤鍄𡧛苮𣳈砼杄拟𤤳𨦪𠊠𦮳𡌅侫𢓭倈𦴩𧪄𣘀𤪱𢔓倩𠍾徤𠎀𠍇滛𠐟偽儁㑺儎顬㝃萖𤦤𠒇兠𣎴兪𠯿𢃼𠋥𢔰𠖎𣈳𡦃宂蝽𠖳𣲙冲冸"
	],
	[
		"faa1",
		"鴴凉减凑㳜凓𤪦决凢卂凭菍椾𣜭彻刋刦刼劵剗劔効勅簕蕂勠蘍𦬓包𨫞啉滙𣾀𠥔𣿬匳卄𠯢泋𡜦栛珕恊㺪㣌𡛨燝䒢卭却𨚫卾卿𡖖𡘓矦厓𨪛厠厫厮玧𥝲㽙玜叁叅汉义埾叙㪫𠮏叠𣿫𢶣叶𠱷吓灹唫晗浛呭𦭓𠵴啝咏咤䞦𡜍𠻝㶴𠵍"
	],
	[
		"fb40",
		"𨦼𢚘啇䳭启琗喆喩嘅𡣗𤀺䕒𤐵暳𡂴嘷曍𣊊暤暭噍噏磱囱鞇叾圀囯园𨭦㘣𡉏坆𤆥汮炋坂㚱𦱾埦𡐖堃𡑔𤍣堦𤯵塜墪㕡壠壜𡈼壻寿坃𪅐𤉸鏓㖡够梦㛃湙"
	],
	[
		"fba1",
		"𡘾娤啓𡚒蔅姉𠵎𦲁𦴪𡟜姙𡟻𡞲𦶦浱𡠨𡛕姹𦹅媫婣㛦𤦩婷㜈媖瑥嫓𦾡𢕔㶅𡤑㜲𡚸広勐孶斈孼𧨎䀄䡝𠈄寕慠𡨴𥧌𠖥寳宝䴐尅𡭄尓珎尔𡲥𦬨屉䣝岅峩峯嶋𡷹𡸷崐崘嵆𡺤岺巗苼㠭𤤁𢁉𢅳芇㠶㯂帮檊幵幺𤒼𠳓厦亷廐厨𡝱帉廴𨒂"
	],
	[
		"fc40",
		"廹廻㢠廼栾鐛弍𠇁弢㫞䢮𡌺强𦢈𢏐彘𢑱彣鞽𦹮彲鍀𨨶徧嶶㵟𥉐𡽪𧃸𢙨釖𠊞𨨩怱暅𡡷㥣㷇㘹垐𢞴祱㹀悞悤悳𤦂𤦏𧩓璤僡媠慤萤慂慈𦻒憁凴𠙖憇宪𣾷"
	],
	[
		"fca1",
		"𢡟懓𨮝𩥝懐㤲𢦀𢣁怣慜攞掋𠄘担𡝰拕𢸍捬𤧟㨗搸揸𡎎𡟼撐澊𢸶頔𤂌𥜝擡擥鑻㩦携㩗敍漖𤨨𤨣斅敭敟𣁾斵𤥀䬷旑䃘𡠩无旣忟𣐀昘𣇷𣇸晄𣆤𣆥晋𠹵晧𥇦晳晴𡸽𣈱𨗴𣇈𥌓矅𢣷馤朂𤎜𤨡㬫槺𣟂杞杧杢𤇍𩃭柗䓩栢湐鈼栁𣏦𦶠桝"
	],
	[
		"fd40",
		"𣑯槡樋𨫟楳棃𣗍椁椀㴲㨁𣘼㮀枬楡𨩊䋼椶榘㮡𠏉荣傐槹𣙙𢄪橅𣜃檝㯳枱櫈𩆜㰍欝𠤣惞欵歴𢟍溵𣫛𠎵𡥘㝀吡𣭚毡𣻼毜氷𢒋𤣱𦭑汚舦汹𣶼䓅𣶽𤆤𤤌𤤀"
	],
	[
		"fda1",
		"𣳉㛥㳫𠴲鮃𣇹𢒑羏样𦴥𦶡𦷫涖浜湼漄𤥿𤂅𦹲蔳𦽴凇沜渝萮𨬡港𣸯瑓𣾂秌湏媑𣁋濸㜍澝𣸰滺𡒗𤀽䕕鏰潄潜㵎潴𩅰㴻澟𤅄濓𤂑𤅕𤀹𣿰𣾴𤄿凟𤅖𤅗𤅀𦇝灋灾炧炁烌烕烖烟䄄㷨熴熖𤉷焫煅媈煊煮岜𤍥煏鍢𤋁焬𤑚𤨧𤨢熺𨯨炽爎"
	],
	[
		"fe40",
		"鑂爕夑鑃爤鍁𥘅爮牀𤥴梽牕牗㹕𣁄栍漽犂猪猫𤠣𨠫䣭𨠄猨献珏玪𠰺𦨮珉瑉𤇢𡛧𤨤昣㛅𤦷𤦍𤧻珷琕椃𤨦琹𠗃㻗瑜𢢭瑠𨺲瑇珤瑶莹瑬㜰瑴鏱樬璂䥓𤪌"
	],
	[
		"fea1",
		"𤅟𤩹𨮏孆𨰃𡢞瓈𡦈甎瓩甞𨻙𡩋寗𨺬鎅畍畊畧畮𤾂㼄𤴓疎瑝疞疴瘂瘬癑癏癯癶𦏵皐臯㟸𦤑𦤎皡皥皷盌𦾟葢𥂝𥅽𡸜眞眦着撯𥈠睘𣊬瞯𨥤𨥨𡛁矴砉𡍶𤨒棊碯磇磓隥礮𥗠磗礴碱𧘌辸袄𨬫𦂃𢘜禆褀椂禀𥡗禝𧬹礼禩渪𧄦㺨秆𩄍秔"
	]
];

var dbcsData;
var hasRequiredDbcsData;

function requireDbcsData () {
	if (hasRequiredDbcsData) return dbcsData;
	hasRequiredDbcsData = 1;

	// Description of supported double byte encodings and aliases.
	// Tables are not require()-d until they are needed to speed up library load.
	// require()-s are direct to support Browserify.

	dbcsData = {
	    
	    // == Japanese/ShiftJIS ====================================================
	    // All japanese encodings are based on JIS X set of standards:
	    // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF.
	    // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. 
	    //              Has several variations in 1978, 1983, 1990 and 1997.
	    // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead.
	    // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233.
	    //              2 planes, first is superset of 0208, second - revised 0212.
	    //              Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx)

	    // Byte encodings are:
	    //  * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte
	    //               encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC.
	    //               Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI.
	    //  * EUC-JP:    Up to 3 bytes per character. Used mostly on *nixes.
	    //               0x00-0x7F       - lower part of 0201
	    //               0x8E, 0xA1-0xDF - upper part of 0201
	    //               (0xA1-0xFE)x2   - 0208 plane (94x94).
	    //               0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94).
	    //  * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon.
	    //               Used as-is in ISO2022 family.
	    //  * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, 
	    //                0201-1976 Roman, 0208-1978, 0208-1983.
	    //  * ISO2022-JP-1: Adds esc seq for 0212-1990.
	    //  * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7.
	    //  * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2.
	    //  * ISO2022-JP-2004: Adds 0213-2004 Plane 1.
	    //
	    // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes.
	    //
	    // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html

	    'shiftjis': {
	        type: '_dbcs',
	        table: function() { return require$$0$3 },
	        encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
	        encodeSkipVals: [{from: 0xED40, to: 0xF940}],
	    },
	    'csshiftjis': 'shiftjis',
	    'mskanji': 'shiftjis',
	    'sjis': 'shiftjis',
	    'windows31j': 'shiftjis',
	    'ms31j': 'shiftjis',
	    'xsjis': 'shiftjis',
	    'windows932': 'shiftjis',
	    'ms932': 'shiftjis',
	    '932': 'shiftjis',
	    'cp932': 'shiftjis',

	    'eucjp': {
	        type: '_dbcs',
	        table: function() { return require$$1 },
	        encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
	    },

	    // TODO: KDDI extension to Shift_JIS
	    // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes.
	    // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars.


	    // == Chinese/GBK ==========================================================
	    // http://en.wikipedia.org/wiki/GBK
	    // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder

	    // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936
	    'gb2312': 'cp936',
	    'gb231280': 'cp936',
	    'gb23121980': 'cp936',
	    'csgb2312': 'cp936',
	    'csiso58gb231280': 'cp936',
	    'euccn': 'cp936',

	    // Microsoft's CP936 is a subset and approximation of GBK.
	    'windows936': 'cp936',
	    'ms936': 'cp936',
	    '936': 'cp936',
	    'cp936': {
	        type: '_dbcs',
	        table: function() { return require$$2$1 },
	    },

	    // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other.
	    'gbk': {
	        type: '_dbcs',
	        table: function() { return require$$2$1.concat(require$$3$1) },
	    },
	    'xgbk': 'gbk',
	    'isoir58': 'gbk',

	    // GB18030 is an algorithmic extension of GBK.
	    // Main source: https://www.w3.org/TR/encoding/#gbk-encoder
	    // http://icu-project.org/docs/papers/gb18030.html
	    // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml
	    // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0
	    'gb18030': {
	        type: '_dbcs',
	        table: function() { return require$$2$1.concat(require$$3$1) },
	        gb18030: function() { return require$$4$1 },
	        encodeSkipVals: [0x80],
	        encodeAdd: {'€': 0xA2E3},
	    },

	    'chinese': 'gb18030',


	    // == Korean ===============================================================
	    // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same.
	    'windows949': 'cp949',
	    'ms949': 'cp949',
	    '949': 'cp949',
	    'cp949': {
	        type: '_dbcs',
	        table: function() { return require$$5 },
	    },

	    'cseuckr': 'cp949',
	    'csksc56011987': 'cp949',
	    'euckr': 'cp949',
	    'isoir149': 'cp949',
	    'korean': 'cp949',
	    'ksc56011987': 'cp949',
	    'ksc56011989': 'cp949',
	    'ksc5601': 'cp949',


	    // == Big5/Taiwan/Hong Kong ================================================
	    // There are lots of tables for Big5 and cp950. Please see the following links for history:
	    // http://moztw.org/docs/big5/  http://www.haible.de/bruno/charsets/conversion-tables/Big5.html
	    // Variations, in roughly number of defined chars:
	    //  * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT
	    //  * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/
	    //  * Big5-2003 (Taiwan standard) almost superset of cp950.
	    //  * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers.
	    //  * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. 
	    //    many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years.
	    //    Plus, it has 4 combining sequences.
	    //    Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299
	    //    because big5-hkscs is the only encoding to include astral characters in non-algorithmic way.
	    //    Implementations are not consistent within browsers; sometimes labeled as just big5.
	    //    MS Internet Explorer switches from big5 to big5-hkscs when a patch applied.
	    //    Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31
	    //    In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s.
	    //    Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt
	    //                   http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt
	    // 
	    // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder
	    // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong.

	    'windows950': 'cp950',
	    'ms950': 'cp950',
	    '950': 'cp950',
	    'cp950': {
	        type: '_dbcs',
	        table: function() { return require$$6 },
	    },

	    // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus.
	    'big5': 'big5hkscs',
	    'big5hkscs': {
	        type: '_dbcs',
	        table: function() { return require$$6.concat(require$$7) },
	        encodeSkipVals: [0xa2cc],
	    },

	    'cnbig5': 'big5hkscs',
	    'csbig5': 'big5hkscs',
	    'xxbig5': 'big5hkscs',
	};
	return dbcsData;
}

var hasRequiredEncodings;

function requireEncodings () {
	if (hasRequiredEncodings) return encodings;
	hasRequiredEncodings = 1;
	(function (exports$1) {

		// Update this array if you add/rename/remove files in this directory.
		// We support Browserify by skipping automatic module discovery and requiring modules directly.
		var modules = [
		    requireInternal(),
		    requireUtf32(),
		    requireUtf16(),
		    requireUtf7(),
		    requireSbcsCodec(),
		    requireSbcsData(),
		    requireSbcsDataGenerated(),
		    requireDbcsCodec(),
		    requireDbcsData(),
		];

		// Put all encoding/alias/codec definitions to single object and export it.
		for (var i = 0; i < modules.length; i++) {
		    var module = modules[i];
		    for (var enc in module)
		        if (Object.prototype.hasOwnProperty.call(module, enc))
		            exports$1[enc] = module[enc];
		} 
	} (encodings));
	return encodings;
}

const __viteBrowserExternal = {};

const __viteBrowserExternal$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
    __proto__: null,
    default: __viteBrowserExternal
}, Symbol.toStringTag, { value: 'Module' }));

const require$$4 = /*@__PURE__*/getAugmentedNamespace(__viteBrowserExternal$1);

var hasRequiredLib$3;

function requireLib$3 () {
	if (hasRequiredLib$3) return lib$4.exports;
	hasRequiredLib$3 = 1;
	(function (module) {

		// Some environments don't have global Buffer (e.g. React Native).
		// Solution would be installing npm modules "buffer" and "stream" explicitly.
		var Buffer = requireSafer().Buffer;

		var bomHandling = requireBomHandling(),
		    iconv = module.exports;

		// All codecs and aliases are kept here, keyed by encoding name/alias.
		// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`.
		iconv.encodings = null;

		// Characters emitted in case of error.
		iconv.defaultCharUnicode = '�';
		iconv.defaultCharSingleByte = '?';

		// Public API.
		iconv.encode = function encode(str, encoding, options) {
		    str = "" + (str || ""); // Ensure string.

		    var encoder = iconv.getEncoder(encoding, options);

		    var res = encoder.write(str);
		    var trail = encoder.end();
		    
		    return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res;
		};

		iconv.decode = function decode(buf, encoding, options) {
		    if (typeof buf === 'string') {
		        if (!iconv.skipDecodeWarning) {
		            console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding');
		            iconv.skipDecodeWarning = true;
		        }

		        buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer.
		    }

		    var decoder = iconv.getDecoder(encoding, options);

		    var res = decoder.write(buf);
		    var trail = decoder.end();

		    return trail ? (res + trail) : res;
		};

		iconv.encodingExists = function encodingExists(enc) {
		    try {
		        iconv.getCodec(enc);
		        return true;
		    } catch (e) {
		        return false;
		    }
		};

		// Legacy aliases to convert functions
		iconv.toEncoding = iconv.encode;
		iconv.fromEncoding = iconv.decode;

		// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache.
		iconv._codecDataCache = {};
		iconv.getCodec = function getCodec(encoding) {
		    if (!iconv.encodings)
		        iconv.encodings = requireEncodings(); // Lazy load all encoding definitions.
		    
		    // Canonicalize encoding name: strip all non-alphanumeric chars and appended year.
		    var enc = iconv._canonicalizeEncoding(encoding);

		    // Traverse iconv.encodings to find actual codec.
		    var codecOptions = {};
		    while (true) {
		        var codec = iconv._codecDataCache[enc];
		        if (codec)
		            return codec;

		        var codecDef = iconv.encodings[enc];

		        switch (typeof codecDef) {
		            case "string": // Direct alias to other encoding.
		                enc = codecDef;
		                break;

		            case "object": // Alias with options. Can be layered.
		                for (var key in codecDef)
		                    codecOptions[key] = codecDef[key];

		                if (!codecOptions.encodingName)
		                    codecOptions.encodingName = enc;
		                
		                enc = codecDef.type;
		                break;

		            case "function": // Codec itself.
		                if (!codecOptions.encodingName)
		                    codecOptions.encodingName = enc;

		                // The codec function must load all tables and return object with .encoder and .decoder methods.
		                // It'll be called only once (for each different options object).
		                codec = new codecDef(codecOptions, iconv);

		                iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later.
		                return codec;

		            default:
		                throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')");
		        }
		    }
		};

		iconv._canonicalizeEncoding = function(encoding) {
		    // Canonicalize encoding name: strip all non-alphanumeric chars and appended year.
		    return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, "");
		};

		iconv.getEncoder = function getEncoder(encoding, options) {
		    var codec = iconv.getCodec(encoding),
		        encoder = new codec.encoder(options, codec);

		    if (codec.bomAware && options && options.addBOM)
		        encoder = new bomHandling.PrependBOM(encoder, options);

		    return encoder;
		};

		iconv.getDecoder = function getDecoder(encoding, options) {
		    var codec = iconv.getCodec(encoding),
		        decoder = new codec.decoder(options, codec);

		    if (codec.bomAware && !(options && options.stripBOM === false))
		        decoder = new bomHandling.StripBOM(decoder, options);

		    return decoder;
		};


		// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json.
		var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node;
		if (nodeVer) {

		    // Load streaming support in Node v0.10+
		    var nodeVerArr = nodeVer.split(".").map(Number);
		    if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) {
		        require$$4(iconv);
		    }

		    // Load Node primitive extensions.
		    require$$4(iconv);
		}
	} (lib$4));
	return lib$4.exports;
}

var uncompress_stream$3;
var hasRequiredUncompress_stream$3;

function requireUncompress_stream$3 () {
	if (hasRequiredUncompress_stream$3) return uncompress_stream$3;
	hasRequiredUncompress_stream$3 = 1;

	// https://github.com/thejoshwolfe/yauzl#no-streaming-unzip-api

	const yauzl = requireYauzl();
	const stream = require$$1$1;
	const UncompressBaseStream = requireBase_write_stream();
	const utils = requireUtils$2();

	// lazy load iconv-lite
	let iconv;

	const YAUZL_CALLBACK = Symbol('ZipUncompressStream#yauzlCallback');
	const STRIP_NAME = Symbol('ZipUncompressStream#stripName');

	// don't decodeStrings on yauzl, we should handle fileName by ourself
	// see validateFileName on https://github.com/thejoshwolfe/yauzl/blob/51010ce4e8c7e6345efe195e1b4150518f37b393/index.js#L607
	//  - support "absolute path"
	const DEFAULTS = { lazyEntries: true, decodeStrings: false };

	// from: https://github.com/microsoft/vscode/blob/c0769274fa136b45799edeccc0d0a2f645b75caf/src/vs/base/node/zip.ts#L51
	function modeFromEntry(entry) {
	  const attr = entry.externalFileAttributes >> 16 || 33188;

	  return [ 448 /* S_IRWXU */, 56 /* S_IRWXG */, 7 /* S_IRWXO */ ]
	    .map(mask => attr & mask)
	    .reduce((a, b) => a + b, attr & 61440 /* S_IFMT */);
	}

	class ZipUncompressStream extends UncompressBaseStream {
	  constructor(opts) {
	    opts = opts || {};
	    super(opts);

	    this._chunks = [];
	    this._strip = Number(opts.strip) || 0;
	    this._zipFileNameEncoding = opts.zipFileNameEncoding || 'utf8';
	    if (this._zipFileNameEncoding === 'utf-8') {
	      this._zipFileNameEncoding = 'utf8';
	    }

	    this[YAUZL_CALLBACK] = this[YAUZL_CALLBACK].bind(this);

	    const sourceType = utils.sourceType(opts.source);

	    const yauzlOpts = this._yauzlOpts = Object.assign({}, DEFAULTS, opts.yauzl);
	    if (sourceType === 'file') {
	      yauzl.open(opts.source, yauzlOpts, this[YAUZL_CALLBACK]);
	      return;
	    }

	    if (sourceType === 'buffer') {
	      yauzl.fromBuffer(opts.source, yauzlOpts, this[YAUZL_CALLBACK]);
	      return;
	    }

	    if (sourceType === 'stream') {
	      utils.streamToBuffer(opts.source)
	        .then(buf => yauzl.fromBuffer(buf, yauzlOpts, this[YAUZL_CALLBACK]))
	        .catch(e => this.emit('error', e));
	      return;
	    }

	    this.on('pipe', srcStream => {
	      srcStream.unpipe(srcStream);

	      utils.streamToBuffer(srcStream)
	        .then(buf => {
	          this._chunks.push(buf);
	          buf = Buffer.concat(this._chunks);
	          yauzl.fromBuffer(buf, yauzlOpts, this[YAUZL_CALLBACK]);
	        })
	        .catch(e => this.emit('error', e));
	    });
	  }

	  _write(chunk) {
	    // push to _chunks array, this will only happen once, for stream will be unpiped.
	    this._chunks.push(chunk);
	  }

	  [YAUZL_CALLBACK](err, zipFile) {
	    if (err) return this.emit('error', err);

	    zipFile.readEntry();

	    zipFile
	      .on('entry', entry => {
	        const mode = modeFromEntry(entry);
	        // fileName is buffer by default because decodeStrings = false
	        if (Buffer.isBuffer(entry.fileName)) {
	          if (this._zipFileNameEncoding === 'utf8') {
	            entry.fileName = entry.fileName.toString();
	          } else {
	            if (!iconv) {
	              iconv = requireLib$3();
	            }
	            entry.fileName = iconv.decode(entry.fileName, this._zipFileNameEncoding);
	          }
	        }
	        // directory file names end with '/' (for Linux and macOS) or '\' (for Windows)
	        const type = /[\\\/]$/.test(entry.fileName) ? 'directory' : 'file';
	        const name = entry.fileName = this[STRIP_NAME](entry.fileName, type);

	        const header = { name, type, yauzl: entry, mode };

	        if (type === 'file') {
	          zipFile.openReadStream(entry, (err, readStream) => {
	            if (err) return this.emit('error', err);
	            this.emit('entry', header, readStream, next);
	          });
	        } else { // directory
	          const placeholder = new stream.Readable({ read() {} });
	          this.emit('entry', header, placeholder, next);
	          setImmediate(() => placeholder.emit('end'));
	        }
	      })
	      .on('end', () => this.emit('finish'))
	      .on('error', err => this.emit('error', err));

	    function next() {
	      zipFile.readEntry();
	    }
	  }

	  [STRIP_NAME](fileName, type) {
	    return utils.stripFileName(this._strip, fileName, type);
	  }
	}

	uncompress_stream$3 = ZipUncompressStream;
	return uncompress_stream$3;
}

var hasRequiredZip;

function requireZip () {
	if (hasRequiredZip) return zip;
	hasRequiredZip = 1;

	const utils = requireUtils$2();
	const ZipStream = requireStream$2();
	const ZipFileStream = requireFile_stream$3();
	const ZipUncompressStream = requireUncompress_stream$3();

	zip.Stream = ZipStream;
	zip.FileStream = ZipFileStream;
	zip.UncompressStream = ZipUncompressStream;
	zip.compressDir = utils.makeCompressDirFn(ZipStream);
	zip.compressFile = utils.makeFileProcessFn(ZipFileStream);
	zip.uncompress = utils.makeUncompressFn(ZipUncompressStream);
	zip.decompress = utils.makeUncompressFn(ZipUncompressStream);
	return zip;
}

var gzip = {};

var lib$3 = {};

var hasRequiredLib$2;

function requireLib$2 () {
	if (hasRequiredLib$2) return lib$3;
	hasRequiredLib$2 = 1;

	var util = require$$0$6;
	var stream = require$$1$1;

	lib$3.createReadStream = function (object, options) {
	  return new MultiStream (object, options);
	};

	var MultiStream = function (object, options) {
	  if (object instanceof Buffer || typeof object === 'string') {
	    options = options || {};
	    stream.Readable.call(this, {
	      highWaterMark: options.highWaterMark,
	      encoding: options.encoding
	    });
	  } else {
	    stream.Readable.call(this, { objectMode: true });
	  }
	  this._object = object;
	};

	util.inherits(MultiStream, stream.Readable);

	MultiStream.prototype._read = function () {
	  this.push(this._object);
	  this._object = null;
	};
	return lib$3;
}

var file_stream$2;
var hasRequiredFile_stream$2;

function requireFile_stream$2 () {
	if (hasRequiredFile_stream$2) return file_stream$2;
	hasRequiredFile_stream$2 = 1;

	const fs = fs__default;
	const zlib = require$$1$2;
	const utils = requireUtils$2();
	const streamifier = requireLib$2();

	class GzipFileStream extends zlib.Gzip {
	  constructor(opts) {
	    opts = opts || {};
	    super(opts.zlib);

	    const sourceType = utils.sourceType(opts.source);

	    if (sourceType === 'file') {
	      const stream = fs.createReadStream(opts.source, opts.fs);
	      stream.on('error', err => this.emit('error', err));
	      stream.pipe(this);
	      return;
	    }

	    if (sourceType === 'buffer') {
	      const stream = streamifier.createReadStream(opts.source, opts.streamifier);
	      stream.on('error', err => this.emit('error', err));
	      stream.pipe(this);
	      return;
	    }

	    if (sourceType === 'stream') {
	      opts.source.on('error', err => this.emit('error', err));
	      opts.source.pipe(this);
	    }

	    // else undefined: do nothing
	  }
	}

	file_stream$2 = GzipFileStream;
	return file_stream$2;
}

var uncompress_stream$2;
var hasRequiredUncompress_stream$2;

function requireUncompress_stream$2 () {
	if (hasRequiredUncompress_stream$2) return uncompress_stream$2;
	hasRequiredUncompress_stream$2 = 1;

	const fs = fs__default;
	const zlib = require$$1$2;
	const utils = requireUtils$2();
	const streamifier = requireLib$2();

	class GzipUncompressStream extends zlib.Unzip {
	  constructor(opts) {
	    opts = opts || {};
	    super(opts.zlib);

	    const sourceType = utils.sourceType(opts.source);

	    if (sourceType === 'file') {
	      const stream = fs.createReadStream(opts.source, opts.fs);
	      stream.on('error', err => this.emit('error', err));
	      stream.pipe(this);
	      return;
	    }

	    if (sourceType === 'buffer') {
	      const stream = streamifier.createReadStream(opts.source, opts.streamifier);
	      stream.on('error', err => this.emit('error', err));
	      stream.pipe(this);
	      return;
	    }

	    if (sourceType === 'stream') {
	      opts.source.on('error', err => this.emit('error', err));
	      opts.source.pipe(this);
	    }

	    // else: waiting to be piped
	  }
	}

	uncompress_stream$2 = GzipUncompressStream;
	return uncompress_stream$2;
}

var hasRequiredGzip;

function requireGzip () {
	if (hasRequiredGzip) return gzip;
	hasRequiredGzip = 1;

	const utils = requireUtils$2();
	const GzipFileStream = requireFile_stream$2();
	const GzipUncompressStream = requireUncompress_stream$2();

	gzip.FileStream = GzipFileStream;
	gzip.UncompressStream = GzipUncompressStream;
	gzip.compressFile = utils.makeFileProcessFn(GzipFileStream);
	gzip.uncompress = utils.makeFileProcessFn(GzipUncompressStream);
	gzip.decompress = utils.makeFileProcessFn(GzipUncompressStream);
	return gzip;
}

var tar = {};

var file_stream$1;
var hasRequiredFile_stream$1;

function requireFile_stream$1 () {
	if (hasRequiredFile_stream$1) return file_stream$1;
	hasRequiredFile_stream$1 = 1;

	const fs = fs__default;
	const path = path__default;
	const stream = require$$1$1;
	const tar = requireTarStream();
	const utils = requireUtils$2();
	const ready = requireGetReady();

	class TarFileStream extends stream.Transform {
	  constructor(opts) {
	    super(opts);

	    const pack = tar.pack();
	    pack.on('data', chunk => this.push(chunk));
	    pack.on('end', () => this.ready(true));

	    const sourceType = utils.sourceType(opts.source);

	    if (sourceType === 'file') {
	      // stat file to get file size
	      fs.stat(opts.source, (err, stat) => {
	        if (err) return this.emit('error', err);
	        this.entry = pack.entry({ name: opts.relativePath || path.basename(opts.source), size: stat.size, mode: stat.mode & 0o777 }, err => {
	          if (err) return this.emit('error', err);
	          pack.finalize();
	        });
	        const stream = fs.createReadStream(opts.source, opts.fs);
	        stream.on('error', err => this.emit('error', err));
	        stream.pipe(this);
	      });
	    } else if (sourceType === 'buffer') {
	      if (!opts.relativePath) return this.emit('error', 'opts.relativePath is required if opts.source is a buffer');

	      pack.entry({ name: opts.relativePath }, opts.source);
	      pack.finalize();
	      this.end();
	    } else { // stream or undefined
	      if (!opts.relativePath) return process.nextTick(() => this.emit('error', 'opts.relativePath is required'));

	      if (opts.size) {
	        this.entry = pack.entry({ name: opts.relativePath, size: opts.size }, err => {
	          if (err) return this.emit('error', err);
	          pack.finalize();
	        });
	      } else {
	        if (!opts.suppressSizeWarning) {
	          console.warn('You should specify the size of streamming data by opts.size to prevent all streaming data from loading into memory. If you are sure about memory cost, pass opts.suppressSizeWarning: true to suppress this warning');
	        }
	        const buf = [];
	        this.entry = new stream.Writable({
	          write(chunk, _, callback) {
	            buf.push(chunk);
	            callback();
	          },
	        });
	        this.entry.on('finish', () => {
	          pack.entry({ name: opts.relativePath }, Buffer.concat(buf));
	          pack.finalize();
	        });
	      }

	      if (sourceType === 'stream') {
	        opts.source.on('error', err => this.emit('error', err));
	        opts.source.pipe(this);
	      }
	    }
	  }

	  _transform(chunk, encoding, callback) {
	    if (this.entry) {
	      this.entry.write(chunk, encoding, callback);
	    }
	  }

	  _flush(callback) {
	    if (this.entry) {
	      this.entry.end();
	    }
	    this.ready(callback);
	  }
	}

	ready.mixin(TarFileStream.prototype);

	file_stream$1 = TarFileStream;
	return file_stream$1;
}

var uncompress_stream$1;
var hasRequiredUncompress_stream$1;

function requireUncompress_stream$1 () {
	if (hasRequiredUncompress_stream$1) return uncompress_stream$1;
	hasRequiredUncompress_stream$1 = 1;

	const fs = fs__default;
	const tar = requireTarStream();
	const utils = requireUtils$2();
	const streamifier = requireLib$2();

	// stream.Writable
	class TarUncompressStream extends tar.extract {
	  constructor(opts) {
	    opts = opts || {};
	    super(opts);

	    const sourceType = utils.sourceType(opts.source);

	    if (sourceType === 'file') {
	      const stream = fs.createReadStream(opts.source, opts.fs);
	      stream.on('error', err => this.emit('error', err));
	      stream.pipe(this);
	      return;
	    }

	    if (sourceType === 'buffer') {
	      const stream = streamifier.createReadStream(opts.source, opts.streamifier);
	      stream.on('error', err => this.emit('error', err));
	      stream.pipe(this);
	      return;
	    }

	    if (sourceType === 'stream') {
	      opts.source.on('error', err => this.emit('error', err));
	      opts.source.pipe(this);
	    }

	    // else: waiting to be piped
	  }
	}

	uncompress_stream$1 = TarUncompressStream;
	return uncompress_stream$1;
}

var hasRequiredTar;

function requireTar () {
	if (hasRequiredTar) return tar;
	hasRequiredTar = 1;

	const utils = requireUtils$2();
	const TarStream = requireStream$3();
	const TarFileStream = requireFile_stream$1();
	const TarUncompressStream = requireUncompress_stream$1();

	tar.Stream = TarStream;
	tar.FileStream = TarFileStream;
	tar.UncompressStream = TarUncompressStream;
	tar.compressDir = utils.makeCompressDirFn(TarStream);
	tar.compressFile = utils.makeFileProcessFn(TarFileStream);
	tar.uncompress = utils.makeUncompressFn(TarUncompressStream);
	tar.decompress = utils.makeUncompressFn(TarUncompressStream);
	return tar;
}

var tgz = {};

var stream$1;
var hasRequiredStream$1;

function requireStream$1 () {
	if (hasRequiredStream$1) return stream$1;
	hasRequiredStream$1 = 1;

	const tar = requireTar();
	const gzip = requireGzip();
	const BaseStream = requireBase_stream();

	class TgzStream extends BaseStream {
	  constructor(opts) {
	    super(opts);

	    const tarStream = this._tarStream = new tar.Stream();
	    tarStream.on('error', err => this.emit('error', err));

	    const gzipStream = new gzip.FileStream();
	    gzipStream.on('end', () => this.push(null));
	    gzipStream.on('data', chunk => this.push(chunk));
	    gzipStream.on('error', err => this.emit('error', err));

	    tarStream.pipe(gzipStream);
	  }

	  addEntry(entry, opts) {
	    this._tarStream.addEntry(entry, opts);
	  }
	}

	stream$1 = TgzStream;
	return stream$1;
}

var file_stream;
var hasRequiredFile_stream;

function requireFile_stream () {
	if (hasRequiredFile_stream) return file_stream;
	hasRequiredFile_stream = 1;

	const tar = requireTar();
	const gzip = requireGzip();
	const utils = requireUtils$2();
	const stream = require$$1$1;
	const pump = requirePump();
	const ready = requireGetReady();

	class TgzFileStream extends stream.Transform {
	  constructor(opts) {
	    opts = opts || {};
	    super(opts);

	    const sourceType = this._sourceType = utils.sourceType(opts.source);

	    const tarStream = this._tarStream = new tar.FileStream(opts);
	    opts = utils.clone(opts);
	    delete opts.source;
	    const gzipStream = new gzip.FileStream(opts);

	    gzipStream.on('data', chunk => {
	      this.push(chunk);
	    });
	    gzipStream.on('end', () => this.ready(true));

	    pump(tarStream, gzipStream, err => {
	      err && this.emit('error', err);
	    });

	    if (sourceType !== 'stream' && sourceType !== undefined) {
	      this.end();
	    }
	  }

	  _transform(chunk, encoding, callback) {
	    this._tarStream.write(chunk, encoding, callback);
	  }

	  _flush(callback) {
	    if (this._sourceType === 'stream' || this._sourceType === undefined) {
	      this._tarStream.end();
	    }
	    this.ready(callback);
	  }
	}

	ready.mixin(TgzFileStream.prototype);
	file_stream = TgzFileStream;
	return file_stream;
}

/*
 * FlushWritable
 * Copyright 2014 Tom Frost
 */

var FlushWritable_1;
var hasRequiredFlushWritable;

function requireFlushWritable () {
	if (hasRequiredFlushWritable) return FlushWritable_1;
	hasRequiredFlushWritable = 1;
	var EventEmitter = require$$0$5.EventEmitter,
		Writable = require$$1$1.Writable,
		util = require$$0$6;

	/**
	 * FlushWritable is a drop-in replacement for stream.Writable that implements
	 * the Transform stream's _flush() method.  FlushWritable is meant to be
	 * extended, just like stream.Writable.  However, in the child class's
	 * prototype, a method called _flush(cb) can be defined that will halt the
	 * firing of the 'finish' event until the callback is called.  If the callback
	 * if called with a truthy first argument, 'error' is emitted instead.
	 * @param {Object} [opts] Options to configure this Writable stream.  See the
	 *      Node.js docs for stream.Writable.
	 * @constructor
	 */
	function FlushWritable(opts) {
		Writable.call(this, opts);
	}
	util.inherits(FlushWritable, Writable);

	FlushWritable.prototype.emit = function(evt) {
		if (evt === 'finish' && this._flush && !Writable.prototype._flush) {
			this._flush(function(err) {
				if (err)
					EventEmitter.prototype.emit.call(this, 'error', err);
				else
					EventEmitter.prototype.emit.call(this, 'finish');
			}.bind(this));
		}
		else {
			var args = Array.prototype.slice.call(arguments);
			EventEmitter.prototype.emit.apply(this, args);
		}
	};

	FlushWritable_1 = FlushWritable;
	return FlushWritable_1;
}

var uncompress_stream;
var hasRequiredUncompress_stream;

function requireUncompress_stream () {
	if (hasRequiredUncompress_stream) return uncompress_stream;
	hasRequiredUncompress_stream = 1;

	const fs = fs__default;
	const utils = requireUtils$2();
	const ready = requireGetReady();
	const streamifier = requireLib$2();
	const FlushWritable = requireFlushWritable();
	const GzipUncompressStream = requireGzip().UncompressStream;
	const TarUncompressStream = requireTar().UncompressStream;

	class TgzUncompressStream extends FlushWritable {
	  constructor(opts) {
	    opts = opts || {};
	    super(opts);

	    const newOpts = utils.clone(opts);
	    newOpts.source = undefined;
	    this._gzipStream = new GzipUncompressStream(newOpts)
	      .on('error', err => this.emit('error', err));

	    const tarStream = new TarUncompressStream(newOpts)
	      .on('finish', () => this.ready(true))
	      .on('entry', this.emit.bind(this, 'entry'))
	      .on('error', err => this.emit('error', err));

	    this._gzipStream.pipe(tarStream);

	    const sourceType = utils.sourceType(opts.source);

	    if (sourceType === 'file') {
	      const stream = fs.createReadStream(opts.source, opts.fs);
	      stream.on('error', err => this.emit('error', err));
	      stream.pipe(this);
	      return;
	    }

	    if (sourceType === 'buffer') {
	      const stream = streamifier.createReadStream(opts.source, opts.streamifier);
	      stream.on('error', err => this.emit('error', err));
	      stream.pipe(this);
	      return;
	    }

	    if (sourceType === 'stream') {
	      opts.source.on('error', err => this.emit('error', err));
	      opts.source.pipe(this);
	    }

	    // else: waiting to be piped
	  }

	  _write(chunk, encoding, callback) {
	    this._gzipStream.write(chunk, encoding, callback);
	  }

	  _flush(callback) {
	    this._gzipStream.end();
	    this.ready(callback);
	  }
	}

	ready.mixin(TgzUncompressStream.prototype);

	uncompress_stream = TgzUncompressStream;
	return uncompress_stream;
}

var hasRequiredTgz;

function requireTgz () {
	if (hasRequiredTgz) return tgz;
	hasRequiredTgz = 1;

	const utils = requireUtils$2();
	const TgzStream = requireStream$1();
	const TgzFileStream = requireFile_stream();
	const TgzUncompressStream = requireUncompress_stream();

	tgz.Stream = TgzStream;
	tgz.FileStream = TgzFileStream;
	tgz.UncompressStream = TgzUncompressStream;
	tgz.compressDir = utils.makeCompressDirFn(TgzStream);
	tgz.compressFile = utils.makeFileProcessFn(TgzFileStream);
	tgz.uncompress = utils.makeUncompressFn(TgzUncompressStream);
	tgz.decompress = utils.makeUncompressFn(TgzUncompressStream);
	return tgz;
}

var hasRequiredCompressing;

function requireCompressing () {
	if (hasRequiredCompressing) return compressing$1;
	hasRequiredCompressing = 1;

	compressing$1.zip = requireZip();
	compressing$1.gzip = requireGzip();
	compressing$1.tar = requireTar();
	compressing$1.tgz = requireTgz();
	return compressing$1;
}

var compressingExports = requireCompressing();
const compressing = /*@__PURE__*/getDefaultExportFromCjs(compressingExports);

const downloadOri = "https://github.com/NapNeko/ffmpeg-build/releases/download/v1.0.0/ffmpeg-7.1.1-win64.zip";
const urls = [
  "https://j.1win.ggff.net/" + downloadOri,
  "https://git.yylx.win/" + downloadOri,
  "https://ghfile.geekertao.top/" + downloadOri,
  "https://gh-proxy.net/" + downloadOri,
  "https://ghm.078465.xyz/" + downloadOri,
  "https://gitproxy.127731.xyz/" + downloadOri,
  "https://jiashu.1win.eu.org/" + downloadOri,
  "https://github.tbedu.top/" + downloadOri,
  downloadOri
];
async function testUrl$1(url) {
  return new Promise((resolve) => {
    const req = https.get(url, { timeout: 5e3 }, (res) => {
      const statusCode = res.statusCode || 0;
      if (statusCode >= 200 && statusCode < 300) {
        req.destroy();
        resolve(true);
      } else {
        req.destroy();
        resolve(false);
      }
    });
    req.on("error", () => {
      resolve(false);
    });
    req.on("timeout", () => {
      req.destroy();
      resolve(false);
    });
  });
}
async function findAvailableUrl$1() {
  for (const url of urls) {
    try {
      const available = await testUrl$1(url);
      if (available) {
        return url;
      }
    } catch (_error) {
    }
  }
  return null;
}
async function downloadFile$1(url, destPath, progressCallback) {
  return new Promise((resolve) => {
    const file = fs.createWriteStream(destPath);
    const req = https.get(url, (res) => {
      const statusCode = res.statusCode || 0;
      if (statusCode >= 200 && statusCode < 300) {
        const totalSize = parseInt(res.headers["content-length"] || "0", 10);
        let downloadedSize = 0;
        let lastReportedPercent = -1;
        let lastReportTime = 0;
        if (totalSize > 0 && progressCallback) {
          progressCallback(0);
          lastReportTime = Date.now();
          res.on("data", (chunk) => {
            downloadedSize += chunk.length;
            const currentPercent = Math.floor(downloadedSize / totalSize * 100);
            const now = Date.now();
            if (currentPercent !== lastReportedPercent && (currentPercent - lastReportedPercent >= 1 || currentPercent === 100) && (now - lastReportTime >= 1e3 || currentPercent === 100)) {
              progressCallback(currentPercent);
              lastReportedPercent = currentPercent;
              lastReportTime = now;
            }
          });
        }
        pipeline$1(res, file).then(() => {
          if (progressCallback && lastReportedPercent !== 100) {
            progressCallback(100);
          }
          resolve(true);
        }).catch(() => resolve(false));
      } else {
        file.close();
        fs.unlink(destPath, () => {
        });
        resolve(false);
      }
    });
    req.on("error", () => {
      file.close();
      fs.unlink(destPath, () => {
      });
      resolve(false);
    });
  });
}
async function extractBinDirectory(zipPath, extractDir) {
  if (!fs.existsSync(extractDir)) {
    fs.mkdirSync(extractDir, { recursive: true });
  }
  const zipStream = new compressingExports.zip.UncompressStream({ source: zipPath });
  return new Promise((resolve, reject) => {
    zipStream.on("entry", (header, stream, next) => {
      const filePath = header.name;
      if (filePath.includes("/bin/") && filePath.endsWith(".exe")) {
        const fileName = path.basename(filePath);
        const targetPath = path.join(extractDir, fileName);
        const writeStream = fs.createWriteStream(targetPath);
        stream.pipe(writeStream);
        writeStream.on("finish", () => {
          next();
        });
        writeStream.on("error", () => {
          next();
        });
      } else {
        stream.resume();
        next();
      }
    });
    zipStream.on("error", (err) => {
      reject(err);
    });
    zipStream.on("finish", () => {
      resolve();
    });
  });
}
async function downloadFFmpeg(destDir, tempDir, progressCallback) {
  if (os.platform() !== "win32") {
    return null;
  }
  const destinationDir = destDir || path.join(os.tmpdir(), "ffmpeg");
  const tempDirectory = tempDir || os.tmpdir();
  const zipFilePath = path.join(tempDirectory, "ffmpeg.zip");
  const ffmpegExePath = path.join(destinationDir, "ffmpeg.exe");
  if (!fs.existsSync(destinationDir)) {
    fs.mkdirSync(destinationDir, { recursive: true });
  }
  if (!fs.existsSync(tempDirectory)) {
    fs.mkdirSync(tempDirectory, { recursive: true });
  }
  if (fs.existsSync(ffmpegExePath)) {
    if (progressCallback) progressCallback(100, "已找到FFmpeg");
    return ffmpegExePath;
  }
  if (progressCallback) progressCallback(0, "查找可用下载源");
  const availableUrl = await findAvailableUrl$1();
  if (!availableUrl) {
    return null;
  }
  if (progressCallback) progressCallback(5, "开始下载FFmpeg");
  const downloaded = await downloadFile$1(
    availableUrl,
    zipFilePath,
    (percent) => {
      if (progressCallback) progressCallback(5 + Math.floor(percent * 0.7), "下载FFmpeg");
    }
  );
  if (!downloaded) {
    return null;
  }
  try {
    if (progressCallback) progressCallback(75, "解压FFmpeg");
    await extractBinDirectory(zipFilePath, destinationDir);
    if (progressCallback) progressCallback(95, "清理临时文件");
    try {
      fs.unlinkSync(zipFilePath);
    } catch (_err) {
    }
    if (fs.existsSync(ffmpegExePath)) {
      if (progressCallback) progressCallback(100, "FFmpeg安装完成");
      return ffmpegExePath;
    } else {
      return null;
    }
  } catch (_err) {
    return null;
  }
}
function findExecutableInPath(executable) {
  if (os.platform() !== "win32") return null;
  const pathEnv = process.env["PATH"] || "";
  const pathDirs = pathEnv.split(";");
  for (const dir of pathDirs) {
    if (!dir) continue;
    try {
      const filePath = path.join(dir, executable);
      if (fs.existsSync(filePath)) {
        return filePath;
      }
    } catch (_error) {
      continue;
    }
  }
  return null;
}
async function downloadFFmpegIfNotExists(log) {
  if (os.platform() !== "win32") {
    return {
      path: null,
      reset: false
    };
  }
  const ffmpegInPath = findExecutableInPath("ffmpeg.exe");
  const ffprobeInPath = findExecutableInPath("ffprobe.exe");
  if (ffmpegInPath && ffprobeInPath) {
    const ffmpegDir = path.dirname(ffmpegInPath);
    return {
      path: ffmpegDir,
      reset: true
    };
  }
  const currentPath = path.dirname(fileURLToPath(import.meta.url));
  const ffmpeg_exist = fs.existsSync(path.join(currentPath, "ffmpeg", "ffmpeg.exe"));
  const ffprobe_exist = fs.existsSync(path.join(currentPath, "ffmpeg", "ffprobe.exe"));
  if (!ffmpeg_exist || !ffprobe_exist) {
    const url = await downloadFFmpeg(path.join(currentPath, "ffmpeg"), path.join(currentPath, "cache"), (percentage, message) => {
      log.log(`[FFmpeg] [Download] ${percentage}% - ${message}`);
    });
    if (!url) {
      log.log("[FFmpeg] [Error] 下载FFmpeg失败");
      return {
        path: null,
        reset: false
      };
    }
    return {
      path: path.join(currentPath, "ffmpeg"),
      reset: true
    };
  }
  return {
    path: path.join(currentPath, "ffmpeg"),
    reset: true
  };
}

const execFileAsync = promisify(execFile);
function ensureDirExists(filePath) {
  const dir = dirname(filePath);
  if (!existsSync$1(dir)) {
    mkdirSync(dir, { recursive: true });
  }
}
class FFmpegExecAdapter {
  constructor(ffmpegPath = "ffmpeg", ffprobePath = "ffprobe", binaryPath, logger) {
    this.ffmpegPath = ffmpegPath;
    this.ffprobePath = ffprobePath;
    this.binaryPath = binaryPath;
    this.logger = logger;
  }
  name = "FFmpegExec";
  downloadAttempted = false;
  /**
     * 检查 FFmpeg 是否可用，如果不可用则尝试下载
     */
  async isAvailable() {
    try {
      await execFileAsync(this.ffmpegPath, ["-version"]);
      return true;
    } catch {
      if (!this.downloadAttempted && this.binaryPath && this.logger) {
        this.downloadAttempted = true;
        if (process.env["NAPCAT_DISABLE_FFMPEG_DOWNLOAD"]) {
          return false;
        }
        this.logger.log("[FFmpeg] 未找到可用的 FFmpeg，尝试自动下载...");
        const result = await downloadFFmpegIfNotExists(this.logger);
        if (result.path && result.reset) {
          if (process.platform === "win32") {
            this.ffmpegPath = join(result.path, "ffmpeg.exe");
            this.ffprobePath = join(result.path, "ffprobe.exe");
            this.logger.log("[FFmpeg] 已更新路径:", this.ffmpegPath);
            try {
              await execFileAsync(this.ffmpegPath, ["-version"]);
              return true;
            } catch {
              return false;
            }
          }
        }
      }
      return false;
    }
  }
  /**
     * 设置 FFmpeg 路径
     */
  setFFmpegPath(ffmpegPath) {
    this.ffmpegPath = ffmpegPath;
  }
  /**
     * 设置 FFprobe 路径
     */
  setFFprobePath(ffprobePath) {
    this.ffprobePath = ffprobePath;
  }
  /**
     * 获取视频信息
     */
  async getVideoInfo(videoPath) {
    const [fileType, duration] = await Promise.all([
      fileTypeFromFile(videoPath).catch(() => null),
      this.getDuration(videoPath)
    ]);
    const thumbnailPath = `${videoPath}.thumbnail.bmp`;
    let width = 100;
    let height = 100;
    let thumbnail;
    try {
      await this.extractThumbnail(videoPath, thumbnailPath);
      const dimensions = await imageSizeFallBack(thumbnailPath);
      width = dimensions.width ?? 100;
      height = dimensions.height ?? 100;
      if (existsSync$1(thumbnailPath)) {
        thumbnail = readFileSync$1(thumbnailPath);
      }
    } catch (_error) {
    }
    return {
      width,
      height,
      duration,
      format: fileType?.ext ?? "mp4",
      thumbnail
    };
  }
  /**
     * 获取时长
     */
  async getDuration(filePath) {
    try {
      const { stdout } = await execFileAsync(this.ffprobePath, [
        "-v",
        "error",
        "-show_entries",
        "format=duration",
        "-of",
        "default=noprint_wrappers=1:nokey=1",
        filePath
      ]);
      const duration = parseFloat(stdout.trim());
      return isNaN(duration) ? 60 : duration;
    } catch {
      return 60;
    }
  }
  /**
     * 转换为 PCM
     */
  async convertToPCM(filePath, pcmPath) {
    try {
      ensureDirExists(pcmPath);
      await execFileAsync(this.ffmpegPath, [
        "-y",
        "-i",
        filePath,
        "-ar",
        "24000",
        "-ac",
        "1",
        "-f",
        "s16le",
        pcmPath
      ]);
      if (!existsSync$1(pcmPath)) {
        throw new Error("转换PCM失败，输出文件不存在");
      }
      return { result: true, sampleRate: 24e3 };
    } catch (error) {
      throw new Error(`FFmpeg处理转换出错: ${error.message}`);
    }
  }
  /**
     * 转换文件
     */
  async convertFile(inputFile, outputFile, format) {
    try {
      ensureDirExists(outputFile);
      const params = format === "amr" ? [
        "-f",
        "s16le",
        "-ar",
        "24000",
        "-ac",
        "1",
        "-i",
        inputFile,
        "-ar",
        "8000",
        "-b:a",
        "12.2k",
        "-y",
        outputFile
      ] : [
        "-f",
        "s16le",
        "-ar",
        "24000",
        "-ac",
        "1",
        "-i",
        inputFile,
        "-y",
        outputFile
      ];
      await execFileAsync(this.ffmpegPath, params);
      if (!existsSync$1(outputFile)) {
        throw new Error("转换失败,输出文件不存在");
      }
    } catch (error) {
      console.error("Error converting file:", error);
      throw new Error(`文件转换失败: ${error.message}`);
    }
  }
  /**
     * 提取缩略图
     */
  async extractThumbnail(videoPath, thumbnailPath) {
    try {
      ensureDirExists(thumbnailPath);
      const { stderr } = await execFileAsync(this.ffmpegPath, [
        "-i",
        videoPath,
        "-ss",
        "00:00:01.000",
        "-vframes",
        "1",
        "-y",
        // 覆盖输出文件
        thumbnailPath
      ]);
      if (!existsSync$1(thumbnailPath)) {
        throw new Error(`提取缩略图失败，输出文件不存在: ${stderr}`);
      }
    } catch (error) {
      console.error("Error extracting thumbnail:", error);
      throw new Error(`提取缩略图失败: ${error.message}`);
    }
  }
}

class FFmpegAdapterFactory {
  static instance = null;
  static initPromise = null;
  /**
     * 初始化并获取最佳的 FFmpeg 适配器
     * @param logger 日志记录器
     * @param ffmpegPath FFmpeg 可执行文件路径(用于 Exec 适配器)
     * @param ffprobePath FFprobe 可执行文件路径(用于 Exec 适配器)
     * @param binaryPath 二进制文件路径(来自 pathWrapper.binaryPath,用于 Addon 适配器)
     */
  static async getAdapter(logger, ffmpegPath = "ffmpeg", ffprobePath = "ffprobe", binaryPath) {
    if (this.instance) {
      return this.instance;
    }
    if (this.initPromise) {
      return this.initPromise;
    }
    this.initPromise = this.initialize(logger, ffmpegPath, ffprobePath, binaryPath);
    try {
      this.instance = await this.initPromise;
      return this.instance;
    } finally {
      this.initPromise = null;
    }
  }
  /**
     * 初始化适配器
     */
  static async initialize(logger, ffmpegPath, ffprobePath, binaryPath) {
    if (binaryPath) {
      const addonAdapter = new FFmpegAddonAdapter(binaryPath);
      logger.log("[FFmpeg] 检查 Native Addon 可用性...");
      if (await addonAdapter.isAvailable()) {
        logger.log("[FFmpeg] ✓ 使用 Native Addon 适配器");
        return addonAdapter;
      }
      logger.log("[FFmpeg] Native Addon 不可用，尝试使用命令行工具");
    } else {
      logger.log("[FFmpeg] 未提供 binaryPath，跳过 Native Addon 检测");
    }
    const execAdapter = new FFmpegExecAdapter(ffmpegPath, ffprobePath, binaryPath, logger);
    logger.log(`[FFmpeg] 检查命令行工具可用性: ${ffmpegPath}`);
    if (await execAdapter.isAvailable()) {
      logger.log("[FFmpeg] 使用命令行工具适配器 ✓");
      return execAdapter;
    }
    logger.logError("[FFmpeg] 警告: FFmpeg 不可用，将使用命令行适配器但可能失败");
    return execAdapter;
  }
  /**
     * 重置适配器(用于测试或重新初始化)
     */
  static reset() {
    this.instance = null;
    this.initPromise = null;
  }
  /**
     * 更新 FFmpeg 路径并重新初始化
     * @param logger 日志记录器
     * @param ffmpegPath FFmpeg 可执行文件路径
     * @param ffprobePath FFprobe 可执行文件路径
     */
  static async updateFFmpegPath(logger, ffmpegPath, ffprobePath) {
    if (this.instance && this.instance instanceof FFmpegExecAdapter) {
      logger.log(`[FFmpeg] 更新 FFmpeg 路径: ${ffmpegPath}`);
      this.instance.setFFmpegPath(ffmpegPath);
      this.instance.setFFprobePath(ffprobePath);
      if (await this.instance.isAvailable()) {
        logger.log("[FFmpeg] 新路径验证成功 ✓");
      } else {
        logger.logError("[FFmpeg] 警告: 新 FFmpeg 路径不可用");
      }
    }
  }
  /**
     * 获取当前适配器(不初始化)
     */
  static getCurrentAdapter() {
    return this.instance;
  }
}

const getFFmpegPath = (tool, binaryPath) => {
  if (process.platform === "win32" && binaryPath) {
    const exeName = `${tool}.exe`;
    const localPath = path__default.join(binaryPath, "ffmpeg", exeName);
    const isLocalExeExists = existsSync$1(localPath);
    return isLocalExeExists ? localPath : exeName;
  }
  return tool;
};
let FFMPEG_CMD = "ffmpeg";
let FFPROBE_CMD = "ffprobe";
class FFmpegService {
  static adapter = null;
  static initialized = false;
  /**
     * 初始化 FFmpeg 服务
     * @param binaryPath 二进制文件路径(来自 pathWrapper.binaryPath)
     * @param logger 日志记录器
     */
  static async init(binaryPath, logger) {
    if (this.initialized) {
      return;
    }
    FFMPEG_CMD = getFFmpegPath("ffmpeg", binaryPath);
    FFPROBE_CMD = getFFmpegPath("ffprobe", binaryPath);
    this.adapter = await FFmpegAdapterFactory.getAdapter(
      logger,
      FFMPEG_CMD,
      FFPROBE_CMD,
      binaryPath
    );
    this.initialized = true;
  }
  static getAdapterName() {
    if (!this.adapter) {
      throw new Error("FFmpeg service not initialized. Please call FFmpegService.init() first.");
    }
    return this.adapter.name;
  }
  /**
     * 获取 FFmpeg 适配器
     */
  static async getAdapter() {
    if (!this.adapter) {
      throw new Error("FFmpeg service not initialized. Please call FFmpegService.init() first.");
    }
    return this.adapter;
  }
  /**
     * 设置 FFmpeg 路径并更新适配器
     * @deprecated 建议使用 init() 方法初始化
     */
  static async setFfmpegPath(ffmpegPath, logger) {
    if (platform() === "win32") {
      FFMPEG_CMD = path__default.join(ffmpegPath, "ffmpeg.exe");
      FFPROBE_CMD = path__default.join(ffmpegPath, "ffprobe.exe");
      logger.log("[Check] ffmpeg:", FFMPEG_CMD);
      logger.log("[Check] ffprobe:", FFPROBE_CMD);
      await FFmpegAdapterFactory.updateFFmpegPath(logger, FFMPEG_CMD, FFPROBE_CMD);
    }
  }
  /**
     * 提取视频缩略图
     */
  static async extractThumbnail(videoPath, thumbnailPath) {
    const adapter = await this.getAdapter();
    await adapter.extractThumbnail(videoPath, thumbnailPath);
  }
  /**
     * 转换音频文件
     */
  static async convertFile(inputFile, outputFile, format) {
    const adapter = await this.getAdapter();
    await adapter.convertFile(inputFile, outputFile, format);
  }
  /**
     * 转换为 PCM 格式
     */
  static async convert(filePath, pcmPath) {
    const adapter = await this.getAdapter();
    return adapter.convertToPCM(filePath, pcmPath);
  }
  /**
     * 获取视频信息
     */
  static async getVideoInfo(videoPath, thumbnailPath) {
    const adapter = await this.getAdapter();
    try {
      const fileSize = statSync$1(videoPath).size;
      const videoInfo = await adapter.getVideoInfo(videoPath);
      if (thumbnailPath && videoInfo.thumbnail) {
        writeFileSync(thumbnailPath, videoInfo.thumbnail);
      }
      const result = {
        width: videoInfo.width,
        height: videoInfo.height,
        time: videoInfo.duration,
        format: videoInfo.format,
        size: fileSize,
        filePath: videoPath
      };
      return result;
    } catch (_error) {
      const fileType = await fileTypeFromFile(videoPath).catch(() => null);
      const fileSize = statSync$1(videoPath).size;
      return {
        width: 100,
        height: 100,
        time: 60,
        format: fileType?.ext ?? "mp4",
        size: fileSize,
        filePath: videoPath
      };
    }
  }
}

const defaultVideoThumbB64 = " ";

const BlockSize = 1024 * 1024;
class PacketHighwayContext {
  napcore;
  client;
  sig;
  logger;
  hwClient;
  cachedPrepareReq = null;
  constructor(napcore, logger, client) {
    this.napcore = napcore;
    this.client = client;
    this.sig = {
      uin: String(this.napcore.basicInfo.uin),
      uid: this.napcore.basicInfo.uid,
      sigSession: null,
      sessionKey: null,
      serverAddr: []
    };
    this.logger = logger;
    this.hwClient = new PacketHighwayClient(this.sig, this.logger);
  }
  async checkAvailable() {
    if (this.sig.sigSession === null || this.sig.sessionKey === null) {
      if (this.cachedPrepareReq === null) {
        this.cachedPrepareReq = this.prepareUpload().finally(() => {
          this.cachedPrepareReq = null;
        });
      }
      await this.cachedPrepareReq;
    }
  }
  async prepareUpload() {
    this.logger.debug("[Highway] on prepareUpload!");
    const packet = FetchSessionKey$1.build();
    const req = await this.client.sendOidbPacket(packet, true);
    const rsp = FetchSessionKey$1.parse(req);
    this.sig.sigSession = rsp.httpConn.sigSession;
    this.sig.sessionKey = rsp.httpConn.sessionKey;
    for (const info of rsp.httpConn.serverInfos) {
      if (info.serviceType !== 1) continue;
      for (const addr of info.serverAddrs) {
        this.logger.debug(`[Highway PrepareUpload] server addr add: ${int32ip2str(addr.ip)}:${addr.port}`);
        this.sig.serverAddr.push({
          ip: int32ip2str(addr.ip),
          port: addr.port
        });
        this.hwClient.changeServer(int32ip2str(addr.ip), addr.port);
      }
    }
    if (this.sig.serverAddr.length === 0) {
      this.logger.warn("[Highway PrepareUpload] server addr is empty!");
    }
  }
  async uploadImage(peer, img) {
    await this.checkAvailable();
    if (peer.chatType === ChatType.KCHATTYPEGROUP) {
      await this.uploadGroupImage(+peer.peerUid, img);
    } else if (peer.chatType === ChatType.KCHATTYPEC2C) {
      await this.uploadC2CImage(peer.peerUid, img);
    } else {
      throw new Error(`[Highway] unsupported chatType: ${peer.chatType}`);
    }
  }
  async uploadVideo(peer, video) {
    await this.checkAvailable();
    if (+(video.fileSize ?? 0) > 1024 * 1024 * 100) {
      throw new Error(`[Highway] 视频文件过大: ${(+(video.fileSize ?? 0) / (1024 * 1024)).toFixed(2)} MB > 100 MB，请使用文件上传！`);
    }
    let tempThumbPath = null;
    let thumbExists = false;
    if (video.thumbPath) {
      try {
        await fs__default.promises.access(video.thumbPath, fs__default.constants.F_OK);
        thumbExists = true;
      } catch {
        thumbExists = false;
      }
    }
    if (!video.thumbPath || !thumbExists) {
      tempThumbPath = await this.ensureVideoThumb(video);
    }
    try {
      if (peer.chatType === ChatType.KCHATTYPEGROUP) {
        await this.uploadGroupVideo(+peer.peerUid, video);
      } else if (peer.chatType === ChatType.KCHATTYPEC2C) {
        await this.uploadC2CVideo(peer.peerUid, video);
      } else {
        throw new Error(`[Highway] unsupported chatType: ${peer.chatType}`);
      }
    } finally {
      if (tempThumbPath) {
        const thumbToClean = tempThumbPath;
        fs__default.promises.unlink(thumbToClean).then(() => this.logger.debug(`[Highway] Cleaned up temp thumbnail: ${thumbToClean}`)).catch((e) => {
          if (e.code !== "ENOENT") {
            this.logger.warn(`[Highway] Failed to clean up temp thumbnail: ${thumbToClean}, reason: ${e instanceof Error ? e.message : e}`);
          }
        });
      }
    }
  }
  /**
   * 确保视频缩略图存在，如果不存在则自动生成
   * @returns 生成的临时缩略图路径，用于后续清理
   */
  async ensureVideoThumb(video) {
    if (!video.filePath) {
      throw new Error("video.filePath is empty, cannot generate thumbnail");
    }
    const videoDir = path__default.dirname(video.filePath);
    const videoBasename = path__default.basename(video.filePath, path__default.extname(video.filePath));
    const thumbPath = path__default.join(videoDir, `${videoBasename}_thumb.png`);
    this.logger.debug(`[Highway] Video thumb missing, generating at: ${thumbPath}`);
    try {
      await FFmpegService.extractThumbnail(video.filePath, thumbPath);
      try {
        await fs__default.promises.access(thumbPath, fs__default.constants.F_OK);
        this.logger.debug("[Highway] Video thumbnail generated successfully using FFmpeg");
      } catch {
        throw new Error("FFmpeg failed to generate thumbnail");
      }
    } catch (e) {
      this.logger.warn(`[Highway] Failed to extract thumbnail, using default. Reason: ${e instanceof Error ? e.message : e}`);
      await fs__default.promises.writeFile(thumbPath, Buffer.from(defaultVideoThumbB64, "base64"));
    }
    video.thumbPath = thumbPath;
    const thumbStat = await fs__default.promises.stat(thumbPath);
    video.thumbSize = thumbStat.size;
    video.thumbMd5 = await calculateFileMD5(thumbPath);
    if (!video.thumbWidth) video.thumbWidth = 240;
    if (!video.thumbHeight) video.thumbHeight = 383;
    this.logger.debug(`[Highway] Video thumb info set: path=${thumbPath}, size=${video.thumbSize}, md5=${video.thumbMd5}`);
    return thumbPath;
  }
  async uploadPtt(peer, ptt) {
    await this.checkAvailable();
    if (peer.chatType === ChatType.KCHATTYPEGROUP) {
      await this.uploadGroupPtt(+peer.peerUid, ptt);
    } else if (peer.chatType === ChatType.KCHATTYPEC2C) {
      await this.uploadC2CPtt(peer.peerUid, ptt);
    } else {
      throw new Error(`[Highway] unsupported chatType: ${peer.chatType}`);
    }
  }
  async uploadFile(peer, file) {
    await this.checkAvailable();
    if (peer.chatType === ChatType.KCHATTYPEGROUP) {
      await this.uploadGroupFile(+peer.peerUid, file);
    } else if (peer.chatType === ChatType.KCHATTYPEC2C) {
      await this.uploadC2CFile(peer.peerUid, file);
    } else {
      throw new Error(`[Highway] unsupported chatType: ${peer.chatType}`);
    }
  }
  async uploadGroupImage(groupUin, img) {
    img.sha1 = Buffer.from(await calculateSha1(img.path)).toString("hex");
    const req = UploadGroupImage$1.build(groupUin, img);
    const resp = await this.client.sendOidbPacket(req, true);
    const preRespData = UploadGroupImage$1.parse(resp);
    const ukey = preRespData.upload.uKey;
    if (ukey && ukey !== "") {
      this.logger.debug(`[Highway] uploadGroupImageReq get upload ukey: ${ukey}, need upload!`);
      const index = preRespData.upload.msgInfo.msgInfoBody[0].index;
      const sha1 = Buffer.from(index.info.fileSha1, "hex");
      const md5 = Buffer.from(index.info.fileHash, "hex");
      const extend = new NapProtoMsg(NTV2RichMediaHighwayExt).encode({
        fileUuid: index.fileUuid,
        uKey: ukey,
        network: {
          ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S)
        },
        msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
        blockSize: BlockSize,
        hash: {
          fileSha1: [sha1]
        }
      });
      await this.hwClient.upload(
        1004,
        fs__default.createReadStream(img.path, { highWaterMark: BlockSize }),
        img.size,
        md5,
        extend
      );
    } else {
      this.logger.debug(`[Highway] uploadGroupImageReq get upload invalid ukey ${ukey}, don't need upload!`);
    }
    img.msgInfo = preRespData.upload.msgInfo;
  }
  async uploadC2CImage(peerUid, img) {
    img.sha1 = Buffer.from(await calculateSha1(img.path)).toString("hex");
    const req = UploadPrivateImage_default.build(peerUid, img);
    const resp = await this.client.sendOidbPacket(req, true);
    const preRespData = UploadPrivateImage_default.parse(resp);
    const ukey = preRespData.upload.uKey;
    if (ukey && ukey !== "") {
      this.logger.debug(`[Highway] uploadC2CImageReq get upload ukey: ${ukey}, need upload!`);
      const index = preRespData.upload.msgInfo.msgInfoBody[0].index;
      const sha1 = Buffer.from(index.info.fileSha1, "hex");
      const md5 = Buffer.from(index.info.fileHash, "hex");
      const extend = new NapProtoMsg(NTV2RichMediaHighwayExt).encode({
        fileUuid: index.fileUuid,
        uKey: ukey,
        network: {
          ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S)
        },
        msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
        blockSize: BlockSize,
        hash: {
          fileSha1: [sha1]
        }
      });
      await this.hwClient.upload(
        1003,
        fs__default.createReadStream(img.path, { highWaterMark: BlockSize }),
        img.size,
        md5,
        extend
      );
    } else {
      this.logger.debug(`[Highway] uploadC2CImageReq get upload invalid ukey ${ukey}, don't need upload!`);
    }
    img.msgInfo = preRespData.upload.msgInfo;
  }
  async uploadGroupVideo(groupUin, video) {
    if (!video.filePath || !video.thumbPath) throw new Error("video.filePath or video.thumbPath is empty");
    video.fileSha1 = Buffer.from(await calculateSha1(video.filePath)).toString("hex");
    video.thumbSha1 = Buffer.from(await calculateSha1(video.thumbPath)).toString("hex");
    const req = UploadGroupVideo_default.build(groupUin, video);
    const resp = await this.client.sendOidbPacket(req, true);
    const preRespData = UploadGroupVideo_default.parse(resp);
    const ukey = preRespData.upload.uKey;
    if (ukey && ukey !== "") {
      this.logger.debug(`[Highway] uploadGroupVideoReq get upload video ukey: ${ukey}, need upload!`);
      const index = preRespData.upload.msgInfo.msgInfoBody[0].index;
      const md5 = Buffer.from(index.info.fileHash, "hex");
      const extend = new NapProtoMsg(NTV2RichMediaHighwayExt).encode({
        fileUuid: index.fileUuid,
        uKey: ukey,
        network: {
          ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S)
        },
        msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
        blockSize: BlockSize,
        hash: {
          fileSha1: await calculateSha1StreamBytes(video.filePath)
        }
      });
      await this.hwClient.upload(
        1005,
        fs__default.createReadStream(video.filePath, { highWaterMark: BlockSize }),
        +video.fileSize,
        md5,
        extend
      );
    } else {
      this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid ukey ${ukey}, don't need upload!`);
    }
    const subFile = preRespData.upload.subFileInfos[0];
    if (subFile.uKey && subFile.uKey !== "") {
      this.logger.debug(`[Highway] uploadGroupVideoReq get upload video thumb ukey: ${subFile.uKey}, need upload!`);
      const index = preRespData.upload.msgInfo.msgInfoBody[1].index;
      const md5 = Buffer.from(index.info.fileHash, "hex");
      const sha1 = Buffer.from(index.info.fileSha1, "hex");
      const extend = new NapProtoMsg(NTV2RichMediaHighwayExt).encode({
        fileUuid: index.fileUuid,
        uKey: subFile.uKey,
        network: {
          ipv4S: oidbIpv4s2HighwayIpv4s(subFile.ipv4S)
        },
        msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
        blockSize: BlockSize,
        hash: {
          fileSha1: [sha1]
        }
      });
      await this.hwClient.upload(
        1006,
        fs__default.createReadStream(video.thumbPath, { highWaterMark: BlockSize }),
        +video.thumbSize,
        md5,
        extend
      );
    } else {
      this.logger.debug(`[Highway] uploadGroupVideoReq get upload invalid thumb ukey ${subFile.uKey}, don't need upload!`);
    }
    video.msgInfo = preRespData.upload.msgInfo;
  }
  async uploadC2CVideo(peerUid, video) {
    if (!video.filePath || !video.thumbPath) throw new Error("video.filePath or video.thumbPath is empty");
    video.fileSha1 = Buffer.from(await calculateSha1(video.filePath)).toString("hex");
    video.thumbSha1 = Buffer.from(await calculateSha1(video.thumbPath)).toString("hex");
    const req = UploadPrivateVideo_default.build(peerUid, video);
    const resp = await this.client.sendOidbPacket(req, true);
    const preRespData = UploadPrivateVideo_default.parse(resp);
    const ukey = preRespData.upload.uKey;
    if (ukey && ukey !== "") {
      this.logger.debug(`[Highway] uploadC2CVideoReq get upload video ukey: ${ukey}, need upload!`);
      const index = preRespData.upload.msgInfo.msgInfoBody[0].index;
      const md5 = Buffer.from(index.info.fileHash, "hex");
      const extend = new NapProtoMsg(NTV2RichMediaHighwayExt).encode({
        fileUuid: index.fileUuid,
        uKey: ukey,
        network: {
          ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S)
        },
        msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
        blockSize: BlockSize,
        hash: {
          fileSha1: await calculateSha1StreamBytes(video.filePath)
        }
      });
      await this.hwClient.upload(
        1001,
        fs__default.createReadStream(video.filePath, { highWaterMark: BlockSize }),
        +video.fileSize,
        md5,
        extend
      );
    } else {
      this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid ukey ${ukey}, don't need upload!`);
    }
    const subFile = preRespData.upload.subFileInfos[0];
    if (subFile.uKey && subFile.uKey !== "") {
      this.logger.debug(`[Highway] uploadC2CVideoReq get upload video thumb ukey: ${subFile.uKey}, need upload!`);
      const index = preRespData.upload.msgInfo.msgInfoBody[1].index;
      const md5 = Buffer.from(index.info.fileHash, "hex");
      const sha1 = Buffer.from(index.info.fileSha1, "hex");
      const extend = new NapProtoMsg(NTV2RichMediaHighwayExt).encode({
        fileUuid: index.fileUuid,
        uKey: subFile.uKey,
        network: {
          ipv4S: oidbIpv4s2HighwayIpv4s(subFile.ipv4S)
        },
        msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
        blockSize: BlockSize,
        hash: {
          fileSha1: [sha1]
        }
      });
      await this.hwClient.upload(
        1002,
        fs__default.createReadStream(video.thumbPath, { highWaterMark: BlockSize }),
        +video.thumbSize,
        md5,
        extend
      );
    } else {
      this.logger.debug(`[Highway] uploadC2CVideoReq get upload invalid thumb ukey ${subFile.uKey}, don't need upload!`);
    }
    video.msgInfo = preRespData.upload.msgInfo;
  }
  async uploadGroupPtt(groupUin, ptt) {
    ptt.fileSha1 = Buffer.from(await calculateSha1(ptt.filePath)).toString("hex");
    const req = instance$1.build(groupUin, ptt);
    const resp = await this.client.sendOidbPacket(req, true);
    const preRespData = instance$1.parse(resp);
    const ukey = preRespData.upload.uKey;
    if (ukey && ukey !== "") {
      this.logger.debug(`[Highway] uploadGroupPttReq get upload ptt ukey: ${ukey}, need upload!`);
      const index = preRespData.upload.msgInfo.msgInfoBody[0].index;
      const md5 = Buffer.from(index.info.fileHash, "hex");
      const sha1 = Buffer.from(index.info.fileSha1, "hex");
      const extend = new NapProtoMsg(NTV2RichMediaHighwayExt).encode({
        fileUuid: index.fileUuid,
        uKey: ukey,
        network: {
          ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S)
        },
        msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
        blockSize: BlockSize,
        hash: {
          fileSha1: [sha1]
        }
      });
      await this.hwClient.upload(
        1008,
        fs__default.createReadStream(ptt.filePath, { highWaterMark: BlockSize }),
        ptt.fileSize,
        md5,
        extend
      );
    } else {
      this.logger.debug(`[Highway] uploadGroupPttReq get upload invalid ukey ${ukey}, don't need upload!`);
    }
    ptt.msgInfo = preRespData.upload.msgInfo;
  }
  async uploadC2CPtt(peerUid, ptt) {
    ptt.fileSha1 = Buffer.from(await calculateSha1(ptt.filePath)).toString("hex");
    const req = UploadPrivatePtt_default.build(peerUid, ptt);
    const resp = await this.client.sendOidbPacket(req, true);
    const preRespData = UploadPrivatePtt_default.parse(resp);
    const ukey = preRespData.upload.uKey;
    if (ukey && ukey !== "") {
      this.logger.debug(`[Highway] uploadC2CPttReq get upload ptt ukey: ${ukey}, need upload!`);
      const index = preRespData.upload.msgInfo.msgInfoBody[0].index;
      const md5 = Buffer.from(index.info.fileHash, "hex");
      const sha1 = Buffer.from(index.info.fileSha1, "hex");
      const extend = new NapProtoMsg(NTV2RichMediaHighwayExt).encode({
        fileUuid: index.fileUuid,
        uKey: ukey,
        network: {
          ipv4S: oidbIpv4s2HighwayIpv4s(preRespData.upload.ipv4S)
        },
        msgInfoBody: preRespData.upload.msgInfo.msgInfoBody,
        blockSize: BlockSize,
        hash: {
          fileSha1: [sha1]
        }
      });
      await this.hwClient.upload(
        1007,
        fs__default.createReadStream(ptt.filePath, { highWaterMark: BlockSize }),
        ptt.fileSize,
        md5,
        extend
      );
    } else {
      this.logger.debug(`[Highway] uploadC2CPttReq get upload invalid ukey ${ukey}, don't need upload!`);
    }
    ptt.msgInfo = preRespData.upload.msgInfo;
  }
  async uploadGroupFile(groupUin, file) {
    file.isGroupFile = true;
    file.fileMd5 = await computeMd5AndLengthWithLimit(file.filePath);
    file.fileSha1 = await calculateSha1(file.filePath);
    const req = UploadGroupFile_default.build(groupUin, file);
    const resp = await this.client.sendOidbPacket(req, true);
    const preRespData = UploadGroupFile_default.parse(resp);
    if (!preRespData?.upload?.boolFileExist) {
      this.logger.debug("[Highway] uploadGroupFileReq file not exist, need upload!");
      const ext = new NapProtoMsg(FileUploadExt).encode({
        unknown1: 100,
        unknown2: 1,
        entry: {
          busiBuff: {
            senderUin: BigInt(this.sig.uin),
            receiverUin: BigInt(groupUin),
            groupCode: BigInt(groupUin)
          },
          fileEntry: {
            fileSize: BigInt(file.fileSize),
            md5: file.fileMd5,
            md5S2: file.fileMd5,
            checkKey: preRespData.upload.checkKey,
            fileId: preRespData.upload.fileId,
            uploadKey: preRespData.upload.fileKey
          },
          clientInfo: {
            clientType: 3,
            appId: "100",
            terminalType: 3,
            clientVer: "1.1.1",
            unknown: 4
          },
          fileNameInfo: {
            fileName: file.fileName
          },
          host: {
            hosts: [
              {
                url: {
                  host: preRespData.upload.uploadIp,
                  unknown: 1
                },
                port: preRespData.upload.uploadPort
              }
            ]
          }
        },
        unknown200: 0
      });
      await this.hwClient.upload(
        71,
        fs__default.createReadStream(file.filePath, { highWaterMark: BlockSize }),
        file.fileSize,
        file.fileMd5,
        ext
      );
    } else {
      this.logger.debug("[Highway] uploadGroupFileReq file exist, don't need upload!");
    }
    file.fileUuid = preRespData.upload.fileId;
  }
  async uploadC2CFile(peerUid, file) {
    file.isGroupFile = false;
    file.fileMd5 = await computeMd5AndLengthWithLimit(file.filePath);
    file.fileSha1 = await calculateSha1(file.filePath);
    const req = await UploadPrivateFile_default.build(this.sig.uid, peerUid, file);
    const res = await this.client.sendOidbPacket(req, true);
    const preRespData = UploadPrivateFile_default.parse(res);
    if (!preRespData.upload?.boolFileExist) {
      this.logger.debug("[Highway] uploadC2CFileReq file not exist, need upload!");
      const ext = new NapProtoMsg(FileUploadExt).encode({
        unknown1: 100,
        unknown2: 1,
        entry: {
          busiBuff: {
            senderUin: BigInt(this.sig.uin)
          },
          fileEntry: {
            fileSize: BigInt(file.fileSize),
            md5: file.fileMd5,
            md5S2: file.fileMd5,
            checkKey: file.fileSha1,
            fileId: preRespData.upload?.uuid,
            uploadKey: preRespData.upload?.mediaPlatformUploadKey
          },
          clientInfo: {
            clientType: 3,
            appId: "100",
            terminalType: 3,
            clientVer: "1.1.1",
            unknown: 4
          },
          fileNameInfo: {
            fileName: file.fileName
          },
          host: {
            hosts: [
              {
                url: {
                  host: preRespData.upload?.uploadIp,
                  unknown: 1
                },
                port: preRespData.upload?.uploadPort
              }
            ]
          }
        },
        unknown200: 1,
        unknown3: 0
      });
      await this.hwClient.upload(
        95,
        fs__default.createReadStream(file.filePath, { highWaterMark: BlockSize }),
        file.fileSize,
        file.fileMd5,
        ext
      );
    }
    file.fileUuid = preRespData.upload?.uuid;
    file.fileHash = preRespData.upload?.fileAddon;
    const fileExistReq = DownloadOfflineFile_default.build(file.fileUuid, file.fileHash, this.sig.uid, peerUid);
    const fileExistRes = await this.client.sendOidbPacket(fileExistReq, true);
    file._e37_800_rsp = DownloadOfflineFile_default.parse(fileExistRes);
    file._private_send_uid = this.sig.uid;
    file._private_recv_uid = peerUid;
  }
}

var winston$1 = {};

var browser$2 = {};

var format$4;
var hasRequiredFormat$3;

function requireFormat$3 () {
	if (hasRequiredFormat$3) return format$4;
	hasRequiredFormat$3 = 1;

	/*
	 * Displays a helpful message and the source of
	 * the format when it is invalid.
	 */
	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _createClass(e, r, t) { return Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
	function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
	function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
	function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: true, configurable: true } }), Object.defineProperty(t, "prototype", { writable: false }), e && _setPrototypeOf(t, e); }
	function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); }
	function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; }
	function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
	function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } }
	function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
	function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
	var InvalidFormatError = /*#__PURE__*/function (_Error) {
	  function InvalidFormatError(formatFn) {
	    var _this;
	    _classCallCheck(this, InvalidFormatError);
	    _this = _callSuper(this, InvalidFormatError, ["Format functions must be synchronous taking a two arguments: (info, opts)\nFound: ".concat(formatFn.toString().split('\n')[0], "\n")]);
	    Error.captureStackTrace(_this, InvalidFormatError);
	    return _this;
	  }
	  _inherits(InvalidFormatError, _Error);
	  return _createClass(InvalidFormatError);
	}(/*#__PURE__*/_wrapNativeSuper(Error));
	/*
	 * function format (formatFn)
	 * Returns a create function for the `formatFn`.
	 */
	format$4 = function (formatFn) {
	  if (formatFn.length > 2) {
	    throw new InvalidFormatError(formatFn);
	  }

	  /*
	   * function Format (options)
	   * Base prototype which calls a `_format`
	   * function and pushes the result.
	   */
	  function Format() {
	    var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
	    this.options = options;
	  }
	  Format.prototype.transform = formatFn;

	  //
	  // Create a function which returns new instances of
	  // FormatWrap for simple syntax like:
	  //
	  // require('winston').formats.json();
	  //
	  function createFormatWrap(opts) {
	    return new Format(opts);
	  }

	  //
	  // Expose the FormatWrap through the create function
	  // for testability.
	  //
	  createFormatWrap.Format = Format;
	  return createFormatWrap;
	};
	return format$4;
}

var colorize = {exports: {}};

var safe = {exports: {}};

var colors = {exports: {}};

var styles = {exports: {}};

/*
The MIT License (MIT)

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

var hasRequiredStyles;

function requireStyles () {
	if (hasRequiredStyles) return styles.exports;
	hasRequiredStyles = 1;
	(function (module) {
		var styles = {};
		module['exports'] = styles;

		var codes = {
		  reset: [0, 0],

		  bold: [1, 22],
		  dim: [2, 22],
		  italic: [3, 23],
		  underline: [4, 24],
		  inverse: [7, 27],
		  hidden: [8, 28],
		  strikethrough: [9, 29],

		  black: [30, 39],
		  red: [31, 39],
		  green: [32, 39],
		  yellow: [33, 39],
		  blue: [34, 39],
		  magenta: [35, 39],
		  cyan: [36, 39],
		  white: [37, 39],
		  gray: [90, 39],
		  grey: [90, 39],

		  brightRed: [91, 39],
		  brightGreen: [92, 39],
		  brightYellow: [93, 39],
		  brightBlue: [94, 39],
		  brightMagenta: [95, 39],
		  brightCyan: [96, 39],
		  brightWhite: [97, 39],

		  bgBlack: [40, 49],
		  bgRed: [41, 49],
		  bgGreen: [42, 49],
		  bgYellow: [43, 49],
		  bgBlue: [44, 49],
		  bgMagenta: [45, 49],
		  bgCyan: [46, 49],
		  bgWhite: [47, 49],
		  bgGray: [100, 49],
		  bgGrey: [100, 49],

		  bgBrightRed: [101, 49],
		  bgBrightGreen: [102, 49],
		  bgBrightYellow: [103, 49],
		  bgBrightBlue: [104, 49],
		  bgBrightMagenta: [105, 49],
		  bgBrightCyan: [106, 49],
		  bgBrightWhite: [107, 49],

		  // legacy styles for colors pre v1.0.0
		  blackBG: [40, 49],
		  redBG: [41, 49],
		  greenBG: [42, 49],
		  yellowBG: [43, 49],
		  blueBG: [44, 49],
		  magentaBG: [45, 49],
		  cyanBG: [46, 49],
		  whiteBG: [47, 49],

		};

		Object.keys(codes).forEach(function(key) {
		  var val = codes[key];
		  var style = styles[key] = [];
		  style.open = '\u001b[' + val[0] + 'm';
		  style.close = '\u001b[' + val[1] + 'm';
		}); 
	} (styles));
	return styles.exports;
}

/*
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

var hasFlag;
var hasRequiredHasFlag;

function requireHasFlag () {
	if (hasRequiredHasFlag) return hasFlag;
	hasRequiredHasFlag = 1;

	hasFlag = function(flag, argv) {
	  argv = argv || process.argv || [];

	  var terminatorPos = argv.indexOf('--');
	  var prefix = /^-{1,2}/.test(flag) ? '' : '--';
	  var pos = argv.indexOf(prefix + flag);

	  return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
	};
	return hasFlag;
}

/*
The MIT License (MIT)

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

var supportsColors;
var hasRequiredSupportsColors;

function requireSupportsColors () {
	if (hasRequiredSupportsColors) return supportsColors;
	hasRequiredSupportsColors = 1;

	var os = os__default;
	var hasFlag = requireHasFlag();

	var env = process.env;

	var forceColor = void 0;
	if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
	  forceColor = false;
	} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true')
	           || hasFlag('color=always')) {
	  forceColor = true;
	}
	if ('FORCE_COLOR' in env) {
	  forceColor = env.FORCE_COLOR.length === 0
	    || parseInt(env.FORCE_COLOR, 10) !== 0;
	}

	function translateLevel(level) {
	  if (level === 0) {
	    return false;
	  }

	  return {
	    level: level,
	    hasBasic: true,
	    has256: level >= 2,
	    has16m: level >= 3,
	  };
	}

	function supportsColor(stream) {
	  if (forceColor === false) {
	    return 0;
	  }

	  if (hasFlag('color=16m') || hasFlag('color=full')
	      || hasFlag('color=truecolor')) {
	    return 3;
	  }

	  if (hasFlag('color=256')) {
	    return 2;
	  }

	  if (stream && !stream.isTTY && forceColor !== true) {
	    return 0;
	  }

	  var min = forceColor ? 1 : 0;

	  if (process.platform === 'win32') {
	    // Node.js 7.5.0 is the first version of Node.js to include a patch to
	    // libuv that enables 256 color output on Windows. Anything earlier and it
	    // won't work. However, here we target Node.js 8 at minimum as it is an LTS
	    // release, and Node.js 7 is not. Windows 10 build 10586 is the first
	    // Windows release that supports 256 colors. Windows 10 build 14931 is the
	    // first release that supports 16m/TrueColor.
	    var osRelease = os.release().split('.');
	    if (Number(process.versions.node.split('.')[0]) >= 8
	        && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
	      return Number(osRelease[2]) >= 14931 ? 3 : 2;
	    }

	    return 1;
	  }

	  if ('CI' in env) {
	    if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) {
	      return sign in env;
	    }) || env.CI_NAME === 'codeship') {
	      return 1;
	    }

	    return min;
	  }

	  if ('TEAMCITY_VERSION' in env) {
	    return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0
	    );
	  }

	  if ('TERM_PROGRAM' in env) {
	    var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);

	    switch (env.TERM_PROGRAM) {
	      case 'iTerm.app':
	        return version >= 3 ? 3 : 2;
	      case 'Hyper':
	        return 3;
	      case 'Apple_Terminal':
	        return 2;
	      // No default
	    }
	  }

	  if (/-256(color)?$/i.test(env.TERM)) {
	    return 2;
	  }

	  if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
	    return 1;
	  }

	  if ('COLORTERM' in env) {
	    return 1;
	  }

	  if (env.TERM === 'dumb') {
	    return min;
	  }

	  return min;
	}

	function getSupportLevel(stream) {
	  var level = supportsColor(stream);
	  return translateLevel(level);
	}

	supportsColors = {
	  supportsColor: getSupportLevel,
	  stdout: getSupportLevel(process.stdout),
	  stderr: getSupportLevel(process.stderr),
	};
	return supportsColors;
}

var trap = {exports: {}};

var hasRequiredTrap;

function requireTrap () {
	if (hasRequiredTrap) return trap.exports;
	hasRequiredTrap = 1;
	(function (module) {
		module['exports'] = function runTheTrap(text, options) {
		  var result = '';
		  text = text || 'Run the trap, drop the bass';
		  text = text.split('');
		  var trap = {
		    a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'],
		    b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'],
		    c: ['\u00a9', '\u023b', '\u03fe'],
		    d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'],
		    e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc',
		      '\u0a6c'],
		    f: ['\u04fa'],
		    g: ['\u0262'],
		    h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'],
		    i: ['\u0f0f'],
		    j: ['\u0134'],
		    k: ['\u0138', '\u04a0', '\u04c3', '\u051e'],
		    l: ['\u0139'],
		    m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'],
		    n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'],
		    o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd',
		      '\u06dd', '\u0e4f'],
		    p: ['\u01f7', '\u048e'],
		    q: ['\u09cd'],
		    r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'],
		    s: ['\u00a7', '\u03de', '\u03df', '\u03e8'],
		    t: ['\u0141', '\u0166', '\u0373'],
		    u: ['\u01b1', '\u054d'],
		    v: ['\u05d8'],
		    w: ['\u0428', '\u0460', '\u047c', '\u0d70'],
		    x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'],
		    y: ['\u00a5', '\u04b0', '\u04cb'],
		    z: ['\u01b5', '\u0240'],
		  };
		  text.forEach(function(c) {
		    c = c.toLowerCase();
		    var chars = trap[c] || [' '];
		    var rand = Math.floor(Math.random() * chars.length);
		    if (typeof trap[c] !== 'undefined') {
		      result += trap[c][rand];
		    } else {
		      result += c;
		    }
		  });
		  return result;
		}; 
	} (trap));
	return trap.exports;
}

var zalgo = {exports: {}};

var hasRequiredZalgo;

function requireZalgo () {
	if (hasRequiredZalgo) return zalgo.exports;
	hasRequiredZalgo = 1;
	(function (module) {
		// please no
		module['exports'] = function zalgo(text, options) {
		  text = text || '   he is here   ';
		  var soul = {
		    'up': [
		      '̍', '̎', '̄', '̅',
		      '̿', '̑', '̆', '̐',
		      '͒', '͗', '͑', '̇',
		      '̈', '̊', '͂', '̓',
		      '̈', '͊', '͋', '͌',
		      '̃', '̂', '̌', '͐',
		      '̀', '́', '̋', '̏',
		      '̒', '̓', '̔', '̽',
		      '̉', 'ͣ', 'ͤ', 'ͥ',
		      'ͦ', 'ͧ', 'ͨ', 'ͩ',
		      'ͪ', 'ͫ', 'ͬ', 'ͭ',
		      'ͮ', 'ͯ', '̾', '͛',
		      '͆', '̚',
		    ],
		    'down': [
		      '̖', '̗', '̘', '̙',
		      '̜', '̝', '̞', '̟',
		      '̠', '̤', '̥', '̦',
		      '̩', '̪', '̫', '̬',
		      '̭', '̮', '̯', '̰',
		      '̱', '̲', '̳', '̹',
		      '̺', '̻', '̼', 'ͅ',
		      '͇', '͈', '͉', '͍',
		      '͎', '͓', '͔', '͕',
		      '͖', '͙', '͚', '̣',
		    ],
		    'mid': [
		      '̕', '̛', '̀', '́',
		      '͘', '̡', '̢', '̧',
		      '̨', '̴', '̵', '̶',
		      '͜', '͝', '͞',
		      '͟', '͠', '͢', '̸',
		      '̷', '͡', ' ҉',
		    ],
		  };
		  var all = [].concat(soul.up, soul.down, soul.mid);

		  function randomNumber(range) {
		    var r = Math.floor(Math.random() * range);
		    return r;
		  }

		  function isChar(character) {
		    var bool = false;
		    all.filter(function(i) {
		      bool = (i === character);
		    });
		    return bool;
		  }


		  function heComes(text, options) {
		    var result = '';
		    var counts;
		    var l;
		    options = options || {};
		    options['up'] =
		      typeof options['up'] !== 'undefined' ? options['up'] : true;
		    options['mid'] =
		      typeof options['mid'] !== 'undefined' ? options['mid'] : true;
		    options['down'] =
		      typeof options['down'] !== 'undefined' ? options['down'] : true;
		    options['size'] =
		      typeof options['size'] !== 'undefined' ? options['size'] : 'maxi';
		    text = text.split('');
		    for (l in text) {
		      if (isChar(l)) {
		        continue;
		      }
		      result = result + text[l];
		      counts = {'up': 0, 'down': 0, 'mid': 0};
		      switch (options.size) {
		        case 'mini':
		          counts.up = randomNumber(8);
		          counts.mid = randomNumber(2);
		          counts.down = randomNumber(8);
		          break;
		        case 'maxi':
		          counts.up = randomNumber(16) + 3;
		          counts.mid = randomNumber(4) + 1;
		          counts.down = randomNumber(64) + 3;
		          break;
		        default:
		          counts.up = randomNumber(8) + 1;
		          counts.mid = randomNumber(6) / 2;
		          counts.down = randomNumber(8) + 1;
		          break;
		      }

		      var arr = ['up', 'mid', 'down'];
		      for (var d in arr) {
		        var index = arr[d];
		        for (var i = 0; i <= counts[index]; i++) {
		          if (options[index]) {
		            result = result + soul[index][randomNumber(soul[index].length)];
		          }
		        }
		      }
		    }
		    return result;
		  }
		  // don't summon him
		  return heComes(text, options);
		}; 
	} (zalgo));
	return zalgo.exports;
}

var america = {exports: {}};

var hasRequiredAmerica;

function requireAmerica () {
	if (hasRequiredAmerica) return america.exports;
	hasRequiredAmerica = 1;
	(function (module) {
		module['exports'] = function(colors) {
		  return function(letter, i, exploded) {
		    if (letter === ' ') return letter;
		    switch (i%3) {
		      case 0: return colors.red(letter);
		      case 1: return colors.white(letter);
		      case 2: return colors.blue(letter);
		    }
		  };
		}; 
	} (america));
	return america.exports;
}

var zebra = {exports: {}};

var hasRequiredZebra;

function requireZebra () {
	if (hasRequiredZebra) return zebra.exports;
	hasRequiredZebra = 1;
	(function (module) {
		module['exports'] = function(colors) {
		  return function(letter, i, exploded) {
		    return i % 2 === 0 ? letter : colors.inverse(letter);
		  };
		}; 
	} (zebra));
	return zebra.exports;
}

var rainbow = {exports: {}};

var hasRequiredRainbow;

function requireRainbow () {
	if (hasRequiredRainbow) return rainbow.exports;
	hasRequiredRainbow = 1;
	(function (module) {
		module['exports'] = function(colors) {
		  // RoY G BiV
		  var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta'];
		  return function(letter, i, exploded) {
		    if (letter === ' ') {
		      return letter;
		    } else {
		      return colors[rainbowColors[i++ % rainbowColors.length]](letter);
		    }
		  };
		}; 
	} (rainbow));
	return rainbow.exports;
}

var random = {exports: {}};

var hasRequiredRandom;

function requireRandom () {
	if (hasRequiredRandom) return random.exports;
	hasRequiredRandom = 1;
	(function (module) {
		module['exports'] = function(colors) {
		  var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green',
		    'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed',
		    'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta'];
		  return function(letter, i, exploded) {
		    return letter === ' ' ? letter :
		      colors[
		          available[Math.round(Math.random() * (available.length - 2))]
		      ](letter);
		  };
		}; 
	} (random));
	return random.exports;
}

/*

The MIT License (MIT)

Original Library
  - Copyright (c) Marak Squires

Additional functionality
 - Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

var hasRequiredColors;

function requireColors () {
	if (hasRequiredColors) return colors.exports;
	hasRequiredColors = 1;
	(function (module) {
		var colors = {};
		module['exports'] = colors;

		colors.themes = {};

		var util = require$$0$6;
		var ansiStyles = colors.styles = requireStyles();
		var defineProps = Object.defineProperties;
		var newLineRegex = new RegExp(/[\r\n]+/g);

		colors.supportsColor = requireSupportsColors().supportsColor;

		if (typeof colors.enabled === 'undefined') {
		  colors.enabled = colors.supportsColor() !== false;
		}

		colors.enable = function() {
		  colors.enabled = true;
		};

		colors.disable = function() {
		  colors.enabled = false;
		};

		colors.stripColors = colors.strip = function(str) {
		  return ('' + str).replace(/\x1B\[\d+m/g, '');
		};

		// eslint-disable-next-line no-unused-vars
		colors.stylize = function stylize(str, style) {
		  if (!colors.enabled) {
		    return str+'';
		  }

		  var styleMap = ansiStyles[style];

		  // Stylize should work for non-ANSI styles, too
		  if (!styleMap && style in colors) {
		    // Style maps like trap operate as functions on strings;
		    // they don't have properties like open or close.
		    return colors[style](str);
		  }

		  return styleMap.open + str + styleMap.close;
		};

		var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
		var escapeStringRegexp = function(str) {
		  if (typeof str !== 'string') {
		    throw new TypeError('Expected a string');
		  }
		  return str.replace(matchOperatorsRe, '\\$&');
		};

		function build(_styles) {
		  var builder = function builder() {
		    return applyStyle.apply(builder, arguments);
		  };
		  builder._styles = _styles;
		  // __proto__ is used because we must return a function, but there is
		  // no way to create a function with a different prototype.
		  builder.__proto__ = proto;
		  return builder;
		}

		var styles = (function() {
		  var ret = {};
		  ansiStyles.grey = ansiStyles.gray;
		  Object.keys(ansiStyles).forEach(function(key) {
		    ansiStyles[key].closeRe =
		      new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
		    ret[key] = {
		      get: function() {
		        return build(this._styles.concat(key));
		      },
		    };
		  });
		  return ret;
		})();

		var proto = defineProps(function colors() {}, styles);

		function applyStyle() {
		  var args = Array.prototype.slice.call(arguments);

		  var str = args.map(function(arg) {
		    // Use weak equality check so we can colorize null/undefined in safe mode
		    if (arg != null && arg.constructor === String) {
		      return arg;
		    } else {
		      return util.inspect(arg);
		    }
		  }).join(' ');

		  if (!colors.enabled || !str) {
		    return str;
		  }

		  var newLinesPresent = str.indexOf('\n') != -1;

		  var nestedStyles = this._styles;

		  var i = nestedStyles.length;
		  while (i--) {
		    var code = ansiStyles[nestedStyles[i]];
		    str = code.open + str.replace(code.closeRe, code.open) + code.close;
		    if (newLinesPresent) {
		      str = str.replace(newLineRegex, function(match) {
		        return code.close + match + code.open;
		      });
		    }
		  }

		  return str;
		}

		colors.setTheme = function(theme) {
		  if (typeof theme === 'string') {
		    console.log('colors.setTheme now only accepts an object, not a string.  ' +
		      'If you are trying to set a theme from a file, it is now your (the ' +
		      'caller\'s) responsibility to require the file.  The old syntax ' +
		      'looked like colors.setTheme(__dirname + ' +
		      '\'/../themes/generic-logging.js\'); The new syntax looks like '+
		      'colors.setTheme(require(__dirname + ' +
		      '\'/../themes/generic-logging.js\'));');
		    return;
		  }
		  for (var style in theme) {
		    (function(style) {
		      colors[style] = function(str) {
		        if (typeof theme[style] === 'object') {
		          var out = str;
		          for (var i in theme[style]) {
		            out = colors[theme[style][i]](out);
		          }
		          return out;
		        }
		        return colors[theme[style]](str);
		      };
		    })(style);
		  }
		};

		function init() {
		  var ret = {};
		  Object.keys(styles).forEach(function(name) {
		    ret[name] = {
		      get: function() {
		        return build([name]);
		      },
		    };
		  });
		  return ret;
		}

		var sequencer = function sequencer(map, str) {
		  var exploded = str.split('');
		  exploded = exploded.map(map);
		  return exploded.join('');
		};

		// custom formatter methods
		colors.trap = requireTrap();
		colors.zalgo = requireZalgo();

		// maps
		colors.maps = {};
		colors.maps.america = requireAmerica()(colors);
		colors.maps.zebra = requireZebra()(colors);
		colors.maps.rainbow = requireRainbow()(colors);
		colors.maps.random = requireRandom()(colors);

		for (var map in colors.maps) {
		  (function(map) {
		    colors[map] = function(str) {
		      return sequencer(colors.maps[map], str);
		    };
		  })(map);
		}

		defineProps(colors, init()); 
	} (colors));
	return colors.exports;
}

var hasRequiredSafe;

function requireSafe () {
	if (hasRequiredSafe) return safe.exports;
	hasRequiredSafe = 1;
	(function (module) {
		//
		// Remark: Requiring this file will use the "safe" colors API,
		// which will not touch String.prototype.
		//
		//   var colors = require('colors/safe');
		//   colors.red("foo")
		//
		//
		var colors = requireColors();
		module['exports'] = colors; 
	} (safe));
	return safe.exports;
}

var tripleBeam = {};

var config$1 = {};

var cli$1 = {};

/**
 * cli.js: Config that conform to commonly used CLI logging levels.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var hasRequiredCli$1;

function requireCli$1 () {
	if (hasRequiredCli$1) return cli$1;
	hasRequiredCli$1 = 1;

	/**
	 * Default levels for the CLI configuration.
	 * @type {Object}
	 */
	cli$1.levels = {
	  error: 0,
	  warn: 1,
	  help: 2,
	  data: 3,
	  info: 4,
	  debug: 5,
	  prompt: 6,
	  verbose: 7,
	  input: 8,
	  silly: 9
	};

	/**
	 * Default colors for the CLI configuration.
	 * @type {Object}
	 */
	cli$1.colors = {
	  error: 'red',
	  warn: 'yellow',
	  help: 'cyan',
	  data: 'grey',
	  info: 'green',
	  debug: 'blue',
	  prompt: 'grey',
	  verbose: 'cyan',
	  input: 'grey',
	  silly: 'magenta'
	};
	return cli$1;
}

var npm = {};

/**
 * npm.js: Config that conform to npm logging levels.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var hasRequiredNpm;

function requireNpm () {
	if (hasRequiredNpm) return npm;
	hasRequiredNpm = 1;

	/**
	 * Default levels for the npm configuration.
	 * @type {Object}
	 */
	npm.levels = {
	  error: 0,
	  warn: 1,
	  info: 2,
	  http: 3,
	  verbose: 4,
	  debug: 5,
	  silly: 6
	};

	/**
	 * Default levels for the npm configuration.
	 * @type {Object}
	 */
	npm.colors = {
	  error: 'red',
	  warn: 'yellow',
	  info: 'green',
	  http: 'green',
	  verbose: 'cyan',
	  debug: 'blue',
	  silly: 'magenta'
	};
	return npm;
}

var syslog = {};

/**
 * syslog.js: Config that conform to syslog logging levels.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var hasRequiredSyslog;

function requireSyslog () {
	if (hasRequiredSyslog) return syslog;
	hasRequiredSyslog = 1;

	/**
	 * Default levels for the syslog configuration.
	 * @type {Object}
	 */
	syslog.levels = {
	  emerg: 0,
	  alert: 1,
	  crit: 2,
	  error: 3,
	  warning: 4,
	  notice: 5,
	  info: 6,
	  debug: 7
	};

	/**
	 * Default levels for the syslog configuration.
	 * @type {Object}
	 */
	syslog.colors = {
	  emerg: 'red',
	  alert: 'yellow',
	  crit: 'red',
	  error: 'red',
	  warning: 'red',
	  notice: 'yellow',
	  info: 'green',
	  debug: 'blue'
	};
	return syslog;
}

/**
 * index.js: Default settings for all levels that winston knows about.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var hasRequiredConfig$1;

function requireConfig$1 () {
	if (hasRequiredConfig$1) return config$1;
	hasRequiredConfig$1 = 1;
	(function (exports$1) {

		/**
		 * Export config set for the CLI.
		 * @type {Object}
		 */
		Object.defineProperty(exports$1, 'cli', {
		  value: requireCli$1()
		});

		/**
		 * Export config set for npm.
		 * @type {Object}
		 */
		Object.defineProperty(exports$1, 'npm', {
		  value: requireNpm()
		});

		/**
		 * Export config set for the syslog.
		 * @type {Object}
		 */
		Object.defineProperty(exports$1, 'syslog', {
		  value: requireSyslog()
		}); 
	} (config$1));
	return config$1;
}

var hasRequiredTripleBeam;

function requireTripleBeam () {
	if (hasRequiredTripleBeam) return tripleBeam;
	hasRequiredTripleBeam = 1;
	(function (exports$1) {

		/**
		 * A shareable symbol constant that can be used
		 * as a non-enumerable / semi-hidden level identifier
		 * to allow the readable level property to be mutable for
		 * operations like colorization
		 *
		 * @type {Symbol}
		 */
		Object.defineProperty(exports$1, 'LEVEL', {
		  value: Symbol.for('level')
		});

		/**
		 * A shareable symbol constant that can be used
		 * as a non-enumerable / semi-hidden message identifier
		 * to allow the final message property to not have
		 * side effects on another.
		 *
		 * @type {Symbol}
		 */
		Object.defineProperty(exports$1, 'MESSAGE', {
		  value: Symbol.for('message')
		});

		/**
		 * A shareable symbol constant that can be used
		 * as a non-enumerable / semi-hidden message identifier
		 * to allow the extracted splat property be hidden
		 *
		 * @type {Symbol}
		 */
		Object.defineProperty(exports$1, 'SPLAT', {
		  value: Symbol.for('splat')
		});

		/**
		 * A shareable object constant  that can be used
		 * as a standard configuration for winston@3.
		 *
		 * @type {Object}
		 */
		Object.defineProperty(exports$1, 'configs', {
		  value: requireConfig$1()
		}); 
	} (tripleBeam));
	return tripleBeam;
}

var hasRequiredColorize;

function requireColorize () {
	if (hasRequiredColorize) return colorize.exports;
	hasRequiredColorize = 1;

	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
	function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
	var colors = requireSafe();
	var _require = requireTripleBeam(),
	  LEVEL = _require.LEVEL,
	  MESSAGE = _require.MESSAGE;

	//
	// Fix colors not appearing in non-tty environments
	//
	colors.enabled = true;

	/**
	 * @property {RegExp} hasSpace
	 * Simple regex to check for presence of spaces.
	 */
	var hasSpace = /\s+/;

	/*
	 * Colorizer format. Wraps the `level` and/or `message` properties
	 * of the `info` objects with ANSI color codes based on a few options.
	 */
	var Colorizer = /*#__PURE__*/function () {
	  function Colorizer() {
	    var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
	    _classCallCheck(this, Colorizer);
	    if (opts.colors) {
	      this.addColors(opts.colors);
	    }
	    this.options = opts;
	  }

	  /*
	   * Adds the colors Object to the set of allColors
	   * known by the Colorizer
	   *
	   * @param {Object} colors Set of color mappings to add.
	   */
	  return _createClass(Colorizer, [{
	    key: "addColors",
	    value:
	    /*
	     * Adds the colors Object to the set of allColors
	     * known by the Colorizer
	     *
	     * @param {Object} colors Set of color mappings to add.
	     */
	    function addColors(clrs) {
	      return Colorizer.addColors(clrs);
	    }

	    /*
	     * function colorize (lookup, level, message)
	     * Performs multi-step colorization using @colors/colors/safe
	     */
	  }, {
	    key: "colorize",
	    value: function colorize(lookup, level, message) {
	      if (typeof message === 'undefined') {
	        message = level;
	      }

	      //
	      // If the color for the level is just a string
	      // then attempt to colorize the message with it.
	      //
	      if (!Array.isArray(Colorizer.allColors[lookup])) {
	        return colors[Colorizer.allColors[lookup]](message);
	      }

	      //
	      // If it is an Array then iterate over that Array, applying
	      // the colors function for each item.
	      //
	      for (var i = 0, len = Colorizer.allColors[lookup].length; i < len; i++) {
	        message = colors[Colorizer.allColors[lookup][i]](message);
	      }
	      return message;
	    }

	    /*
	     * function transform (info, opts)
	     * Attempts to colorize the { level, message } of the given
	     * `logform` info object.
	     */
	  }, {
	    key: "transform",
	    value: function transform(info, opts) {
	      if (opts.all && typeof info[MESSAGE] === 'string') {
	        info[MESSAGE] = this.colorize(info[LEVEL], info.level, info[MESSAGE]);
	      }
	      if (opts.level || opts.all || !opts.message) {
	        info.level = this.colorize(info[LEVEL], info.level);
	      }
	      if (opts.all || opts.message) {
	        info.message = this.colorize(info[LEVEL], info.level, info.message);
	      }
	      return info;
	    }
	  }], [{
	    key: "addColors",
	    value: function addColors(clrs) {
	      var nextColors = Object.keys(clrs).reduce(function (acc, level) {
	        acc[level] = hasSpace.test(clrs[level]) ? clrs[level].split(hasSpace) : clrs[level];
	        return acc;
	      }, {});
	      Colorizer.allColors = Object.assign({}, Colorizer.allColors || {}, nextColors);
	      return Colorizer.allColors;
	    }
	  }]);
	}();
	/*
	 * function colorize (info)
	 * Returns a new instance of the colorize Format that applies
	 * level colors to `info` objects. This was previously exposed
	 * as { colorize: true } to transports in `winston < 3.0.0`.
	 */
	colorize.exports = function (opts) {
	  return new Colorizer(opts);
	};

	//
	// Attach the Colorizer for registration purposes
	//
	colorize.exports.Colorizer = colorize.exports.Format = Colorizer;
	return colorize.exports;
}

var levels;
var hasRequiredLevels;

function requireLevels () {
	if (hasRequiredLevels) return levels;
	hasRequiredLevels = 1;

	var _require = requireColorize(),
	  Colorizer = _require.Colorizer;

	/*
	 * Simple method to register colors with a simpler require
	 * path within the module.
	 */
	levels = function (config) {
	  Colorizer.addColors(config.colors || config);
	  return config;
	};
	return levels;
}

var align;
var hasRequiredAlign;

function requireAlign () {
	if (hasRequiredAlign) return align;
	hasRequiredAlign = 1;

	var format = requireFormat$3();

	/*
	 * function align (info)
	 * Returns a new instance of the align Format which adds a `\t`
	 * delimiter before the message to properly align it in the same place.
	 * It was previously { align: true } in winston < 3.0.0
	 */
	align = format(function (info) {
	  info.message = "\t".concat(info.message);
	  return info;
	});
	return align;
}

var cli = {exports: {}};

var padLevels = {exports: {}};

/* eslint no-unused-vars: 0 */

var hasRequiredPadLevels;

function requirePadLevels () {
	if (hasRequiredPadLevels) return padLevels.exports;
	hasRequiredPadLevels = 1;

	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
	function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
	function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
	function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
	function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
	function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
	function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
	var _require = requireTripleBeam(),
	  configs = _require.configs,
	  LEVEL = _require.LEVEL,
	  MESSAGE = _require.MESSAGE;
	var Padder = /*#__PURE__*/function () {
	  function Padder() {
	    var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
	      levels: configs.npm.levels
	    };
	    _classCallCheck(this, Padder);
	    this.paddings = Padder.paddingForLevels(opts.levels, opts.filler);
	    this.options = opts;
	  }

	  /**
	   * Returns the maximum length of keys in the specified `levels` Object.
	   * @param  {Object} levels Set of all levels to calculate longest level against.
	   * @returns {Number} Maximum length of the longest level string.
	   */
	  return _createClass(Padder, [{
	    key: "transform",
	    value:
	    /**
	     * Prepends the padding onto the `message` based on the `LEVEL` of
	     * the `info`. This is based on the behavior of `winston@2` which also
	     * prepended the level onto the message.
	     *
	     * See: https://github.com/winstonjs/winston/blob/2.x/lib/winston/logger.js#L198-L201
	     *
	     * @param  {Info} info Logform info object
	     * @param  {Object} opts Options passed along to this instance.
	     * @returns {Info} Modified logform info object.
	     */
	    function transform(info, opts) {
	      info.message = "".concat(this.paddings[info[LEVEL]]).concat(info.message);
	      if (info[MESSAGE]) {
	        info[MESSAGE] = "".concat(this.paddings[info[LEVEL]]).concat(info[MESSAGE]);
	      }
	      return info;
	    }
	  }], [{
	    key: "getLongestLevel",
	    value: function getLongestLevel(levels) {
	      var lvls = Object.keys(levels).map(function (level) {
	        return level.length;
	      });
	      return Math.max.apply(Math, _toConsumableArray(lvls));
	    }

	    /**
	     * Returns the padding for the specified `level` assuming that the
	     * maximum length of all levels it's associated with is `maxLength`.
	     * @param  {String} level Level to calculate padding for.
	     * @param  {String} filler Repeatable text to use for padding.
	     * @param  {Number} maxLength Length of the longest level
	     * @returns {String} Padding string for the `level`
	     */
	  }, {
	    key: "paddingForLevel",
	    value: function paddingForLevel(level, filler, maxLength) {
	      var targetLen = maxLength + 1 - level.length;
	      var rep = Math.floor(targetLen / filler.length);
	      var padding = "".concat(filler).concat(filler.repeat(rep));
	      return padding.slice(0, targetLen);
	    }

	    /**
	     * Returns an object with the string paddings for the given `levels`
	     * using the specified `filler`.
	     * @param  {Object} levels Set of all levels to calculate padding for.
	     * @param  {String} filler Repeatable text to use for padding.
	     * @returns {Object} Mapping of level to desired padding.
	     */
	  }, {
	    key: "paddingForLevels",
	    value: function paddingForLevels(levels) {
	      var filler = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ' ';
	      var maxLength = Padder.getLongestLevel(levels);
	      return Object.keys(levels).reduce(function (acc, level) {
	        acc[level] = Padder.paddingForLevel(level, filler, maxLength);
	        return acc;
	      }, {});
	    }
	  }]);
	}();
	/*
	 * function padLevels (info)
	 * Returns a new instance of the padLevels Format which pads
	 * levels to be the same length. This was previously exposed as
	 * { padLevels: true } to transports in `winston < 3.0.0`.
	 */
	padLevels.exports = function (opts) {
	  return new Padder(opts);
	};
	padLevels.exports.Padder = padLevels.exports.Format = Padder;
	return padLevels.exports;
}

var hasRequiredCli;

function requireCli () {
	if (hasRequiredCli) return cli.exports;
	hasRequiredCli = 1;

	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
	function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
	var _require = requireColorize(),
	  Colorizer = _require.Colorizer;
	var _require2 = requirePadLevels(),
	  Padder = _require2.Padder;
	var _require3 = requireTripleBeam(),
	  configs = _require3.configs,
	  MESSAGE = _require3.MESSAGE;

	/**
	 * Cli format class that handles initial state for a a separate
	 * Colorizer and Padder instance.
	 */
	var CliFormat = /*#__PURE__*/function () {
	  function CliFormat() {
	    var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
	    _classCallCheck(this, CliFormat);
	    if (!opts.levels) {
	      opts.levels = configs.cli.levels;
	    }
	    this.colorizer = new Colorizer(opts);
	    this.padder = new Padder(opts);
	    this.options = opts;
	  }

	  /*
	   * function transform (info, opts)
	   * Attempts to both:
	   * 1. Pad the { level }
	   * 2. Colorize the { level, message }
	   * of the given `logform` info object depending on the `opts`.
	   */
	  return _createClass(CliFormat, [{
	    key: "transform",
	    value: function transform(info, opts) {
	      this.colorizer.transform(this.padder.transform(info, opts), opts);
	      info[MESSAGE] = "".concat(info.level, ":").concat(info.message);
	      return info;
	    }
	  }]);
	}();
	/*
	 * function cli (opts)
	 * Returns a new instance of the CLI format that turns a log
	 * `info` object into the same format previously available
	 * in `winston.cli()` in `winston < 3.0.0`.
	 */
	cli.exports = function (opts) {
	  return new CliFormat(opts);
	};

	//
	// Attach the CliFormat for registration purposes
	//
	cli.exports.Format = CliFormat;
	return cli.exports;
}

var combine$1 = {exports: {}};

var hasRequiredCombine;

function requireCombine () {
	if (hasRequiredCombine) return combine$1.exports;
	hasRequiredCombine = 1;

	var format = requireFormat$3();

	/*
	 * function cascade(formats)
	 * Returns a function that invokes the `._format` function in-order
	 * for the specified set of `formats`. In this manner we say that Formats
	 * are "pipe-like", but not a pure pumpify implementation. Since there is no back
	 * pressure we can remove all of the "readable" plumbing in Node streams.
	 */
	function cascade(formats) {
	  if (!formats.every(isValidFormat)) {
	    return;
	  }
	  return function (info) {
	    var obj = info;
	    for (var i = 0; i < formats.length; i++) {
	      obj = formats[i].transform(obj, formats[i].options);
	      if (!obj) {
	        return false;
	      }
	    }
	    return obj;
	  };
	}

	/*
	 * function isValidFormat(format)
	 * If the format does not define a `transform` function throw an error
	 * with more detailed usage.
	 */
	function isValidFormat(fmt) {
	  if (typeof fmt.transform !== 'function') {
	    throw new Error(['No transform function found on format. Did you create a format instance?', 'const myFormat = format(formatFn);', 'const instance = myFormat();'].join('\n'));
	  }
	  return true;
	}

	/*
	 * function combine (info)
	 * Returns a new instance of the combine Format which combines the specified
	 * formats into a new format. This is similar to a pipe-chain in transform streams.
	 * We choose to combine the prototypes this way because there is no back pressure in
	 * an in-memory transform chain.
	 */
	combine$1.exports = function () {
	  for (var _len = arguments.length, formats = new Array(_len), _key = 0; _key < _len; _key++) {
	    formats[_key] = arguments[_key];
	  }
	  var combinedFormat = format(cascade(formats));
	  var instance = combinedFormat();
	  instance.Format = combinedFormat.Format;
	  return instance;
	};

	//
	// Export the cascade method for use in cli and other
	// combined formats that should not be assumed to be
	// singletons.
	//
	combine$1.exports.cascade = cascade;
	return combine$1.exports;
}

/* eslint no-undefined: 0 */

var errors$1;
var hasRequiredErrors$1;

function requireErrors$1 () {
	if (hasRequiredErrors$1) return errors$1;
	hasRequiredErrors$1 = 1;

	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
	var format = requireFormat$3();
	var _require = requireTripleBeam(),
	  LEVEL = _require.LEVEL,
	  MESSAGE = _require.MESSAGE;

	/*
	 * function errors (info)
	 * If the `message` property of the `info` object is an instance of `Error`,
	 * replace the `Error` object its own `message` property.
	 *
	 * Optionally, the Error's `stack` and/or `cause` properties can also be appended to the `info` object.
	 */
	errors$1 = format(function (einfo, _ref) {
	  var stack = _ref.stack,
	    cause = _ref.cause;
	  if (einfo instanceof Error) {
	    var info = Object.assign({}, einfo, _defineProperty(_defineProperty(_defineProperty({
	      level: einfo.level
	    }, LEVEL, einfo[LEVEL] || einfo.level), "message", einfo.message), MESSAGE, einfo[MESSAGE] || einfo.message));
	    if (stack) info.stack = einfo.stack;
	    if (cause) info.cause = einfo.cause;
	    return info;
	  }
	  if (!(einfo.message instanceof Error)) return einfo;

	  // Assign all enumerable properties and the
	  // message property from the error provided.
	  var err = einfo.message;
	  Object.assign(einfo, err);
	  einfo.message = err.message;
	  einfo[MESSAGE] = err.message;

	  // Assign the stack and/or cause if requested.
	  if (stack) einfo.stack = err.stack;
	  if (cause) einfo.cause = err.cause;
	  return einfo;
	});
	return errors$1;
}

var safeStableStringify = {exports: {}};

var hasRequiredSafeStableStringify;

function requireSafeStableStringify () {
	if (hasRequiredSafeStableStringify) return safeStableStringify.exports;
	hasRequiredSafeStableStringify = 1;
	(function (module, exports$1) {

		const { hasOwnProperty } = Object.prototype;

		const stringify = configure();

		// @ts-expect-error
		stringify.configure = configure;
		// @ts-expect-error
		stringify.stringify = stringify;

		// @ts-expect-error
		stringify.default = stringify;

		// @ts-expect-error used for named export
		exports$1.stringify = stringify;
		// @ts-expect-error used for named export
		exports$1.configure = configure;

		module.exports = stringify;

		// eslint-disable-next-line no-control-regex
		const strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;

		// Escape C0 control characters, double quotes, the backslash and every code
		// unit with a numeric value in the inclusive range 0xD800 to 0xDFFF.
		function strEscape (str) {
		  // Some magic numbers that worked out fine while benchmarking with v8 8.0
		  if (str.length < 5000 && !strEscapeSequencesRegExp.test(str)) {
		    return `"${str}"`
		  }
		  return JSON.stringify(str)
		}

		function sort (array, comparator) {
		  // Insertion sort is very efficient for small input sizes, but it has a bad
		  // worst case complexity. Thus, use native array sort for bigger values.
		  if (array.length > 2e2 || comparator) {
		    return array.sort(comparator)
		  }
		  for (let i = 1; i < array.length; i++) {
		    const currentValue = array[i];
		    let position = i;
		    while (position !== 0 && array[position - 1] > currentValue) {
		      array[position] = array[position - 1];
		      position--;
		    }
		    array[position] = currentValue;
		  }
		  return array
		}

		const typedArrayPrototypeGetSymbolToStringTag =
		  Object.getOwnPropertyDescriptor(
		    Object.getPrototypeOf(
		      Object.getPrototypeOf(
		        new Int8Array()
		      )
		    ),
		    Symbol.toStringTag
		  ).get;

		function isTypedArrayWithEntries (value) {
		  return typedArrayPrototypeGetSymbolToStringTag.call(value) !== undefined && value.length !== 0
		}

		function stringifyTypedArray (array, separator, maximumBreadth) {
		  if (array.length < maximumBreadth) {
		    maximumBreadth = array.length;
		  }
		  const whitespace = separator === ',' ? '' : ' ';
		  let res = `"0":${whitespace}${array[0]}`;
		  for (let i = 1; i < maximumBreadth; i++) {
		    res += `${separator}"${i}":${whitespace}${array[i]}`;
		  }
		  return res
		}

		function getCircularValueOption (options) {
		  if (hasOwnProperty.call(options, 'circularValue')) {
		    const circularValue = options.circularValue;
		    if (typeof circularValue === 'string') {
		      return `"${circularValue}"`
		    }
		    if (circularValue == null) {
		      return circularValue
		    }
		    if (circularValue === Error || circularValue === TypeError) {
		      return {
		        toString () {
		          throw new TypeError('Converting circular structure to JSON')
		        }
		      }
		    }
		    throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')
		  }
		  return '"[Circular]"'
		}

		function getDeterministicOption (options) {
		  let value;
		  if (hasOwnProperty.call(options, 'deterministic')) {
		    value = options.deterministic;
		    if (typeof value !== 'boolean' && typeof value !== 'function') {
		      throw new TypeError('The "deterministic" argument must be of type boolean or comparator function')
		    }
		  }
		  return value === undefined ? true : value
		}

		function getBooleanOption (options, key) {
		  let value;
		  if (hasOwnProperty.call(options, key)) {
		    value = options[key];
		    if (typeof value !== 'boolean') {
		      throw new TypeError(`The "${key}" argument must be of type boolean`)
		    }
		  }
		  return value === undefined ? true : value
		}

		function getPositiveIntegerOption (options, key) {
		  let value;
		  if (hasOwnProperty.call(options, key)) {
		    value = options[key];
		    if (typeof value !== 'number') {
		      throw new TypeError(`The "${key}" argument must be of type number`)
		    }
		    if (!Number.isInteger(value)) {
		      throw new TypeError(`The "${key}" argument must be an integer`)
		    }
		    if (value < 1) {
		      throw new RangeError(`The "${key}" argument must be >= 1`)
		    }
		  }
		  return value === undefined ? Infinity : value
		}

		function getItemCount (number) {
		  if (number === 1) {
		    return '1 item'
		  }
		  return `${number} items`
		}

		function getUniqueReplacerSet (replacerArray) {
		  const replacerSet = new Set();
		  for (const value of replacerArray) {
		    if (typeof value === 'string' || typeof value === 'number') {
		      replacerSet.add(String(value));
		    }
		  }
		  return replacerSet
		}

		function getStrictOption (options) {
		  if (hasOwnProperty.call(options, 'strict')) {
		    const value = options.strict;
		    if (typeof value !== 'boolean') {
		      throw new TypeError('The "strict" argument must be of type boolean')
		    }
		    if (value) {
		      return (value) => {
		        let message = `Object can not safely be stringified. Received type ${typeof value}`;
		        if (typeof value !== 'function') message += ` (${value.toString()})`;
		        throw new Error(message)
		      }
		    }
		  }
		}

		function configure (options) {
		  options = { ...options };
		  const fail = getStrictOption(options);
		  if (fail) {
		    if (options.bigint === undefined) {
		      options.bigint = false;
		    }
		    if (!('circularValue' in options)) {
		      options.circularValue = Error;
		    }
		  }
		  const circularValue = getCircularValueOption(options);
		  const bigint = getBooleanOption(options, 'bigint');
		  const deterministic = getDeterministicOption(options);
		  const comparator = typeof deterministic === 'function' ? deterministic : undefined;
		  const maximumDepth = getPositiveIntegerOption(options, 'maximumDepth');
		  const maximumBreadth = getPositiveIntegerOption(options, 'maximumBreadth');

		  function stringifyFnReplacer (key, parent, stack, replacer, spacer, indentation) {
		    let value = parent[key];

		    if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {
		      value = value.toJSON(key);
		    }
		    value = replacer.call(parent, key, value);

		    switch (typeof value) {
		      case 'string':
		        return strEscape(value)
		      case 'object': {
		        if (value === null) {
		          return 'null'
		        }
		        if (stack.indexOf(value) !== -1) {
		          return circularValue
		        }

		        let res = '';
		        let join = ',';
		        const originalIndentation = indentation;

		        if (Array.isArray(value)) {
		          if (value.length === 0) {
		            return '[]'
		          }
		          if (maximumDepth < stack.length + 1) {
		            return '"[Array]"'
		          }
		          stack.push(value);
		          if (spacer !== '') {
		            indentation += spacer;
		            res += `\n${indentation}`;
		            join = `,\n${indentation}`;
		          }
		          const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
		          let i = 0;
		          for (; i < maximumValuesToStringify - 1; i++) {
		            const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
		            res += tmp !== undefined ? tmp : 'null';
		            res += join;
		          }
		          const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
		          res += tmp !== undefined ? tmp : 'null';
		          if (value.length - 1 > maximumBreadth) {
		            const removedKeys = value.length - maximumBreadth - 1;
		            res += `${join}"... ${getItemCount(removedKeys)} not stringified"`;
		          }
		          if (spacer !== '') {
		            res += `\n${originalIndentation}`;
		          }
		          stack.pop();
		          return `[${res}]`
		        }

		        let keys = Object.keys(value);
		        const keyLength = keys.length;
		        if (keyLength === 0) {
		          return '{}'
		        }
		        if (maximumDepth < stack.length + 1) {
		          return '"[Object]"'
		        }
		        let whitespace = '';
		        let separator = '';
		        if (spacer !== '') {
		          indentation += spacer;
		          join = `,\n${indentation}`;
		          whitespace = ' ';
		        }
		        const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
		        if (deterministic && !isTypedArrayWithEntries(value)) {
		          keys = sort(keys, comparator);
		        }
		        stack.push(value);
		        for (let i = 0; i < maximumPropertiesToStringify; i++) {
		          const key = keys[i];
		          const tmp = stringifyFnReplacer(key, value, stack, replacer, spacer, indentation);
		          if (tmp !== undefined) {
		            res += `${separator}${strEscape(key)}:${whitespace}${tmp}`;
		            separator = join;
		          }
		        }
		        if (keyLength > maximumBreadth) {
		          const removedKeys = keyLength - maximumBreadth;
		          res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`;
		          separator = join;
		        }
		        if (spacer !== '' && separator.length > 1) {
		          res = `\n${indentation}${res}\n${originalIndentation}`;
		        }
		        stack.pop();
		        return `{${res}}`
		      }
		      case 'number':
		        return isFinite(value) ? String(value) : fail ? fail(value) : 'null'
		      case 'boolean':
		        return value === true ? 'true' : 'false'
		      case 'undefined':
		        return undefined
		      case 'bigint':
		        if (bigint) {
		          return String(value)
		        }
		        // fallthrough
		      default:
		        return fail ? fail(value) : undefined
		    }
		  }

		  function stringifyArrayReplacer (key, value, stack, replacer, spacer, indentation) {
		    if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {
		      value = value.toJSON(key);
		    }

		    switch (typeof value) {
		      case 'string':
		        return strEscape(value)
		      case 'object': {
		        if (value === null) {
		          return 'null'
		        }
		        if (stack.indexOf(value) !== -1) {
		          return circularValue
		        }

		        const originalIndentation = indentation;
		        let res = '';
		        let join = ',';

		        if (Array.isArray(value)) {
		          if (value.length === 0) {
		            return '[]'
		          }
		          if (maximumDepth < stack.length + 1) {
		            return '"[Array]"'
		          }
		          stack.push(value);
		          if (spacer !== '') {
		            indentation += spacer;
		            res += `\n${indentation}`;
		            join = `,\n${indentation}`;
		          }
		          const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
		          let i = 0;
		          for (; i < maximumValuesToStringify - 1; i++) {
		            const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
		            res += tmp !== undefined ? tmp : 'null';
		            res += join;
		          }
		          const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
		          res += tmp !== undefined ? tmp : 'null';
		          if (value.length - 1 > maximumBreadth) {
		            const removedKeys = value.length - maximumBreadth - 1;
		            res += `${join}"... ${getItemCount(removedKeys)} not stringified"`;
		          }
		          if (spacer !== '') {
		            res += `\n${originalIndentation}`;
		          }
		          stack.pop();
		          return `[${res}]`
		        }
		        stack.push(value);
		        let whitespace = '';
		        if (spacer !== '') {
		          indentation += spacer;
		          join = `,\n${indentation}`;
		          whitespace = ' ';
		        }
		        let separator = '';
		        for (const key of replacer) {
		          const tmp = stringifyArrayReplacer(key, value[key], stack, replacer, spacer, indentation);
		          if (tmp !== undefined) {
		            res += `${separator}${strEscape(key)}:${whitespace}${tmp}`;
		            separator = join;
		          }
		        }
		        if (spacer !== '' && separator.length > 1) {
		          res = `\n${indentation}${res}\n${originalIndentation}`;
		        }
		        stack.pop();
		        return `{${res}}`
		      }
		      case 'number':
		        return isFinite(value) ? String(value) : fail ? fail(value) : 'null'
		      case 'boolean':
		        return value === true ? 'true' : 'false'
		      case 'undefined':
		        return undefined
		      case 'bigint':
		        if (bigint) {
		          return String(value)
		        }
		        // fallthrough
		      default:
		        return fail ? fail(value) : undefined
		    }
		  }

		  function stringifyIndent (key, value, stack, spacer, indentation) {
		    switch (typeof value) {
		      case 'string':
		        return strEscape(value)
		      case 'object': {
		        if (value === null) {
		          return 'null'
		        }
		        if (typeof value.toJSON === 'function') {
		          value = value.toJSON(key);
		          // Prevent calling `toJSON` again.
		          if (typeof value !== 'object') {
		            return stringifyIndent(key, value, stack, spacer, indentation)
		          }
		          if (value === null) {
		            return 'null'
		          }
		        }
		        if (stack.indexOf(value) !== -1) {
		          return circularValue
		        }
		        const originalIndentation = indentation;

		        if (Array.isArray(value)) {
		          if (value.length === 0) {
		            return '[]'
		          }
		          if (maximumDepth < stack.length + 1) {
		            return '"[Array]"'
		          }
		          stack.push(value);
		          indentation += spacer;
		          let res = `\n${indentation}`;
		          const join = `,\n${indentation}`;
		          const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
		          let i = 0;
		          for (; i < maximumValuesToStringify - 1; i++) {
		            const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation);
		            res += tmp !== undefined ? tmp : 'null';
		            res += join;
		          }
		          const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation);
		          res += tmp !== undefined ? tmp : 'null';
		          if (value.length - 1 > maximumBreadth) {
		            const removedKeys = value.length - maximumBreadth - 1;
		            res += `${join}"... ${getItemCount(removedKeys)} not stringified"`;
		          }
		          res += `\n${originalIndentation}`;
		          stack.pop();
		          return `[${res}]`
		        }

		        let keys = Object.keys(value);
		        const keyLength = keys.length;
		        if (keyLength === 0) {
		          return '{}'
		        }
		        if (maximumDepth < stack.length + 1) {
		          return '"[Object]"'
		        }
		        indentation += spacer;
		        const join = `,\n${indentation}`;
		        let res = '';
		        let separator = '';
		        let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
		        if (isTypedArrayWithEntries(value)) {
		          res += stringifyTypedArray(value, join, maximumBreadth);
		          keys = keys.slice(value.length);
		          maximumPropertiesToStringify -= value.length;
		          separator = join;
		        }
		        if (deterministic) {
		          keys = sort(keys, comparator);
		        }
		        stack.push(value);
		        for (let i = 0; i < maximumPropertiesToStringify; i++) {
		          const key = keys[i];
		          const tmp = stringifyIndent(key, value[key], stack, spacer, indentation);
		          if (tmp !== undefined) {
		            res += `${separator}${strEscape(key)}: ${tmp}`;
		            separator = join;
		          }
		        }
		        if (keyLength > maximumBreadth) {
		          const removedKeys = keyLength - maximumBreadth;
		          res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`;
		          separator = join;
		        }
		        if (separator !== '') {
		          res = `\n${indentation}${res}\n${originalIndentation}`;
		        }
		        stack.pop();
		        return `{${res}}`
		      }
		      case 'number':
		        return isFinite(value) ? String(value) : fail ? fail(value) : 'null'
		      case 'boolean':
		        return value === true ? 'true' : 'false'
		      case 'undefined':
		        return undefined
		      case 'bigint':
		        if (bigint) {
		          return String(value)
		        }
		        // fallthrough
		      default:
		        return fail ? fail(value) : undefined
		    }
		  }

		  function stringifySimple (key, value, stack) {
		    switch (typeof value) {
		      case 'string':
		        return strEscape(value)
		      case 'object': {
		        if (value === null) {
		          return 'null'
		        }
		        if (typeof value.toJSON === 'function') {
		          value = value.toJSON(key);
		          // Prevent calling `toJSON` again
		          if (typeof value !== 'object') {
		            return stringifySimple(key, value, stack)
		          }
		          if (value === null) {
		            return 'null'
		          }
		        }
		        if (stack.indexOf(value) !== -1) {
		          return circularValue
		        }

		        let res = '';

		        const hasLength = value.length !== undefined;
		        if (hasLength && Array.isArray(value)) {
		          if (value.length === 0) {
		            return '[]'
		          }
		          if (maximumDepth < stack.length + 1) {
		            return '"[Array]"'
		          }
		          stack.push(value);
		          const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
		          let i = 0;
		          for (; i < maximumValuesToStringify - 1; i++) {
		            const tmp = stringifySimple(String(i), value[i], stack);
		            res += tmp !== undefined ? tmp : 'null';
		            res += ',';
		          }
		          const tmp = stringifySimple(String(i), value[i], stack);
		          res += tmp !== undefined ? tmp : 'null';
		          if (value.length - 1 > maximumBreadth) {
		            const removedKeys = value.length - maximumBreadth - 1;
		            res += `,"... ${getItemCount(removedKeys)} not stringified"`;
		          }
		          stack.pop();
		          return `[${res}]`
		        }

		        let keys = Object.keys(value);
		        const keyLength = keys.length;
		        if (keyLength === 0) {
		          return '{}'
		        }
		        if (maximumDepth < stack.length + 1) {
		          return '"[Object]"'
		        }
		        let separator = '';
		        let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
		        if (hasLength && isTypedArrayWithEntries(value)) {
		          res += stringifyTypedArray(value, ',', maximumBreadth);
		          keys = keys.slice(value.length);
		          maximumPropertiesToStringify -= value.length;
		          separator = ',';
		        }
		        if (deterministic) {
		          keys = sort(keys, comparator);
		        }
		        stack.push(value);
		        for (let i = 0; i < maximumPropertiesToStringify; i++) {
		          const key = keys[i];
		          const tmp = stringifySimple(key, value[key], stack);
		          if (tmp !== undefined) {
		            res += `${separator}${strEscape(key)}:${tmp}`;
		            separator = ',';
		          }
		        }
		        if (keyLength > maximumBreadth) {
		          const removedKeys = keyLength - maximumBreadth;
		          res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"`;
		        }
		        stack.pop();
		        return `{${res}}`
		      }
		      case 'number':
		        return isFinite(value) ? String(value) : fail ? fail(value) : 'null'
		      case 'boolean':
		        return value === true ? 'true' : 'false'
		      case 'undefined':
		        return undefined
		      case 'bigint':
		        if (bigint) {
		          return String(value)
		        }
		        // fallthrough
		      default:
		        return fail ? fail(value) : undefined
		    }
		  }

		  function stringify (value, replacer, space) {
		    if (arguments.length > 1) {
		      let spacer = '';
		      if (typeof space === 'number') {
		        spacer = ' '.repeat(Math.min(space, 10));
		      } else if (typeof space === 'string') {
		        spacer = space.slice(0, 10);
		      }
		      if (replacer != null) {
		        if (typeof replacer === 'function') {
		          return stringifyFnReplacer('', { '': value }, [], replacer, spacer, '')
		        }
		        if (Array.isArray(replacer)) {
		          return stringifyArrayReplacer('', value, [], getUniqueReplacerSet(replacer), spacer, '')
		        }
		      }
		      if (spacer.length !== 0) {
		        return stringifyIndent('', value, [], spacer, '')
		      }
		    }
		    return stringifySimple('', value, [])
		  }

		  return stringify
		} 
	} (safeStableStringify, safeStableStringify.exports));
	return safeStableStringify.exports;
}

var json$1;
var hasRequiredJson$1;

function requireJson$1 () {
	if (hasRequiredJson$1) return json$1;
	hasRequiredJson$1 = 1;

	var format = requireFormat$3();
	var _require = requireTripleBeam(),
	  MESSAGE = _require.MESSAGE;
	var stringify = requireSafeStableStringify();

	/*
	 * function replacer (key, value)
	 * Handles proper stringification of Buffer and bigint output.
	 */
	function replacer(key, value) {
	  // safe-stable-stringify does support BigInt, however, it doesn't wrap the value in quotes.
	  // Leading to a loss in fidelity if the resulting string is parsed.
	  // It would also be a breaking change for logform.
	  if (typeof value === 'bigint') return value.toString();
	  return value;
	}

	/*
	 * function json (info)
	 * Returns a new instance of the JSON format that turns a log `info`
	 * object into pure JSON. This was previously exposed as { json: true }
	 * to transports in `winston < 3.0.0`.
	 */
	json$1 = format(function (info, opts) {
	  var jsonStringify = stringify.configure(opts);
	  info[MESSAGE] = jsonStringify(info, opts.replacer || replacer, opts.space);
	  return info;
	});
	return json$1;
}

var label;
var hasRequiredLabel;

function requireLabel () {
	if (hasRequiredLabel) return label;
	hasRequiredLabel = 1;

	var format = requireFormat$3();

	/*
	 * function label (info)
	 * Returns a new instance of the label Format which adds the specified
	 * `opts.label` before the message. This was previously exposed as
	 * { label: 'my label' } to transports in `winston < 3.0.0`.
	 */
	label = format(function (info, opts) {
	  if (opts.message) {
	    info.message = "[".concat(opts.label, "] ").concat(info.message);
	    return info;
	  }
	  info.label = opts.label;
	  return info;
	});
	return label;
}

var logstash;
var hasRequiredLogstash;

function requireLogstash () {
	if (hasRequiredLogstash) return logstash;
	hasRequiredLogstash = 1;

	var format = requireFormat$3();
	var _require = requireTripleBeam(),
	  MESSAGE = _require.MESSAGE;
	var jsonStringify = requireSafeStableStringify();

	/*
	 * function logstash (info)
	 * Returns a new instance of the LogStash Format that turns a
	 * log `info` object into pure JSON with the appropriate logstash
	 * options. This was previously exposed as { logstash: true }
	 * to transports in `winston < 3.0.0`.
	 */
	logstash = format(function (info) {
	  var logstash = {};
	  if (info.message) {
	    logstash['@message'] = info.message;
	    delete info.message;
	  }
	  if (info.timestamp) {
	    logstash['@timestamp'] = info.timestamp;
	    delete info.timestamp;
	  }
	  logstash['@fields'] = info;
	  info[MESSAGE] = jsonStringify(logstash);
	  return info;
	});
	return logstash;
}

var metadata$1;
var hasRequiredMetadata$1;

function requireMetadata$1 () {
	if (hasRequiredMetadata$1) return metadata$1;
	hasRequiredMetadata$1 = 1;

	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
	var format = requireFormat$3();
	function fillExcept(info, fillExceptKeys, metadataKey) {
	  var savedKeys = fillExceptKeys.reduce(function (acc, key) {
	    acc[key] = info[key];
	    delete info[key];
	    return acc;
	  }, {});
	  var metadata = Object.keys(info).reduce(function (acc, key) {
	    acc[key] = info[key];
	    delete info[key];
	    return acc;
	  }, {});
	  Object.assign(info, savedKeys, _defineProperty({}, metadataKey, metadata));
	  return info;
	}
	function fillWith(info, fillWithKeys, metadataKey) {
	  info[metadataKey] = fillWithKeys.reduce(function (acc, key) {
	    acc[key] = info[key];
	    delete info[key];
	    return acc;
	  }, {});
	  return info;
	}

	/**
	 * Adds in a "metadata" object to collect extraneous data, similar to the metadata
	 * object in winston 2.x.
	 */
	metadata$1 = format(function (info) {
	  var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
	  var metadataKey = 'metadata';
	  if (opts.key) {
	    metadataKey = opts.key;
	  }
	  var fillExceptKeys = [];
	  if (!opts.fillExcept && !opts.fillWith) {
	    fillExceptKeys.push('level');
	    fillExceptKeys.push('message');
	  }
	  if (opts.fillExcept) {
	    fillExceptKeys = opts.fillExcept;
	  }
	  if (fillExceptKeys.length > 0) {
	    return fillExcept(info, fillExceptKeys, metadataKey);
	  }
	  if (opts.fillWith) {
	    return fillWith(info, opts.fillWith, metadataKey);
	  }
	  return info;
	});
	return metadata$1;
}

var ms_1;
var hasRequiredMs$1;

function requireMs$1 () {
	if (hasRequiredMs$1) return ms_1;
	hasRequiredMs$1 = 1;

	var _this = void 0;
	var format = requireFormat$3();
	var ms = requireMs$2();

	/*
	 * function ms (info)
	 * Returns an `info` with a `ms` property. The `ms` property holds the Value
	 * of the time difference between two calls in milliseconds.
	 */
	ms_1 = format(function (info) {
	  var curr = +new Date();
	  _this.diff = curr - (_this.prevTime || curr);
	  _this.prevTime = curr;
	  info.ms = "+".concat(ms(_this.diff));
	  return info;
	});
	return ms_1;
}

var prettyPrint;
var hasRequiredPrettyPrint;

function requirePrettyPrint () {
	if (hasRequiredPrettyPrint) return prettyPrint;
	hasRequiredPrettyPrint = 1;

	var inspect = require$$0$6.inspect;
	var format = requireFormat$3();
	var _require = requireTripleBeam(),
	  LEVEL = _require.LEVEL,
	  MESSAGE = _require.MESSAGE,
	  SPLAT = _require.SPLAT;

	/*
	 * function prettyPrint (info)
	 * Returns a new instance of the prettyPrint Format that "prettyPrint"
	 * serializes `info` objects. This was previously exposed as
	 * { prettyPrint: true } to transports in `winston < 3.0.0`.
	 */
	prettyPrint = format(function (info) {
	  var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
	  //
	  // info[{LEVEL, MESSAGE, SPLAT}] are enumerable here. Since they
	  // are internal, we remove them before util.inspect so they
	  // are not printed.
	  //
	  var stripped = Object.assign({}, info);

	  // Remark (indexzero): update this technique in April 2019
	  // when node@6 is EOL
	  delete stripped[LEVEL];
	  delete stripped[MESSAGE];
	  delete stripped[SPLAT];
	  info[MESSAGE] = inspect(stripped, false, opts.depth || null, opts.colorize);
	  return info;
	});
	return prettyPrint;
}

var printf = {exports: {}};

var hasRequiredPrintf;

function requirePrintf () {
	if (hasRequiredPrintf) return printf.exports;
	hasRequiredPrintf = 1;

	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
	function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
	var _require = requireTripleBeam(),
	  MESSAGE = _require.MESSAGE;
	var Printf = /*#__PURE__*/function () {
	  function Printf(templateFn) {
	    _classCallCheck(this, Printf);
	    this.template = templateFn;
	  }
	  return _createClass(Printf, [{
	    key: "transform",
	    value: function transform(info) {
	      info[MESSAGE] = this.template(info);
	      return info;
	    }
	  }]);
	}();
	/*
	 * function printf (templateFn)
	 * Returns a new instance of the printf Format that creates an
	 * intermediate prototype to store the template string-based formatter
	 * function.
	 */
	printf.exports = function (opts) {
	  return new Printf(opts);
	};
	printf.exports.Printf = printf.exports.Format = Printf;
	return printf.exports;
}

/* eslint no-undefined: 0 */

var simple;
var hasRequiredSimple;

function requireSimple () {
	if (hasRequiredSimple) return simple;
	hasRequiredSimple = 1;

	var format = requireFormat$3();
	var _require = requireTripleBeam(),
	  MESSAGE = _require.MESSAGE;
	var jsonStringify = requireSafeStableStringify();

	/*
	 * function simple (info)
	 * Returns a new instance of the simple format TransformStream
	 * which writes a simple representation of logs.
	 *
	 *    const { level, message, splat, ...rest } = info;
	 *
	 *    ${level}: ${message}                            if rest is empty
	 *    ${level}: ${message} ${JSON.stringify(rest)}    otherwise
	 */
	simple = format(function (info) {
	  var stringifiedRest = jsonStringify(Object.assign({}, info, {
	    level: undefined,
	    message: undefined,
	    splat: undefined
	  }));
	  var padding = info.padding && info.padding[info.level] || '';
	  if (stringifiedRest !== '{}') {
	    info[MESSAGE] = "".concat(info.level, ":").concat(padding, " ").concat(info.message, " ").concat(stringifiedRest);
	  } else {
	    info[MESSAGE] = "".concat(info.level, ":").concat(padding, " ").concat(info.message);
	  }
	  return info;
	});
	return simple;
}

var splat;
var hasRequiredSplat;

function requireSplat () {
	if (hasRequiredSplat) return splat;
	hasRequiredSplat = 1;

	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
	function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
	function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
	function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
	function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
	function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
	function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
	var util = require$$0$6;
	var _require = requireTripleBeam(),
	  SPLAT = _require.SPLAT;

	/**
	 * Captures the number of format (i.e. %s strings) in a given string.
	 * Based on `util.format`, see Node.js source:
	 * https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230
	 * @type {RegExp}
	 */
	var formatRegExp = /%[scdjifoO%]/g;

	/**
	 * Captures the number of escaped % signs in a format string (i.e. %s strings).
	 * @type {RegExp}
	 */
	var escapedPercent = /%%/g;
	var Splatter = /*#__PURE__*/function () {
	  function Splatter(opts) {
	    _classCallCheck(this, Splatter);
	    this.options = opts;
	  }

	  /**
	     * Check to see if tokens <= splat.length, assign { splat, meta } into the
	     * `info` accordingly, and write to this instance.
	     *
	     * @param  {Info} info Logform info message.
	     * @param  {String[]} tokens Set of string interpolation tokens.
	     * @returns {Info} Modified info message
	     * @private
	     */
	  return _createClass(Splatter, [{
	    key: "_splat",
	    value: function _splat(info, tokens) {
	      var msg = info.message;
	      var splat = info[SPLAT] || info.splat || [];
	      var percents = msg.match(escapedPercent);
	      var escapes = percents && percents.length || 0;

	      // The expected splat is the number of tokens minus the number of escapes
	      // e.g.
	      // - { expectedSplat: 3 } '%d %s %j'
	      // - { expectedSplat: 5 } '[%s] %d%% %d%% %s %j'
	      //
	      // Any "meta" will be arugments in addition to the expected splat size
	      // regardless of type. e.g.
	      //
	      // logger.log('info', '%d%% %s %j', 100, 'wow', { such: 'js' }, { thisIsMeta: true });
	      // would result in splat of four (4), but only three (3) are expected. Therefore:
	      //
	      // extraSplat = 3 - 4 = -1
	      // metas = [100, 'wow', { such: 'js' }, { thisIsMeta: true }].splice(-1, -1 * -1);
	      // splat = [100, 'wow', { such: 'js' }]
	      var expectedSplat = tokens.length - escapes;
	      var extraSplat = expectedSplat - splat.length;
	      var metas = extraSplat < 0 ? splat.splice(extraSplat, -1 * extraSplat) : [];

	      // Now that { splat } has been separated from any potential { meta }. we
	      // can assign this to the `info` object and write it to our format stream.
	      // If the additional metas are **NOT** objects or **LACK** enumerable properties
	      // you are going to have a bad time.
	      var metalen = metas.length;
	      if (metalen) {
	        for (var i = 0; i < metalen; i++) {
	          Object.assign(info, metas[i]);
	        }
	      }
	      info.message = util.format.apply(util, [msg].concat(_toConsumableArray(splat)));
	      return info;
	    }

	    /**
	      * Transforms the `info` message by using `util.format` to complete
	      * any `info.message` provided it has string interpolation tokens.
	      * If no tokens exist then `info` is immutable.
	      *
	      * @param  {Info} info Logform info message.
	      * @param  {Object} opts Options for this instance.
	      * @returns {Info} Modified info message
	      */
	  }, {
	    key: "transform",
	    value: function transform(info) {
	      var msg = info.message;
	      var splat = info[SPLAT] || info.splat;

	      // No need to process anything if splat is undefined
	      if (!splat || !splat.length) {
	        return info;
	      }

	      // Extract tokens, if none available default to empty array to
	      // ensure consistancy in expected results
	      var tokens = msg && msg.match && msg.match(formatRegExp);

	      // This condition will take care of inputs with info[SPLAT]
	      // but no tokens present
	      if (!tokens && (splat || splat.length)) {
	        var metas = splat.length > 1 ? splat.splice(0) : splat;

	        // Now that { splat } has been separated from any potential { meta }. we
	        // can assign this to the `info` object and write it to our format stream.
	        // If the additional metas are **NOT** objects or **LACK** enumerable properties
	        // you are going to have a bad time.
	        var metalen = metas.length;
	        if (metalen) {
	          for (var i = 0; i < metalen; i++) {
	            Object.assign(info, metas[i]);
	          }
	        }
	        return info;
	      }
	      if (tokens) {
	        return this._splat(info, tokens);
	      }
	      return info;
	    }
	  }]);
	}();
	/*
	 * function splat (info)
	 * Returns a new instance of the splat format TransformStream
	 * which performs string interpolation from `info` objects. This was
	 * previously exposed implicitly in `winston < 3.0.0`.
	 */
	splat = function (opts) {
	  return new Splatter(opts);
	};
	return splat;
}

var token$1 = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g;
var twoDigitsOptional = "\\d\\d?";
var twoDigits = "\\d\\d";
var threeDigits = "\\d{3}";
var fourDigits = "\\d{4}";
var word = "[^\\s]+";
var literal$1 = /\[([^]*?)\]/gm;
function shorten(arr, sLen) {
    var newArr = [];
    for (var i = 0, len = arr.length; i < len; i++) {
        newArr.push(arr[i].substr(0, sLen));
    }
    return newArr;
}
var monthUpdate = function (arrName) { return function (v, i18n) {
    var lowerCaseArr = i18n[arrName].map(function (v) { return v.toLowerCase(); });
    var index = lowerCaseArr.indexOf(v.toLowerCase());
    if (index > -1) {
        return index;
    }
    return null;
}; };
function assign$1(origObj) {
    var args = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        args[_i - 1] = arguments[_i];
    }
    for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
        var obj = args_1[_a];
        for (var key in obj) {
            // @ts-ignore ex
            origObj[key] = obj[key];
        }
    }
    return origObj;
}
var dayNames = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
];
var monthNames = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
];
var monthNamesShort = shorten(monthNames, 3);
var dayNamesShort = shorten(dayNames, 3);
var defaultI18n = {
    dayNamesShort: dayNamesShort,
    dayNames: dayNames,
    monthNamesShort: monthNamesShort,
    monthNames: monthNames,
    amPm: ["am", "pm"],
    DoFn: function (dayOfMonth) {
        return (dayOfMonth +
            ["th", "st", "nd", "rd"][dayOfMonth % 10 > 3
                ? 0
                : ((dayOfMonth - (dayOfMonth % 10) !== 10 ? 1 : 0) * dayOfMonth) % 10]);
    }
};
var globalI18n = assign$1({}, defaultI18n);
var setGlobalDateI18n = function (i18n) {
    return (globalI18n = assign$1(globalI18n, i18n));
};
var regexEscape = function (str) {
    return str.replace(/[|\\{()[^$+*?.-]/g, "\\$&");
};
var pad = function (val, len) {
    if (len === void 0) { len = 2; }
    val = String(val);
    while (val.length < len) {
        val = "0" + val;
    }
    return val;
};
var formatFlags = {
    D: function (dateObj) { return String(dateObj.getDate()); },
    DD: function (dateObj) { return pad(dateObj.getDate()); },
    Do: function (dateObj, i18n) {
        return i18n.DoFn(dateObj.getDate());
    },
    d: function (dateObj) { return String(dateObj.getDay()); },
    dd: function (dateObj) { return pad(dateObj.getDay()); },
    ddd: function (dateObj, i18n) {
        return i18n.dayNamesShort[dateObj.getDay()];
    },
    dddd: function (dateObj, i18n) {
        return i18n.dayNames[dateObj.getDay()];
    },
    M: function (dateObj) { return String(dateObj.getMonth() + 1); },
    MM: function (dateObj) { return pad(dateObj.getMonth() + 1); },
    MMM: function (dateObj, i18n) {
        return i18n.monthNamesShort[dateObj.getMonth()];
    },
    MMMM: function (dateObj, i18n) {
        return i18n.monthNames[dateObj.getMonth()];
    },
    YY: function (dateObj) {
        return pad(String(dateObj.getFullYear()), 4).substr(2);
    },
    YYYY: function (dateObj) { return pad(dateObj.getFullYear(), 4); },
    h: function (dateObj) { return String(dateObj.getHours() % 12 || 12); },
    hh: function (dateObj) { return pad(dateObj.getHours() % 12 || 12); },
    H: function (dateObj) { return String(dateObj.getHours()); },
    HH: function (dateObj) { return pad(dateObj.getHours()); },
    m: function (dateObj) { return String(dateObj.getMinutes()); },
    mm: function (dateObj) { return pad(dateObj.getMinutes()); },
    s: function (dateObj) { return String(dateObj.getSeconds()); },
    ss: function (dateObj) { return pad(dateObj.getSeconds()); },
    S: function (dateObj) {
        return String(Math.round(dateObj.getMilliseconds() / 100));
    },
    SS: function (dateObj) {
        return pad(Math.round(dateObj.getMilliseconds() / 10), 2);
    },
    SSS: function (dateObj) { return pad(dateObj.getMilliseconds(), 3); },
    a: function (dateObj, i18n) {
        return dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1];
    },
    A: function (dateObj, i18n) {
        return dateObj.getHours() < 12
            ? i18n.amPm[0].toUpperCase()
            : i18n.amPm[1].toUpperCase();
    },
    ZZ: function (dateObj) {
        var offset = dateObj.getTimezoneOffset();
        return ((offset > 0 ? "-" : "+") +
            pad(Math.floor(Math.abs(offset) / 60) * 100 + (Math.abs(offset) % 60), 4));
    },
    Z: function (dateObj) {
        var offset = dateObj.getTimezoneOffset();
        return ((offset > 0 ? "-" : "+") +
            pad(Math.floor(Math.abs(offset) / 60), 2) +
            ":" +
            pad(Math.abs(offset) % 60, 2));
    }
};
var monthParse = function (v) { return +v - 1; };
var emptyDigits = [null, twoDigitsOptional];
var emptyWord = [null, word];
var amPm = [
    "isPm",
    word,
    function (v, i18n) {
        var val = v.toLowerCase();
        if (val === i18n.amPm[0]) {
            return 0;
        }
        else if (val === i18n.amPm[1]) {
            return 1;
        }
        return null;
    }
];
var timezoneOffset = [
    "timezoneOffset",
    "[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?",
    function (v) {
        var parts = (v + "").match(/([+-]|\d\d)/gi);
        if (parts) {
            var minutes = +parts[1] * 60 + parseInt(parts[2], 10);
            return parts[0] === "+" ? minutes : -minutes;
        }
        return 0;
    }
];
var parseFlags = {
    D: ["day", twoDigitsOptional],
    DD: ["day", twoDigits],
    Do: ["day", twoDigitsOptional + word, function (v) { return parseInt(v, 10); }],
    M: ["month", twoDigitsOptional, monthParse],
    MM: ["month", twoDigits, monthParse],
    YY: [
        "year",
        twoDigits,
        function (v) {
            var now = new Date();
            var cent = +("" + now.getFullYear()).substr(0, 2);
            return +("" + (+v > 68 ? cent - 1 : cent) + v);
        }
    ],
    h: ["hour", twoDigitsOptional, undefined, "isPm"],
    hh: ["hour", twoDigits, undefined, "isPm"],
    H: ["hour", twoDigitsOptional],
    HH: ["hour", twoDigits],
    m: ["minute", twoDigitsOptional],
    mm: ["minute", twoDigits],
    s: ["second", twoDigitsOptional],
    ss: ["second", twoDigits],
    YYYY: ["year", fourDigits],
    S: ["millisecond", "\\d", function (v) { return +v * 100; }],
    SS: ["millisecond", twoDigits, function (v) { return +v * 10; }],
    SSS: ["millisecond", threeDigits],
    d: emptyDigits,
    dd: emptyDigits,
    ddd: emptyWord,
    dddd: emptyWord,
    MMM: ["month", word, monthUpdate("monthNamesShort")],
    MMMM: ["month", word, monthUpdate("monthNames")],
    a: amPm,
    A: amPm,
    ZZ: timezoneOffset,
    Z: timezoneOffset
};
// Some common format strings
var globalMasks = {
    default: "ddd MMM DD YYYY HH:mm:ss",
    shortDate: "M/D/YY",
    mediumDate: "MMM D, YYYY",
    longDate: "MMMM D, YYYY",
    fullDate: "dddd, MMMM D, YYYY",
    isoDate: "YYYY-MM-DD",
    isoDateTime: "YYYY-MM-DDTHH:mm:ssZ",
    shortTime: "HH:mm",
    mediumTime: "HH:mm:ss",
    longTime: "HH:mm:ss.SSS"
};
var setGlobalDateMasks = function (masks) { return assign$1(globalMasks, masks); };
/***
 * Format a date
 * @method format
 * @param {Date|number} dateObj
 * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate'
 * @returns {string} Formatted date string
 */
var format$3 = function (dateObj, mask, i18n) {
    if (mask === void 0) { mask = globalMasks["default"]; }
    if (i18n === void 0) { i18n = {}; }
    if (typeof dateObj === "number") {
        dateObj = new Date(dateObj);
    }
    if (Object.prototype.toString.call(dateObj) !== "[object Date]" ||
        isNaN(dateObj.getTime())) {
        throw new Error("Invalid Date pass to format");
    }
    mask = globalMasks[mask] || mask;
    var literals = [];
    // Make literals inactive by replacing them with @@@
    mask = mask.replace(literal$1, function ($0, $1) {
        literals.push($1);
        return "@@@";
    });
    var combinedI18nSettings = assign$1(assign$1({}, globalI18n), i18n);
    // Apply formatting rules
    mask = mask.replace(token$1, function ($0) {
        return formatFlags[$0](dateObj, combinedI18nSettings);
    });
    // Inline literal values back into the formatted value
    return mask.replace(/@@@/g, function () { return literals.shift(); });
};
/**
 * Parse a date string into a Javascript Date object /
 * @method parse
 * @param {string} dateStr Date string
 * @param {string} format Date parse format
 * @param {i18n} I18nSettingsOptional Full or subset of I18N settings
 * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format
 */
function parse$1(dateStr, format, i18n) {
    if (i18n === void 0) { i18n = {}; }
    if (typeof format !== "string") {
        throw new Error("Invalid format in fecha parse");
    }
    // Check to see if the format is actually a mask
    format = globalMasks[format] || format;
    // Avoid regular expression denial of service, fail early for really long strings
    // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS
    if (dateStr.length > 1000) {
        return null;
    }
    // Default to the beginning of the year.
    var today = new Date();
    var dateInfo = {
        year: today.getFullYear(),
        month: 0,
        day: 1,
        hour: 0,
        minute: 0,
        second: 0,
        millisecond: 0,
        isPm: null,
        timezoneOffset: null
    };
    var parseInfo = [];
    var literals = [];
    // Replace all the literals with @@@. Hopefully a string that won't exist in the format
    var newFormat = format.replace(literal$1, function ($0, $1) {
        literals.push(regexEscape($1));
        return "@@@";
    });
    var specifiedFields = {};
    var requiredFields = {};
    // Change every token that we find into the correct regex
    newFormat = regexEscape(newFormat).replace(token$1, function ($0) {
        var info = parseFlags[$0];
        var field = info[0], regex = info[1], requiredField = info[3];
        // Check if the person has specified the same field twice. This will lead to confusing results.
        if (specifiedFields[field]) {
            throw new Error("Invalid format. " + field + " specified twice in format");
        }
        specifiedFields[field] = true;
        // Check if there are any required fields. For instance, 12 hour time requires AM/PM specified
        if (requiredField) {
            requiredFields[requiredField] = true;
        }
        parseInfo.push(info);
        return "(" + regex + ")";
    });
    // Check all the required fields are present
    Object.keys(requiredFields).forEach(function (field) {
        if (!specifiedFields[field]) {
            throw new Error("Invalid format. " + field + " is required in specified format");
        }
    });
    // Add back all the literals after
    newFormat = newFormat.replace(/@@@/g, function () { return literals.shift(); });
    // Check if the date string matches the format. If it doesn't return null
    var matches = dateStr.match(new RegExp(newFormat, "i"));
    if (!matches) {
        return null;
    }
    var combinedI18nSettings = assign$1(assign$1({}, globalI18n), i18n);
    // For each match, call the parser function for that date part
    for (var i = 1; i < matches.length; i++) {
        var _a = parseInfo[i - 1], field = _a[0], parser = _a[2];
        var value = parser
            ? parser(matches[i], combinedI18nSettings)
            : +matches[i];
        // If the parser can't make sense of the value, return null
        if (value == null) {
            return null;
        }
        dateInfo[field] = value;
    }
    if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) {
        dateInfo.hour = +dateInfo.hour + 12;
    }
    else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) {
        dateInfo.hour = 0;
    }
    var dateTZ;
    if (dateInfo.timezoneOffset == null) {
        dateTZ = new Date(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute, dateInfo.second, dateInfo.millisecond);
        var validateFields = [
            ["month", "getMonth"],
            ["day", "getDate"],
            ["hour", "getHours"],
            ["minute", "getMinutes"],
            ["second", "getSeconds"]
        ];
        for (var i = 0, len = validateFields.length; i < len; i++) {
            // Check to make sure the date field is within the allowed range. Javascript dates allows values
            // outside the allowed range. If the values don't match the value was invalid
            if (specifiedFields[validateFields[i][0]] &&
                dateInfo[validateFields[i][0]] !== dateTZ[validateFields[i][1]]()) {
                return null;
            }
        }
    }
    else {
        dateTZ = new Date(Date.UTC(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute - dateInfo.timezoneOffset, dateInfo.second, dateInfo.millisecond));
        // We can't validate dates in another timezone unfortunately. Do a basic check instead
        if (dateInfo.month > 11 ||
            dateInfo.month < 0 ||
            dateInfo.day > 31 ||
            dateInfo.day < 1 ||
            dateInfo.hour > 23 ||
            dateInfo.hour < 0 ||
            dateInfo.minute > 59 ||
            dateInfo.minute < 0 ||
            dateInfo.second > 59 ||
            dateInfo.second < 0) {
            return null;
        }
    }
    // Don't allow invalid dates
    return dateTZ;
}
var fecha = {
    format: format$3,
    parse: parse$1,
    defaultI18n: defaultI18n,
    setGlobalDateI18n: setGlobalDateI18n,
    setGlobalDateMasks: setGlobalDateMasks
};

const fecha$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
    __proto__: null,
    assign: assign$1,
    default: fecha,
    defaultI18n,
    format: format$3,
    parse: parse$1,
    setGlobalDateI18n,
    setGlobalDateMasks
}, Symbol.toStringTag, { value: 'Module' }));

const require$$0$2 = /*@__PURE__*/getAugmentedNamespace(fecha$1);

var timestamp;
var hasRequiredTimestamp;

function requireTimestamp () {
	if (hasRequiredTimestamp) return timestamp;
	hasRequiredTimestamp = 1;

	var fecha = require$$0$2;
	var format = requireFormat$3();

	/*
	 * function timestamp (info)
	 * Returns a new instance of the timestamp Format which adds a timestamp
	 * to the info. It was previously available in winston < 3.0.0 as:
	 *
	 * - { timestamp: true }             // `new Date.toISOString()`
	 * - { timestamp: function:String }  // Value returned by `timestamp()`
	 */
	timestamp = format(function (info) {
	  var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
	  if (opts.format) {
	    info.timestamp = typeof opts.format === 'function' ? opts.format() : fecha.format(new Date(), opts.format);
	  }
	  if (!info.timestamp) {
	    info.timestamp = new Date().toISOString();
	  }
	  if (opts.alias) {
	    info[opts.alias] = info.timestamp;
	  }
	  return info;
	});
	return timestamp;
}

var uncolorize;
var hasRequiredUncolorize;

function requireUncolorize () {
	if (hasRequiredUncolorize) return uncolorize;
	hasRequiredUncolorize = 1;

	var colors = requireSafe();
	var format = requireFormat$3();
	var _require = requireTripleBeam(),
	  MESSAGE = _require.MESSAGE;

	/*
	 * function uncolorize (info)
	 * Returns a new instance of the uncolorize Format that strips colors
	 * from `info` objects. This was previously exposed as { stripColors: true }
	 * to transports in `winston < 3.0.0`.
	 */
	uncolorize = format(function (info, opts) {
	  if (opts.level !== false) {
	    info.level = colors.strip(info.level);
	  }
	  if (opts.message !== false) {
	    info.message = colors.strip(String(info.message));
	  }
	  if (opts.raw !== false && info[MESSAGE]) {
	    info[MESSAGE] = colors.strip(String(info[MESSAGE]));
	  }
	  return info;
	});
	return uncolorize;
}

var hasRequiredBrowser$2;

function requireBrowser$2 () {
	if (hasRequiredBrowser$2) return browser$2;
	hasRequiredBrowser$2 = 1;

	/*
	 * @api public
	 * @property {function} format
	 * Both the construction method and set of exposed
	 * formats.
	 */
	var format = browser$2.format = requireFormat$3();

	/*
	 * @api public
	 * @method {function} levels
	 * Registers the specified levels with logform.
	 */
	browser$2.levels = requireLevels();

	//
	// Setup all transports as eager-loaded exports
	// so that they are static for the bundlers.
	//
	Object.defineProperty(format, 'align', {
	  value: requireAlign()
	});
	Object.defineProperty(format, 'cli', {
	  value: requireCli()
	});
	Object.defineProperty(format, 'colorize', {
	  value: requireColorize()
	});
	Object.defineProperty(format, 'combine', {
	  value: requireCombine()
	});
	Object.defineProperty(format, 'errors', {
	  value: requireErrors$1()
	});
	Object.defineProperty(format, 'json', {
	  value: requireJson$1()
	});
	Object.defineProperty(format, 'label', {
	  value: requireLabel()
	});
	Object.defineProperty(format, 'logstash', {
	  value: requireLogstash()
	});
	Object.defineProperty(format, 'metadata', {
	  value: requireMetadata$1()
	});
	Object.defineProperty(format, 'ms', {
	  value: requireMs$1()
	});
	Object.defineProperty(format, 'padLevels', {
	  value: requirePadLevels()
	});
	Object.defineProperty(format, 'prettyPrint', {
	  value: requirePrettyPrint()
	});
	Object.defineProperty(format, 'printf', {
	  value: requirePrintf()
	});
	Object.defineProperty(format, 'simple', {
	  value: requireSimple()
	});
	Object.defineProperty(format, 'splat', {
	  value: requireSplat()
	});
	Object.defineProperty(format, 'timestamp', {
	  value: requireTimestamp()
	});
	Object.defineProperty(format, 'uncolorize', {
	  value: requireUncolorize()
	});
	return browser$2;
}

var common = {};

/**
 * common.js: Internal helper and utility functions for winston.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var hasRequiredCommon;

function requireCommon () {
	if (hasRequiredCommon) return common;
	hasRequiredCommon = 1;
	(function (exports$1) {

		var _require = require$$0$6,
		  format = _require.format;

		/**
		 * Set of simple deprecation notices and a way to expose them for a set of
		 * properties.
		 * @type {Object}
		 * @private
		 */
		exports$1.warn = {
		  deprecated: function deprecated(prop) {
		    return function () {
		      throw new Error(format('{ %s } was removed in winston@3.0.0.', prop));
		    };
		  },
		  useFormat: function useFormat(prop) {
		    return function () {
		      throw new Error([format('{ %s } was removed in winston@3.0.0.', prop), 'Use a custom winston.format = winston.format(function) instead.'].join('\n'));
		    };
		  },
		  forFunctions: function forFunctions(obj, type, props) {
		    props.forEach(function (prop) {
		      obj[prop] = exports$1.warn[type](prop);
		    });
		  },
		  forProperties: function forProperties(obj, type, props) {
		    props.forEach(function (prop) {
		      var notice = exports$1.warn[type](prop);
		      Object.defineProperty(obj, prop, {
		        get: notice,
		        set: notice
		      });
		    });
		  }
		}; 
	} (common));
	return common;
}

const version = "3.18.3";
const require$$2 = {
  version};

var transports = {};

var dist = {exports: {}};

var modern$1 = {exports: {}};

var streamBrowser;
var hasRequiredStreamBrowser;

function requireStreamBrowser () {
	if (hasRequiredStreamBrowser) return streamBrowser;
	hasRequiredStreamBrowser = 1;
	streamBrowser = require$$0$5.EventEmitter;
	return streamBrowser;
}

var destroy_1;
var hasRequiredDestroy;

function requireDestroy () {
	if (hasRequiredDestroy) return destroy_1;
	hasRequiredDestroy = 1;

	// undocumented cb() API, needed for core, not for public API
	function destroy(err, cb) {
	  var _this = this;
	  var readableDestroyed = this._readableState && this._readableState.destroyed;
	  var writableDestroyed = this._writableState && this._writableState.destroyed;
	  if (readableDestroyed || writableDestroyed) {
	    if (cb) {
	      cb(err);
	    } else if (err) {
	      if (!this._writableState) {
	        process.nextTick(emitErrorNT, this, err);
	      } else if (!this._writableState.errorEmitted) {
	        this._writableState.errorEmitted = true;
	        process.nextTick(emitErrorNT, this, err);
	      }
	    }
	    return this;
	  }

	  // we set destroyed to true before firing error callbacks in order
	  // to make it re-entrance safe in case destroy() is called within callbacks

	  if (this._readableState) {
	    this._readableState.destroyed = true;
	  }

	  // if this is a duplex stream mark the writable part as destroyed as well
	  if (this._writableState) {
	    this._writableState.destroyed = true;
	  }
	  this._destroy(err || null, function (err) {
	    if (!cb && err) {
	      if (!_this._writableState) {
	        process.nextTick(emitErrorAndCloseNT, _this, err);
	      } else if (!_this._writableState.errorEmitted) {
	        _this._writableState.errorEmitted = true;
	        process.nextTick(emitErrorAndCloseNT, _this, err);
	      } else {
	        process.nextTick(emitCloseNT, _this);
	      }
	    } else if (cb) {
	      process.nextTick(emitCloseNT, _this);
	      cb(err);
	    } else {
	      process.nextTick(emitCloseNT, _this);
	    }
	  });
	  return this;
	}
	function emitErrorAndCloseNT(self, err) {
	  emitErrorNT(self, err);
	  emitCloseNT(self);
	}
	function emitCloseNT(self) {
	  if (self._writableState && !self._writableState.emitClose) return;
	  if (self._readableState && !self._readableState.emitClose) return;
	  self.emit('close');
	}
	function undestroy() {
	  if (this._readableState) {
	    this._readableState.destroyed = false;
	    this._readableState.reading = false;
	    this._readableState.ended = false;
	    this._readableState.endEmitted = false;
	  }
	  if (this._writableState) {
	    this._writableState.destroyed = false;
	    this._writableState.ended = false;
	    this._writableState.ending = false;
	    this._writableState.finalCalled = false;
	    this._writableState.prefinished = false;
	    this._writableState.finished = false;
	    this._writableState.errorEmitted = false;
	  }
	}
	function emitErrorNT(self, err) {
	  self.emit('error', err);
	}
	function errorOrDestroy(stream, err) {
	  // We have tests that rely on errors being emitted
	  // in the same tick, so changing this is semver major.
	  // For now when you opt-in to autoDestroy we allow
	  // the error to be emitted nextTick. In a future
	  // semver major update we should change the default to this.

	  var rState = stream._readableState;
	  var wState = stream._writableState;
	  if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
	}
	destroy_1 = {
	  destroy: destroy,
	  undestroy: undestroy,
	  errorOrDestroy: errorOrDestroy
	};
	return destroy_1;
}

var errorsBrowser = {};

var hasRequiredErrorsBrowser;

function requireErrorsBrowser () {
	if (hasRequiredErrorsBrowser) return errorsBrowser;
	hasRequiredErrorsBrowser = 1;

	function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }

	var codes = {};

	function createErrorType(code, message, Base) {
	  if (!Base) {
	    Base = Error;
	  }

	  function getMessage(arg1, arg2, arg3) {
	    if (typeof message === 'string') {
	      return message;
	    } else {
	      return message(arg1, arg2, arg3);
	    }
	  }

	  var NodeError =
	  /*#__PURE__*/
	  function (_Base) {
	    _inheritsLoose(NodeError, _Base);

	    function NodeError(arg1, arg2, arg3) {
	      return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
	    }

	    return NodeError;
	  }(Base);

	  NodeError.prototype.name = Base.name;
	  NodeError.prototype.code = code;
	  codes[code] = NodeError;
	} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js


	function oneOf(expected, thing) {
	  if (Array.isArray(expected)) {
	    var len = expected.length;
	    expected = expected.map(function (i) {
	      return String(i);
	    });

	    if (len > 2) {
	      return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
	    } else if (len === 2) {
	      return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
	    } else {
	      return "of ".concat(thing, " ").concat(expected[0]);
	    }
	  } else {
	    return "of ".concat(thing, " ").concat(String(expected));
	  }
	} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith


	function startsWith(str, search, pos) {
	  return str.substr(0 , search.length) === search;
	} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith


	function endsWith(str, search, this_len) {
	  if (this_len === undefined || this_len > str.length) {
	    this_len = str.length;
	  }

	  return str.substring(this_len - search.length, this_len) === search;
	} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes


	function includes(str, search, start) {
	  if (typeof start !== 'number') {
	    start = 0;
	  }

	  if (start + search.length > str.length) {
	    return false;
	  } else {
	    return str.indexOf(search, start) !== -1;
	  }
	}

	createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
	  return 'The value "' + value + '" is invalid for option "' + name + '"';
	}, TypeError);
	createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
	  // determiner: 'must be' or 'must not be'
	  var determiner;

	  if (typeof expected === 'string' && startsWith(expected, 'not ')) {
	    determiner = 'must not be';
	    expected = expected.replace(/^not /, '');
	  } else {
	    determiner = 'must be';
	  }

	  var msg;

	  if (endsWith(name, ' argument')) {
	    // For cases like 'first argument'
	    msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
	  } else {
	    var type = includes(name, '.') ? 'property' : 'argument';
	    msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
	  }

	  msg += ". Received type ".concat(typeof actual);
	  return msg;
	}, TypeError);
	createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
	createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
	  return 'The ' + name + ' method is not implemented';
	});
	createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
	createErrorType('ERR_STREAM_DESTROYED', function (name) {
	  return 'Cannot call ' + name + ' after a stream was destroyed';
	});
	createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
	createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
	createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
	createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
	createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
	  return 'Unknown encoding: ' + arg;
	}, TypeError);
	createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
	errorsBrowser.codes = codes;
	return errorsBrowser;
}

var state;
var hasRequiredState;

function requireState () {
	if (hasRequiredState) return state;
	hasRequiredState = 1;

	var ERR_INVALID_OPT_VALUE = requireErrorsBrowser().codes.ERR_INVALID_OPT_VALUE;
	function highWaterMarkFrom(options, isDuplex, duplexKey) {
	  return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
	}
	function getHighWaterMark(state, options, duplexKey, isDuplex) {
	  var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
	  if (hwm != null) {
	    if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
	      var name = isDuplex ? duplexKey : 'highWaterMark';
	      throw new ERR_INVALID_OPT_VALUE(name, hwm);
	    }
	    return Math.floor(hwm);
	  }

	  // Default value
	  return state.objectMode ? 16 : 16 * 1024;
	}
	state = {
	  getHighWaterMark: getHighWaterMark
	};
	return state;
}

var buffer_list;
var hasRequiredBuffer_list;

function requireBuffer_list () {
	if (hasRequiredBuffer_list) return buffer_list;
	hasRequiredBuffer_list = 1;

	function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
	function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
	function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
	function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
	function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
	function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
	function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
	function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(input); }
	var _require = require$$0$4,
	  Buffer = _require.Buffer;
	var _require2 = require$$0$6,
	  inspect = _require2.inspect;
	var custom = inspect && inspect.custom || 'inspect';
	function copyBuffer(src, target, offset) {
	  Buffer.prototype.copy.call(src, target, offset);
	}
	buffer_list = /*#__PURE__*/function () {
	  function BufferList() {
	    _classCallCheck(this, BufferList);
	    this.head = null;
	    this.tail = null;
	    this.length = 0;
	  }
	  _createClass(BufferList, [{
	    key: "push",
	    value: function push(v) {
	      var entry = {
	        data: v,
	        next: null
	      };
	      if (this.length > 0) this.tail.next = entry;else this.head = entry;
	      this.tail = entry;
	      ++this.length;
	    }
	  }, {
	    key: "unshift",
	    value: function unshift(v) {
	      var entry = {
	        data: v,
	        next: this.head
	      };
	      if (this.length === 0) this.tail = entry;
	      this.head = entry;
	      ++this.length;
	    }
	  }, {
	    key: "shift",
	    value: function shift() {
	      if (this.length === 0) return;
	      var ret = this.head.data;
	      if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
	      --this.length;
	      return ret;
	    }
	  }, {
	    key: "clear",
	    value: function clear() {
	      this.head = this.tail = null;
	      this.length = 0;
	    }
	  }, {
	    key: "join",
	    value: function join(s) {
	      if (this.length === 0) return '';
	      var p = this.head;
	      var ret = '' + p.data;
	      while (p = p.next) ret += s + p.data;
	      return ret;
	    }
	  }, {
	    key: "concat",
	    value: function concat(n) {
	      if (this.length === 0) return Buffer.alloc(0);
	      var ret = Buffer.allocUnsafe(n >>> 0);
	      var p = this.head;
	      var i = 0;
	      while (p) {
	        copyBuffer(p.data, ret, i);
	        i += p.data.length;
	        p = p.next;
	      }
	      return ret;
	    }

	    // Consumes a specified amount of bytes or characters from the buffered data.
	  }, {
	    key: "consume",
	    value: function consume(n, hasStrings) {
	      var ret;
	      if (n < this.head.data.length) {
	        // `slice` is the same for buffers and strings.
	        ret = this.head.data.slice(0, n);
	        this.head.data = this.head.data.slice(n);
	      } else if (n === this.head.data.length) {
	        // First chunk is a perfect match.
	        ret = this.shift();
	      } else {
	        // Result spans more than one buffer.
	        ret = hasStrings ? this._getString(n) : this._getBuffer(n);
	      }
	      return ret;
	    }
	  }, {
	    key: "first",
	    value: function first() {
	      return this.head.data;
	    }

	    // Consumes a specified amount of characters from the buffered data.
	  }, {
	    key: "_getString",
	    value: function _getString(n) {
	      var p = this.head;
	      var c = 1;
	      var ret = p.data;
	      n -= ret.length;
	      while (p = p.next) {
	        var str = p.data;
	        var nb = n > str.length ? str.length : n;
	        if (nb === str.length) ret += str;else ret += str.slice(0, n);
	        n -= nb;
	        if (n === 0) {
	          if (nb === str.length) {
	            ++c;
	            if (p.next) this.head = p.next;else this.head = this.tail = null;
	          } else {
	            this.head = p;
	            p.data = str.slice(nb);
	          }
	          break;
	        }
	        ++c;
	      }
	      this.length -= c;
	      return ret;
	    }

	    // Consumes a specified amount of bytes from the buffered data.
	  }, {
	    key: "_getBuffer",
	    value: function _getBuffer(n) {
	      var ret = Buffer.allocUnsafe(n);
	      var p = this.head;
	      var c = 1;
	      p.data.copy(ret);
	      n -= p.data.length;
	      while (p = p.next) {
	        var buf = p.data;
	        var nb = n > buf.length ? buf.length : n;
	        buf.copy(ret, ret.length - n, 0, nb);
	        n -= nb;
	        if (n === 0) {
	          if (nb === buf.length) {
	            ++c;
	            if (p.next) this.head = p.next;else this.head = this.tail = null;
	          } else {
	            this.head = p;
	            p.data = buf.slice(nb);
	          }
	          break;
	        }
	        ++c;
	      }
	      this.length -= c;
	      return ret;
	    }

	    // Make sure the linked list only shows the minimal necessary information.
	  }, {
	    key: custom,
	    value: function value(_, options) {
	      return inspect(this, _objectSpread(_objectSpread({}, options), {}, {
	        // Only inspect one level.
	        depth: 0,
	        // It should not recurse.
	        customInspect: false
	      }));
	    }
	  }]);
	  return BufferList;
	}();
	return buffer_list;
}

var string_decoder = {};

var hasRequiredString_decoder;

function requireString_decoder () {
	if (hasRequiredString_decoder) return string_decoder;
	hasRequiredString_decoder = 1;

	/*<replacement>*/

	var Buffer = requireSafeBuffer().Buffer;
	/*</replacement>*/

	var isEncoding = Buffer.isEncoding || function (encoding) {
	  encoding = '' + encoding;
	  switch (encoding && encoding.toLowerCase()) {
	    case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
	      return true;
	    default:
	      return false;
	  }
	};

	function _normalizeEncoding(enc) {
	  if (!enc) return 'utf8';
	  var retried;
	  while (true) {
	    switch (enc) {
	      case 'utf8':
	      case 'utf-8':
	        return 'utf8';
	      case 'ucs2':
	      case 'ucs-2':
	      case 'utf16le':
	      case 'utf-16le':
	        return 'utf16le';
	      case 'latin1':
	      case 'binary':
	        return 'latin1';
	      case 'base64':
	      case 'ascii':
	      case 'hex':
	        return enc;
	      default:
	        if (retried) return; // undefined
	        enc = ('' + enc).toLowerCase();
	        retried = true;
	    }
	  }
	}
	// Do not cache `Buffer.isEncoding` when checking encoding names as some
	// modules monkey-patch it to support additional encodings
	function normalizeEncoding(enc) {
	  var nenc = _normalizeEncoding(enc);
	  if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
	  return nenc || enc;
	}

	// StringDecoder provides an interface for efficiently splitting a series of
	// buffers into a series of JS strings without breaking apart multi-byte
	// characters.
	string_decoder.StringDecoder = StringDecoder;
	function StringDecoder(encoding) {
	  this.encoding = normalizeEncoding(encoding);
	  var nb;
	  switch (this.encoding) {
	    case 'utf16le':
	      this.text = utf16Text;
	      this.end = utf16End;
	      nb = 4;
	      break;
	    case 'utf8':
	      this.fillLast = utf8FillLast;
	      nb = 4;
	      break;
	    case 'base64':
	      this.text = base64Text;
	      this.end = base64End;
	      nb = 3;
	      break;
	    default:
	      this.write = simpleWrite;
	      this.end = simpleEnd;
	      return;
	  }
	  this.lastNeed = 0;
	  this.lastTotal = 0;
	  this.lastChar = Buffer.allocUnsafe(nb);
	}

	StringDecoder.prototype.write = function (buf) {
	  if (buf.length === 0) return '';
	  var r;
	  var i;
	  if (this.lastNeed) {
	    r = this.fillLast(buf);
	    if (r === undefined) return '';
	    i = this.lastNeed;
	    this.lastNeed = 0;
	  } else {
	    i = 0;
	  }
	  if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
	  return r || '';
	};

	StringDecoder.prototype.end = utf8End;

	// Returns only complete characters in a Buffer
	StringDecoder.prototype.text = utf8Text;

	// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
	StringDecoder.prototype.fillLast = function (buf) {
	  if (this.lastNeed <= buf.length) {
	    buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
	    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
	  }
	  buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
	  this.lastNeed -= buf.length;
	};

	// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
	// continuation byte. If an invalid byte is detected, -2 is returned.
	function utf8CheckByte(byte) {
	  if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
	  return byte >> 6 === 0x02 ? -1 : -2;
	}

	// Checks at most 3 bytes at the end of a Buffer in order to detect an
	// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
	// needed to complete the UTF-8 character (if applicable) are returned.
	function utf8CheckIncomplete(self, buf, i) {
	  var j = buf.length - 1;
	  if (j < i) return 0;
	  var nb = utf8CheckByte(buf[j]);
	  if (nb >= 0) {
	    if (nb > 0) self.lastNeed = nb - 1;
	    return nb;
	  }
	  if (--j < i || nb === -2) return 0;
	  nb = utf8CheckByte(buf[j]);
	  if (nb >= 0) {
	    if (nb > 0) self.lastNeed = nb - 2;
	    return nb;
	  }
	  if (--j < i || nb === -2) return 0;
	  nb = utf8CheckByte(buf[j]);
	  if (nb >= 0) {
	    if (nb > 0) {
	      if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
	    }
	    return nb;
	  }
	  return 0;
	}

	// Validates as many continuation bytes for a multi-byte UTF-8 character as
	// needed or are available. If we see a non-continuation byte where we expect
	// one, we "replace" the validated continuation bytes we've seen so far with
	// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
	// behavior. The continuation byte check is included three times in the case
	// where all of the continuation bytes for a character exist in the same buffer.
	// It is also done this way as a slight performance increase instead of using a
	// loop.
	function utf8CheckExtraBytes(self, buf, p) {
	  if ((buf[0] & 0xC0) !== 0x80) {
	    self.lastNeed = 0;
	    return '\ufffd';
	  }
	  if (self.lastNeed > 1 && buf.length > 1) {
	    if ((buf[1] & 0xC0) !== 0x80) {
	      self.lastNeed = 1;
	      return '\ufffd';
	    }
	    if (self.lastNeed > 2 && buf.length > 2) {
	      if ((buf[2] & 0xC0) !== 0x80) {
	        self.lastNeed = 2;
	        return '\ufffd';
	      }
	    }
	  }
	}

	// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
	function utf8FillLast(buf) {
	  var p = this.lastTotal - this.lastNeed;
	  var r = utf8CheckExtraBytes(this, buf);
	  if (r !== undefined) return r;
	  if (this.lastNeed <= buf.length) {
	    buf.copy(this.lastChar, p, 0, this.lastNeed);
	    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
	  }
	  buf.copy(this.lastChar, p, 0, buf.length);
	  this.lastNeed -= buf.length;
	}

	// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
	// partial character, the character's bytes are buffered until the required
	// number of bytes are available.
	function utf8Text(buf, i) {
	  var total = utf8CheckIncomplete(this, buf, i);
	  if (!this.lastNeed) return buf.toString('utf8', i);
	  this.lastTotal = total;
	  var end = buf.length - (total - this.lastNeed);
	  buf.copy(this.lastChar, 0, end);
	  return buf.toString('utf8', i, end);
	}

	// For UTF-8, a replacement character is added when ending on a partial
	// character.
	function utf8End(buf) {
	  var r = buf && buf.length ? this.write(buf) : '';
	  if (this.lastNeed) return r + '\ufffd';
	  return r;
	}

	// UTF-16LE typically needs two bytes per character, but even if we have an even
	// number of bytes available, we need to check if we end on a leading/high
	// surrogate. In that case, we need to wait for the next two bytes in order to
	// decode the last character properly.
	function utf16Text(buf, i) {
	  if ((buf.length - i) % 2 === 0) {
	    var r = buf.toString('utf16le', i);
	    if (r) {
	      var c = r.charCodeAt(r.length - 1);
	      if (c >= 0xD800 && c <= 0xDBFF) {
	        this.lastNeed = 2;
	        this.lastTotal = 4;
	        this.lastChar[0] = buf[buf.length - 2];
	        this.lastChar[1] = buf[buf.length - 1];
	        return r.slice(0, -1);
	      }
	    }
	    return r;
	  }
	  this.lastNeed = 1;
	  this.lastTotal = 2;
	  this.lastChar[0] = buf[buf.length - 1];
	  return buf.toString('utf16le', i, buf.length - 1);
	}

	// For UTF-16LE we do not explicitly append special replacement characters if we
	// end on a partial character, we simply let v8 handle that.
	function utf16End(buf) {
	  var r = buf && buf.length ? this.write(buf) : '';
	  if (this.lastNeed) {
	    var end = this.lastTotal - this.lastNeed;
	    return r + this.lastChar.toString('utf16le', 0, end);
	  }
	  return r;
	}

	function base64Text(buf, i) {
	  var n = (buf.length - i) % 3;
	  if (n === 0) return buf.toString('base64', i);
	  this.lastNeed = 3 - n;
	  this.lastTotal = 3;
	  if (n === 1) {
	    this.lastChar[0] = buf[buf.length - 1];
	  } else {
	    this.lastChar[0] = buf[buf.length - 2];
	    this.lastChar[1] = buf[buf.length - 1];
	  }
	  return buf.toString('base64', i, buf.length - n);
	}

	function base64End(buf) {
	  var r = buf && buf.length ? this.write(buf) : '';
	  if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
	  return r;
	}

	// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
	function simpleWrite(buf) {
	  return buf.toString(this.encoding);
	}

	function simpleEnd(buf) {
	  return buf && buf.length ? this.write(buf) : '';
	}
	return string_decoder;
}

var endOfStream;
var hasRequiredEndOfStream;

function requireEndOfStream () {
	if (hasRequiredEndOfStream) return endOfStream;
	hasRequiredEndOfStream = 1;

	var ERR_STREAM_PREMATURE_CLOSE = requireErrorsBrowser().codes.ERR_STREAM_PREMATURE_CLOSE;
	function once(callback) {
	  var called = false;
	  return function () {
	    if (called) return;
	    called = true;
	    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
	      args[_key] = arguments[_key];
	    }
	    callback.apply(this, args);
	  };
	}
	function noop() {}
	function isRequest(stream) {
	  return stream.setHeader && typeof stream.abort === 'function';
	}
	function eos(stream, opts, callback) {
	  if (typeof opts === 'function') return eos(stream, null, opts);
	  if (!opts) opts = {};
	  callback = once(callback || noop);
	  var readable = opts.readable || opts.readable !== false && stream.readable;
	  var writable = opts.writable || opts.writable !== false && stream.writable;
	  var onlegacyfinish = function onlegacyfinish() {
	    if (!stream.writable) onfinish();
	  };
	  var writableEnded = stream._writableState && stream._writableState.finished;
	  var onfinish = function onfinish() {
	    writable = false;
	    writableEnded = true;
	    if (!readable) callback.call(stream);
	  };
	  var readableEnded = stream._readableState && stream._readableState.endEmitted;
	  var onend = function onend() {
	    readable = false;
	    readableEnded = true;
	    if (!writable) callback.call(stream);
	  };
	  var onerror = function onerror(err) {
	    callback.call(stream, err);
	  };
	  var onclose = function onclose() {
	    var err;
	    if (readable && !readableEnded) {
	      if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
	      return callback.call(stream, err);
	    }
	    if (writable && !writableEnded) {
	      if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
	      return callback.call(stream, err);
	    }
	  };
	  var onrequest = function onrequest() {
	    stream.req.on('finish', onfinish);
	  };
	  if (isRequest(stream)) {
	    stream.on('complete', onfinish);
	    stream.on('abort', onclose);
	    if (stream.req) onrequest();else stream.on('request', onrequest);
	  } else if (writable && !stream._writableState) {
	    // legacy streams
	    stream.on('end', onlegacyfinish);
	    stream.on('close', onlegacyfinish);
	  }
	  stream.on('end', onend);
	  stream.on('finish', onfinish);
	  if (opts.error !== false) stream.on('error', onerror);
	  stream.on('close', onclose);
	  return function () {
	    stream.removeListener('complete', onfinish);
	    stream.removeListener('abort', onclose);
	    stream.removeListener('request', onrequest);
	    if (stream.req) stream.req.removeListener('finish', onfinish);
	    stream.removeListener('end', onlegacyfinish);
	    stream.removeListener('close', onlegacyfinish);
	    stream.removeListener('finish', onfinish);
	    stream.removeListener('end', onend);
	    stream.removeListener('error', onerror);
	    stream.removeListener('close', onclose);
	  };
	}
	endOfStream = eos;
	return endOfStream;
}

var async_iterator;
var hasRequiredAsync_iterator;

function requireAsync_iterator () {
	if (hasRequiredAsync_iterator) return async_iterator;
	hasRequiredAsync_iterator = 1;

	var _Object$setPrototypeO;
	function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
	function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
	function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
	var finished = requireEndOfStream();
	var kLastResolve = Symbol('lastResolve');
	var kLastReject = Symbol('lastReject');
	var kError = Symbol('error');
	var kEnded = Symbol('ended');
	var kLastPromise = Symbol('lastPromise');
	var kHandlePromise = Symbol('handlePromise');
	var kStream = Symbol('stream');
	function createIterResult(value, done) {
	  return {
	    value: value,
	    done: done
	  };
	}
	function readAndResolve(iter) {
	  var resolve = iter[kLastResolve];
	  if (resolve !== null) {
	    var data = iter[kStream].read();
	    // we defer if data is null
	    // we can be expecting either 'end' or
	    // 'error'
	    if (data !== null) {
	      iter[kLastPromise] = null;
	      iter[kLastResolve] = null;
	      iter[kLastReject] = null;
	      resolve(createIterResult(data, false));
	    }
	  }
	}
	function onReadable(iter) {
	  // we wait for the next tick, because it might
	  // emit an error with process.nextTick
	  process.nextTick(readAndResolve, iter);
	}
	function wrapForNext(lastPromise, iter) {
	  return function (resolve, reject) {
	    lastPromise.then(function () {
	      if (iter[kEnded]) {
	        resolve(createIterResult(undefined, true));
	        return;
	      }
	      iter[kHandlePromise](resolve, reject);
	    }, reject);
	  };
	}
	var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
	var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
	  get stream() {
	    return this[kStream];
	  },
	  next: function next() {
	    var _this = this;
	    // if we have detected an error in the meanwhile
	    // reject straight away
	    var error = this[kError];
	    if (error !== null) {
	      return Promise.reject(error);
	    }
	    if (this[kEnded]) {
	      return Promise.resolve(createIterResult(undefined, true));
	    }
	    if (this[kStream].destroyed) {
	      // We need to defer via nextTick because if .destroy(err) is
	      // called, the error will be emitted via nextTick, and
	      // we cannot guarantee that there is no error lingering around
	      // waiting to be emitted.
	      return new Promise(function (resolve, reject) {
	        process.nextTick(function () {
	          if (_this[kError]) {
	            reject(_this[kError]);
	          } else {
	            resolve(createIterResult(undefined, true));
	          }
	        });
	      });
	    }

	    // if we have multiple next() calls
	    // we will wait for the previous Promise to finish
	    // this logic is optimized to support for await loops,
	    // where next() is only called once at a time
	    var lastPromise = this[kLastPromise];
	    var promise;
	    if (lastPromise) {
	      promise = new Promise(wrapForNext(lastPromise, this));
	    } else {
	      // fast path needed to support multiple this.push()
	      // without triggering the next() queue
	      var data = this[kStream].read();
	      if (data !== null) {
	        return Promise.resolve(createIterResult(data, false));
	      }
	      promise = new Promise(this[kHandlePromise]);
	    }
	    this[kLastPromise] = promise;
	    return promise;
	  }
	}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
	  return this;
	}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
	  var _this2 = this;
	  // destroy(err, cb) is a private API
	  // we can guarantee we have that here, because we control the
	  // Readable class this is attached to
	  return new Promise(function (resolve, reject) {
	    _this2[kStream].destroy(null, function (err) {
	      if (err) {
	        reject(err);
	        return;
	      }
	      resolve(createIterResult(undefined, true));
	    });
	  });
	}), _Object$setPrototypeO), AsyncIteratorPrototype);
	var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
	  var _Object$create;
	  var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
	    value: stream,
	    writable: true
	  }), _defineProperty(_Object$create, kLastResolve, {
	    value: null,
	    writable: true
	  }), _defineProperty(_Object$create, kLastReject, {
	    value: null,
	    writable: true
	  }), _defineProperty(_Object$create, kError, {
	    value: null,
	    writable: true
	  }), _defineProperty(_Object$create, kEnded, {
	    value: stream._readableState.endEmitted,
	    writable: true
	  }), _defineProperty(_Object$create, kHandlePromise, {
	    value: function value(resolve, reject) {
	      var data = iterator[kStream].read();
	      if (data) {
	        iterator[kLastPromise] = null;
	        iterator[kLastResolve] = null;
	        iterator[kLastReject] = null;
	        resolve(createIterResult(data, false));
	      } else {
	        iterator[kLastResolve] = resolve;
	        iterator[kLastReject] = reject;
	      }
	    },
	    writable: true
	  }), _Object$create));
	  iterator[kLastPromise] = null;
	  finished(stream, function (err) {
	    if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
	      var reject = iterator[kLastReject];
	      // reject if we are waiting for data in the Promise
	      // returned by next() and store the error
	      if (reject !== null) {
	        iterator[kLastPromise] = null;
	        iterator[kLastResolve] = null;
	        iterator[kLastReject] = null;
	        reject(err);
	      }
	      iterator[kError] = err;
	      return;
	    }
	    var resolve = iterator[kLastResolve];
	    if (resolve !== null) {
	      iterator[kLastPromise] = null;
	      iterator[kLastResolve] = null;
	      iterator[kLastReject] = null;
	      resolve(createIterResult(undefined, true));
	    }
	    iterator[kEnded] = true;
	  });
	  stream.on('readable', onReadable.bind(null, iterator));
	  return iterator;
	};
	async_iterator = createReadableStreamAsyncIterator;
	return async_iterator;
}

var fromBrowser;
var hasRequiredFromBrowser;

function requireFromBrowser () {
	if (hasRequiredFromBrowser) return fromBrowser;
	hasRequiredFromBrowser = 1;
	fromBrowser = function () {
	  throw new Error('Readable.from is not available in the browser')
	};
	return fromBrowser;
}

var _stream_readable;
var hasRequired_stream_readable;

function require_stream_readable () {
	if (hasRequired_stream_readable) return _stream_readable;
	hasRequired_stream_readable = 1;

	_stream_readable = Readable;

	/*<replacement>*/
	var Duplex;
	/*</replacement>*/

	Readable.ReadableState = ReadableState;

	/*<replacement>*/
	require$$0$5.EventEmitter;
	var EElistenerCount = function EElistenerCount(emitter, type) {
	  return emitter.listeners(type).length;
	};
	/*</replacement>*/

	/*<replacement>*/
	var Stream = requireStreamBrowser();
	/*</replacement>*/

	var Buffer = require$$0$4.Buffer;
	var OurUint8Array = (typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
	function _uint8ArrayToBuffer(chunk) {
	  return Buffer.from(chunk);
	}
	function _isUint8Array(obj) {
	  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
	}

	/*<replacement>*/
	var debugUtil = require$$0$6;
	var debug;
	if (debugUtil && debugUtil.debuglog) {
	  debug = debugUtil.debuglog('stream');
	} else {
	  debug = function debug() {};
	}
	/*</replacement>*/

	var BufferList = requireBuffer_list();
	var destroyImpl = requireDestroy();
	var _require = requireState(),
	  getHighWaterMark = _require.getHighWaterMark;
	var _require$codes = requireErrorsBrowser().codes,
	  ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
	  ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
	  ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
	  ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;

	// Lazy loaded to improve the startup performance.
	var StringDecoder;
	var createReadableStreamAsyncIterator;
	var from;
	requireInherits_browser()(Readable, Stream);
	var errorOrDestroy = destroyImpl.errorOrDestroy;
	var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
	function prependListener(emitter, event, fn) {
	  // Sadly this is not cacheable as some libraries bundle their own
	  // event emitter implementation with them.
	  if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);

	  // This is a hack to make sure that our error handler is attached before any
	  // userland ones.  NEVER DO THIS. This is here only because this code needs
	  // to continue to work with older versions of Node.js that do not include
	  // the prependListener() method. The goal is to eventually remove this hack.
	  if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
	}
	function ReadableState(options, stream, isDuplex) {
	  Duplex = Duplex || require_stream_duplex();
	  options = options || {};

	  // Duplex streams are both readable and writable, but share
	  // the same options object.
	  // However, some cases require setting options to different
	  // values for the readable and the writable sides of the duplex stream.
	  // These options can be provided separately as readableXXX and writableXXX.
	  if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;

	  // object stream flag. Used to make read(n) ignore n and to
	  // make all the buffer merging and length checks go away
	  this.objectMode = !!options.objectMode;
	  if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;

	  // the point at which it stops calling _read() to fill the buffer
	  // Note: 0 is a valid value, means "don't call _read preemptively ever"
	  this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex);

	  // A linked list is used to store data chunks instead of an array because the
	  // linked list can remove elements from the beginning faster than
	  // array.shift()
	  this.buffer = new BufferList();
	  this.length = 0;
	  this.pipes = null;
	  this.pipesCount = 0;
	  this.flowing = null;
	  this.ended = false;
	  this.endEmitted = false;
	  this.reading = false;

	  // a flag to be able to tell if the event 'readable'/'data' is emitted
	  // immediately, or on a later tick.  We set this to true at first, because
	  // any actions that shouldn't happen until "later" should generally also
	  // not happen before the first read call.
	  this.sync = true;

	  // whenever we return null, then we set a flag to say
	  // that we're awaiting a 'readable' event emission.
	  this.needReadable = false;
	  this.emittedReadable = false;
	  this.readableListening = false;
	  this.resumeScheduled = false;
	  this.paused = true;

	  // Should close be emitted on destroy. Defaults to true.
	  this.emitClose = options.emitClose !== false;

	  // Should .destroy() be called after 'end' (and potentially 'finish')
	  this.autoDestroy = !!options.autoDestroy;

	  // has it been destroyed
	  this.destroyed = false;

	  // Crypto is kind of old and crusty.  Historically, its default string
	  // encoding is 'binary' so we have to make this configurable.
	  // Everything else in the universe uses 'utf8', though.
	  this.defaultEncoding = options.defaultEncoding || 'utf8';

	  // the number of writers that are awaiting a drain event in .pipe()s
	  this.awaitDrain = 0;

	  // if true, a maybeReadMore has been scheduled
	  this.readingMore = false;
	  this.decoder = null;
	  this.encoding = null;
	  if (options.encoding) {
	    if (!StringDecoder) StringDecoder = requireString_decoder().StringDecoder;
	    this.decoder = new StringDecoder(options.encoding);
	    this.encoding = options.encoding;
	  }
	}
	function Readable(options) {
	  Duplex = Duplex || require_stream_duplex();
	  if (!(this instanceof Readable)) return new Readable(options);

	  // Checking for a Stream.Duplex instance is faster here instead of inside
	  // the ReadableState constructor, at least with V8 6.5
	  var isDuplex = this instanceof Duplex;
	  this._readableState = new ReadableState(options, this, isDuplex);

	  // legacy
	  this.readable = true;
	  if (options) {
	    if (typeof options.read === 'function') this._read = options.read;
	    if (typeof options.destroy === 'function') this._destroy = options.destroy;
	  }
	  Stream.call(this);
	}
	Object.defineProperty(Readable.prototype, 'destroyed', {
	  // making it explicit this property is not enumerable
	  // because otherwise some prototype manipulation in
	  // userland will fail
	  enumerable: false,
	  get: function get() {
	    if (this._readableState === undefined) {
	      return false;
	    }
	    return this._readableState.destroyed;
	  },
	  set: function set(value) {
	    // we ignore the value if the stream
	    // has not been initialized yet
	    if (!this._readableState) {
	      return;
	    }

	    // backward compatibility, the user is explicitly
	    // managing destroyed
	    this._readableState.destroyed = value;
	  }
	});
	Readable.prototype.destroy = destroyImpl.destroy;
	Readable.prototype._undestroy = destroyImpl.undestroy;
	Readable.prototype._destroy = function (err, cb) {
	  cb(err);
	};

	// Manually shove something into the read() buffer.
	// This returns true if the highWaterMark has not been hit yet,
	// similar to how Writable.write() returns true if you should
	// write() some more.
	Readable.prototype.push = function (chunk, encoding) {
	  var state = this._readableState;
	  var skipChunkCheck;
	  if (!state.objectMode) {
	    if (typeof chunk === 'string') {
	      encoding = encoding || state.defaultEncoding;
	      if (encoding !== state.encoding) {
	        chunk = Buffer.from(chunk, encoding);
	        encoding = '';
	      }
	      skipChunkCheck = true;
	    }
	  } else {
	    skipChunkCheck = true;
	  }
	  return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
	};

	// Unshift should *always* be something directly out of read()
	Readable.prototype.unshift = function (chunk) {
	  return readableAddChunk(this, chunk, null, true, false);
	};
	function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
	  debug('readableAddChunk', chunk);
	  var state = stream._readableState;
	  if (chunk === null) {
	    state.reading = false;
	    onEofChunk(stream, state);
	  } else {
	    var er;
	    if (!skipChunkCheck) er = chunkInvalid(state, chunk);
	    if (er) {
	      errorOrDestroy(stream, er);
	    } else if (state.objectMode || chunk && chunk.length > 0) {
	      if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
	        chunk = _uint8ArrayToBuffer(chunk);
	      }
	      if (addToFront) {
	        if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
	      } else if (state.ended) {
	        errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
	      } else if (state.destroyed) {
	        return false;
	      } else {
	        state.reading = false;
	        if (state.decoder && !encoding) {
	          chunk = state.decoder.write(chunk);
	          if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
	        } else {
	          addChunk(stream, state, chunk, false);
	        }
	      }
	    } else if (!addToFront) {
	      state.reading = false;
	      maybeReadMore(stream, state);
	    }
	  }

	  // We can push more data if we are below the highWaterMark.
	  // Also, if we have no data yet, we can stand some more bytes.
	  // This is to work around cases where hwm=0, such as the repl.
	  return !state.ended && (state.length < state.highWaterMark || state.length === 0);
	}
	function addChunk(stream, state, chunk, addToFront) {
	  if (state.flowing && state.length === 0 && !state.sync) {
	    state.awaitDrain = 0;
	    stream.emit('data', chunk);
	  } else {
	    // update the buffer info.
	    state.length += state.objectMode ? 1 : chunk.length;
	    if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
	    if (state.needReadable) emitReadable(stream);
	  }
	  maybeReadMore(stream, state);
	}
	function chunkInvalid(state, chunk) {
	  var er;
	  if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
	    er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
	  }
	  return er;
	}
	Readable.prototype.isPaused = function () {
	  return this._readableState.flowing === false;
	};

	// backwards compatibility.
	Readable.prototype.setEncoding = function (enc) {
	  if (!StringDecoder) StringDecoder = requireString_decoder().StringDecoder;
	  var decoder = new StringDecoder(enc);
	  this._readableState.decoder = decoder;
	  // If setEncoding(null), decoder.encoding equals utf8
	  this._readableState.encoding = this._readableState.decoder.encoding;

	  // Iterate over current buffer to convert already stored Buffers:
	  var p = this._readableState.buffer.head;
	  var content = '';
	  while (p !== null) {
	    content += decoder.write(p.data);
	    p = p.next;
	  }
	  this._readableState.buffer.clear();
	  if (content !== '') this._readableState.buffer.push(content);
	  this._readableState.length = content.length;
	  return this;
	};

	// Don't raise the hwm > 1GB
	var MAX_HWM = 0x40000000;
	function computeNewHighWaterMark(n) {
	  if (n >= MAX_HWM) {
	    // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
	    n = MAX_HWM;
	  } else {
	    // Get the next highest power of 2 to prevent increasing hwm excessively in
	    // tiny amounts
	    n--;
	    n |= n >>> 1;
	    n |= n >>> 2;
	    n |= n >>> 4;
	    n |= n >>> 8;
	    n |= n >>> 16;
	    n++;
	  }
	  return n;
	}

	// This function is designed to be inlinable, so please take care when making
	// changes to the function body.
	function howMuchToRead(n, state) {
	  if (n <= 0 || state.length === 0 && state.ended) return 0;
	  if (state.objectMode) return 1;
	  if (n !== n) {
	    // Only flow one buffer at a time
	    if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
	  }
	  // If we're asking for more than the current hwm, then raise the hwm.
	  if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
	  if (n <= state.length) return n;
	  // Don't have enough
	  if (!state.ended) {
	    state.needReadable = true;
	    return 0;
	  }
	  return state.length;
	}

	// you can override either this method, or the async _read(n) below.
	Readable.prototype.read = function (n) {
	  debug('read', n);
	  n = parseInt(n, 10);
	  var state = this._readableState;
	  var nOrig = n;
	  if (n !== 0) state.emittedReadable = false;

	  // if we're doing read(0) to trigger a readable event, but we
	  // already have a bunch of data in the buffer, then just trigger
	  // the 'readable' event and move on.
	  if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
	    debug('read: emitReadable', state.length, state.ended);
	    if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
	    return null;
	  }
	  n = howMuchToRead(n, state);

	  // if we've ended, and we're now clear, then finish it up.
	  if (n === 0 && state.ended) {
	    if (state.length === 0) endReadable(this);
	    return null;
	  }

	  // All the actual chunk generation logic needs to be
	  // *below* the call to _read.  The reason is that in certain
	  // synthetic stream cases, such as passthrough streams, _read
	  // may be a completely synchronous operation which may change
	  // the state of the read buffer, providing enough data when
	  // before there was *not* enough.
	  //
	  // So, the steps are:
	  // 1. Figure out what the state of things will be after we do
	  // a read from the buffer.
	  //
	  // 2. If that resulting state will trigger a _read, then call _read.
	  // Note that this may be asynchronous, or synchronous.  Yes, it is
	  // deeply ugly to write APIs this way, but that still doesn't mean
	  // that the Readable class should behave improperly, as streams are
	  // designed to be sync/async agnostic.
	  // Take note if the _read call is sync or async (ie, if the read call
	  // has returned yet), so that we know whether or not it's safe to emit
	  // 'readable' etc.
	  //
	  // 3. Actually pull the requested chunks out of the buffer and return.

	  // if we need a readable event, then we need to do some reading.
	  var doRead = state.needReadable;
	  debug('need readable', doRead);

	  // if we currently have less than the highWaterMark, then also read some
	  if (state.length === 0 || state.length - n < state.highWaterMark) {
	    doRead = true;
	    debug('length less than watermark', doRead);
	  }

	  // however, if we've ended, then there's no point, and if we're already
	  // reading, then it's unnecessary.
	  if (state.ended || state.reading) {
	    doRead = false;
	    debug('reading or ended', doRead);
	  } else if (doRead) {
	    debug('do read');
	    state.reading = true;
	    state.sync = true;
	    // if the length is currently zero, then we *need* a readable event.
	    if (state.length === 0) state.needReadable = true;
	    // call internal read method
	    this._read(state.highWaterMark);
	    state.sync = false;
	    // If _read pushed data synchronously, then `reading` will be false,
	    // and we need to re-evaluate how much data we can return to the user.
	    if (!state.reading) n = howMuchToRead(nOrig, state);
	  }
	  var ret;
	  if (n > 0) ret = fromList(n, state);else ret = null;
	  if (ret === null) {
	    state.needReadable = state.length <= state.highWaterMark;
	    n = 0;
	  } else {
	    state.length -= n;
	    state.awaitDrain = 0;
	  }
	  if (state.length === 0) {
	    // If we have nothing in the buffer, then we want to know
	    // as soon as we *do* get something into the buffer.
	    if (!state.ended) state.needReadable = true;

	    // If we tried to read() past the EOF, then emit end on the next tick.
	    if (nOrig !== n && state.ended) endReadable(this);
	  }
	  if (ret !== null) this.emit('data', ret);
	  return ret;
	};
	function onEofChunk(stream, state) {
	  debug('onEofChunk');
	  if (state.ended) return;
	  if (state.decoder) {
	    var chunk = state.decoder.end();
	    if (chunk && chunk.length) {
	      state.buffer.push(chunk);
	      state.length += state.objectMode ? 1 : chunk.length;
	    }
	  }
	  state.ended = true;
	  if (state.sync) {
	    // if we are sync, wait until next tick to emit the data.
	    // Otherwise we risk emitting data in the flow()
	    // the readable code triggers during a read() call
	    emitReadable(stream);
	  } else {
	    // emit 'readable' now to make sure it gets picked up.
	    state.needReadable = false;
	    if (!state.emittedReadable) {
	      state.emittedReadable = true;
	      emitReadable_(stream);
	    }
	  }
	}

	// Don't emit readable right away in sync mode, because this can trigger
	// another read() call => stack overflow.  This way, it might trigger
	// a nextTick recursion warning, but that's not so bad.
	function emitReadable(stream) {
	  var state = stream._readableState;
	  debug('emitReadable', state.needReadable, state.emittedReadable);
	  state.needReadable = false;
	  if (!state.emittedReadable) {
	    debug('emitReadable', state.flowing);
	    state.emittedReadable = true;
	    process.nextTick(emitReadable_, stream);
	  }
	}
	function emitReadable_(stream) {
	  var state = stream._readableState;
	  debug('emitReadable_', state.destroyed, state.length, state.ended);
	  if (!state.destroyed && (state.length || state.ended)) {
	    stream.emit('readable');
	    state.emittedReadable = false;
	  }

	  // The stream needs another readable event if
	  // 1. It is not flowing, as the flow mechanism will take
	  //    care of it.
	  // 2. It is not ended.
	  // 3. It is below the highWaterMark, so we can schedule
	  //    another readable later.
	  state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
	  flow(stream);
	}

	// at this point, the user has presumably seen the 'readable' event,
	// and called read() to consume some data.  that may have triggered
	// in turn another _read(n) call, in which case reading = true if
	// it's in progress.
	// However, if we're not ended, or reading, and the length < hwm,
	// then go ahead and try to read some more preemptively.
	function maybeReadMore(stream, state) {
	  if (!state.readingMore) {
	    state.readingMore = true;
	    process.nextTick(maybeReadMore_, stream, state);
	  }
	}
	function maybeReadMore_(stream, state) {
	  // Attempt to read more data if we should.
	  //
	  // The conditions for reading more data are (one of):
	  // - Not enough data buffered (state.length < state.highWaterMark). The loop
	  //   is responsible for filling the buffer with enough data if such data
	  //   is available. If highWaterMark is 0 and we are not in the flowing mode
	  //   we should _not_ attempt to buffer any extra data. We'll get more data
	  //   when the stream consumer calls read() instead.
	  // - No data in the buffer, and the stream is in flowing mode. In this mode
	  //   the loop below is responsible for ensuring read() is called. Failing to
	  //   call read here would abort the flow and there's no other mechanism for
	  //   continuing the flow if the stream consumer has just subscribed to the
	  //   'data' event.
	  //
	  // In addition to the above conditions to keep reading data, the following
	  // conditions prevent the data from being read:
	  // - The stream has ended (state.ended).
	  // - There is already a pending 'read' operation (state.reading). This is a
	  //   case where the the stream has called the implementation defined _read()
	  //   method, but they are processing the call asynchronously and have _not_
	  //   called push() with new data. In this case we skip performing more
	  //   read()s. The execution ends in this method again after the _read() ends
	  //   up calling push() with more data.
	  while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
	    var len = state.length;
	    debug('maybeReadMore read 0');
	    stream.read(0);
	    if (len === state.length)
	      // didn't get any data, stop spinning.
	      break;
	  }
	  state.readingMore = false;
	}

	// abstract method.  to be overridden in specific implementation classes.
	// call cb(er, data) where data is <= n in length.
	// for virtual (non-string, non-buffer) streams, "length" is somewhat
	// arbitrary, and perhaps not very meaningful.
	Readable.prototype._read = function (n) {
	  errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
	};
	Readable.prototype.pipe = function (dest, pipeOpts) {
	  var src = this;
	  var state = this._readableState;
	  switch (state.pipesCount) {
	    case 0:
	      state.pipes = dest;
	      break;
	    case 1:
	      state.pipes = [state.pipes, dest];
	      break;
	    default:
	      state.pipes.push(dest);
	      break;
	  }
	  state.pipesCount += 1;
	  debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
	  var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
	  var endFn = doEnd ? onend : unpipe;
	  if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
	  dest.on('unpipe', onunpipe);
	  function onunpipe(readable, unpipeInfo) {
	    debug('onunpipe');
	    if (readable === src) {
	      if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
	        unpipeInfo.hasUnpiped = true;
	        cleanup();
	      }
	    }
	  }
	  function onend() {
	    debug('onend');
	    dest.end();
	  }

	  // when the dest drains, it reduces the awaitDrain counter
	  // on the source.  This would be more elegant with a .once()
	  // handler in flow(), but adding and removing repeatedly is
	  // too slow.
	  var ondrain = pipeOnDrain(src);
	  dest.on('drain', ondrain);
	  var cleanedUp = false;
	  function cleanup() {
	    debug('cleanup');
	    // cleanup event handlers once the pipe is broken
	    dest.removeListener('close', onclose);
	    dest.removeListener('finish', onfinish);
	    dest.removeListener('drain', ondrain);
	    dest.removeListener('error', onerror);
	    dest.removeListener('unpipe', onunpipe);
	    src.removeListener('end', onend);
	    src.removeListener('end', unpipe);
	    src.removeListener('data', ondata);
	    cleanedUp = true;

	    // if the reader is waiting for a drain event from this
	    // specific writer, then it would cause it to never start
	    // flowing again.
	    // So, if this is awaiting a drain, then we just call it now.
	    // If we don't know, then assume that we are waiting for one.
	    if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
	  }
	  src.on('data', ondata);
	  function ondata(chunk) {
	    debug('ondata');
	    var ret = dest.write(chunk);
	    debug('dest.write', ret);
	    if (ret === false) {
	      // If the user unpiped during `dest.write()`, it is possible
	      // to get stuck in a permanently paused state if that write
	      // also returned false.
	      // => Check whether `dest` is still a piping destination.
	      if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
	        debug('false write response, pause', state.awaitDrain);
	        state.awaitDrain++;
	      }
	      src.pause();
	    }
	  }

	  // if the dest has an error, then stop piping into it.
	  // however, don't suppress the throwing behavior for this.
	  function onerror(er) {
	    debug('onerror', er);
	    unpipe();
	    dest.removeListener('error', onerror);
	    if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
	  }

	  // Make sure our error handler is attached before userland ones.
	  prependListener(dest, 'error', onerror);

	  // Both close and finish should trigger unpipe, but only once.
	  function onclose() {
	    dest.removeListener('finish', onfinish);
	    unpipe();
	  }
	  dest.once('close', onclose);
	  function onfinish() {
	    debug('onfinish');
	    dest.removeListener('close', onclose);
	    unpipe();
	  }
	  dest.once('finish', onfinish);
	  function unpipe() {
	    debug('unpipe');
	    src.unpipe(dest);
	  }

	  // tell the dest that it's being piped to
	  dest.emit('pipe', src);

	  // start the flow if it hasn't been started already.
	  if (!state.flowing) {
	    debug('pipe resume');
	    src.resume();
	  }
	  return dest;
	};
	function pipeOnDrain(src) {
	  return function pipeOnDrainFunctionResult() {
	    var state = src._readableState;
	    debug('pipeOnDrain', state.awaitDrain);
	    if (state.awaitDrain) state.awaitDrain--;
	    if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
	      state.flowing = true;
	      flow(src);
	    }
	  };
	}
	Readable.prototype.unpipe = function (dest) {
	  var state = this._readableState;
	  var unpipeInfo = {
	    hasUnpiped: false
	  };

	  // if we're not piping anywhere, then do nothing.
	  if (state.pipesCount === 0) return this;

	  // just one destination.  most common case.
	  if (state.pipesCount === 1) {
	    // passed in one, but it's not the right one.
	    if (dest && dest !== state.pipes) return this;
	    if (!dest) dest = state.pipes;

	    // got a match.
	    state.pipes = null;
	    state.pipesCount = 0;
	    state.flowing = false;
	    if (dest) dest.emit('unpipe', this, unpipeInfo);
	    return this;
	  }

	  // slow case. multiple pipe destinations.

	  if (!dest) {
	    // remove all.
	    var dests = state.pipes;
	    var len = state.pipesCount;
	    state.pipes = null;
	    state.pipesCount = 0;
	    state.flowing = false;
	    for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, {
	      hasUnpiped: false
	    });
	    return this;
	  }

	  // try to find the right one.
	  var index = indexOf(state.pipes, dest);
	  if (index === -1) return this;
	  state.pipes.splice(index, 1);
	  state.pipesCount -= 1;
	  if (state.pipesCount === 1) state.pipes = state.pipes[0];
	  dest.emit('unpipe', this, unpipeInfo);
	  return this;
	};

	// set up data events if they are asked for
	// Ensure readable listeners eventually get something
	Readable.prototype.on = function (ev, fn) {
	  var res = Stream.prototype.on.call(this, ev, fn);
	  var state = this._readableState;
	  if (ev === 'data') {
	    // update readableListening so that resume() may be a no-op
	    // a few lines down. This is needed to support once('readable').
	    state.readableListening = this.listenerCount('readable') > 0;

	    // Try start flowing on next tick if stream isn't explicitly paused
	    if (state.flowing !== false) this.resume();
	  } else if (ev === 'readable') {
	    if (!state.endEmitted && !state.readableListening) {
	      state.readableListening = state.needReadable = true;
	      state.flowing = false;
	      state.emittedReadable = false;
	      debug('on readable', state.length, state.reading);
	      if (state.length) {
	        emitReadable(this);
	      } else if (!state.reading) {
	        process.nextTick(nReadingNextTick, this);
	      }
	    }
	  }
	  return res;
	};
	Readable.prototype.addListener = Readable.prototype.on;
	Readable.prototype.removeListener = function (ev, fn) {
	  var res = Stream.prototype.removeListener.call(this, ev, fn);
	  if (ev === 'readable') {
	    // We need to check if there is someone still listening to
	    // readable and reset the state. However this needs to happen
	    // after readable has been emitted but before I/O (nextTick) to
	    // support once('readable', fn) cycles. This means that calling
	    // resume within the same tick will have no
	    // effect.
	    process.nextTick(updateReadableListening, this);
	  }
	  return res;
	};
	Readable.prototype.removeAllListeners = function (ev) {
	  var res = Stream.prototype.removeAllListeners.apply(this, arguments);
	  if (ev === 'readable' || ev === undefined) {
	    // We need to check if there is someone still listening to
	    // readable and reset the state. However this needs to happen
	    // after readable has been emitted but before I/O (nextTick) to
	    // support once('readable', fn) cycles. This means that calling
	    // resume within the same tick will have no
	    // effect.
	    process.nextTick(updateReadableListening, this);
	  }
	  return res;
	};
	function updateReadableListening(self) {
	  var state = self._readableState;
	  state.readableListening = self.listenerCount('readable') > 0;
	  if (state.resumeScheduled && !state.paused) {
	    // flowing needs to be set to true now, otherwise
	    // the upcoming resume will not flow.
	    state.flowing = true;

	    // crude way to check if we should resume
	  } else if (self.listenerCount('data') > 0) {
	    self.resume();
	  }
	}
	function nReadingNextTick(self) {
	  debug('readable nexttick read 0');
	  self.read(0);
	}

	// pause() and resume() are remnants of the legacy readable stream API
	// If the user uses them, then switch into old mode.
	Readable.prototype.resume = function () {
	  var state = this._readableState;
	  if (!state.flowing) {
	    debug('resume');
	    // we flow only if there is no one listening
	    // for readable, but we still have to call
	    // resume()
	    state.flowing = !state.readableListening;
	    resume(this, state);
	  }
	  state.paused = false;
	  return this;
	};
	function resume(stream, state) {
	  if (!state.resumeScheduled) {
	    state.resumeScheduled = true;
	    process.nextTick(resume_, stream, state);
	  }
	}
	function resume_(stream, state) {
	  debug('resume', state.reading);
	  if (!state.reading) {
	    stream.read(0);
	  }
	  state.resumeScheduled = false;
	  stream.emit('resume');
	  flow(stream);
	  if (state.flowing && !state.reading) stream.read(0);
	}
	Readable.prototype.pause = function () {
	  debug('call pause flowing=%j', this._readableState.flowing);
	  if (this._readableState.flowing !== false) {
	    debug('pause');
	    this._readableState.flowing = false;
	    this.emit('pause');
	  }
	  this._readableState.paused = true;
	  return this;
	};
	function flow(stream) {
	  var state = stream._readableState;
	  debug('flow', state.flowing);
	  while (state.flowing && stream.read() !== null);
	}

	// wrap an old-style stream as the async data source.
	// This is *not* part of the readable stream interface.
	// It is an ugly unfortunate mess of history.
	Readable.prototype.wrap = function (stream) {
	  var _this = this;
	  var state = this._readableState;
	  var paused = false;
	  stream.on('end', function () {
	    debug('wrapped end');
	    if (state.decoder && !state.ended) {
	      var chunk = state.decoder.end();
	      if (chunk && chunk.length) _this.push(chunk);
	    }
	    _this.push(null);
	  });
	  stream.on('data', function (chunk) {
	    debug('wrapped data');
	    if (state.decoder) chunk = state.decoder.write(chunk);

	    // don't skip over falsy values in objectMode
	    if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
	    var ret = _this.push(chunk);
	    if (!ret) {
	      paused = true;
	      stream.pause();
	    }
	  });

	  // proxy all the other methods.
	  // important when wrapping filters and duplexes.
	  for (var i in stream) {
	    if (this[i] === undefined && typeof stream[i] === 'function') {
	      this[i] = function methodWrap(method) {
	        return function methodWrapReturnFunction() {
	          return stream[method].apply(stream, arguments);
	        };
	      }(i);
	    }
	  }

	  // proxy certain important events.
	  for (var n = 0; n < kProxyEvents.length; n++) {
	    stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
	  }

	  // when we try to consume some more bytes, simply unpause the
	  // underlying stream.
	  this._read = function (n) {
	    debug('wrapped _read', n);
	    if (paused) {
	      paused = false;
	      stream.resume();
	    }
	  };
	  return this;
	};
	if (typeof Symbol === 'function') {
	  Readable.prototype[Symbol.asyncIterator] = function () {
	    if (createReadableStreamAsyncIterator === undefined) {
	      createReadableStreamAsyncIterator = requireAsync_iterator();
	    }
	    return createReadableStreamAsyncIterator(this);
	  };
	}
	Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
	  // making it explicit this property is not enumerable
	  // because otherwise some prototype manipulation in
	  // userland will fail
	  enumerable: false,
	  get: function get() {
	    return this._readableState.highWaterMark;
	  }
	});
	Object.defineProperty(Readable.prototype, 'readableBuffer', {
	  // making it explicit this property is not enumerable
	  // because otherwise some prototype manipulation in
	  // userland will fail
	  enumerable: false,
	  get: function get() {
	    return this._readableState && this._readableState.buffer;
	  }
	});
	Object.defineProperty(Readable.prototype, 'readableFlowing', {
	  // making it explicit this property is not enumerable
	  // because otherwise some prototype manipulation in
	  // userland will fail
	  enumerable: false,
	  get: function get() {
	    return this._readableState.flowing;
	  },
	  set: function set(state) {
	    if (this._readableState) {
	      this._readableState.flowing = state;
	    }
	  }
	});

	// exposed for testing purposes only.
	Readable._fromList = fromList;
	Object.defineProperty(Readable.prototype, 'readableLength', {
	  // making it explicit this property is not enumerable
	  // because otherwise some prototype manipulation in
	  // userland will fail
	  enumerable: false,
	  get: function get() {
	    return this._readableState.length;
	  }
	});

	// Pluck off n bytes from an array of buffers.
	// Length is the combined lengths of all the buffers in the list.
	// This function is designed to be inlinable, so please take care when making
	// changes to the function body.
	function fromList(n, state) {
	  // nothing buffered
	  if (state.length === 0) return null;
	  var ret;
	  if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
	    // read it all, truncate the list
	    if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
	    state.buffer.clear();
	  } else {
	    // read part of list
	    ret = state.buffer.consume(n, state.decoder);
	  }
	  return ret;
	}
	function endReadable(stream) {
	  var state = stream._readableState;
	  debug('endReadable', state.endEmitted);
	  if (!state.endEmitted) {
	    state.ended = true;
	    process.nextTick(endReadableNT, state, stream);
	  }
	}
	function endReadableNT(state, stream) {
	  debug('endReadableNT', state.endEmitted, state.length);

	  // Check that we didn't get one last unshift.
	  if (!state.endEmitted && state.length === 0) {
	    state.endEmitted = true;
	    stream.readable = false;
	    stream.emit('end');
	    if (state.autoDestroy) {
	      // In case of duplex streams we need a way to detect
	      // if the writable side is ready for autoDestroy as well
	      var wState = stream._writableState;
	      if (!wState || wState.autoDestroy && wState.finished) {
	        stream.destroy();
	      }
	    }
	  }
	}
	if (typeof Symbol === 'function') {
	  Readable.from = function (iterable, opts) {
	    if (from === undefined) {
	      from = requireFromBrowser();
	    }
	    return from(Readable, iterable, opts);
	  };
	}
	function indexOf(xs, x) {
	  for (var i = 0, l = xs.length; i < l; i++) {
	    if (xs[i] === x) return i;
	  }
	  return -1;
	}
	return _stream_readable;
}

var _stream_duplex;
var hasRequired_stream_duplex;

function require_stream_duplex () {
	if (hasRequired_stream_duplex) return _stream_duplex;
	hasRequired_stream_duplex = 1;

	/*<replacement>*/
	var objectKeys = Object.keys || function (obj) {
	  var keys = [];
	  for (var key in obj) keys.push(key);
	  return keys;
	};
	/*</replacement>*/

	_stream_duplex = Duplex;
	var Readable = require_stream_readable();
	var Writable = require_stream_writable();
	requireInherits_browser()(Duplex, Readable);
	{
	  // Allow the keys array to be GC'ed.
	  var keys = objectKeys(Writable.prototype);
	  for (var v = 0; v < keys.length; v++) {
	    var method = keys[v];
	    if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
	  }
	}
	function Duplex(options) {
	  if (!(this instanceof Duplex)) return new Duplex(options);
	  Readable.call(this, options);
	  Writable.call(this, options);
	  this.allowHalfOpen = true;
	  if (options) {
	    if (options.readable === false) this.readable = false;
	    if (options.writable === false) this.writable = false;
	    if (options.allowHalfOpen === false) {
	      this.allowHalfOpen = false;
	      this.once('end', onend);
	    }
	  }
	}
	Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
	  // making it explicit this property is not enumerable
	  // because otherwise some prototype manipulation in
	  // userland will fail
	  enumerable: false,
	  get: function get() {
	    return this._writableState.highWaterMark;
	  }
	});
	Object.defineProperty(Duplex.prototype, 'writableBuffer', {
	  // making it explicit this property is not enumerable
	  // because otherwise some prototype manipulation in
	  // userland will fail
	  enumerable: false,
	  get: function get() {
	    return this._writableState && this._writableState.getBuffer();
	  }
	});
	Object.defineProperty(Duplex.prototype, 'writableLength', {
	  // making it explicit this property is not enumerable
	  // because otherwise some prototype manipulation in
	  // userland will fail
	  enumerable: false,
	  get: function get() {
	    return this._writableState.length;
	  }
	});

	// the no-half-open enforcer
	function onend() {
	  // If the writable side ended, then we're ok.
	  if (this._writableState.ended) return;

	  // no more data can be written.
	  // But allow more writes to happen in this tick.
	  process.nextTick(onEndNT, this);
	}
	function onEndNT(self) {
	  self.end();
	}
	Object.defineProperty(Duplex.prototype, 'destroyed', {
	  // making it explicit this property is not enumerable
	  // because otherwise some prototype manipulation in
	  // userland will fail
	  enumerable: false,
	  get: function get() {
	    if (this._readableState === undefined || this._writableState === undefined) {
	      return false;
	    }
	    return this._readableState.destroyed && this._writableState.destroyed;
	  },
	  set: function set(value) {
	    // we ignore the value if the stream
	    // has not been initialized yet
	    if (this._readableState === undefined || this._writableState === undefined) {
	      return;
	    }

	    // backward compatibility, the user is explicitly
	    // managing destroyed
	    this._readableState.destroyed = value;
	    this._writableState.destroyed = value;
	  }
	});
	return _stream_duplex;
}

var _stream_writable;
var hasRequired_stream_writable;

function require_stream_writable () {
	if (hasRequired_stream_writable) return _stream_writable;
	hasRequired_stream_writable = 1;

	_stream_writable = Writable;

	// It seems a linked list but it is not
	// there will be only 2 of these for each stream
	function CorkedRequest(state) {
	  var _this = this;
	  this.next = null;
	  this.entry = null;
	  this.finish = function () {
	    onCorkedFinish(_this, state);
	  };
	}
	/* </replacement> */

	/*<replacement>*/
	var Duplex;
	/*</replacement>*/

	Writable.WritableState = WritableState;

	/*<replacement>*/
	var internalUtil = {
	  deprecate: requireBrowser$4()
	};
	/*</replacement>*/

	/*<replacement>*/
	var Stream = requireStreamBrowser();
	/*</replacement>*/

	var Buffer = require$$0$4.Buffer;
	var OurUint8Array = (typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
	function _uint8ArrayToBuffer(chunk) {
	  return Buffer.from(chunk);
	}
	function _isUint8Array(obj) {
	  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
	}
	var destroyImpl = requireDestroy();
	var _require = requireState(),
	  getHighWaterMark = _require.getHighWaterMark;
	var _require$codes = requireErrorsBrowser().codes,
	  ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
	  ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
	  ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
	  ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
	  ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
	  ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
	  ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
	  ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
	var errorOrDestroy = destroyImpl.errorOrDestroy;
	requireInherits_browser()(Writable, Stream);
	function nop() {}
	function WritableState(options, stream, isDuplex) {
	  Duplex = Duplex || require_stream_duplex();
	  options = options || {};

	  // Duplex streams are both readable and writable, but share
	  // the same options object.
	  // However, some cases require setting options to different
	  // values for the readable and the writable sides of the duplex stream,
	  // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
	  if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;

	  // object stream flag to indicate whether or not this stream
	  // contains buffers or objects.
	  this.objectMode = !!options.objectMode;
	  if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;

	  // the point at which write() starts returning false
	  // Note: 0 is a valid value, means that we always return false if
	  // the entire buffer is not flushed immediately on write()
	  this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex);

	  // if _final has been called
	  this.finalCalled = false;

	  // drain event flag.
	  this.needDrain = false;
	  // at the start of calling end()
	  this.ending = false;
	  // when end() has been called, and returned
	  this.ended = false;
	  // when 'finish' is emitted
	  this.finished = false;

	  // has it been destroyed
	  this.destroyed = false;

	  // should we decode strings into buffers before passing to _write?
	  // this is here so that some node-core streams can optimize string
	  // handling at a lower level.
	  var noDecode = options.decodeStrings === false;
	  this.decodeStrings = !noDecode;

	  // Crypto is kind of old and crusty.  Historically, its default string
	  // encoding is 'binary' so we have to make this configurable.
	  // Everything else in the universe uses 'utf8', though.
	  this.defaultEncoding = options.defaultEncoding || 'utf8';

	  // not an actual buffer we keep track of, but a measurement
	  // of how much we're waiting to get pushed to some underlying
	  // socket or file.
	  this.length = 0;

	  // a flag to see when we're in the middle of a write.
	  this.writing = false;

	  // when true all writes will be buffered until .uncork() call
	  this.corked = 0;

	  // a flag to be able to tell if the onwrite cb is called immediately,
	  // or on a later tick.  We set this to true at first, because any
	  // actions that shouldn't happen until "later" should generally also
	  // not happen before the first write call.
	  this.sync = true;

	  // a flag to know if we're processing previously buffered items, which
	  // may call the _write() callback in the same tick, so that we don't
	  // end up in an overlapped onwrite situation.
	  this.bufferProcessing = false;

	  // the callback that's passed to _write(chunk,cb)
	  this.onwrite = function (er) {
	    onwrite(stream, er);
	  };

	  // the callback that the user supplies to write(chunk,encoding,cb)
	  this.writecb = null;

	  // the amount that is being written when _write is called.
	  this.writelen = 0;
	  this.bufferedRequest = null;
	  this.lastBufferedRequest = null;

	  // number of pending user-supplied write callbacks
	  // this must be 0 before 'finish' can be emitted
	  this.pendingcb = 0;

	  // emit prefinish if the only thing we're waiting for is _write cbs
	  // This is relevant for synchronous Transform streams
	  this.prefinished = false;

	  // True if the error was already emitted and should not be thrown again
	  this.errorEmitted = false;

	  // Should close be emitted on destroy. Defaults to true.
	  this.emitClose = options.emitClose !== false;

	  // Should .destroy() be called after 'finish' (and potentially 'end')
	  this.autoDestroy = !!options.autoDestroy;

	  // count buffered requests
	  this.bufferedRequestCount = 0;

	  // allocate the first CorkedRequest, there is always
	  // one allocated and free to use, and we maintain at most two
	  this.corkedRequestsFree = new CorkedRequest(this);
	}
	WritableState.prototype.getBuffer = function getBuffer() {
	  var current = this.bufferedRequest;
	  var out = [];
	  while (current) {
	    out.push(current);
	    current = current.next;
	  }
	  return out;
	};
	(function () {
	  try {
	    Object.defineProperty(WritableState.prototype, 'buffer', {
	      get: internalUtil.deprecate(function writableStateBufferGetter() {
	        return this.getBuffer();
	      }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
	    });
	  } catch (_) {}
	})();

	// Test _writableState for inheritance to account for Duplex streams,
	// whose prototype chain only points to Readable.
	var realHasInstance;
	if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
	  realHasInstance = Function.prototype[Symbol.hasInstance];
	  Object.defineProperty(Writable, Symbol.hasInstance, {
	    value: function value(object) {
	      if (realHasInstance.call(this, object)) return true;
	      if (this !== Writable) return false;
	      return object && object._writableState instanceof WritableState;
	    }
	  });
	} else {
	  realHasInstance = function realHasInstance(object) {
	    return object instanceof this;
	  };
	}
	function Writable(options) {
	  Duplex = Duplex || require_stream_duplex();

	  // Writable ctor is applied to Duplexes, too.
	  // `realHasInstance` is necessary because using plain `instanceof`
	  // would return false, as no `_writableState` property is attached.

	  // Trying to use the custom `instanceof` for Writable here will also break the
	  // Node.js LazyTransform implementation, which has a non-trivial getter for
	  // `_writableState` that would lead to infinite recursion.

	  // Checking for a Stream.Duplex instance is faster here instead of inside
	  // the WritableState constructor, at least with V8 6.5
	  var isDuplex = this instanceof Duplex;
	  if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
	  this._writableState = new WritableState(options, this, isDuplex);

	  // legacy.
	  this.writable = true;
	  if (options) {
	    if (typeof options.write === 'function') this._write = options.write;
	    if (typeof options.writev === 'function') this._writev = options.writev;
	    if (typeof options.destroy === 'function') this._destroy = options.destroy;
	    if (typeof options.final === 'function') this._final = options.final;
	  }
	  Stream.call(this);
	}

	// Otherwise people can pipe Writable streams, which is just wrong.
	Writable.prototype.pipe = function () {
	  errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
	};
	function writeAfterEnd(stream, cb) {
	  var er = new ERR_STREAM_WRITE_AFTER_END();
	  // TODO: defer error events consistently everywhere, not just the cb
	  errorOrDestroy(stream, er);
	  process.nextTick(cb, er);
	}

	// Checks that a user-supplied chunk is valid, especially for the particular
	// mode the stream is in. Currently this means that `null` is never accepted
	// and undefined/non-string values are only allowed in object mode.
	function validChunk(stream, state, chunk, cb) {
	  var er;
	  if (chunk === null) {
	    er = new ERR_STREAM_NULL_VALUES();
	  } else if (typeof chunk !== 'string' && !state.objectMode) {
	    er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
	  }
	  if (er) {
	    errorOrDestroy(stream, er);
	    process.nextTick(cb, er);
	    return false;
	  }
	  return true;
	}
	Writable.prototype.write = function (chunk, encoding, cb) {
	  var state = this._writableState;
	  var ret = false;
	  var isBuf = !state.objectMode && _isUint8Array(chunk);
	  if (isBuf && !Buffer.isBuffer(chunk)) {
	    chunk = _uint8ArrayToBuffer(chunk);
	  }
	  if (typeof encoding === 'function') {
	    cb = encoding;
	    encoding = null;
	  }
	  if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
	  if (typeof cb !== 'function') cb = nop;
	  if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
	    state.pendingcb++;
	    ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
	  }
	  return ret;
	};
	Writable.prototype.cork = function () {
	  this._writableState.corked++;
	};
	Writable.prototype.uncork = function () {
	  var state = this._writableState;
	  if (state.corked) {
	    state.corked--;
	    if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
	  }
	};
	Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
	  // node::ParseEncoding() requires lower case.
	  if (typeof encoding === 'string') encoding = encoding.toLowerCase();
	  if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
	  this._writableState.defaultEncoding = encoding;
	  return this;
	};
	Object.defineProperty(Writable.prototype, 'writableBuffer', {
	  // making it explicit this property is not enumerable
	  // because otherwise some prototype manipulation in
	  // userland will fail
	  enumerable: false,
	  get: function get() {
	    return this._writableState && this._writableState.getBuffer();
	  }
	});
	function decodeChunk(state, chunk, encoding) {
	  if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
	    chunk = Buffer.from(chunk, encoding);
	  }
	  return chunk;
	}
	Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
	  // making it explicit this property is not enumerable
	  // because otherwise some prototype manipulation in
	  // userland will fail
	  enumerable: false,
	  get: function get() {
	    return this._writableState.highWaterMark;
	  }
	});

	// if we're already writing something, then just put this
	// in the queue, and wait our turn.  Otherwise, call _write
	// If we return false, then we need a drain event, so set that flag.
	function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
	  if (!isBuf) {
	    var newChunk = decodeChunk(state, chunk, encoding);
	    if (chunk !== newChunk) {
	      isBuf = true;
	      encoding = 'buffer';
	      chunk = newChunk;
	    }
	  }
	  var len = state.objectMode ? 1 : chunk.length;
	  state.length += len;
	  var ret = state.length < state.highWaterMark;
	  // we must ensure that previous needDrain will not be reset to false.
	  if (!ret) state.needDrain = true;
	  if (state.writing || state.corked) {
	    var last = state.lastBufferedRequest;
	    state.lastBufferedRequest = {
	      chunk: chunk,
	      encoding: encoding,
	      isBuf: isBuf,
	      callback: cb,
	      next: null
	    };
	    if (last) {
	      last.next = state.lastBufferedRequest;
	    } else {
	      state.bufferedRequest = state.lastBufferedRequest;
	    }
	    state.bufferedRequestCount += 1;
	  } else {
	    doWrite(stream, state, false, len, chunk, encoding, cb);
	  }
	  return ret;
	}
	function doWrite(stream, state, writev, len, chunk, encoding, cb) {
	  state.writelen = len;
	  state.writecb = cb;
	  state.writing = true;
	  state.sync = true;
	  if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
	  state.sync = false;
	}
	function onwriteError(stream, state, sync, er, cb) {
	  --state.pendingcb;
	  if (sync) {
	    // defer the callback if we are being called synchronously
	    // to avoid piling up things on the stack
	    process.nextTick(cb, er);
	    // this can emit finish, and it will always happen
	    // after error
	    process.nextTick(finishMaybe, stream, state);
	    stream._writableState.errorEmitted = true;
	    errorOrDestroy(stream, er);
	  } else {
	    // the caller expect this to happen before if
	    // it is async
	    cb(er);
	    stream._writableState.errorEmitted = true;
	    errorOrDestroy(stream, er);
	    // this can emit finish, but finish must
	    // always follow error
	    finishMaybe(stream, state);
	  }
	}
	function onwriteStateUpdate(state) {
	  state.writing = false;
	  state.writecb = null;
	  state.length -= state.writelen;
	  state.writelen = 0;
	}
	function onwrite(stream, er) {
	  var state = stream._writableState;
	  var sync = state.sync;
	  var cb = state.writecb;
	  if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
	  onwriteStateUpdate(state);
	  if (er) onwriteError(stream, state, sync, er, cb);else {
	    // Check if we're actually ready to finish, but don't emit yet
	    var finished = needFinish(state) || stream.destroyed;
	    if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
	      clearBuffer(stream, state);
	    }
	    if (sync) {
	      process.nextTick(afterWrite, stream, state, finished, cb);
	    } else {
	      afterWrite(stream, state, finished, cb);
	    }
	  }
	}
	function afterWrite(stream, state, finished, cb) {
	  if (!finished) onwriteDrain(stream, state);
	  state.pendingcb--;
	  cb();
	  finishMaybe(stream, state);
	}

	// Must force callback to be called on nextTick, so that we don't
	// emit 'drain' before the write() consumer gets the 'false' return
	// value, and has a chance to attach a 'drain' listener.
	function onwriteDrain(stream, state) {
	  if (state.length === 0 && state.needDrain) {
	    state.needDrain = false;
	    stream.emit('drain');
	  }
	}

	// if there's something in the buffer waiting, then process it
	function clearBuffer(stream, state) {
	  state.bufferProcessing = true;
	  var entry = state.bufferedRequest;
	  if (stream._writev && entry && entry.next) {
	    // Fast case, write everything using _writev()
	    var l = state.bufferedRequestCount;
	    var buffer = new Array(l);
	    var holder = state.corkedRequestsFree;
	    holder.entry = entry;
	    var count = 0;
	    var allBuffers = true;
	    while (entry) {
	      buffer[count] = entry;
	      if (!entry.isBuf) allBuffers = false;
	      entry = entry.next;
	      count += 1;
	    }
	    buffer.allBuffers = allBuffers;
	    doWrite(stream, state, true, state.length, buffer, '', holder.finish);

	    // doWrite is almost always async, defer these to save a bit of time
	    // as the hot path ends with doWrite
	    state.pendingcb++;
	    state.lastBufferedRequest = null;
	    if (holder.next) {
	      state.corkedRequestsFree = holder.next;
	      holder.next = null;
	    } else {
	      state.corkedRequestsFree = new CorkedRequest(state);
	    }
	    state.bufferedRequestCount = 0;
	  } else {
	    // Slow case, write chunks one-by-one
	    while (entry) {
	      var chunk = entry.chunk;
	      var encoding = entry.encoding;
	      var cb = entry.callback;
	      var len = state.objectMode ? 1 : chunk.length;
	      doWrite(stream, state, false, len, chunk, encoding, cb);
	      entry = entry.next;
	      state.bufferedRequestCount--;
	      // if we didn't call the onwrite immediately, then
	      // it means that we need to wait until it does.
	      // also, that means that the chunk and cb are currently
	      // being processed, so move the buffer counter past them.
	      if (state.writing) {
	        break;
	      }
	    }
	    if (entry === null) state.lastBufferedRequest = null;
	  }
	  state.bufferedRequest = entry;
	  state.bufferProcessing = false;
	}
	Writable.prototype._write = function (chunk, encoding, cb) {
	  cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
	};
	Writable.prototype._writev = null;
	Writable.prototype.end = function (chunk, encoding, cb) {
	  var state = this._writableState;
	  if (typeof chunk === 'function') {
	    cb = chunk;
	    chunk = null;
	    encoding = null;
	  } else if (typeof encoding === 'function') {
	    cb = encoding;
	    encoding = null;
	  }
	  if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);

	  // .end() fully uncorks
	  if (state.corked) {
	    state.corked = 1;
	    this.uncork();
	  }

	  // ignore unnecessary end() calls.
	  if (!state.ending) endWritable(this, state, cb);
	  return this;
	};
	Object.defineProperty(Writable.prototype, 'writableLength', {
	  // making it explicit this property is not enumerable
	  // because otherwise some prototype manipulation in
	  // userland will fail
	  enumerable: false,
	  get: function get() {
	    return this._writableState.length;
	  }
	});
	function needFinish(state) {
	  return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
	}
	function callFinal(stream, state) {
	  stream._final(function (err) {
	    state.pendingcb--;
	    if (err) {
	      errorOrDestroy(stream, err);
	    }
	    state.prefinished = true;
	    stream.emit('prefinish');
	    finishMaybe(stream, state);
	  });
	}
	function prefinish(stream, state) {
	  if (!state.prefinished && !state.finalCalled) {
	    if (typeof stream._final === 'function' && !state.destroyed) {
	      state.pendingcb++;
	      state.finalCalled = true;
	      process.nextTick(callFinal, stream, state);
	    } else {
	      state.prefinished = true;
	      stream.emit('prefinish');
	    }
	  }
	}
	function finishMaybe(stream, state) {
	  var need = needFinish(state);
	  if (need) {
	    prefinish(stream, state);
	    if (state.pendingcb === 0) {
	      state.finished = true;
	      stream.emit('finish');
	      if (state.autoDestroy) {
	        // In case of duplex streams we need a way to detect
	        // if the readable side is ready for autoDestroy as well
	        var rState = stream._readableState;
	        if (!rState || rState.autoDestroy && rState.endEmitted) {
	          stream.destroy();
	        }
	      }
	    }
	  }
	  return need;
	}
	function endWritable(stream, state, cb) {
	  state.ending = true;
	  finishMaybe(stream, state);
	  if (cb) {
	    if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
	  }
	  state.ended = true;
	  stream.writable = false;
	}
	function onCorkedFinish(corkReq, state, err) {
	  var entry = corkReq.entry;
	  corkReq.entry = null;
	  while (entry) {
	    var cb = entry.callback;
	    state.pendingcb--;
	    cb(err);
	    entry = entry.next;
	  }

	  // reuse the free corkReq.
	  state.corkedRequestsFree.next = corkReq;
	}
	Object.defineProperty(Writable.prototype, 'destroyed', {
	  // making it explicit this property is not enumerable
	  // because otherwise some prototype manipulation in
	  // userland will fail
	  enumerable: false,
	  get: function get() {
	    if (this._writableState === undefined) {
	      return false;
	    }
	    return this._writableState.destroyed;
	  },
	  set: function set(value) {
	    // we ignore the value if the stream
	    // has not been initialized yet
	    if (!this._writableState) {
	      return;
	    }

	    // backward compatibility, the user is explicitly
	    // managing destroyed
	    this._writableState.destroyed = value;
	  }
	});
	Writable.prototype.destroy = destroyImpl.destroy;
	Writable.prototype._undestroy = destroyImpl.undestroy;
	Writable.prototype._destroy = function (err, cb) {
	  cb(err);
	};
	return _stream_writable;
}

var hasRequiredModern$1;

function requireModern$1 () {
	if (hasRequiredModern$1) return modern$1.exports;
	hasRequiredModern$1 = 1;

	var util = require$$0$6;
	var Writable = require_stream_writable();

	var _require = requireTripleBeam(),
	    LEVEL = _require.LEVEL;

	/**
	 * Constructor function for the TransportStream. This is the base prototype
	 * that all `winston >= 3` transports should inherit from.
	 * @param {Object} options - Options for this TransportStream instance
	 * @param {String} options.level - Highest level according to RFC5424.
	 * @param {Boolean} options.handleExceptions - If true, info with
	 * { exception: true } will be written.
	 * @param {Function} options.log - Custom log function for simple Transport
	 * creation
	 * @param {Function} options.close - Called on "unpipe" from parent.
	 */


	var TransportStream = modern$1.exports = function TransportStream() {
	  var _this = this;

	  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

	  Writable.call(this, { objectMode: true, highWaterMark: options.highWaterMark });

	  this.format = options.format;
	  this.level = options.level;
	  this.handleExceptions = options.handleExceptions;
	  this.handleRejections = options.handleRejections;
	  this.silent = options.silent;

	  if (options.log) this.log = options.log;
	  if (options.logv) this.logv = options.logv;
	  if (options.close) this.close = options.close;

	  // Get the levels from the source we are piped from.
	  this.once('pipe', function (logger) {
	    // Remark (indexzero): this bookkeeping can only support multiple
	    // Logger parents with the same `levels`. This comes into play in
	    // the `winston.Container` code in which `container.add` takes
	    // a fully realized set of options with pre-constructed TransportStreams.
	    _this.levels = logger.levels;
	    _this.parent = logger;
	  });

	  // If and/or when the transport is removed from this instance
	  this.once('unpipe', function (src) {
	    // Remark (indexzero): this bookkeeping can only support multiple
	    // Logger parents with the same `levels`. This comes into play in
	    // the `winston.Container` code in which `container.add` takes
	    // a fully realized set of options with pre-constructed TransportStreams.
	    if (src === _this.parent) {
	      _this.parent = null;
	      if (_this.close) {
	        _this.close();
	      }
	    }
	  });
	};

	/*
	 * Inherit from Writeable using Node.js built-ins
	 */
	util.inherits(TransportStream, Writable);

	/**
	 * Writes the info object to our transport instance.
	 * @param {mixed} info - TODO: add param description.
	 * @param {mixed} enc - TODO: add param description.
	 * @param {function} callback - TODO: add param description.
	 * @returns {undefined}
	 * @private
	 */
	TransportStream.prototype._write = function _write(info, enc, callback) {
	  if (this.silent || info.exception === true && !this.handleExceptions) {
	    return callback(null);
	  }

	  // Remark: This has to be handled in the base transport now because we
	  // cannot conditionally write to our pipe targets as stream. We always
	  // prefer any explicit level set on the Transport itself falling back to
	  // any level set on the parent.
	  var level = this.level || this.parent && this.parent.level;

	  if (!level || this.levels[level] >= this.levels[info[LEVEL]]) {
	    if (info && !this.format) {
	      return this.log(info, callback);
	    }

	    var errState = void 0;
	    var transformed = void 0;

	    // We trap(and re-throw) any errors generated by the user-provided format, but also
	    // guarantee that the streams callback is invoked so that we can continue flowing.
	    try {
	      transformed = this.format.transform(Object.assign({}, info), this.format.options);
	    } catch (err) {
	      errState = err;
	    }

	    if (errState || !transformed) {
	      // eslint-disable-next-line callback-return
	      callback();
	      if (errState) throw errState;
	      return;
	    }

	    return this.log(transformed, callback);
	  }
	  this._writableState.sync = false;
	  return callback(null);
	};

	/**
	 * Writes the batch of info objects (i.e. "object chunks") to our transport
	 * instance after performing any necessary filtering.
	 * @param {mixed} chunks - TODO: add params description.
	 * @param {function} callback - TODO: add params description.
	 * @returns {mixed} - TODO: add returns description.
	 * @private
	 */
	TransportStream.prototype._writev = function _writev(chunks, callback) {
	  if (this.logv) {
	    var infos = chunks.filter(this._accept, this);
	    if (!infos.length) {
	      return callback(null);
	    }

	    // Remark (indexzero): from a performance perspective if Transport
	    // implementers do choose to implement logv should we make it their
	    // responsibility to invoke their format?
	    return this.logv(infos, callback);
	  }

	  for (var i = 0; i < chunks.length; i++) {
	    if (!this._accept(chunks[i])) continue;

	    if (chunks[i].chunk && !this.format) {
	      this.log(chunks[i].chunk, chunks[i].callback);
	      continue;
	    }

	    var errState = void 0;
	    var transformed = void 0;

	    // We trap(and re-throw) any errors generated by the user-provided format, but also
	    // guarantee that the streams callback is invoked so that we can continue flowing.
	    try {
	      transformed = this.format.transform(Object.assign({}, chunks[i].chunk), this.format.options);
	    } catch (err) {
	      errState = err;
	    }

	    if (errState || !transformed) {
	      // eslint-disable-next-line callback-return
	      chunks[i].callback();
	      if (errState) {
	        // eslint-disable-next-line callback-return
	        callback(null);
	        throw errState;
	      }
	    } else {
	      this.log(transformed, chunks[i].callback);
	    }
	  }

	  return callback(null);
	};

	/**
	 * Predicate function that returns true if the specfied `info` on the
	 * WriteReq, `write`, should be passed down into the derived
	 * TransportStream's I/O via `.log(info, callback)`.
	 * @param {WriteReq} write - winston@3 Node.js WriteReq for the `info` object
	 * representing the log message.
	 * @returns {Boolean} - Value indicating if the `write` should be accepted &
	 * logged.
	 */
	TransportStream.prototype._accept = function _accept(write) {
	  var info = write.chunk;
	  if (this.silent) {
	    return false;
	  }

	  // We always prefer any explicit level set on the Transport itself
	  // falling back to any level set on the parent.
	  var level = this.level || this.parent && this.parent.level;

	  // Immediately check the average case: log level filtering.
	  if (info.exception === true || !level || this.levels[level] >= this.levels[info[LEVEL]]) {
	    // Ensure the info object is valid based on `{ exception }`:
	    // 1. { handleExceptions: true }: all `info` objects are valid
	    // 2. { exception: false }: accepted by all transports.
	    if (this.handleExceptions || info.exception !== true) {
	      return true;
	    }
	  }

	  return false;
	};

	/**
	 * _nop is short for "No operation"
	 * @returns {Boolean} Intentionally false.
	 */
	TransportStream.prototype._nop = function _nop() {
	  // eslint-disable-next-line no-undefined
	  return void undefined;
	};
	return modern$1.exports;
}

var legacy$1 = {exports: {}};

var hasRequiredLegacy$1;

function requireLegacy$1 () {
	if (hasRequiredLegacy$1) return legacy$1.exports;
	hasRequiredLegacy$1 = 1;

	var util = require$$0$6;

	var _require = requireTripleBeam(),
	    LEVEL = _require.LEVEL;

	var TransportStream = requireModern$1();

	/**
	 * Constructor function for the LegacyTransportStream. This is an internal
	 * wrapper `winston >= 3` uses to wrap older transports implementing
	 * log(level, message, meta).
	 * @param {Object} options - Options for this TransportStream instance.
	 * @param {Transpot} options.transport - winston@2 or older Transport to wrap.
	 */

	var LegacyTransportStream = legacy$1.exports = function LegacyTransportStream() {
	  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

	  TransportStream.call(this, options);
	  if (!options.transport || typeof options.transport.log !== 'function') {
	    throw new Error('Invalid transport, must be an object with a log method.');
	  }

	  this.transport = options.transport;
	  this.level = this.level || options.transport.level;
	  this.handleExceptions = this.handleExceptions || options.transport.handleExceptions;

	  // Display our deprecation notice.
	  this._deprecated();

	  // Properly bubble up errors from the transport to the
	  // LegacyTransportStream instance, but only once no matter how many times
	  // this transport is shared.
	  function transportError(err) {
	    this.emit('error', err, this.transport);
	  }

	  if (!this.transport.__winstonError) {
	    this.transport.__winstonError = transportError.bind(this);
	    this.transport.on('error', this.transport.__winstonError);
	  }
	};

	/*
	 * Inherit from TransportStream using Node.js built-ins
	 */
	util.inherits(LegacyTransportStream, TransportStream);

	/**
	 * Writes the info object to our transport instance.
	 * @param {mixed} info - TODO: add param description.
	 * @param {mixed} enc - TODO: add param description.
	 * @param {function} callback - TODO: add param description.
	 * @returns {undefined}
	 * @private
	 */
	LegacyTransportStream.prototype._write = function _write(info, enc, callback) {
	  if (this.silent || info.exception === true && !this.handleExceptions) {
	    return callback(null);
	  }

	  // Remark: This has to be handled in the base transport now because we
	  // cannot conditionally write to our pipe targets as stream.
	  if (!this.level || this.levels[this.level] >= this.levels[info[LEVEL]]) {
	    this.transport.log(info[LEVEL], info.message, info, this._nop);
	  }

	  callback(null);
	};

	/**
	 * Writes the batch of info objects (i.e. "object chunks") to our transport
	 * instance after performing any necessary filtering.
	 * @param {mixed} chunks - TODO: add params description.
	 * @param {function} callback - TODO: add params description.
	 * @returns {mixed} - TODO: add returns description.
	 * @private
	 */
	LegacyTransportStream.prototype._writev = function _writev(chunks, callback) {
	  for (var i = 0; i < chunks.length; i++) {
	    if (this._accept(chunks[i])) {
	      this.transport.log(chunks[i].chunk[LEVEL], chunks[i].chunk.message, chunks[i].chunk, this._nop);
	      chunks[i].callback();
	    }
	  }

	  return callback(null);
	};

	/**
	 * Displays a deprecation notice. Defined as a function so it can be
	 * overriden in tests.
	 * @returns {undefined}
	 */
	LegacyTransportStream.prototype._deprecated = function _deprecated() {
	  // eslint-disable-next-line no-console
	  console.error([this.transport.name + ' is a legacy winston transport. Consider upgrading: ', '- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md'].join('\n'));
	};

	/**
	 * Clean up error handling state on the legacy transport associated
	 * with this instance.
	 * @returns {undefined}
	 */
	LegacyTransportStream.prototype.close = function close() {
	  if (this.transport.close) {
	    this.transport.close();
	  }

	  if (this.transport.__winstonError) {
	    this.transport.removeListener('error', this.transport.__winstonError);
	    this.transport.__winstonError = null;
	  }
	};
	return legacy$1.exports;
}

var hasRequiredDist;

function requireDist () {
	if (hasRequiredDist) return dist.exports;
	hasRequiredDist = 1;

	// Expose modern transport directly as the export

	dist.exports = requireModern$1();

	// Expose legacy stream
	dist.exports.LegacyTransportStream = requireLegacy$1();
	return dist.exports;
}

/* eslint-disable no-console */

var console_1$1;
var hasRequiredConsole$1;

function requireConsole$1 () {
	if (hasRequiredConsole$1) return console_1$1;
	hasRequiredConsole$1 = 1;

	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
	function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
	function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
	function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
	function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
	function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
	function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
	function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: true, configurable: true } }), Object.defineProperty(t, "prototype", { writable: false }), e && _setPrototypeOf(t, e); }
	function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
	var os = os__default;
	var _require = requireTripleBeam(),
	  LEVEL = _require.LEVEL,
	  MESSAGE = _require.MESSAGE;
	var TransportStream = requireDist();

	/**
	 * Transport for outputting to the console.
	 * @type {Console}
	 * @extends {TransportStream}
	 */
	console_1$1 = /*#__PURE__*/function (_TransportStream) {
	  /**
	   * Constructor function for the Console transport object responsible for
	   * persisting log messages and metadata to a terminal or TTY.
	   * @param {!Object} [options={}] - Options for this instance.
	   */
	  function Console() {
	    var _this;
	    var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
	    _classCallCheck(this, Console);
	    _this = _callSuper(this, Console, [options]);

	    // Expose the name of this Transport on the prototype
	    _this.name = options.name || 'console';
	    _this.stderrLevels = _this._stringArrayToSet(options.stderrLevels);
	    _this.consoleWarnLevels = _this._stringArrayToSet(options.consoleWarnLevels);
	    _this.eol = typeof options.eol === 'string' ? options.eol : os.EOL;
	    _this.forceConsole = options.forceConsole || false;

	    // Keep a reference to the log, warn, and error console methods
	    // in case they get redirected to this transport after the logger is
	    // instantiated. This prevents a circular reference issue.
	    _this._consoleLog = console.log.bind(console);
	    _this._consoleWarn = console.warn.bind(console);
	    _this._consoleError = console.error.bind(console);
	    _this.setMaxListeners(30);
	    return _this;
	  }

	  /**
	   * Core logging method exposed to Winston.
	   * @param {Object} info - TODO: add param description.
	   * @param {Function} callback - TODO: add param description.
	   * @returns {undefined}
	   */
	  _inherits(Console, _TransportStream);
	  return _createClass(Console, [{
	    key: "log",
	    value: function log(info, callback) {
	      var _this2 = this;
	      setImmediate(function () {
	        return _this2.emit('logged', info);
	      });

	      // Remark: what if there is no raw...?
	      if (this.stderrLevels[info[LEVEL]]) {
	        if (console._stderr && !this.forceConsole) {
	          // Node.js maps `process.stderr` to `console._stderr`.
	          console._stderr.write("".concat(info[MESSAGE]).concat(this.eol));
	        } else {
	          // console.error adds a newline
	          this._consoleError(info[MESSAGE]);
	        }
	        if (callback) {
	          callback(); // eslint-disable-line callback-return
	        }
	        return;
	      } else if (this.consoleWarnLevels[info[LEVEL]]) {
	        if (console._stderr && !this.forceConsole) {
	          // Node.js maps `process.stderr` to `console._stderr`.
	          // in Node.js console.warn is an alias for console.error
	          console._stderr.write("".concat(info[MESSAGE]).concat(this.eol));
	        } else {
	          // console.warn adds a newline
	          this._consoleWarn(info[MESSAGE]);
	        }
	        if (callback) {
	          callback(); // eslint-disable-line callback-return
	        }
	        return;
	      }
	      if (console._stdout && !this.forceConsole) {
	        // Node.js maps `process.stdout` to `console._stdout`.
	        console._stdout.write("".concat(info[MESSAGE]).concat(this.eol));
	      } else {
	        // console.log adds a newline.
	        this._consoleLog(info[MESSAGE]);
	      }
	      if (callback) {
	        callback(); // eslint-disable-line callback-return
	      }
	    }

	    /**
	     * Returns a Set-like object with strArray's elements as keys (each with the
	     * value true).
	     * @param {Array} strArray - Array of Set-elements as strings.
	     * @param {?string} [errMsg] - Custom error message thrown on invalid input.
	     * @returns {Object} - TODO: add return description.
	     * @private
	     */
	  }, {
	    key: "_stringArrayToSet",
	    value: function _stringArrayToSet(strArray, errMsg) {
	      if (!strArray) return {};
	      errMsg = errMsg || 'Cannot make set from type other than Array of string elements';
	      if (!Array.isArray(strArray)) {
	        throw new Error(errMsg);
	      }
	      return strArray.reduce(function (set, el) {
	        if (typeof el !== 'string') {
	          throw new Error(errMsg);
	        }
	        set[el] = true;
	        return set;
	      }, {});
	    }
	  }]);
	}(TransportStream);
	return console_1$1;
}

var series = {exports: {}};

var parallel = {exports: {}};

var isArrayLike = {exports: {}};

var hasRequiredIsArrayLike;

function requireIsArrayLike () {
	if (hasRequiredIsArrayLike) return isArrayLike.exports;
	hasRequiredIsArrayLike = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});
		exports$1.default = isArrayLike;
		function isArrayLike(value) {
		    return value && typeof value.length === 'number' && value.length >= 0 && value.length % 1 === 0;
		}
		module.exports = exports$1.default; 
	} (isArrayLike, isArrayLike.exports));
	return isArrayLike.exports;
}

var wrapAsync = {};

var asyncify = {exports: {}};

var initialParams = {exports: {}};

var hasRequiredInitialParams;

function requireInitialParams () {
	if (hasRequiredInitialParams) return initialParams.exports;
	hasRequiredInitialParams = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});

		exports$1.default = function (fn) {
		    return function (...args /*, callback*/) {
		        var callback = args.pop();
		        return fn.call(this, args, callback);
		    };
		};

		module.exports = exports$1.default; 
	} (initialParams, initialParams.exports));
	return initialParams.exports;
}

var setImmediate$1 = {};

var hasRequiredSetImmediate;

function requireSetImmediate () {
	if (hasRequiredSetImmediate) return setImmediate$1;
	hasRequiredSetImmediate = 1;

	Object.defineProperty(setImmediate$1, "__esModule", {
	    value: true
	});
	setImmediate$1.fallback = fallback;
	setImmediate$1.wrap = wrap;
	/* istanbul ignore file */

	var hasQueueMicrotask = setImmediate$1.hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask;
	var hasSetImmediate = setImmediate$1.hasSetImmediate = typeof setImmediate === 'function' && setImmediate;
	var hasNextTick = setImmediate$1.hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';

	function fallback(fn) {
	    setTimeout(fn, 0);
	}

	function wrap(defer) {
	    return (fn, ...args) => defer(() => fn(...args));
	}

	var _defer;

	if (hasQueueMicrotask) {
	    _defer = queueMicrotask;
	} else if (hasSetImmediate) {
	    _defer = setImmediate;
	} else if (hasNextTick) {
	    _defer = process.nextTick;
	} else {
	    _defer = fallback;
	}

	setImmediate$1.default = wrap(_defer);
	return setImmediate$1;
}

var hasRequiredAsyncify;

function requireAsyncify () {
	if (hasRequiredAsyncify) return asyncify.exports;
	hasRequiredAsyncify = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});
		exports$1.default = asyncify;

		var _initialParams = requireInitialParams();

		var _initialParams2 = _interopRequireDefault(_initialParams);

		var _setImmediate = requireSetImmediate();

		var _setImmediate2 = _interopRequireDefault(_setImmediate);

		var _wrapAsync = requireWrapAsync();

		function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

		/**
		 * Take a sync function and make it async, passing its return value to a
		 * callback. This is useful for plugging sync functions into a waterfall,
		 * series, or other async functions. Any arguments passed to the generated
		 * function will be passed to the wrapped function (except for the final
		 * callback argument). Errors thrown will be passed to the callback.
		 *
		 * If the function passed to `asyncify` returns a Promise, that promises's
		 * resolved/rejected state will be used to call the callback, rather than simply
		 * the synchronous return value.
		 *
		 * This also means you can asyncify ES2017 `async` functions.
		 *
		 * @name asyncify
		 * @static
		 * @memberOf module:Utils
		 * @method
		 * @alias wrapSync
		 * @category Util
		 * @param {Function} func - The synchronous function, or Promise-returning
		 * function to convert to an {@link AsyncFunction}.
		 * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be
		 * invoked with `(args..., callback)`.
		 * @example
		 *
		 * // passing a regular synchronous function
		 * async.waterfall([
		 *     async.apply(fs.readFile, filename, "utf8"),
		 *     async.asyncify(JSON.parse),
		 *     function (data, next) {
		 *         // data is the result of parsing the text.
		 *         // If there was a parsing error, it would have been caught.
		 *     }
		 * ], callback);
		 *
		 * // passing a function returning a promise
		 * async.waterfall([
		 *     async.apply(fs.readFile, filename, "utf8"),
		 *     async.asyncify(function (contents) {
		 *         return db.model.create(contents);
		 *     }),
		 *     function (model, next) {
		 *         // `model` is the instantiated model object.
		 *         // If there was an error, this function would be skipped.
		 *     }
		 * ], callback);
		 *
		 * // es2017 example, though `asyncify` is not needed if your JS environment
		 * // supports async functions out of the box
		 * var q = async.queue(async.asyncify(async function(file) {
		 *     var intermediateStep = await processFile(file);
		 *     return await somePromise(intermediateStep)
		 * }));
		 *
		 * q.push(files);
		 */
		function asyncify(func) {
		    if ((0, _wrapAsync.isAsync)(func)) {
		        return function (...args /*, callback*/) {
		            const callback = args.pop();
		            const promise = func.apply(this, args);
		            return handlePromise(promise, callback);
		        };
		    }

		    return (0, _initialParams2.default)(function (args, callback) {
		        var result;
		        try {
		            result = func.apply(this, args);
		        } catch (e) {
		            return callback(e);
		        }
		        // if result is Promise object
		        if (result && typeof result.then === 'function') {
		            return handlePromise(result, callback);
		        } else {
		            callback(null, result);
		        }
		    });
		}

		function handlePromise(promise, callback) {
		    return promise.then(value => {
		        invokeCallback(callback, null, value);
		    }, err => {
		        invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err));
		    });
		}

		function invokeCallback(callback, error, value) {
		    try {
		        callback(error, value);
		    } catch (err) {
		        (0, _setImmediate2.default)(e => {
		            throw e;
		        }, err);
		    }
		}
		module.exports = exports$1.default; 
	} (asyncify, asyncify.exports));
	return asyncify.exports;
}

var hasRequiredWrapAsync;

function requireWrapAsync () {
	if (hasRequiredWrapAsync) return wrapAsync;
	hasRequiredWrapAsync = 1;

	Object.defineProperty(wrapAsync, "__esModule", {
	    value: true
	});
	wrapAsync.isAsyncIterable = wrapAsync.isAsyncGenerator = wrapAsync.isAsync = undefined;

	var _asyncify = requireAsyncify();

	var _asyncify2 = _interopRequireDefault(_asyncify);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	function isAsync(fn) {
	    return fn[Symbol.toStringTag] === 'AsyncFunction';
	}

	function isAsyncGenerator(fn) {
	    return fn[Symbol.toStringTag] === 'AsyncGenerator';
	}

	function isAsyncIterable(obj) {
	    return typeof obj[Symbol.asyncIterator] === 'function';
	}

	function wrapAsync$1(asyncFn) {
	    if (typeof asyncFn !== 'function') throw new Error('expected a function');
	    return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn;
	}

	wrapAsync.default = wrapAsync$1;
	wrapAsync.isAsync = isAsync;
	wrapAsync.isAsyncGenerator = isAsyncGenerator;
	wrapAsync.isAsyncIterable = isAsyncIterable;
	return wrapAsync;
}

var awaitify = {exports: {}};

var hasRequiredAwaitify;

function requireAwaitify () {
	if (hasRequiredAwaitify) return awaitify.exports;
	hasRequiredAwaitify = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});
		exports$1.default = awaitify;
		// conditionally promisify a function.
		// only return a promise if a callback is omitted
		function awaitify(asyncFn, arity) {
		    if (!arity) arity = asyncFn.length;
		    if (!arity) throw new Error('arity is undefined');
		    function awaitable(...args) {
		        if (typeof args[arity - 1] === 'function') {
		            return asyncFn.apply(this, args);
		        }

		        return new Promise((resolve, reject) => {
		            args[arity - 1] = (err, ...cbArgs) => {
		                if (err) return reject(err);
		                resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);
		            };
		            asyncFn.apply(this, args);
		        });
		    }

		    return awaitable;
		}
		module.exports = exports$1.default; 
	} (awaitify, awaitify.exports));
	return awaitify.exports;
}

var hasRequiredParallel;

function requireParallel () {
	if (hasRequiredParallel) return parallel.exports;
	hasRequiredParallel = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});

		var _isArrayLike = requireIsArrayLike();

		var _isArrayLike2 = _interopRequireDefault(_isArrayLike);

		var _wrapAsync = requireWrapAsync();

		var _wrapAsync2 = _interopRequireDefault(_wrapAsync);

		var _awaitify = requireAwaitify();

		var _awaitify2 = _interopRequireDefault(_awaitify);

		function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

		exports$1.default = (0, _awaitify2.default)((eachfn, tasks, callback) => {
		    var results = (0, _isArrayLike2.default)(tasks) ? [] : {};

		    eachfn(tasks, (task, key, taskCb) => {
		        (0, _wrapAsync2.default)(task)((err, ...result) => {
		            if (result.length < 2) {
		                [result] = result;
		            }
		            results[key] = result;
		            taskCb(err);
		        });
		    }, err => callback(err, results));
		}, 3);
		module.exports = exports$1.default; 
	} (parallel, parallel.exports));
	return parallel.exports;
}

var eachOfSeries = {exports: {}};

var eachOfLimit$1 = {exports: {}};

var eachOfLimit = {exports: {}};

var once = {exports: {}};

var hasRequiredOnce;

function requireOnce () {
	if (hasRequiredOnce) return once.exports;
	hasRequiredOnce = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});
		exports$1.default = once;
		function once(fn) {
		    function wrapper(...args) {
		        if (fn === null) return;
		        var callFn = fn;
		        fn = null;
		        callFn.apply(this, args);
		    }
		    Object.assign(wrapper, fn);
		    return wrapper;
		}
		module.exports = exports$1.default; 
	} (once, once.exports));
	return once.exports;
}

var iterator = {exports: {}};

var getIterator = {exports: {}};

var hasRequiredGetIterator;

function requireGetIterator () {
	if (hasRequiredGetIterator) return getIterator.exports;
	hasRequiredGetIterator = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});

		exports$1.default = function (coll) {
		    return coll[Symbol.iterator] && coll[Symbol.iterator]();
		};

		module.exports = exports$1.default; 
	} (getIterator, getIterator.exports));
	return getIterator.exports;
}

var hasRequiredIterator;

function requireIterator () {
	if (hasRequiredIterator) return iterator.exports;
	hasRequiredIterator = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});
		exports$1.default = createIterator;

		var _isArrayLike = requireIsArrayLike();

		var _isArrayLike2 = _interopRequireDefault(_isArrayLike);

		var _getIterator = requireGetIterator();

		var _getIterator2 = _interopRequireDefault(_getIterator);

		function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

		function createArrayIterator(coll) {
		    var i = -1;
		    var len = coll.length;
		    return function next() {
		        return ++i < len ? { value: coll[i], key: i } : null;
		    };
		}

		function createES2015Iterator(iterator) {
		    var i = -1;
		    return function next() {
		        var item = iterator.next();
		        if (item.done) return null;
		        i++;
		        return { value: item.value, key: i };
		    };
		}

		function createObjectIterator(obj) {
		    var okeys = obj ? Object.keys(obj) : [];
		    var i = -1;
		    var len = okeys.length;
		    return function next() {
		        var key = okeys[++i];
		        if (key === '__proto__') {
		            return next();
		        }
		        return i < len ? { value: obj[key], key } : null;
		    };
		}

		function createIterator(coll) {
		    if ((0, _isArrayLike2.default)(coll)) {
		        return createArrayIterator(coll);
		    }

		    var iterator = (0, _getIterator2.default)(coll);
		    return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);
		}
		module.exports = exports$1.default; 
	} (iterator, iterator.exports));
	return iterator.exports;
}

var onlyOnce = {exports: {}};

var hasRequiredOnlyOnce;

function requireOnlyOnce () {
	if (hasRequiredOnlyOnce) return onlyOnce.exports;
	hasRequiredOnlyOnce = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});
		exports$1.default = onlyOnce;
		function onlyOnce(fn) {
		    return function (...args) {
		        if (fn === null) throw new Error("Callback was already called.");
		        var callFn = fn;
		        fn = null;
		        callFn.apply(this, args);
		    };
		}
		module.exports = exports$1.default; 
	} (onlyOnce, onlyOnce.exports));
	return onlyOnce.exports;
}

var asyncEachOfLimit = {exports: {}};

var breakLoop = {exports: {}};

var hasRequiredBreakLoop;

function requireBreakLoop () {
	if (hasRequiredBreakLoop) return breakLoop.exports;
	hasRequiredBreakLoop = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});
		// A temporary value used to identify if the loop should be broken.
		// See #1064, #1293
		const breakLoop = {};
		exports$1.default = breakLoop;
		module.exports = exports$1.default; 
	} (breakLoop, breakLoop.exports));
	return breakLoop.exports;
}

var hasRequiredAsyncEachOfLimit;

function requireAsyncEachOfLimit () {
	if (hasRequiredAsyncEachOfLimit) return asyncEachOfLimit.exports;
	hasRequiredAsyncEachOfLimit = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});
		exports$1.default = asyncEachOfLimit;

		var _breakLoop = requireBreakLoop();

		var _breakLoop2 = _interopRequireDefault(_breakLoop);

		function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

		// for async generators
		function asyncEachOfLimit(generator, limit, iteratee, callback) {
		    let done = false;
		    let canceled = false;
		    let awaiting = false;
		    let running = 0;
		    let idx = 0;

		    function replenish() {
		        //console.log('replenish')
		        if (running >= limit || awaiting || done) return;
		        //console.log('replenish awaiting')
		        awaiting = true;
		        generator.next().then(({ value, done: iterDone }) => {
		            //console.log('got value', value)
		            if (canceled || done) return;
		            awaiting = false;
		            if (iterDone) {
		                done = true;
		                if (running <= 0) {
		                    //console.log('done nextCb')
		                    callback(null);
		                }
		                return;
		            }
		            running++;
		            iteratee(value, idx, iterateeCallback);
		            idx++;
		            replenish();
		        }).catch(handleError);
		    }

		    function iterateeCallback(err, result) {
		        //console.log('iterateeCallback')
		        running -= 1;
		        if (canceled) return;
		        if (err) return handleError(err);

		        if (err === false) {
		            done = true;
		            canceled = true;
		            return;
		        }

		        if (result === _breakLoop2.default || done && running <= 0) {
		            done = true;
		            //console.log('done iterCb')
		            return callback(null);
		        }
		        replenish();
		    }

		    function handleError(err) {
		        if (canceled) return;
		        awaiting = false;
		        done = true;
		        callback(err);
		    }

		    replenish();
		}
		module.exports = exports$1.default; 
	} (asyncEachOfLimit, asyncEachOfLimit.exports));
	return asyncEachOfLimit.exports;
}

var hasRequiredEachOfLimit$1;

function requireEachOfLimit$1 () {
	if (hasRequiredEachOfLimit$1) return eachOfLimit.exports;
	hasRequiredEachOfLimit$1 = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});

		var _once = requireOnce();

		var _once2 = _interopRequireDefault(_once);

		var _iterator = requireIterator();

		var _iterator2 = _interopRequireDefault(_iterator);

		var _onlyOnce = requireOnlyOnce();

		var _onlyOnce2 = _interopRequireDefault(_onlyOnce);

		var _wrapAsync = requireWrapAsync();

		var _asyncEachOfLimit = requireAsyncEachOfLimit();

		var _asyncEachOfLimit2 = _interopRequireDefault(_asyncEachOfLimit);

		var _breakLoop = requireBreakLoop();

		var _breakLoop2 = _interopRequireDefault(_breakLoop);

		function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

		exports$1.default = limit => {
		    return (obj, iteratee, callback) => {
		        callback = (0, _once2.default)(callback);
		        if (limit <= 0) {
		            throw new RangeError('concurrency limit cannot be less than 1');
		        }
		        if (!obj) {
		            return callback(null);
		        }
		        if ((0, _wrapAsync.isAsyncGenerator)(obj)) {
		            return (0, _asyncEachOfLimit2.default)(obj, limit, iteratee, callback);
		        }
		        if ((0, _wrapAsync.isAsyncIterable)(obj)) {
		            return (0, _asyncEachOfLimit2.default)(obj[Symbol.asyncIterator](), limit, iteratee, callback);
		        }
		        var nextElem = (0, _iterator2.default)(obj);
		        var done = false;
		        var canceled = false;
		        var running = 0;
		        var looping = false;

		        function iterateeCallback(err, value) {
		            if (canceled) return;
		            running -= 1;
		            if (err) {
		                done = true;
		                callback(err);
		            } else if (err === false) {
		                done = true;
		                canceled = true;
		            } else if (value === _breakLoop2.default || done && running <= 0) {
		                done = true;
		                return callback(null);
		            } else if (!looping) {
		                replenish();
		            }
		        }

		        function replenish() {
		            looping = true;
		            while (running < limit && !done) {
		                var elem = nextElem();
		                if (elem === null) {
		                    done = true;
		                    if (running <= 0) {
		                        callback(null);
		                    }
		                    return;
		                }
		                running += 1;
		                iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback));
		            }
		            looping = false;
		        }

		        replenish();
		    };
		};

		module.exports = exports$1.default; 
	} (eachOfLimit, eachOfLimit.exports));
	return eachOfLimit.exports;
}

var hasRequiredEachOfLimit;

function requireEachOfLimit () {
	if (hasRequiredEachOfLimit) return eachOfLimit$1.exports;
	hasRequiredEachOfLimit = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});

		var _eachOfLimit2 = requireEachOfLimit$1();

		var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2);

		var _wrapAsync = requireWrapAsync();

		var _wrapAsync2 = _interopRequireDefault(_wrapAsync);

		var _awaitify = requireAwaitify();

		var _awaitify2 = _interopRequireDefault(_awaitify);

		function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

		/**
		 * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a
		 * time.
		 *
		 * @name eachOfLimit
		 * @static
		 * @memberOf module:Collections
		 * @method
		 * @see [async.eachOf]{@link module:Collections.eachOf}
		 * @alias forEachOfLimit
		 * @category Collection
		 * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
		 * @param {number} limit - The maximum number of async operations at a time.
		 * @param {AsyncFunction} iteratee - An async function to apply to each
		 * item in `coll`. The `key` is the item's key, or index in the case of an
		 * array.
		 * Invoked with (item, key, callback).
		 * @param {Function} [callback] - A callback which is called when all
		 * `iteratee` functions have finished, or an error occurs. Invoked with (err).
		 * @returns {Promise} a promise, if a callback is omitted
		 */
		function eachOfLimit(coll, limit, iteratee, callback) {
		    return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback);
		}

		exports$1.default = (0, _awaitify2.default)(eachOfLimit, 4);
		module.exports = exports$1.default; 
	} (eachOfLimit$1, eachOfLimit$1.exports));
	return eachOfLimit$1.exports;
}

var hasRequiredEachOfSeries;

function requireEachOfSeries () {
	if (hasRequiredEachOfSeries) return eachOfSeries.exports;
	hasRequiredEachOfSeries = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});

		var _eachOfLimit = requireEachOfLimit();

		var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);

		var _awaitify = requireAwaitify();

		var _awaitify2 = _interopRequireDefault(_awaitify);

		function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

		/**
		 * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.
		 *
		 * @name eachOfSeries
		 * @static
		 * @memberOf module:Collections
		 * @method
		 * @see [async.eachOf]{@link module:Collections.eachOf}
		 * @alias forEachOfSeries
		 * @category Collection
		 * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
		 * @param {AsyncFunction} iteratee - An async function to apply to each item in
		 * `coll`.
		 * Invoked with (item, key, callback).
		 * @param {Function} [callback] - A callback which is called when all `iteratee`
		 * functions have finished, or an error occurs. Invoked with (err).
		 * @returns {Promise} a promise, if a callback is omitted
		 */
		function eachOfSeries(coll, iteratee, callback) {
		    return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback);
		}
		exports$1.default = (0, _awaitify2.default)(eachOfSeries, 3);
		module.exports = exports$1.default; 
	} (eachOfSeries, eachOfSeries.exports));
	return eachOfSeries.exports;
}

var hasRequiredSeries;

function requireSeries () {
	if (hasRequiredSeries) return series.exports;
	hasRequiredSeries = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});
		exports$1.default = series;

		var _parallel2 = requireParallel();

		var _parallel3 = _interopRequireDefault(_parallel2);

		var _eachOfSeries = requireEachOfSeries();

		var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);

		function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

		/**
		 * Run the functions in the `tasks` collection in series, each one running once
		 * the previous function has completed. If any functions in the series pass an
		 * error to its callback, no more functions are run, and `callback` is
		 * immediately called with the value of the error. Otherwise, `callback`
		 * receives an array of results when `tasks` have completed.
		 *
		 * It is also possible to use an object instead of an array. Each property will
		 * be run as a function, and the results will be passed to the final `callback`
		 * as an object instead of an array. This can be a more readable way of handling
		 *  results from {@link async.series}.
		 *
		 * **Note** that while many implementations preserve the order of object
		 * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
		 * explicitly states that
		 *
		 * > The mechanics and order of enumerating the properties is not specified.
		 *
		 * So if you rely on the order in which your series of functions are executed,
		 * and want this to work on all platforms, consider using an array.
		 *
		 * @name series
		 * @static
		 * @memberOf module:ControlFlow
		 * @method
		 * @category Control Flow
		 * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing
		 * [async functions]{@link AsyncFunction} to run in series.
		 * Each function can complete with any number of optional `result` values.
		 * @param {Function} [callback] - An optional callback to run once all the
		 * functions have completed. This function gets a results array (or object)
		 * containing all the result arguments passed to the `task` callbacks. Invoked
		 * with (err, result).
		 * @return {Promise} a promise, if no callback is passed
		 * @example
		 *
		 * //Using Callbacks
		 * async.series([
		 *     function(callback) {
		 *         setTimeout(function() {
		 *             // do some async task
		 *             callback(null, 'one');
		 *         }, 200);
		 *     },
		 *     function(callback) {
		 *         setTimeout(function() {
		 *             // then do another async task
		 *             callback(null, 'two');
		 *         }, 100);
		 *     }
		 * ], function(err, results) {
		 *     console.log(results);
		 *     // results is equal to ['one','two']
		 * });
		 *
		 * // an example using objects instead of arrays
		 * async.series({
		 *     one: function(callback) {
		 *         setTimeout(function() {
		 *             // do some async task
		 *             callback(null, 1);
		 *         }, 200);
		 *     },
		 *     two: function(callback) {
		 *         setTimeout(function() {
		 *             // then do another async task
		 *             callback(null, 2);
		 *         }, 100);
		 *     }
		 * }, function(err, results) {
		 *     console.log(results);
		 *     // results is equal to: { one: 1, two: 2 }
		 * });
		 *
		 * //Using Promises
		 * async.series([
		 *     function(callback) {
		 *         setTimeout(function() {
		 *             callback(null, 'one');
		 *         }, 200);
		 *     },
		 *     function(callback) {
		 *         setTimeout(function() {
		 *             callback(null, 'two');
		 *         }, 100);
		 *     }
		 * ]).then(results => {
		 *     console.log(results);
		 *     // results is equal to ['one','two']
		 * }).catch(err => {
		 *     console.log(err);
		 * });
		 *
		 * // an example using an object instead of an array
		 * async.series({
		 *     one: function(callback) {
		 *         setTimeout(function() {
		 *             // do some async task
		 *             callback(null, 1);
		 *         }, 200);
		 *     },
		 *     two: function(callback) {
		 *         setTimeout(function() {
		 *             // then do another async task
		 *             callback(null, 2);
		 *         }, 100);
		 *     }
		 * }).then(results => {
		 *     console.log(results);
		 *     // results is equal to: { one: 1, two: 2 }
		 * }).catch(err => {
		 *     console.log(err);
		 * });
		 *
		 * //Using async/await
		 * async () => {
		 *     try {
		 *         let results = await async.series([
		 *             function(callback) {
		 *                 setTimeout(function() {
		 *                     // do some async task
		 *                     callback(null, 'one');
		 *                 }, 200);
		 *             },
		 *             function(callback) {
		 *                 setTimeout(function() {
		 *                     // then do another async task
		 *                     callback(null, 'two');
		 *                 }, 100);
		 *             }
		 *         ]);
		 *         console.log(results);
		 *         // results is equal to ['one','two']
		 *     }
		 *     catch (err) {
		 *         console.log(err);
		 *     }
		 * }
		 *
		 * // an example using an object instead of an array
		 * async () => {
		 *     try {
		 *         let results = await async.parallel({
		 *             one: function(callback) {
		 *                 setTimeout(function() {
		 *                     // do some async task
		 *                     callback(null, 1);
		 *                 }, 200);
		 *             },
		 *            two: function(callback) {
		 *                 setTimeout(function() {
		 *                     // then do another async task
		 *                     callback(null, 2);
		 *                 }, 100);
		 *            }
		 *         });
		 *         console.log(results);
		 *         // results is equal to: { one: 1, two: 2 }
		 *     }
		 *     catch (err) {
		 *         console.log(err);
		 *     }
		 * }
		 *
		 */
		function series(tasks, callback) {
		    return (0, _parallel3.default)(_eachOfSeries2.default, tasks, callback);
		}
		module.exports = exports$1.default; 
	} (series, series.exports));
	return series.exports;
}

var readableBrowser = {exports: {}};

var _stream_transform;
var hasRequired_stream_transform;

function require_stream_transform () {
	if (hasRequired_stream_transform) return _stream_transform;
	hasRequired_stream_transform = 1;

	_stream_transform = Transform;
	var _require$codes = requireErrorsBrowser().codes,
	  ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
	  ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
	  ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
	  ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
	var Duplex = require_stream_duplex();
	requireInherits_browser()(Transform, Duplex);
	function afterTransform(er, data) {
	  var ts = this._transformState;
	  ts.transforming = false;
	  var cb = ts.writecb;
	  if (cb === null) {
	    return this.emit('error', new ERR_MULTIPLE_CALLBACK());
	  }
	  ts.writechunk = null;
	  ts.writecb = null;
	  if (data != null)
	    // single equals check for both `null` and `undefined`
	    this.push(data);
	  cb(er);
	  var rs = this._readableState;
	  rs.reading = false;
	  if (rs.needReadable || rs.length < rs.highWaterMark) {
	    this._read(rs.highWaterMark);
	  }
	}
	function Transform(options) {
	  if (!(this instanceof Transform)) return new Transform(options);
	  Duplex.call(this, options);
	  this._transformState = {
	    afterTransform: afterTransform.bind(this),
	    needTransform: false,
	    transforming: false,
	    writecb: null,
	    writechunk: null,
	    writeencoding: null
	  };

	  // start out asking for a readable event once data is transformed.
	  this._readableState.needReadable = true;

	  // we have implemented the _read method, and done the other things
	  // that Readable wants before the first _read call, so unset the
	  // sync guard flag.
	  this._readableState.sync = false;
	  if (options) {
	    if (typeof options.transform === 'function') this._transform = options.transform;
	    if (typeof options.flush === 'function') this._flush = options.flush;
	  }

	  // When the writable side finishes, then flush out anything remaining.
	  this.on('prefinish', prefinish);
	}
	function prefinish() {
	  var _this = this;
	  if (typeof this._flush === 'function' && !this._readableState.destroyed) {
	    this._flush(function (er, data) {
	      done(_this, er, data);
	    });
	  } else {
	    done(this, null, null);
	  }
	}
	Transform.prototype.push = function (chunk, encoding) {
	  this._transformState.needTransform = false;
	  return Duplex.prototype.push.call(this, chunk, encoding);
	};

	// This is the part where you do stuff!
	// override this function in implementation classes.
	// 'chunk' is an input chunk.
	//
	// Call `push(newChunk)` to pass along transformed output
	// to the readable side.  You may call 'push' zero or more times.
	//
	// Call `cb(err)` when you are done with this chunk.  If you pass
	// an error, then that'll put the hurt on the whole operation.  If you
	// never call cb(), then you'll never get another chunk.
	Transform.prototype._transform = function (chunk, encoding, cb) {
	  cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
	};
	Transform.prototype._write = function (chunk, encoding, cb) {
	  var ts = this._transformState;
	  ts.writecb = cb;
	  ts.writechunk = chunk;
	  ts.writeencoding = encoding;
	  if (!ts.transforming) {
	    var rs = this._readableState;
	    if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
	  }
	};

	// Doesn't matter what the args are here.
	// _transform does all the work.
	// That we got here means that the readable side wants more data.
	Transform.prototype._read = function (n) {
	  var ts = this._transformState;
	  if (ts.writechunk !== null && !ts.transforming) {
	    ts.transforming = true;
	    this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
	  } else {
	    // mark that we need a transform, so that any data that comes in
	    // will get processed, now that we've asked for it.
	    ts.needTransform = true;
	  }
	};
	Transform.prototype._destroy = function (err, cb) {
	  Duplex.prototype._destroy.call(this, err, function (err2) {
	    cb(err2);
	  });
	};
	function done(stream, er, data) {
	  if (er) return stream.emit('error', er);
	  if (data != null)
	    // single equals check for both `null` and `undefined`
	    stream.push(data);

	  // TODO(BridgeAR): Write a test for these two error cases
	  // if there's nothing in the write buffer, then that means
	  // that nothing more will ever be provided
	  if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
	  if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
	  return stream.push(null);
	}
	return _stream_transform;
}

var _stream_passthrough;
var hasRequired_stream_passthrough;

function require_stream_passthrough () {
	if (hasRequired_stream_passthrough) return _stream_passthrough;
	hasRequired_stream_passthrough = 1;

	_stream_passthrough = PassThrough;
	var Transform = require_stream_transform();
	requireInherits_browser()(PassThrough, Transform);
	function PassThrough(options) {
	  if (!(this instanceof PassThrough)) return new PassThrough(options);
	  Transform.call(this, options);
	}
	PassThrough.prototype._transform = function (chunk, encoding, cb) {
	  cb(null, chunk);
	};
	return _stream_passthrough;
}

var pipeline_1;
var hasRequiredPipeline;

function requirePipeline () {
	if (hasRequiredPipeline) return pipeline_1;
	hasRequiredPipeline = 1;

	var eos;
	function once(callback) {
	  var called = false;
	  return function () {
	    if (called) return;
	    called = true;
	    callback.apply(void 0, arguments);
	  };
	}
	var _require$codes = requireErrorsBrowser().codes,
	  ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
	  ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
	function noop(err) {
	  // Rethrow the error if it exists to avoid swallowing it
	  if (err) throw err;
	}
	function isRequest(stream) {
	  return stream.setHeader && typeof stream.abort === 'function';
	}
	function destroyer(stream, reading, writing, callback) {
	  callback = once(callback);
	  var closed = false;
	  stream.on('close', function () {
	    closed = true;
	  });
	  if (eos === undefined) eos = requireEndOfStream();
	  eos(stream, {
	    readable: reading,
	    writable: writing
	  }, function (err) {
	    if (err) return callback(err);
	    closed = true;
	    callback();
	  });
	  var destroyed = false;
	  return function (err) {
	    if (closed) return;
	    if (destroyed) return;
	    destroyed = true;

	    // request.destroy just do .end - .abort is what we want
	    if (isRequest(stream)) return stream.abort();
	    if (typeof stream.destroy === 'function') return stream.destroy();
	    callback(err || new ERR_STREAM_DESTROYED('pipe'));
	  };
	}
	function call(fn) {
	  fn();
	}
	function pipe(from, to) {
	  return from.pipe(to);
	}
	function popCallback(streams) {
	  if (!streams.length) return noop;
	  if (typeof streams[streams.length - 1] !== 'function') return noop;
	  return streams.pop();
	}
	function pipeline() {
	  for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
	    streams[_key] = arguments[_key];
	  }
	  var callback = popCallback(streams);
	  if (Array.isArray(streams[0])) streams = streams[0];
	  if (streams.length < 2) {
	    throw new ERR_MISSING_ARGS('streams');
	  }
	  var error;
	  var destroys = streams.map(function (stream, i) {
	    var reading = i < streams.length - 1;
	    var writing = i > 0;
	    return destroyer(stream, reading, writing, function (err) {
	      if (!error) error = err;
	      if (err) destroys.forEach(call);
	      if (reading) return;
	      destroys.forEach(call);
	      callback(error);
	    });
	  });
	  return streams.reduce(pipe);
	}
	pipeline_1 = pipeline;
	return pipeline_1;
}

var hasRequiredReadableBrowser;

function requireReadableBrowser () {
	if (hasRequiredReadableBrowser) return readableBrowser.exports;
	hasRequiredReadableBrowser = 1;
	(function (module, exports$1) {
		exports$1 = module.exports = require_stream_readable();
		exports$1.Stream = exports$1;
		exports$1.Readable = exports$1;
		exports$1.Writable = require_stream_writable();
		exports$1.Duplex = require_stream_duplex();
		exports$1.Transform = require_stream_transform();
		exports$1.PassThrough = require_stream_passthrough();
		exports$1.finished = requireEndOfStream();
		exports$1.pipeline = requirePipeline(); 
	} (readableBrowser, readableBrowser.exports));
	return readableBrowser.exports;
}

var browser$1 = {exports: {}};

/**
 * Contains all configured adapters for the given environment.
 *
 * @type {Array}
 * @public
 */

var diagnostics;
var hasRequiredDiagnostics;

function requireDiagnostics () {
	if (hasRequiredDiagnostics) return diagnostics;
	hasRequiredDiagnostics = 1;
	var adapters = [];

	/**
	 * Contains all modifier functions.
	 *
	 * @typs {Array}
	 * @public
	 */
	var modifiers = [];

	/**
	 * Our default logger.
	 *
	 * @public
	 */
	var logger = function devnull() {};

	/**
	 * Register a new adapter that will used to find environments.
	 *
	 * @param {Function} adapter A function that will return the possible env.
	 * @returns {Boolean} Indication of a successful add.
	 * @public
	 */
	function use(adapter) {
	  if (~adapters.indexOf(adapter)) return false;

	  adapters.push(adapter);
	  return true;
	}

	/**
	 * Assign a new log method.
	 *
	 * @param {Function} custom The log method.
	 * @public
	 */
	function set(custom) {
	  logger = custom;
	}

	/**
	 * Check if the namespace is allowed by any of our adapters.
	 *
	 * @param {String} namespace The namespace that needs to be enabled
	 * @returns {Boolean|Promise} Indication if the namespace is enabled by our adapters.
	 * @public
	 */
	function enabled(namespace) {
	  var async = [];

	  for (var i = 0; i < adapters.length; i++) {
	    if (adapters[i].async) {
	      async.push(adapters[i]);
	      continue;
	    }

	    if (adapters[i](namespace)) return true;
	  }

	  if (!async.length) return false;

	  //
	  // Now that we know that we Async functions, we know we run in an ES6
	  // environment and can use all the API's that they offer, in this case
	  // we want to return a Promise so that we can `await` in React-Native
	  // for an async adapter.
	  //
	  return new Promise(function pinky(resolve) {
	    Promise.all(
	      async.map(function prebind(fn) {
	        return fn(namespace);
	      })
	    ).then(function resolved(values) {
	      resolve(values.some(Boolean));
	    });
	  });
	}

	/**
	 * Add a new message modifier to the debugger.
	 *
	 * @param {Function} fn Modification function.
	 * @returns {Boolean} Indication of a successful add.
	 * @public
	 */
	function modify(fn) {
	  if (~modifiers.indexOf(fn)) return false;

	  modifiers.push(fn);
	  return true;
	}

	/**
	 * Write data to the supplied logger.
	 *
	 * @param {Object} meta Meta information about the log.
	 * @param {Array} args Arguments for console.log.
	 * @public
	 */
	function write() {
	  logger.apply(logger, arguments);
	}

	/**
	 * Process the message with the modifiers.
	 *
	 * @param {Mixed} message The message to be transformed by modifers.
	 * @returns {String} Transformed message.
	 * @public
	 */
	function process(message) {
	  for (var i = 0; i < modifiers.length; i++) {
	    message = modifiers[i].apply(modifiers[i], arguments);
	  }

	  return message;
	}

	/**
	 * Introduce options to the logger function.
	 *
	 * @param {Function} fn Calback function.
	 * @param {Object} options Properties to introduce on fn.
	 * @returns {Function} The passed function
	 * @public
	 */
	function introduce(fn, options) {
	  var has = Object.prototype.hasOwnProperty;

	  for (var key in options) {
	    if (has.call(options, key)) {
	      fn[key] = options[key];
	    }
	  }

	  return fn;
	}

	/**
	 * Nope, we're not allowed to write messages.
	 *
	 * @returns {Boolean} false
	 * @public
	 */
	function nope(options) {
	  options.enabled = false;
	  options.modify = modify;
	  options.set = set;
	  options.use = use;

	  return introduce(function diagnopes() {
	    return false;
	  }, options);
	}

	/**
	 * Yep, we're allowed to write debug messages.
	 *
	 * @param {Object} options The options for the process.
	 * @returns {Function} The function that does the logging.
	 * @public
	 */
	function yep(options) {
	  /**
	   * The function that receives the actual debug information.
	   *
	   * @returns {Boolean} indication that we're logging.
	   * @public
	   */
	  function diagnostics() {
	    var args = Array.prototype.slice.call(arguments, 0);

	    write.call(write, options, process(args, options));
	    return true;
	  }

	  options.enabled = true;
	  options.modify = modify;
	  options.set = set;
	  options.use = use;

	  return introduce(diagnostics, options);
	}

	/**
	 * Simple helper function to introduce various of helper methods to our given
	 * diagnostics function.
	 *
	 * @param {Function} diagnostics The diagnostics function.
	 * @returns {Function} diagnostics
	 * @public
	 */
	diagnostics = function create(diagnostics) {
	  diagnostics.introduce = introduce;
	  diagnostics.enabled = enabled;
	  diagnostics.process = process;
	  diagnostics.modify = modify;
	  diagnostics.write = write;
	  diagnostics.nope = nope;
	  diagnostics.yep = yep;
	  diagnostics.set = set;
	  diagnostics.use = use;

	  return diagnostics;
	};
	return diagnostics;
}

var production;
var hasRequiredProduction;

function requireProduction () {
	if (hasRequiredProduction) return production;
	hasRequiredProduction = 1;
	var create = requireDiagnostics();

	/**
	 * Create a new diagnostics logger.
	 *
	 * @param {String} namespace The namespace it should enable.
	 * @param {Object} options Additional options.
	 * @returns {Function} The logger.
	 * @public
	 */
	var diagnostics = create(function prod(namespace, options) {
	  options = options || {};
	  options.namespace = namespace;
	  options.prod = true;
	  options.dev = false;

	  if (!(options.force || prod.force)) return prod.nope(options);
	  return prod.yep(options);
	});

	//
	// Expose the diagnostics logger.
	//
	production = diagnostics;
	return production;
}

var index_cjs;
var hasRequiredIndex_cjs;

function requireIndex_cjs () {
	if (hasRequiredIndex_cjs) return index_cjs;
	hasRequiredIndex_cjs = 1;

	var cssKeywords = {
		aliceblue: [240, 248, 255],
		antiquewhite: [250, 235, 215],
		aqua: [0, 255, 255],
		aquamarine: [127, 255, 212],
		azure: [240, 255, 255],
		beige: [245, 245, 220],
		bisque: [255, 228, 196],
		black: [0, 0, 0],
		blanchedalmond: [255, 235, 205],
		blue: [0, 0, 255],
		blueviolet: [138, 43, 226],
		brown: [165, 42, 42],
		burlywood: [222, 184, 135],
		cadetblue: [95, 158, 160],
		chartreuse: [127, 255, 0],
		chocolate: [210, 105, 30],
		coral: [255, 127, 80],
		cornflowerblue: [100, 149, 237],
		cornsilk: [255, 248, 220],
		crimson: [220, 20, 60],
		cyan: [0, 255, 255],
		darkblue: [0, 0, 139],
		darkcyan: [0, 139, 139],
		darkgoldenrod: [184, 134, 11],
		darkgray: [169, 169, 169],
		darkgreen: [0, 100, 0],
		darkgrey: [169, 169, 169],
		darkkhaki: [189, 183, 107],
		darkmagenta: [139, 0, 139],
		darkolivegreen: [85, 107, 47],
		darkorange: [255, 140, 0],
		darkorchid: [153, 50, 204],
		darkred: [139, 0, 0],
		darksalmon: [233, 150, 122],
		darkseagreen: [143, 188, 143],
		darkslateblue: [72, 61, 139],
		darkslategray: [47, 79, 79],
		darkslategrey: [47, 79, 79],
		darkturquoise: [0, 206, 209],
		darkviolet: [148, 0, 211],
		deeppink: [255, 20, 147],
		deepskyblue: [0, 191, 255],
		dimgray: [105, 105, 105],
		dimgrey: [105, 105, 105],
		dodgerblue: [30, 144, 255],
		firebrick: [178, 34, 34],
		floralwhite: [255, 250, 240],
		forestgreen: [34, 139, 34],
		fuchsia: [255, 0, 255],
		gainsboro: [220, 220, 220],
		ghostwhite: [248, 248, 255],
		gold: [255, 215, 0],
		goldenrod: [218, 165, 32],
		gray: [128, 128, 128],
		green: [0, 128, 0],
		greenyellow: [173, 255, 47],
		grey: [128, 128, 128],
		honeydew: [240, 255, 240],
		hotpink: [255, 105, 180],
		indianred: [205, 92, 92],
		indigo: [75, 0, 130],
		ivory: [255, 255, 240],
		khaki: [240, 230, 140],
		lavender: [230, 230, 250],
		lavenderblush: [255, 240, 245],
		lawngreen: [124, 252, 0],
		lemonchiffon: [255, 250, 205],
		lightblue: [173, 216, 230],
		lightcoral: [240, 128, 128],
		lightcyan: [224, 255, 255],
		lightgoldenrodyellow: [250, 250, 210],
		lightgray: [211, 211, 211],
		lightgreen: [144, 238, 144],
		lightgrey: [211, 211, 211],
		lightpink: [255, 182, 193],
		lightsalmon: [255, 160, 122],
		lightseagreen: [32, 178, 170],
		lightskyblue: [135, 206, 250],
		lightslategray: [119, 136, 153],
		lightslategrey: [119, 136, 153],
		lightsteelblue: [176, 196, 222],
		lightyellow: [255, 255, 224],
		lime: [0, 255, 0],
		limegreen: [50, 205, 50],
		linen: [250, 240, 230],
		magenta: [255, 0, 255],
		maroon: [128, 0, 0],
		mediumaquamarine: [102, 205, 170],
		mediumblue: [0, 0, 205],
		mediumorchid: [186, 85, 211],
		mediumpurple: [147, 112, 219],
		mediumseagreen: [60, 179, 113],
		mediumslateblue: [123, 104, 238],
		mediumspringgreen: [0, 250, 154],
		mediumturquoise: [72, 209, 204],
		mediumvioletred: [199, 21, 133],
		midnightblue: [25, 25, 112],
		mintcream: [245, 255, 250],
		mistyrose: [255, 228, 225],
		moccasin: [255, 228, 181],
		navajowhite: [255, 222, 173],
		navy: [0, 0, 128],
		oldlace: [253, 245, 230],
		olive: [128, 128, 0],
		olivedrab: [107, 142, 35],
		orange: [255, 165, 0],
		orangered: [255, 69, 0],
		orchid: [218, 112, 214],
		palegoldenrod: [238, 232, 170],
		palegreen: [152, 251, 152],
		paleturquoise: [175, 238, 238],
		palevioletred: [219, 112, 147],
		papayawhip: [255, 239, 213],
		peachpuff: [255, 218, 185],
		peru: [205, 133, 63],
		pink: [255, 192, 203],
		plum: [221, 160, 221],
		powderblue: [176, 224, 230],
		purple: [128, 0, 128],
		rebeccapurple: [102, 51, 153],
		red: [255, 0, 0],
		rosybrown: [188, 143, 143],
		royalblue: [65, 105, 225],
		saddlebrown: [139, 69, 19],
		salmon: [250, 128, 114],
		sandybrown: [244, 164, 96],
		seagreen: [46, 139, 87],
		seashell: [255, 245, 238],
		sienna: [160, 82, 45],
		silver: [192, 192, 192],
		skyblue: [135, 206, 235],
		slateblue: [106, 90, 205],
		slategray: [112, 128, 144],
		slategrey: [112, 128, 144],
		snow: [255, 250, 250],
		springgreen: [0, 255, 127],
		steelblue: [70, 130, 180],
		tan: [210, 180, 140],
		teal: [0, 128, 128],
		thistle: [216, 191, 216],
		tomato: [255, 99, 71],
		turquoise: [64, 224, 208],
		violet: [238, 130, 238],
		wheat: [245, 222, 179],
		white: [255, 255, 255],
		whitesmoke: [245, 245, 245],
		yellow: [255, 255, 0],
		yellowgreen: [154, 205, 50]
	};

	const reverseNames = Object.create(null);

	// Create a list of reverse color names
	for (const name in cssKeywords) {
		if (Object.hasOwn(cssKeywords, name)) {
			reverseNames[cssKeywords[name]] = name;
		}
	}

	const cs = {
		to: {},
		get: {},
	};

	cs.get = function (string) {
		const prefix = string.slice(0, 3).toLowerCase();
		let value;
		let model;
		switch (prefix) {
			case 'hsl': {
				value = cs.get.hsl(string);
				model = 'hsl';
				break;
			}

			case 'hwb': {
				value = cs.get.hwb(string);
				model = 'hwb';
				break;
			}

			default: {
				value = cs.get.rgb(string);
				model = 'rgb';
				break;
			}
		}

		if (!value) {
			return null;
		}

		return {model, value};
	};

	cs.get.rgb = function (string) {
		if (!string) {
			return null;
		}

		const abbr = /^#([a-f\d]{3,4})$/i;
		const hex = /^#([a-f\d]{6})([a-f\d]{2})?$/i;
		const rgba = /^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[\s,|/]\s*([+-]?[\d.]+)(%?)\s*)?\)$/;
		const per = /^rgba?\(\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[\s,|/]\s*([+-]?[\d.]+)(%?)\s*)?\)$/;
		const keyword = /^(\w+)$/;

		let rgb = [0, 0, 0, 1];
		let match;
		let i;
		let hexAlpha;

		if (match = string.match(hex)) {
			hexAlpha = match[2];
			match = match[1];

			for (i = 0; i < 3; i++) {
				// https://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/19
				const i2 = i * 2;
				rgb[i] = Number.parseInt(match.slice(i2, i2 + 2), 16);
			}

			if (hexAlpha) {
				rgb[3] = Number.parseInt(hexAlpha, 16) / 255;
			}
		} else if (match = string.match(abbr)) {
			match = match[1];
			hexAlpha = match[3];

			for (i = 0; i < 3; i++) {
				rgb[i] = Number.parseInt(match[i] + match[i], 16);
			}

			if (hexAlpha) {
				rgb[3] = Number.parseInt(hexAlpha + hexAlpha, 16) / 255;
			}
		} else if (match = string.match(rgba)) {
			for (i = 0; i < 3; i++) {
				rgb[i] = Number.parseInt(match[i + 1], 10);
			}

			if (match[4]) {
				rgb[3] = match[5] ? Number.parseFloat(match[4]) * 0.01 : Number.parseFloat(match[4]);
			}
		} else if (match = string.match(per)) {
			for (i = 0; i < 3; i++) {
				rgb[i] = Math.round(Number.parseFloat(match[i + 1]) * 2.55);
			}

			if (match[4]) {
				rgb[3] = match[5] ? Number.parseFloat(match[4]) * 0.01 : Number.parseFloat(match[4]);
			}
		} else if (match = string.match(keyword)) {
			if (match[1] === 'transparent') {
				return [0, 0, 0, 0];
			}

			if (!Object.hasOwn(cssKeywords, match[1])) {
				return null;
			}

			rgb = cssKeywords[match[1]];
			rgb[3] = 1;

			return rgb;
		} else {
			return null;
		}

		for (i = 0; i < 3; i++) {
			rgb[i] = clamp(rgb[i], 0, 255);
		}

		rgb[3] = clamp(rgb[3], 0, 1);

		return rgb;
	};

	cs.get.hsl = function (string) {
		if (!string) {
			return null;
		}

		const hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[,|/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/;
		const match = string.match(hsl);

		if (match) {
			const alpha = Number.parseFloat(match[4]);
			const h = ((Number.parseFloat(match[1]) % 360) + 360) % 360;
			const s = clamp(Number.parseFloat(match[2]), 0, 100);
			const l = clamp(Number.parseFloat(match[3]), 0, 100);
			const a = clamp(Number.isNaN(alpha) ? 1 : alpha, 0, 1);

			return [h, s, l, a];
		}

		return null;
	};

	cs.get.hwb = function (string) {
		if (!string) {
			return null;
		}

		const hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*[\s,]\s*([+-]?[\d.]+)%\s*[\s,]\s*([+-]?[\d.]+)%\s*(?:[\s,]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/;
		const match = string.match(hwb);

		if (match) {
			const alpha = Number.parseFloat(match[4]);
			const h = ((Number.parseFloat(match[1]) % 360) + 360) % 360;
			const w = clamp(Number.parseFloat(match[2]), 0, 100);
			const b = clamp(Number.parseFloat(match[3]), 0, 100);
			const a = clamp(Number.isNaN(alpha) ? 1 : alpha, 0, 1);
			return [h, w, b, a];
		}

		return null;
	};

	cs.to.hex = function (...rgba) {
		return (
			'#' +
			hexDouble(rgba[0]) +
			hexDouble(rgba[1]) +
			hexDouble(rgba[2]) +
			(rgba[3] < 1
				? (hexDouble(Math.round(rgba[3] * 255)))
				: '')
		);
	};

	cs.to.rgb = function (...rgba) {
		return rgba.length < 4 || rgba[3] === 1
			? 'rgb(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ')'
			: 'rgba(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ', ' + rgba[3] + ')';
	};

	cs.to.rgb.percent = function (...rgba) {
		const r = Math.round(rgba[0] / 255 * 100);
		const g = Math.round(rgba[1] / 255 * 100);
		const b = Math.round(rgba[2] / 255 * 100);

		return rgba.length < 4 || rgba[3] === 1
			? 'rgb(' + r + '%, ' + g + '%, ' + b + '%)'
			: 'rgba(' + r + '%, ' + g + '%, ' + b + '%, ' + rgba[3] + ')';
	};

	cs.to.hsl = function (...hsla) {
		return hsla.length < 4 || hsla[3] === 1
			? 'hsl(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%)'
			: 'hsla(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%, ' + hsla[3] + ')';
	};

	// Hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
	// (hwb have alpha optional & 1 is default value)
	cs.to.hwb = function (...hwba) {
		let a = '';
		if (hwba.length >= 4 && hwba[3] !== 1) {
			a = ', ' + hwba[3];
		}

		return 'hwb(' + hwba[0] + ', ' + hwba[1] + '%, ' + hwba[2] + '%' + a + ')';
	};

	cs.to.keyword = function (...rgb) {
		return reverseNames[rgb.slice(0, 3)];
	};

	// Helpers
	function clamp(number_, min, max) {
		return Math.min(Math.max(min, number_), max);
	}

	function hexDouble(number_) {
		const string_ = Math.round(number_).toString(16).toUpperCase();
		return (string_.length < 2) ? '0' + string_ : string_;
	}

	/* MIT license */
	/* eslint-disable no-mixed-operators */

	// NOTE: conversions should only return primitive values (i.e. arrays, or
	//       values that give correct `typeof` results).
	//       do not use box values types (i.e. Number(), String(), etc.)

	const reverseKeywords = {};
	for (const key of Object.keys(cssKeywords)) {
		reverseKeywords[cssKeywords[key]] = key;
	}

	const convert$1 = {
		rgb: {channels: 3, labels: 'rgb'},
		hsl: {channels: 3, labels: 'hsl'},
		hsv: {channels: 3, labels: 'hsv'},
		hwb: {channels: 3, labels: 'hwb'},
		cmyk: {channels: 4, labels: 'cmyk'},
		xyz: {channels: 3, labels: 'xyz'},
		lab: {channels: 3, labels: 'lab'},
		oklab: {channels: 3, labels: ['okl', 'oka', 'okb']},
		lch: {channels: 3, labels: 'lch'},
		oklch: {channels: 3, labels: ['okl', 'okc', 'okh']},
		hex: {channels: 1, labels: ['hex']},
		keyword: {channels: 1, labels: ['keyword']},
		ansi16: {channels: 1, labels: ['ansi16']},
		ansi256: {channels: 1, labels: ['ansi256']},
		hcg: {channels: 3, labels: ['h', 'c', 'g']},
		apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
		gray: {channels: 1, labels: ['gray']},
	};

	// LAB f(t) constant
	const LAB_FT = (6 / 29) ** 3;

	// SRGB non-linear transform functions
	function srgbNonlinearTransform(c) {
		const cc = c > 0.003_130_8
			? ((1.055 * (c ** (1 / 2.4))) - 0.055)
			: c * 12.92;
		return Math.min(Math.max(0, cc), 1);
	}

	function srgbNonlinearTransformInv(c) {
		return c > 0.040_45 ? (((c + 0.055) / 1.055) ** 2.4) : (c / 12.92);
	}

	// Hide .channels and .labels properties
	for (const model of Object.keys(convert$1)) {
		if (!('channels' in convert$1[model])) {
			throw new Error('missing channels property: ' + model);
		}

		if (!('labels' in convert$1[model])) {
			throw new Error('missing channel labels property: ' + model);
		}

		if (convert$1[model].labels.length !== convert$1[model].channels) {
			throw new Error('channel and label counts mismatch: ' + model);
		}

		const {channels, labels} = convert$1[model];
		delete convert$1[model].channels;
		delete convert$1[model].labels;
		Object.defineProperty(convert$1[model], 'channels', {value: channels});
		Object.defineProperty(convert$1[model], 'labels', {value: labels});
	}

	convert$1.rgb.hsl = function (rgb) {
		const r = rgb[0] / 255;
		const g = rgb[1] / 255;
		const b = rgb[2] / 255;
		const min = Math.min(r, g, b);
		const max = Math.max(r, g, b);
		const delta = max - min;
		let h;
		let s;

		switch (max) {
			case min: {
				h = 0;

				break;
			}

			case r: {
				h = (g - b) / delta;

				break;
			}

			case g: {
				h = 2 + (b - r) / delta;

				break;
			}

			case b: {
				h = 4 + (r - g) / delta;

				break;
			}
		// No default
		}

		h = Math.min(h * 60, 360);

		if (h < 0) {
			h += 360;
		}

		const l = (min + max) / 2;

		if (max === min) {
			s = 0;
		} else if (l <= 0.5) {
			s = delta / (max + min);
		} else {
			s = delta / (2 - max - min);
		}

		return [h, s * 100, l * 100];
	};

	convert$1.rgb.hsv = function (rgb) {
		let rdif;
		let gdif;
		let bdif;
		let h;
		let s;

		const r = rgb[0] / 255;
		const g = rgb[1] / 255;
		const b = rgb[2] / 255;
		const v = Math.max(r, g, b);
		const diff = v - Math.min(r, g, b);
		const diffc = function (c) {
			return (v - c) / 6 / diff + 1 / 2;
		};

		if (diff === 0) {
			h = 0;
			s = 0;
		} else {
			s = diff / v;
			rdif = diffc(r);
			gdif = diffc(g);
			bdif = diffc(b);

			switch (v) {
				case r: {
					h = bdif - gdif;

					break;
				}

				case g: {
					h = (1 / 3) + rdif - bdif;

					break;
				}

				case b: {
					h = (2 / 3) + gdif - rdif;

					break;
				}
			// No default
			}

			if (h < 0) {
				h += 1;
			} else if (h > 1) {
				h -= 1;
			}
		}

		return [
			h * 360,
			s * 100,
			v * 100,
		];
	};

	convert$1.rgb.hwb = function (rgb) {
		const r = rgb[0];
		const g = rgb[1];
		let b = rgb[2];
		const h = convert$1.rgb.hsl(rgb)[0];
		const w = 1 / 255 * Math.min(r, Math.min(g, b));

		b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));

		return [h, w * 100, b * 100];
	};

	convert$1.rgb.oklab = function (rgb) {
		// Assume sRGB
		const r = srgbNonlinearTransformInv(rgb[0] / 255);
		const g = srgbNonlinearTransformInv(rgb[1] / 255);
		const b = srgbNonlinearTransformInv(rgb[2] / 255);

		const lp = Math.cbrt(0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b);
		const mp = Math.cbrt(0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b);
		const sp = Math.cbrt(0.088_302_461_9 * r + 0.281_718_837_6 * g + 0.629_978_700_5 * b);

		const l = 0.210_454_255_3 * lp + 0.793_617_785 * mp - 0.004_072_046_8 * sp;
		const aa = 1.977_998_495_1 * lp - 2.428_592_205 * mp + 0.450_593_709_9 * sp;
		const bb = 0.025_904_037_1 * lp + 0.782_771_766_2 * mp - 0.808_675_766 * sp;

		return [l * 100, aa * 100, bb * 100];
	};

	convert$1.rgb.cmyk = function (rgb) {
		const r = rgb[0] / 255;
		const g = rgb[1] / 255;
		const b = rgb[2] / 255;

		const k = Math.min(1 - r, 1 - g, 1 - b);
		const c = (1 - r - k) / (1 - k) || 0;
		const m = (1 - g - k) / (1 - k) || 0;
		const y = (1 - b - k) / (1 - k) || 0;

		return [c * 100, m * 100, y * 100, k * 100];
	};

	function comparativeDistance(x, y) {
		/*
			See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
		*/
		return (
			((x[0] - y[0]) ** 2) +
			((x[1] - y[1]) ** 2) +
			((x[2] - y[2]) ** 2)
		);
	}

	convert$1.rgb.keyword = function (rgb) {
		const reversed = reverseKeywords[rgb];
		if (reversed) {
			return reversed;
		}

		let currentClosestDistance = Number.POSITIVE_INFINITY;
		let currentClosestKeyword;

		for (const keyword of Object.keys(cssKeywords)) {
			const value = cssKeywords[keyword];

			// Compute comparative distance
			const distance = comparativeDistance(rgb, value);

			// Check if its less, if so set as closest
			if (distance < currentClosestDistance) {
				currentClosestDistance = distance;
				currentClosestKeyword = keyword;
			}
		}

		return currentClosestKeyword;
	};

	convert$1.keyword.rgb = function (keyword) {
		return cssKeywords[keyword];
	};

	convert$1.rgb.xyz = function (rgb) {
		// Assume sRGB
		const r = srgbNonlinearTransformInv(rgb[0] / 255);
		const g = srgbNonlinearTransformInv(rgb[1] / 255);
		const b = srgbNonlinearTransformInv(rgb[2] / 255);

		const x = (r * 0.412_456_4) + (g * 0.357_576_1) + (b * 0.180_437_5);
		const y = (r * 0.212_672_9) + (g * 0.715_152_2) + (b * 0.072_175);
		const z = (r * 0.019_333_9) + (g * 0.119_192) + (b * 0.950_304_1);

		return [x * 100, y * 100, z * 100];
	};

	convert$1.rgb.lab = function (rgb) {
		const xyz = convert$1.rgb.xyz(rgb);
		let x = xyz[0];
		let y = xyz[1];
		let z = xyz[2];

		x /= 95.047;
		y /= 100;
		z /= 108.883;

		x = x > LAB_FT ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
		y = y > LAB_FT ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
		z = z > LAB_FT ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);

		const l = (116 * y) - 16;
		const a = 500 * (x - y);
		const b = 200 * (y - z);

		return [l, a, b];
	};

	convert$1.hsl.rgb = function (hsl) {
		const h = hsl[0] / 360;
		const s = hsl[1] / 100;
		const l = hsl[2] / 100;
		let t3;
		let value;

		if (s === 0) {
			value = l * 255;
			return [value, value, value];
		}

		const t2 = l < 0.5 ? l * (1 + s) : l + s - l * s;

		const t1 = 2 * l - t2;

		const rgb = [0, 0, 0];
		for (let i = 0; i < 3; i++) {
			t3 = h + 1 / 3 * -(i - 1);
			if (t3 < 0) {
				t3++;
			}

			if (t3 > 1) {
				t3--;
			}

			if (6 * t3 < 1) {
				value = t1 + (t2 - t1) * 6 * t3;
			} else if (2 * t3 < 1) {
				value = t2;
			} else if (3 * t3 < 2) {
				value = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
			} else {
				value = t1;
			}

			rgb[i] = value * 255;
		}

		return rgb;
	};

	convert$1.hsl.hsv = function (hsl) {
		const h = hsl[0];
		let s = hsl[1] / 100;
		let l = hsl[2] / 100;
		let smin = s;
		const lmin = Math.max(l, 0.01);

		l *= 2;
		s *= (l <= 1) ? l : 2 - l;
		smin *= lmin <= 1 ? lmin : 2 - lmin;
		const v = (l + s) / 2;
		const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);

		return [h, sv * 100, v * 100];
	};

	convert$1.hsv.rgb = function (hsv) {
		const h = hsv[0] / 60;
		const s = hsv[1] / 100;
		let v = hsv[2] / 100;
		const hi = Math.floor(h) % 6;

		const f = h - Math.floor(h);
		const p = 255 * v * (1 - s);
		const q = 255 * v * (1 - (s * f));
		const t = 255 * v * (1 - (s * (1 - f)));
		v *= 255;

		switch (hi) {
			case 0: {
				return [v, t, p];
			}

			case 1: {
				return [q, v, p];
			}

			case 2: {
				return [p, v, t];
			}

			case 3: {
				return [p, q, v];
			}

			case 4: {
				return [t, p, v];
			}

			case 5: {
				return [v, p, q];
			}
		}
	};

	convert$1.hsv.hsl = function (hsv) {
		const h = hsv[0];
		const s = hsv[1] / 100;
		const v = hsv[2] / 100;
		const vmin = Math.max(v, 0.01);
		let sl;
		let l;

		l = (2 - s) * v;
		const lmin = (2 - s) * vmin;
		sl = s * vmin;
		sl /= (lmin <= 1) ? lmin : 2 - lmin;
		sl = sl || 0;
		l /= 2;

		return [h, sl * 100, l * 100];
	};

	// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
	convert$1.hwb.rgb = function (hwb) {
		const h = hwb[0] / 360;
		let wh = hwb[1] / 100;
		let bl = hwb[2] / 100;
		const ratio = wh + bl;
		let f;

		// Wh + bl cant be > 1
		if (ratio > 1) {
			wh /= ratio;
			bl /= ratio;
		}

		const i = Math.floor(6 * h);
		const v = 1 - bl;
		f = 6 * h - i;

		// eslint-disable-next-line no-bitwise
		if ((i & 0x01) !== 0) {
			f = 1 - f;
		}

		const n = wh + f * (v - wh); // Linear interpolation

		let r;
		let g;
		let b;
		/* eslint-disable max-statements-per-line,no-multi-spaces, default-case-last */
		switch (i) {
			default:
			case 6:
			case 0: { r = v;  g = n;  b = wh; break;
			}

			case 1: { r = n;  g = v;  b = wh; break;
			}

			case 2: { r = wh; g = v;  b = n; break;
			}

			case 3: { r = wh; g = n;  b = v; break;
			}

			case 4: { r = n;  g = wh; b = v; break;
			}

			case 5: { r = v;  g = wh; b = n; break;
			}
		}
		/* eslint-enable max-statements-per-line,no-multi-spaces, default-case-last */

		return [r * 255, g * 255, b * 255];
	};

	convert$1.cmyk.rgb = function (cmyk) {
		const c = cmyk[0] / 100;
		const m = cmyk[1] / 100;
		const y = cmyk[2] / 100;
		const k = cmyk[3] / 100;

		const r = 1 - Math.min(1, c * (1 - k) + k);
		const g = 1 - Math.min(1, m * (1 - k) + k);
		const b = 1 - Math.min(1, y * (1 - k) + k);

		return [r * 255, g * 255, b * 255];
	};

	convert$1.xyz.rgb = function (xyz) {
		const x = xyz[0] / 100;
		const y = xyz[1] / 100;
		const z = xyz[2] / 100;
		let r;
		let g;
		let b;

		r = (x * 3.240_454_2) + (y * -1.5371385) + (z * -0.4985314);
		g = (x * -0.969266) + (y * 1.876_010_8) + (z * 0.041_556);
		b = (x * 0.055_643_4) + (y * -0.2040259) + (z * 1.057_225_2);

		// Assume sRGB
		r = srgbNonlinearTransform(r);
		g = srgbNonlinearTransform(g);
		b = srgbNonlinearTransform(b);

		return [r * 255, g * 255, b * 255];
	};

	convert$1.xyz.lab = function (xyz) {
		let x = xyz[0];
		let y = xyz[1];
		let z = xyz[2];

		x /= 95.047;
		y /= 100;
		z /= 108.883;

		x = x > LAB_FT ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
		y = y > LAB_FT ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
		z = z > LAB_FT ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);

		const l = (116 * y) - 16;
		const a = 500 * (x - y);
		const b = 200 * (y - z);

		return [l, a, b];
	};

	convert$1.xyz.oklab = function (xyz) {
		const x = xyz[0] / 100;
		const y = xyz[1] / 100;
		const z = xyz[2] / 100;

		const lp = Math.cbrt(0.818_933_010_1 * x + 0.361_866_742_4 * y - 0.128_859_713_7 * z);
		const mp = Math.cbrt(0.032_984_543_6 * x + 0.929_311_871_5 * y + 0.036_145_638_7 * z);
		const sp = Math.cbrt(0.048_200_301_8 * x + 0.264_366_269_1 * y + 0.633_851_707 * z);

		const l = 0.210_454_255_3 * lp + 0.793_617_785 * mp - 0.004_072_046_8 * sp;
		const a = 1.977_998_495_1 * lp - 2.428_592_205 * mp + 0.450_593_709_9 * sp;
		const b = 0.025_904_037_1 * lp + 0.782_771_766_2 * mp - 0.808_675_766 * sp;

		return [l * 100, a * 100, b * 100];
	};

	convert$1.oklab.oklch = function (oklab) {
		return convert$1.lab.lch(oklab);
	};

	convert$1.oklab.xyz = function (oklab) {
		const ll = oklab[0] / 100;
		const a = oklab[1] / 100;
		const b = oklab[2] / 100;

		const l = (0.999_999_998 * ll + 0.396_337_792 * a + 0.215_803_758 * b) ** 3;
		const m = (1.000_000_008 * ll - 0.105_561_342 * a - 0.063_854_175 * b) ** 3;
		const s = (1.000_000_055 * ll - 0.089_484_182 * a - 1.291_485_538 * b) ** 3;

		const x = 1.227_013_851 * l - 0.557_799_98 * m + 0.281_256_149 * s;
		const y = -0.040580178 * l + 1.112_256_87 * m - 0.071_676_679 * s;
		const z = -0.076381285 * l - 0.421_481_978 * m + 1.586_163_22 * s;

		return [x * 100, y * 100, z * 100];
	};

	convert$1.oklab.rgb = function (oklab) {
		const ll = oklab[0] / 100;
		const aa = oklab[1] / 100;
		const bb = oklab[2] / 100;

		const l = (ll + 0.396_337_777_4 * aa + 0.215_803_757_3 * bb) ** 3;
		const m = (ll - 0.105_561_345_8 * aa - 0.063_854_172_8 * bb) ** 3;
		const s = (ll - 0.089_484_177_5 * aa - 1.291_485_548 * bb) ** 3;

		// Assume sRGB
		const r = srgbNonlinearTransform(4.076_741_662_1 * l - 3.307_711_591_3 * m + 0.230_969_929_2 * s);
		const g = srgbNonlinearTransform(-1.2684380046 * l + 2.609_757_401_1 * m - 0.341_319_396_5 * s);
		const b = srgbNonlinearTransform(-0.0041960863 * l - 0.703_418_614_7 * m + 1.707_614_701 * s);

		return [r * 255, g * 255, b * 255];
	};

	convert$1.oklch.oklab = function (oklch) {
		return convert$1.lch.lab(oklch);
	};

	convert$1.lab.xyz = function (lab) {
		const l = lab[0];
		const a = lab[1];
		const b = lab[2];
		let x;
		let y;
		let z;

		y = (l + 16) / 116;
		x = a / 500 + y;
		z = y - b / 200;

		const y2 = y ** 3;
		const x2 = x ** 3;
		const z2 = z ** 3;
		y = y2 > LAB_FT ? y2 : (y - 16 / 116) / 7.787;
		x = x2 > LAB_FT ? x2 : (x - 16 / 116) / 7.787;
		z = z2 > LAB_FT ? z2 : (z - 16 / 116) / 7.787;

		// Illuminant D65 XYZ Tristrimulus Values
		// https://en.wikipedia.org/wiki/CIE_1931_color_space
		x *= 95.047;
		y *= 100;
		z *= 108.883;

		return [x, y, z];
	};

	convert$1.lab.lch = function (lab) {
		const l = lab[0];
		const a = lab[1];
		const b = lab[2];
		let h;

		const hr = Math.atan2(b, a);
		h = hr * 360 / 2 / Math.PI;

		if (h < 0) {
			h += 360;
		}

		const c = Math.sqrt(a * a + b * b);

		return [l, c, h];
	};

	convert$1.lch.lab = function (lch) {
		const l = lch[0];
		const c = lch[1];
		const h = lch[2];

		const hr = h / 360 * 2 * Math.PI;
		const a = c * Math.cos(hr);
		const b = c * Math.sin(hr);

		return [l, a, b];
	};

	convert$1.rgb.ansi16 = function (args, saturation = null) {
		const [r, g, b] = args;
		let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization

		value = Math.round(value / 50);

		if (value === 0) {
			return 30;
		}

		let ansi = 30
			/* eslint-disable no-bitwise */
			+ ((Math.round(b / 255) << 2)
			| (Math.round(g / 255) << 1)
			| Math.round(r / 255));
			/* eslint-enable no-bitwise */

		if (value === 2) {
			ansi += 60;
		}

		return ansi;
	};

	convert$1.hsv.ansi16 = function (args) {
		// Optimization here; we already know the value and don't need to get
		// it converted for us.
		return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]);
	};

	convert$1.rgb.ansi256 = function (args) {
		const r = args[0];
		const g = args[1];
		const b = args[2];

		// We use the extended greyscale palette here, with the exception of
		// black and white. normal palette only has 4 greyscale shades.
		// eslint-disable-next-line no-bitwise
		if (r >> 4 === g >> 4 && g >> 4 === b >> 4) {
			if (r < 8) {
				return 16;
			}

			if (r > 248) {
				return 231;
			}

			return Math.round(((r - 8) / 247) * 24) + 232;
		}

		const ansi = 16
			+ (36 * Math.round(r / 255 * 5))
			+ (6 * Math.round(g / 255 * 5))
			+ Math.round(b / 255 * 5);

		return ansi;
	};

	convert$1.ansi16.rgb = function (args) {
		args = args[0];

		let color = args % 10;

		// Handle greyscale
		if (color === 0 || color === 7) {
			if (args > 50) {
				color += 3.5;
			}

			color = color / 10.5 * 255;

			return [color, color, color];
		}

		const mult = (Math.trunc(args > 50) + 1) * 0.5;
		/* eslint-disable no-bitwise */
		const r = ((color & 1) * mult) * 255;
		const g = (((color >> 1) & 1) * mult) * 255;
		const b = (((color >> 2) & 1) * mult) * 255;
		/* eslint-enable no-bitwise */

		return [r, g, b];
	};

	convert$1.ansi256.rgb = function (args) {
		args = args[0];

		// Handle greyscale
		if (args >= 232) {
			const c = (args - 232) * 10 + 8;
			return [c, c, c];
		}

		args -= 16;

		let rem;
		const r = Math.floor(args / 36) / 5 * 255;
		const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
		const b = (rem % 6) / 5 * 255;

		return [r, g, b];
	};

	convert$1.rgb.hex = function (args) {
		/* eslint-disable no-bitwise */
		const integer = ((Math.round(args[0]) & 0xFF) << 16)
			+ ((Math.round(args[1]) & 0xFF) << 8)
			+ (Math.round(args[2]) & 0xFF);
		/* eslint-enable no-bitwise */

		const string = integer.toString(16).toUpperCase();
		return '000000'.slice(string.length) + string;
	};

	convert$1.hex.rgb = function (args) {
		const match = args.toString(16).match(/[a-f\d]{6}|[a-f\d]{3}/i);
		if (!match) {
			return [0, 0, 0];
		}

		let colorString = match[0];

		if (match[0].length === 3) {
			colorString = [...colorString].map(char => char + char).join('');
		}

		const integer = Number.parseInt(colorString, 16);
		/* eslint-disable no-bitwise */
		const r = (integer >> 16) & 0xFF;
		const g = (integer >> 8) & 0xFF;
		const b = integer & 0xFF;
		/* eslint-enable no-bitwise */

		return [r, g, b];
	};

	convert$1.rgb.hcg = function (rgb) {
		const r = rgb[0] / 255;
		const g = rgb[1] / 255;
		const b = rgb[2] / 255;
		const max = Math.max(Math.max(r, g), b);
		const min = Math.min(Math.min(r, g), b);
		const chroma = (max - min);
		let hue;

		const grayscale = chroma < 1 ? min / (1 - chroma) : 0;

		if (chroma <= 0) {
			hue = 0;
		} else if (max === r) {
			hue = ((g - b) / chroma) % 6;
		} else if (max === g) {
			hue = 2 + (b - r) / chroma;
		} else {
			hue = 4 + (r - g) / chroma;
		}

		hue /= 6;
		hue %= 1;

		return [hue * 360, chroma * 100, grayscale * 100];
	};

	convert$1.hsl.hcg = function (hsl) {
		const s = hsl[1] / 100;
		const l = hsl[2] / 100;

		const c = l < 0.5 ? (2 * s * l) : (2 * s * (1 - l));

		let f = 0;
		if (c < 1) {
			f = (l - 0.5 * c) / (1 - c);
		}

		return [hsl[0], c * 100, f * 100];
	};

	convert$1.hsv.hcg = function (hsv) {
		const s = hsv[1] / 100;
		const v = hsv[2] / 100;

		const c = s * v;
		let f = 0;

		if (c < 1) {
			f = (v - c) / (1 - c);
		}

		return [hsv[0], c * 100, f * 100];
	};

	convert$1.hcg.rgb = function (hcg) {
		const h = hcg[0] / 360;
		const c = hcg[1] / 100;
		const g = hcg[2] / 100;

		if (c === 0) {
			return [g * 255, g * 255, g * 255];
		}

		const pure = [0, 0, 0];
		const hi = (h % 1) * 6;
		const v = hi % 1;
		const w = 1 - v;
		let mg = 0;

		/* eslint-disable max-statements-per-line */
		switch (Math.floor(hi)) {
			case 0: {
				pure[0] = 1; pure[1] = v; pure[2] = 0; break;
			}

			case 1: {
				pure[0] = w; pure[1] = 1; pure[2] = 0; break;
			}

			case 2: {
				pure[0] = 0; pure[1] = 1; pure[2] = v; break;
			}

			case 3: {
				pure[0] = 0; pure[1] = w; pure[2] = 1; break;
			}

			case 4: {
				pure[0] = v; pure[1] = 0; pure[2] = 1; break;
			}

			default: {
				pure[0] = 1; pure[1] = 0; pure[2] = w;
			}
		}
		/* eslint-enable max-statements-per-line */

		mg = (1 - c) * g;

		return [
			(c * pure[0] + mg) * 255,
			(c * pure[1] + mg) * 255,
			(c * pure[2] + mg) * 255,
		];
	};

	convert$1.hcg.hsv = function (hcg) {
		const c = hcg[1] / 100;
		const g = hcg[2] / 100;

		const v = c + g * (1 - c);
		let f = 0;

		if (v > 0) {
			f = c / v;
		}

		return [hcg[0], f * 100, v * 100];
	};

	convert$1.hcg.hsl = function (hcg) {
		const c = hcg[1] / 100;
		const g = hcg[2] / 100;

		const l = g * (1 - c) + 0.5 * c;
		let s = 0;

		if (l > 0 && l < 0.5) {
			s = c / (2 * l);
		} else if (l >= 0.5 && l < 1) {
			s = c / (2 * (1 - l));
		}

		return [hcg[0], s * 100, l * 100];
	};

	convert$1.hcg.hwb = function (hcg) {
		const c = hcg[1] / 100;
		const g = hcg[2] / 100;
		const v = c + g * (1 - c);
		return [hcg[0], (v - c) * 100, (1 - v) * 100];
	};

	convert$1.hwb.hcg = function (hwb) {
		const w = hwb[1] / 100;
		const b = hwb[2] / 100;
		const v = 1 - b;
		const c = v - w;
		let g = 0;

		if (c < 1) {
			g = (v - c) / (1 - c);
		}

		return [hwb[0], c * 100, g * 100];
	};

	convert$1.apple.rgb = function (apple) {
		return [(apple[0] / 65_535) * 255, (apple[1] / 65_535) * 255, (apple[2] / 65_535) * 255];
	};

	convert$1.rgb.apple = function (rgb) {
		return [(rgb[0] / 255) * 65_535, (rgb[1] / 255) * 65_535, (rgb[2] / 255) * 65_535];
	};

	convert$1.gray.rgb = function (args) {
		return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
	};

	convert$1.gray.hsl = function (args) {
		return [0, 0, args[0]];
	};

	convert$1.gray.hsv = convert$1.gray.hsl;

	convert$1.gray.hwb = function (gray) {
		return [0, 100, gray[0]];
	};

	convert$1.gray.cmyk = function (gray) {
		return [0, 0, 0, gray[0]];
	};

	convert$1.gray.lab = function (gray) {
		return [gray[0], 0, 0];
	};

	convert$1.gray.hex = function (gray) {
		/* eslint-disable no-bitwise */
		const value = Math.round(gray[0] / 100 * 255) & 0xFF;
		const integer = (value << 16) + (value << 8) + value;
		/* eslint-enable no-bitwise */

		const string = integer.toString(16).toUpperCase();
		return '000000'.slice(string.length) + string;
	};

	convert$1.rgb.gray = function (rgb) {
		const value = (rgb[0] + rgb[1] + rgb[2]) / 3;
		return [value / 255 * 100];
	};

	/*
		This function routes a model to all other models.

		all functions that are routed have a property `.conversion` attached
		to the returned synthetic function. This property is an array
		of strings, each with the steps in between the 'from' and 'to'
		color models (inclusive).

		conversions that are not possible simply are not included.
	*/

	function buildGraph() {
		const graph = {};
		// https://jsperf.com/object-keys-vs-for-in-with-closure/3
		const models = Object.keys(convert$1);

		for (let {length} = models, i = 0; i < length; i++) {
			graph[models[i]] = {
				// http://jsperf.com/1-vs-infinity
				// micro-opt, but this is simple.
				distance: -1,
				parent: null,
			};
		}

		return graph;
	}

	// https://en.wikipedia.org/wiki/Breadth-first_search
	function deriveBFS(fromModel) {
		const graph = buildGraph();
		const queue = [fromModel]; // Unshift -> queue -> pop

		graph[fromModel].distance = 0;

		while (queue.length > 0) {
			const current = queue.pop();
			const adjacents = Object.keys(convert$1[current]);

			for (let {length} = adjacents, i = 0; i < length; i++) {
				const adjacent = adjacents[i];
				const node = graph[adjacent];

				if (node.distance === -1) {
					node.distance = graph[current].distance + 1;
					node.parent = current;
					queue.unshift(adjacent);
				}
			}
		}

		return graph;
	}

	function link(from, to) {
		return function (args) {
			return to(from(args));
		};
	}

	function wrapConversion(toModel, graph) {
		const path = [graph[toModel].parent, toModel];
		let fn = convert$1[graph[toModel].parent][toModel];

		let cur = graph[toModel].parent;
		while (graph[cur].parent) {
			path.unshift(graph[cur].parent);
			fn = link(convert$1[graph[cur].parent][cur], fn);
			cur = graph[cur].parent;
		}

		fn.conversion = path;
		return fn;
	}

	function route(fromModel) {
		const graph = deriveBFS(fromModel);
		const conversion = {};

		const models = Object.keys(graph);
		for (let {length} = models, i = 0; i < length; i++) {
			const toModel = models[i];
			const node = graph[toModel];

			if (node.parent === null) {
				// No possible conversion, or this node is the source model.
				continue;
			}

			conversion[toModel] = wrapConversion(toModel, graph);
		}

		return conversion;
	}

	const convert = {};

	const models = Object.keys(convert$1);

	function wrapRaw(fn) {
		const wrappedFn = function (...args) {
			const arg0 = args[0];
			if (arg0 === undefined || arg0 === null) {
				return arg0;
			}

			if (arg0.length > 1) {
				args = arg0;
			}

			return fn(args);
		};

		// Preserve .conversion property if there is one
		if ('conversion' in fn) {
			wrappedFn.conversion = fn.conversion;
		}

		return wrappedFn;
	}

	function wrapRounded(fn) {
		const wrappedFn = function (...args) {
			const arg0 = args[0];

			if (arg0 === undefined || arg0 === null) {
				return arg0;
			}

			if (arg0.length > 1) {
				args = arg0;
			}

			const result = fn(args);

			// We're assuming the result is an array here.
			// see notice in conversions.js; don't use box types
			// in conversion functions.
			if (typeof result === 'object') {
				for (let {length} = result, i = 0; i < length; i++) {
					result[i] = Math.round(result[i]);
				}
			}

			return result;
		};

		// Preserve .conversion property if there is one
		if ('conversion' in fn) {
			wrappedFn.conversion = fn.conversion;
		}

		return wrappedFn;
	}

	for (const fromModel of models) {
		convert[fromModel] = {};

		Object.defineProperty(convert[fromModel], 'channels', {value: convert$1[fromModel].channels});
		Object.defineProperty(convert[fromModel], 'labels', {value: convert$1[fromModel].labels});

		const routes = route(fromModel);
		const routeModels = Object.keys(routes);

		for (const toModel of routeModels) {
			const fn = routes[toModel];

			convert[fromModel][toModel] = wrapRounded(fn);
			convert[fromModel][toModel].raw = wrapRaw(fn);
		}
	}

	const skippedModels = [
		// To be honest, I don't really feel like keyword belongs in color convert, but eh.
		'keyword',

		// Gray conflicts with some method names, and has its own method defined.
		'gray',

		// Shouldn't really be in color-convert either...
		'hex',
	];

	const hashedModelKeys = {};
	for (const model of Object.keys(convert)) {
		hashedModelKeys[[...convert[model].labels].sort().join('')] = model;
	}

	const limiters = {};

	function Color(object, model) {
		if (!(this instanceof Color)) {
			return new Color(object, model);
		}

		if (model && model in skippedModels) {
			model = null;
		}

		if (model && !(model in convert)) {
			throw new Error('Unknown model: ' + model);
		}

		let i;
		let channels;

		if (object == null) { // eslint-disable-line no-eq-null,eqeqeq
			this.model = 'rgb';
			this.color = [0, 0, 0];
			this.valpha = 1;
		} else if (object instanceof Color) {
			this.model = object.model;
			this.color = [...object.color];
			this.valpha = object.valpha;
		} else if (typeof object === 'string') {
			const result = cs.get(object);
			if (result === null) {
				throw new Error('Unable to parse color from string: ' + object);
			}

			this.model = result.model;
			channels = convert[this.model].channels;
			this.color = result.value.slice(0, channels);
			this.valpha = typeof result.value[channels] === 'number' ? result.value[channels] : 1;
		} else if (object.length > 0) {
			this.model = model || 'rgb';
			channels = convert[this.model].channels;
			const newArray = Array.prototype.slice.call(object, 0, channels);
			this.color = zeroArray(newArray, channels);
			this.valpha = typeof object[channels] === 'number' ? object[channels] : 1;
		} else if (typeof object === 'number') {
			// This is always RGB - can be converted later on.
			this.model = 'rgb';
			this.color = [
				(object >> 16) & 0xFF,
				(object >> 8) & 0xFF,
				object & 0xFF,
			];
			this.valpha = 1;
		} else {
			this.valpha = 1;

			const keys = Object.keys(object);
			if ('alpha' in object) {
				keys.splice(keys.indexOf('alpha'), 1);
				this.valpha = typeof object.alpha === 'number' ? object.alpha : 0;
			}

			const hashedKeys = keys.sort().join('');
			if (!(hashedKeys in hashedModelKeys)) {
				throw new Error('Unable to parse color from object: ' + JSON.stringify(object));
			}

			this.model = hashedModelKeys[hashedKeys];

			const {labels} = convert[this.model];
			const color = [];
			for (i = 0; i < labels.length; i++) {
				color.push(object[labels[i]]);
			}

			this.color = zeroArray(color);
		}

		// Perform limitations (clamping, etc.)
		if (limiters[this.model]) {
			channels = convert[this.model].channels;
			for (i = 0; i < channels; i++) {
				const limit = limiters[this.model][i];
				if (limit) {
					this.color[i] = limit(this.color[i]);
				}
			}
		}

		this.valpha = Math.max(0, Math.min(1, this.valpha));

		if (Object.freeze) {
			Object.freeze(this);
		}
	}

	Color.prototype = {
		toString() {
			return this.string();
		},

		toJSON() {
			return this[this.model]();
		},

		string(places) {
			let self = this.model in cs.to ? this : this.rgb();
			self = self.round(typeof places === 'number' ? places : 1);
			const arguments_ = self.valpha === 1 ? self.color : [...self.color, this.valpha];
			return cs.to[self.model](...arguments_);
		},

		percentString(places) {
			const self = this.rgb().round(typeof places === 'number' ? places : 1);
			const arguments_ = self.valpha === 1 ? self.color : [...self.color, this.valpha];
			return cs.to.rgb.percent(...arguments_);
		},

		array() {
			return this.valpha === 1 ? [...this.color] : [...this.color, this.valpha];
		},

		object() {
			const result = {};
			const {channels} = convert[this.model];
			const {labels} = convert[this.model];

			for (let i = 0; i < channels; i++) {
				result[labels[i]] = this.color[i];
			}

			if (this.valpha !== 1) {
				result.alpha = this.valpha;
			}

			return result;
		},

		unitArray() {
			const rgb = this.rgb().color;
			rgb[0] /= 255;
			rgb[1] /= 255;
			rgb[2] /= 255;

			if (this.valpha !== 1) {
				rgb.push(this.valpha);
			}

			return rgb;
		},

		unitObject() {
			const rgb = this.rgb().object();
			rgb.r /= 255;
			rgb.g /= 255;
			rgb.b /= 255;

			if (this.valpha !== 1) {
				rgb.alpha = this.valpha;
			}

			return rgb;
		},

		round(places) {
			places = Math.max(places || 0, 0);
			return new Color([...this.color.map(roundToPlace(places)), this.valpha], this.model);
		},

		alpha(value) {
			if (value !== undefined) {
				return new Color([...this.color, Math.max(0, Math.min(1, value))], this.model);
			}

			return this.valpha;
		},

		// Rgb
		red: getset('rgb', 0, maxfn(255)),
		green: getset('rgb', 1, maxfn(255)),
		blue: getset('rgb', 2, maxfn(255)),

		hue: getset(['hsl', 'hsv', 'hsl', 'hwb', 'hcg'], 0, value => ((value % 360) + 360) % 360),

		saturationl: getset('hsl', 1, maxfn(100)),
		lightness: getset('hsl', 2, maxfn(100)),

		saturationv: getset('hsv', 1, maxfn(100)),
		value: getset('hsv', 2, maxfn(100)),

		chroma: getset('hcg', 1, maxfn(100)),
		gray: getset('hcg', 2, maxfn(100)),

		white: getset('hwb', 1, maxfn(100)),
		wblack: getset('hwb', 2, maxfn(100)),

		cyan: getset('cmyk', 0, maxfn(100)),
		magenta: getset('cmyk', 1, maxfn(100)),
		yellow: getset('cmyk', 2, maxfn(100)),
		black: getset('cmyk', 3, maxfn(100)),

		x: getset('xyz', 0, maxfn(95.047)),
		y: getset('xyz', 1, maxfn(100)),
		z: getset('xyz', 2, maxfn(108.833)),

		l: getset('lab', 0, maxfn(100)),
		a: getset('lab', 1),
		b: getset('lab', 2),

		keyword(value) {
			if (value !== undefined) {
				return new Color(value);
			}

			return convert[this.model].keyword(this.color);
		},

		hex(value) {
			if (value !== undefined) {
				return new Color(value);
			}

			return cs.to.hex(...this.rgb().round().color);
		},

		hexa(value) {
			if (value !== undefined) {
				return new Color(value);
			}

			const rgbArray = this.rgb().round().color;

			let alphaHex = Math.round(this.valpha * 255).toString(16).toUpperCase();
			if (alphaHex.length === 1) {
				alphaHex = '0' + alphaHex;
			}

			return cs.to.hex(...rgbArray) + alphaHex;
		},

		rgbNumber() {
			const rgb = this.rgb().color;
			return ((rgb[0] & 0xFF) << 16) | ((rgb[1] & 0xFF) << 8) | (rgb[2] & 0xFF);
		},

		luminosity() {
			// http://www.w3.org/TR/WCAG20/#relativeluminancedef
			const rgb = this.rgb().color;

			const lum = [];
			for (const [i, element] of rgb.entries()) {
				const chan = element / 255;
				lum[i] = (chan <= 0.04045) ? chan / 12.92 : ((chan + 0.055) / 1.055) ** 2.4;
			}

			return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
		},

		contrast(color2) {
			// http://www.w3.org/TR/WCAG20/#contrast-ratiodef
			const lum1 = this.luminosity();
			const lum2 = color2.luminosity();

			if (lum1 > lum2) {
				return (lum1 + 0.05) / (lum2 + 0.05);
			}

			return (lum2 + 0.05) / (lum1 + 0.05);
		},

		level(color2) {
			// https://www.w3.org/TR/WCAG/#contrast-enhanced
			const contrastRatio = this.contrast(color2);
			if (contrastRatio >= 7) {
				return 'AAA';
			}

			return (contrastRatio >= 4.5) ? 'AA' : '';
		},

		isDark() {
			// YIQ equation from http://24ways.org/2010/calculating-color-contrast
			const rgb = this.rgb().color;
			const yiq = (rgb[0] * 2126 + rgb[1] * 7152 + rgb[2] * 722) / 10000;
			return yiq < 128;
		},

		isLight() {
			return !this.isDark();
		},

		negate() {
			const rgb = this.rgb();
			for (let i = 0; i < 3; i++) {
				rgb.color[i] = 255 - rgb.color[i];
			}

			return rgb;
		},

		lighten(ratio) {
			const hsl = this.hsl();
			hsl.color[2] += hsl.color[2] * ratio;
			return hsl;
		},

		darken(ratio) {
			const hsl = this.hsl();
			hsl.color[2] -= hsl.color[2] * ratio;
			return hsl;
		},

		saturate(ratio) {
			const hsl = this.hsl();
			hsl.color[1] += hsl.color[1] * ratio;
			return hsl;
		},

		desaturate(ratio) {
			const hsl = this.hsl();
			hsl.color[1] -= hsl.color[1] * ratio;
			return hsl;
		},

		whiten(ratio) {
			const hwb = this.hwb();
			hwb.color[1] += hwb.color[1] * ratio;
			return hwb;
		},

		blacken(ratio) {
			const hwb = this.hwb();
			hwb.color[2] += hwb.color[2] * ratio;
			return hwb;
		},

		grayscale() {
			// http://en.wikipedia.org/wiki/Grayscale#Converting_colour_to_grayscale
			const rgb = this.rgb().color;
			const value = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
			return Color.rgb(value, value, value);
		},

		fade(ratio) {
			return this.alpha(this.valpha - (this.valpha * ratio));
		},

		opaquer(ratio) {
			return this.alpha(this.valpha + (this.valpha * ratio));
		},

		rotate(degrees) {
			const hsl = this.hsl();
			let hue = hsl.color[0];
			hue = (hue + degrees) % 360;
			hue = hue < 0 ? 360 + hue : hue;
			hsl.color[0] = hue;
			return hsl;
		},

		mix(mixinColor, weight) {
			// Ported from sass implementation in C
			// https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
			if (!mixinColor || !mixinColor.rgb) {
				throw new Error('Argument to "mix" was not a Color instance, but rather an instance of ' + typeof mixinColor);
			}

			const color1 = mixinColor.rgb();
			const color2 = this.rgb();
			const p = weight === undefined ? 0.5 : weight;

			const w = 2 * p - 1;
			const a = color1.alpha() - color2.alpha();

			const w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2;
			const w2 = 1 - w1;

			return Color.rgb(
				w1 * color1.red() + w2 * color2.red(),
				w1 * color1.green() + w2 * color2.green(),
				w1 * color1.blue() + w2 * color2.blue(),
				color1.alpha() * p + color2.alpha() * (1 - p));
		},
	};

	// Model conversion methods and static constructors
	for (const model of Object.keys(convert)) {
		if (skippedModels.includes(model)) {
			continue;
		}

		const {channels} = convert[model];

		// Conversion methods
		Color.prototype[model] = function (...arguments_) {
			if (this.model === model) {
				return new Color(this);
			}

			if (arguments_.length > 0) {
				return new Color(arguments_, model);
			}

			return new Color([...assertArray(convert[this.model][model].raw(this.color)), this.valpha], model);
		};

		// 'static' construction methods
		Color[model] = function (...arguments_) {
			let color = arguments_[0];
			if (typeof color === 'number') {
				color = zeroArray(arguments_, channels);
			}

			return new Color(color, model);
		};
	}

	function roundTo(number, places) {
		return Number(number.toFixed(places));
	}

	function roundToPlace(places) {
		return function (number) {
			return roundTo(number, places);
		};
	}

	function getset(model, channel, modifier) {
		model = Array.isArray(model) ? model : [model];

		for (const m of model) {
			(limiters[m] ||= [])[channel] = modifier;
		}

		model = model[0];

		return function (value) {
			let result;

			if (value !== undefined) {
				if (modifier) {
					value = modifier(value);
				}

				result = this[model]();
				result.color[channel] = value;
				return result;
			}

			result = this[model]().color[channel];
			if (modifier) {
				result = modifier(result);
			}

			return result;
		};
	}

	function maxfn(max) {
		return function (v) {
			return Math.max(0, Math.min(max, v));
		};
	}

	function assertArray(value) {
		return Array.isArray(value) ? value : [value];
	}

	function zeroArray(array, length) {
		for (let i = 0; i < length; i++) {
			if (typeof array[i] !== 'number') {
				array[i] = 0;
			}
		}

		return array;
	}

	function getDefaultExportFromCjs (x) {
		return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
	}

	/***
	 * Convert string to hex color.
	 *
	 * @param {String} str Text to hash and convert to hex.
	 * @returns {String}
	 * @api public
	 */
	var textHex = function hex(str) {
	  for (
	    var i = 0, hash = 0;
	    i < str.length;
	    hash = str.charCodeAt(i++) + ((hash << 5) - hash)
	  );

	  var color = Math.floor(
	    Math.abs(
	      (Math.sin(hash) * 10000) % 1 * 16777216
	    )
	  ).toString(16);

	  return '#' + Array(6 - color.length + 1).join('0') + color;
	};

	var hex = /*@__PURE__*/getDefaultExportFromCjs(textHex);

	/**
	 * Generate a color for a given name. But be reasonably smart about it by
	 * understanding name spaces and coloring each namespace a bit lighter so they
	 * still have the same base color as the root.
	 *
	 * @param {string} namespace The namespace
	 * @param {string} [delimiter] The delimiter
	 * @returns {string} color
	 */
	function colorspace(namespace, delimiter) {
	  const split = namespace.split(delimiter || ':');
	  let base = hex(split[0]);
	  if (!split.length) return base;
	  for (let i = 0, l = split.length - 1; i < l; i++) {
	    base = Color(base).mix(Color(hex(split[i + 1]))).saturate(1).hex();
	  }
	  return base;
	}

	index_cjs = colorspace;
	return index_cjs;
}

var namespace;
var hasRequiredNamespace;

function requireNamespace () {
	if (hasRequiredNamespace) return namespace;
	hasRequiredNamespace = 1;
	var colorspace = requireIndex_cjs();

	/**
	 * Prefix the messages with a colored namespace.
	 *
	 * @param {Array} messages The messages array that is getting written.
	 * @param {Object} options Options for diagnostics.
	 * @returns {Array} Altered messages array.
	 * @public
	 */
	namespace = function colorNamespace(args, options) {
	  var namespace = options.namespace;

	  if (options.colors === false) {
	    args[0] = namespace +': '+ args[0];
	    return args;
	  }

	  var color = colorspace(namespace);

	  //
	  // The console API supports a special %c formatter in browsers. This is used
	  // to style console messages with any CSS styling, in our case we want to
	  // use colorize the namespace for clarity. As these are formatters, and
	  // we need to inject our CSS string as second messages argument so it
	  // gets picked up correctly.
	  //
	  args[0] = '%c'+ namespace +':%c '+ args[0];
	  args.splice(1, 0, 'color:'+ color, 'color:inherit');

	  return args;
	};
	return namespace;
}

var enabled;
var hasRequiredEnabled;

function requireEnabled () {
	if (hasRequiredEnabled) return enabled;
	hasRequiredEnabled = 1;

	/**
	 * Checks if a given namespace is allowed by the given variable.
	 *
	 * @param {String} name namespace that should be included.
	 * @param {String} variable Value that needs to be tested.
	 * @returns {Boolean} Indication if namespace is enabled.
	 * @public
	 */
	enabled = function enabled(name, variable) {
	  if (!variable) return false;

	  var variables = variable.split(/[\s,]+/)
	    , i = 0;

	  for (; i < variables.length; i++) {
	    variable = variables[i].replace('*', '.*?');

	    if ('-' === variable.charAt(0)) {
	      if ((new RegExp('^'+ variable.substr(1) +'$')).test(name)) {
	        return false;
	      }

	      continue;
	    }

	    if ((new RegExp('^'+ variable +'$')).test(name)) {
	      return true;
	    }
	  }

	  return false;
	};
	return enabled;
}

var adapters;
var hasRequiredAdapters;

function requireAdapters () {
	if (hasRequiredAdapters) return adapters;
	hasRequiredAdapters = 1;
	var enabled = requireEnabled();

	/**
	 * Creates a new Adapter.
	 *
	 * @param {Function} fn Function that returns the value.
	 * @returns {Function} The adapter logic.
	 * @public
	 */
	adapters = function create(fn) {
	  return function adapter(namespace) {
	    try {
	      return enabled(namespace, fn());
	    } catch (e) { /* Any failure means that we found nothing */ }

	    return false;
	  };
	};
	return adapters;
}

var localstorage;
var hasRequiredLocalstorage;

function requireLocalstorage () {
	if (hasRequiredLocalstorage) return localstorage;
	hasRequiredLocalstorage = 1;
	var adapter = requireAdapters();

	/**
	 * Extracts the values from process.env.
	 *
	 * @type {Function}
	 * @public
	 */
	localstorage = adapter(function storage() {
	  return localStorage.getItem('debug') || localStorage.getItem('diagnostics');
	});
	return localstorage;
}

var hash;
var hasRequiredHash;

function requireHash () {
	if (hasRequiredHash) return hash;
	hasRequiredHash = 1;
	var adapter = requireAdapters();

	/**
	 * Extracts the values from process.env.
	 *
	 * @type {Function}
	 * @public
	 */
	hash = adapter(function hash() {
	  return /(debug|diagnostics)=([^&]+)/i.exec(window.location.hash)[2];
	});
	return hash;
}

/**
 * An idiot proof logger to be used as default. We've wrapped it in a try/catch
 * statement to ensure the environments without the `console` API do not crash
 * as well as an additional fix for ancient browsers like IE8 where the
 * `console.log` API doesn't have an `apply`, so we need to use the Function's
 * apply functionality to apply the arguments.
 *
 * @param {Object} meta Options of the logger.
 * @param {Array} messages The actuall message that needs to be logged.
 * @public
 */

var console_1;
var hasRequiredConsole;

function requireConsole () {
	if (hasRequiredConsole) return console_1;
	hasRequiredConsole = 1;
	console_1 = function (meta, messages) {
	  //
	  // So yea. IE8 doesn't have an apply so we need a work around to puke the
	  // arguments in place.
	  //
	  try { Function.prototype.apply.call(console.log, console, messages); }
	  catch (e) {}
	};
	return console_1;
}

var development;
var hasRequiredDevelopment;

function requireDevelopment () {
	if (hasRequiredDevelopment) return development;
	hasRequiredDevelopment = 1;
	var create = requireDiagnostics();

	/**
	 * Create a new diagnostics logger.
	 *
	 * @param {String} namespace The namespace it should enable.
	 * @param {Object} options Additional options.
	 * @returns {Function} The logger.
	 * @public
	 */
	var diagnostics = create(function dev(namespace, options) {
	  options = options || {};
	  options.namespace = namespace;
	  options.prod = false;
	  options.dev = true;

	  if (!dev.enabled(namespace) && !(options.force || dev.force)) {
	    return dev.nope(options);
	  }

	  return dev.yep(options);
	});

	//
	// Configure the logger for the given environment.
	//
	diagnostics.modify(requireNamespace());
	diagnostics.use(requireLocalstorage());
	diagnostics.use(requireHash());
	diagnostics.set(requireConsole());

	//
	// Expose the diagnostics logger.
	//
	development = diagnostics;
	return development;
}

var hasRequiredBrowser$1;

function requireBrowser$1 () {
	if (hasRequiredBrowser$1) return browser$1.exports;
	hasRequiredBrowser$1 = 1;
	//
	// Select the correct build version depending on the environment.
	//
	if (process.env.NODE_ENV === 'production') {
	  browser$1.exports = requireProduction();
	} else {
	  browser$1.exports = requireDevelopment();
	}
	return browser$1.exports;
}

/**
 * tail-file.js: TODO: add file header description.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var tailFile;
var hasRequiredTailFile;

function requireTailFile () {
	if (hasRequiredTailFile) return tailFile;
	hasRequiredTailFile = 1;

	var fs = fs__default;
	var _require = require$$1$3,
	  StringDecoder = _require.StringDecoder;
	var _require2 = requireReadableBrowser(),
	  Stream = _require2.Stream;

	/**
	 * Simple no-op function.
	 * @returns {undefined}
	 */
	function noop() {}

	/**
	 * TODO: add function description.
	 * @param {Object} options - Options for tail.
	 * @param {function} iter - Iterator function to execute on every line.
	* `tail -f` a file. Options must include file.
	 * @returns {mixed} - TODO: add return description.
	 */
	tailFile = function (options, iter) {
	  var buffer = Buffer.alloc(64 * 1024);
	  var decode = new StringDecoder('utf8');
	  var stream = new Stream();
	  var buff = '';
	  var pos = 0;
	  var row = 0;
	  if (options.start === -1) {
	    delete options.start;
	  }
	  stream.readable = true;
	  stream.destroy = function () {
	    stream.destroyed = true;
	    stream.emit('end');
	    stream.emit('close');
	  };
	  fs.open(options.file, 'a+', '0644', function (err, fd) {
	    if (err) {
	      if (!iter) {
	        stream.emit('error', err);
	      } else {
	        iter(err);
	      }
	      stream.destroy();
	      return;
	    }
	    (function read() {
	      if (stream.destroyed) {
	        fs.close(fd, noop);
	        return;
	      }
	      return fs.read(fd, buffer, 0, buffer.length, pos, function (error, bytes) {
	        if (error) {
	          if (!iter) {
	            stream.emit('error', error);
	          } else {
	            iter(error);
	          }
	          stream.destroy();
	          return;
	        }
	        if (!bytes) {
	          if (buff) {
	            // eslint-disable-next-line eqeqeq
	            if (options.start == null || row > options.start) {
	              if (!iter) {
	                stream.emit('line', buff);
	              } else {
	                iter(null, buff);
	              }
	            }
	            row++;
	            buff = '';
	          }
	          return setTimeout(read, 1000);
	        }
	        var data = decode.write(buffer.slice(0, bytes));
	        if (!iter) {
	          stream.emit('data', data);
	        }
	        data = (buff + data).split(/\n+/);
	        var l = data.length - 1;
	        var i = 0;
	        for (; i < l; i++) {
	          // eslint-disable-next-line eqeqeq
	          if (options.start == null || row > options.start) {
	            if (!iter) {
	              stream.emit('line', data[i]);
	            } else {
	              iter(null, data[i]);
	            }
	          }
	          row++;
	        }
	        buff = data[l];
	        pos += bytes;
	        return read();
	      });
	    })();
	  });
	  if (!iter) {
	    return stream;
	  }
	  return stream.destroy;
	};
	return tailFile;
}

/* eslint-disable complexity,max-statements */

var file;
var hasRequiredFile;

function requireFile () {
	if (hasRequiredFile) return file;
	hasRequiredFile = 1;
	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
	function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
	function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
	function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
	function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
	function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
	function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
	function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: true, configurable: true } }), Object.defineProperty(t, "prototype", { writable: false }), e && _setPrototypeOf(t, e); }
	function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
	var fs = fs__default;
	var path = path__default;
	var asyncSeries = requireSeries();
	var zlib = require$$1$2;
	var _require = requireTripleBeam(),
	  MESSAGE = _require.MESSAGE;
	var _require2 = requireReadableBrowser(),
	  Stream = _require2.Stream,
	  PassThrough = _require2.PassThrough;
	var TransportStream = requireDist();
	var debug = requireBrowser$1()('winston:file');
	var os = os__default;
	var tailFile = requireTailFile();

	/**
	 * Transport for outputting to a local log file.
	 * @type {File}
	 * @extends {TransportStream}
	 */
	file = /*#__PURE__*/function (_TransportStream) {
	  /**
	   * Constructor function for the File transport object responsible for
	   * persisting log messages and metadata to one or more files.
	   * @param {Object} options - Options for this instance.
	   */
	  function File() {
	    var _this;
	    var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
	    _classCallCheck(this, File);
	    _this = _callSuper(this, File, [options]);

	    // Expose the name of this Transport on the prototype.
	    _this.name = options.name || 'file';

	    // Helper function which throws an `Error` in the event that any of the
	    // rest of the arguments is present in `options`.
	    function throwIf(target) {
	      for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
	        args[_key - 1] = arguments[_key];
	      }
	      args.slice(1).forEach(function (name) {
	        if (options[name]) {
	          throw new Error("Cannot set ".concat(name, " and ").concat(target, " together"));
	        }
	      });
	    }

	    // Setup the base stream that always gets piped to to handle buffering.
	    _this._stream = new PassThrough();
	    _this._stream.setMaxListeners(30);

	    // Bind this context for listener methods.
	    _this._onError = _this._onError.bind(_this);
	    if (options.filename || options.dirname) {
	      throwIf('filename or dirname', 'stream');
	      _this._basename = _this.filename = options.filename ? path.basename(options.filename) : 'winston.log';
	      _this.dirname = options.dirname || path.dirname(options.filename);
	      _this.options = options.options || {
	        flags: 'a'
	      };
	    } else if (options.stream) {
	      // eslint-disable-next-line no-console
	      console.warn('options.stream will be removed in winston@4. Use winston.transports.Stream');
	      throwIf('stream', 'filename', 'maxsize');
	      _this._dest = _this._stream.pipe(_this._setupStream(options.stream));
	      _this.dirname = path.dirname(_this._dest.path);
	      // We need to listen for drain events when write() returns false. This
	      // can make node mad at times.
	    } else {
	      throw new Error('Cannot log to file without filename or stream.');
	    }
	    _this.maxsize = options.maxsize || null;
	    _this.rotationFormat = options.rotationFormat || false;
	    _this.zippedArchive = options.zippedArchive || false;
	    _this.maxFiles = options.maxFiles || null;
	    _this.eol = typeof options.eol === 'string' ? options.eol : os.EOL;
	    _this.tailable = options.tailable || false;
	    _this.lazy = options.lazy || false;

	    // Internal state variables representing the number of files this instance
	    // has created and the current size (in bytes) of the current logfile.
	    _this._size = 0;
	    _this._pendingSize = 0;
	    _this._created = 0;
	    _this._drain = false;
	    _this._opening = false;
	    _this._ending = false;
	    _this._fileExist = false;
	    if (_this.dirname) _this._createLogDirIfNotExist(_this.dirname);
	    if (!_this.lazy) _this.open();
	    return _this;
	  }
	  _inherits(File, _TransportStream);
	  return _createClass(File, [{
	    key: "finishIfEnding",
	    value: function finishIfEnding() {
	      var _this2 = this;
	      if (this._ending) {
	        if (this._opening) {
	          this.once('open', function () {
	            _this2._stream.once('finish', function () {
	              return _this2.emit('finish');
	            });
	            setImmediate(function () {
	              return _this2._stream.end();
	            });
	          });
	        } else {
	          this._stream.once('finish', function () {
	            return _this2.emit('finish');
	          });
	          setImmediate(function () {
	            return _this2._stream.end();
	          });
	        }
	      }
	    }

	    /**
	     * Core logging method exposed to Winston. Metadata is optional.
	     * @param {Object} info - TODO: add param description.
	     * @param {Function} callback - TODO: add param description.
	     * @returns {undefined}
	     */
	  }, {
	    key: "log",
	    value: function log(info) {
	      var _this3 = this;
	      var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {};
	      // Remark: (jcrugzz) What is necessary about this callback(null, true) now
	      // when thinking about 3.x? Should silent be handled in the base
	      // TransportStream _write method?
	      if (this.silent) {
	        callback();
	        return true;
	      }

	      // Output stream buffer is full and has asked us to wait for the drain event
	      if (this._drain) {
	        this._stream.once('drain', function () {
	          _this3._drain = false;
	          _this3.log(info, callback);
	        });
	        return;
	      }
	      if (this._rotate) {
	        this._stream.once('rotate', function () {
	          _this3._rotate = false;
	          _this3.log(info, callback);
	        });
	        return;
	      }
	      if (this.lazy) {
	        if (!this._fileExist) {
	          if (!this._opening) {
	            this.open();
	          }
	          this.once('open', function () {
	            _this3._fileExist = true;
	            _this3.log(info, callback);
	            return;
	          });
	          return;
	        }
	        if (this._needsNewFile(this._pendingSize)) {
	          this._dest.once('close', function () {
	            if (!_this3._opening) {
	              _this3.open();
	            }
	            _this3.once('open', function () {
	              _this3.log(info, callback);
	              return;
	            });
	            return;
	          });
	          return;
	        }
	      }

	      // Grab the raw string and append the expected EOL.
	      var output = "".concat(info[MESSAGE]).concat(this.eol);
	      var bytes = Buffer.byteLength(output);

	      // After we have written to the PassThrough check to see if we need
	      // to rotate to the next file.
	      //
	      // Remark: This gets called too early and does not depict when data
	      // has been actually flushed to disk.
	      function logged() {
	        var _this4 = this;
	        this._size += bytes;
	        this._pendingSize -= bytes;
	        debug('logged %s %s', this._size, output);
	        this.emit('logged', info);

	        // Do not attempt to rotate files while rotating
	        if (this._rotate) {
	          return;
	        }

	        // Do not attempt to rotate files while opening
	        if (this._opening) {
	          return;
	        }

	        // Check to see if we need to end the stream and create a new one.
	        if (!this._needsNewFile()) {
	          return;
	        }
	        if (this.lazy) {
	          this._endStream(function () {
	            _this4.emit('fileclosed');
	          });
	          return;
	        }

	        // End the current stream, ensure it flushes and create a new one.
	        // This could potentially be optimized to not run a stat call but its
	        // the safest way since we are supporting `maxFiles`.
	        this._rotate = true;
	        this._endStream(function () {
	          return _this4._rotateFile();
	        });
	      }

	      // Keep track of the pending bytes being written while files are opening
	      // in order to properly rotate the PassThrough this._stream when the file
	      // eventually does open.
	      this._pendingSize += bytes;
	      if (this._opening && !this.rotatedWhileOpening && this._needsNewFile(this._size + this._pendingSize)) {
	        this.rotatedWhileOpening = true;
	      }
	      var written = this._stream.write(output, logged.bind(this));
	      if (!written) {
	        this._drain = true;
	        this._stream.once('drain', function () {
	          _this3._drain = false;
	          callback();
	        });
	      } else {
	        callback(); // eslint-disable-line callback-return
	      }
	      debug('written', written, this._drain);
	      this.finishIfEnding();
	      return written;
	    }

	    /**
	     * Query the transport. Options object is optional.
	     * @param {Object} options - Loggly-like query options for this instance.
	     * @param {function} callback - Continuation to respond to when complete.
	     * TODO: Refactor me.
	     */
	  }, {
	    key: "query",
	    value: function query(options, callback) {
	      if (typeof options === 'function') {
	        callback = options;
	        options = {};
	      }
	      options = normalizeQuery(options);
	      var file = path.join(this.dirname, this.filename);
	      var buff = '';
	      var results = [];
	      var row = 0;
	      var stream = fs.createReadStream(file, {
	        encoding: 'utf8'
	      });
	      stream.on('error', function (err) {
	        if (stream.readable) {
	          stream.destroy();
	        }
	        if (!callback) {
	          return;
	        }
	        return err.code !== 'ENOENT' ? callback(err) : callback(null, results);
	      });
	      stream.on('data', function (data) {
	        data = (buff + data).split(/\n+/);
	        var l = data.length - 1;
	        var i = 0;
	        for (; i < l; i++) {
	          if (!options.start || row >= options.start) {
	            add(data[i]);
	          }
	          row++;
	        }
	        buff = data[l];
	      });
	      stream.on('close', function () {
	        if (buff) {
	          add(buff, true);
	        }
	        if (options.order === 'desc') {
	          results = results.reverse();
	        }

	        // eslint-disable-next-line callback-return
	        if (callback) callback(null, results);
	      });
	      function add(buff, attempt) {
	        try {
	          var log = JSON.parse(buff);
	          if (check(log)) {
	            push(log);
	          }
	        } catch (e) {
	          if (!attempt) {
	            stream.emit('error', e);
	          }
	        }
	      }
	      function push(log) {
	        if (options.rows && results.length >= options.rows && options.order !== 'desc') {
	          if (stream.readable) {
	            stream.destroy();
	          }
	          return;
	        }
	        if (options.fields) {
	          log = options.fields.reduce(function (obj, key) {
	            obj[key] = log[key];
	            return obj;
	          }, {});
	        }
	        if (options.order === 'desc') {
	          if (results.length >= options.rows) {
	            results.shift();
	          }
	        }
	        results.push(log);
	      }
	      function check(log) {
	        if (!log) {
	          return;
	        }
	        if (_typeof(log) !== 'object') {
	          return;
	        }
	        var time = new Date(log.timestamp);
	        if (options.from && time < options.from || options.until && time > options.until || options.level && options.level !== log.level) {
	          return;
	        }
	        return true;
	      }
	      function normalizeQuery(options) {
	        options = options || {};

	        // limit
	        options.rows = options.rows || options.limit || 10;

	        // starting row offset
	        options.start = options.start || 0;

	        // now
	        options.until = options.until || new Date();
	        if (_typeof(options.until) !== 'object') {
	          options.until = new Date(options.until);
	        }

	        // now - 24
	        options.from = options.from || options.until - 24 * 60 * 60 * 1000;
	        if (_typeof(options.from) !== 'object') {
	          options.from = new Date(options.from);
	        }

	        // 'asc' or 'desc'
	        options.order = options.order || 'desc';
	        return options;
	      }
	    }

	    /**
	     * Returns a log stream for this transport. Options object is optional.
	     * @param {Object} options - Stream options for this instance.
	     * @returns {Stream} - TODO: add return description.
	     * TODO: Refactor me.
	     */
	  }, {
	    key: "stream",
	    value: function stream() {
	      var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
	      var file = path.join(this.dirname, this.filename);
	      var stream = new Stream();
	      var tail = {
	        file: file,
	        start: options.start
	      };
	      stream.destroy = tailFile(tail, function (err, line) {
	        if (err) {
	          return stream.emit('error', err);
	        }
	        try {
	          stream.emit('data', line);
	          line = JSON.parse(line);
	          stream.emit('log', line);
	        } catch (e) {
	          stream.emit('error', e);
	        }
	      });
	      return stream;
	    }

	    /**
	     * Checks to see the filesize of.
	     * @returns {undefined}
	     */
	  }, {
	    key: "open",
	    value: function open() {
	      var _this5 = this;
	      // If we do not have a filename then we were passed a stream and
	      // don't need to keep track of size.
	      if (!this.filename) return;
	      if (this._opening) return;
	      this._opening = true;

	      // Stat the target file to get the size and create the stream.
	      this.stat(function (err, size) {
	        if (err) {
	          return _this5.emit('error', err);
	        }
	        debug('stat done: %s { size: %s }', _this5.filename, size);
	        _this5._size = size;
	        _this5._dest = _this5._createStream(_this5._stream);
	        _this5._opening = false;
	        _this5.once('open', function () {
	          if (!_this5._stream.emit('rotate')) {
	            _this5._rotate = false;
	          }
	        });
	      });
	    }

	    /**
	     * Stat the file and assess information in order to create the proper stream.
	     * @param {function} callback - TODO: add param description.
	     * @returns {undefined}
	     */
	  }, {
	    key: "stat",
	    value: function stat(callback) {
	      var _this6 = this;
	      var target = this._getFile();
	      var fullpath = path.join(this.dirname, target);
	      fs.stat(fullpath, function (err, stat) {
	        if (err && err.code === 'ENOENT') {
	          debug('ENOENT ok', fullpath);
	          // Update internally tracked filename with the new target name.
	          _this6.filename = target;
	          return callback(null, 0);
	        }
	        if (err) {
	          debug("err ".concat(err.code, " ").concat(fullpath));
	          return callback(err);
	        }
	        if (!stat || _this6._needsNewFile(stat.size)) {
	          // If `stats.size` is greater than the `maxsize` for this
	          // instance then try again.
	          return _this6._incFile(function () {
	            return _this6.stat(callback);
	          });
	        }

	        // Once we have figured out what the filename is, set it
	        // and return the size.
	        _this6.filename = target;
	        callback(null, stat.size);
	      });
	    }

	    /**
	     * Closes the stream associated with this instance.
	     * @param {function} cb - TODO: add param description.
	     * @returns {undefined}
	     */
	  }, {
	    key: "close",
	    value: function close(cb) {
	      var _this7 = this;
	      if (!this._stream) {
	        return;
	      }
	      this._stream.end(function () {
	        if (cb) {
	          cb(); // eslint-disable-line callback-return
	        }
	        _this7.emit('flush');
	        _this7.emit('closed');
	      });
	    }

	    /**
	     * TODO: add method description.
	     * @param {number} size - TODO: add param description.
	     * @returns {undefined}
	     */
	  }, {
	    key: "_needsNewFile",
	    value: function _needsNewFile(size) {
	      size = size || this._size;
	      return this.maxsize && size >= this.maxsize;
	    }

	    /**
	     * TODO: add method description.
	     * @param {Error} err - TODO: add param description.
	     * @returns {undefined}
	     */
	  }, {
	    key: "_onError",
	    value: function _onError(err) {
	      this.emit('error', err);
	    }

	    /**
	     * TODO: add method description.
	     * @param {Stream} stream - TODO: add param description.
	     * @returns {mixed} - TODO: add return description.
	     */
	  }, {
	    key: "_setupStream",
	    value: function _setupStream(stream) {
	      stream.on('error', this._onError);
	      return stream;
	    }

	    /**
	     * TODO: add method description.
	     * @param {Stream} stream - TODO: add param description.
	     * @returns {mixed} - TODO: add return description.
	     */
	  }, {
	    key: "_cleanupStream",
	    value: function _cleanupStream(stream) {
	      stream.removeListener('error', this._onError);
	      stream.destroy();
	      return stream;
	    }

	    /**
	     * TODO: add method description.
	     */
	  }, {
	    key: "_rotateFile",
	    value: function _rotateFile() {
	      var _this8 = this;
	      this._incFile(function () {
	        return _this8.open();
	      });
	    }

	    /**
	     * Unpipe from the stream that has been marked as full and end it so it
	     * flushes to disk.
	     *
	     * @param {function} callback - Callback for when the current file has closed.
	     * @private
	     */
	  }, {
	    key: "_endStream",
	    value: function _endStream() {
	      var _this9 = this;
	      var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {};
	      if (this._dest) {
	        this._stream.unpipe(this._dest);
	        this._dest.end(function () {
	          _this9._cleanupStream(_this9._dest);
	          callback();
	        });
	      } else {
	        callback(); // eslint-disable-line callback-return
	      }
	    }

	    /**
	     * Returns the WritableStream for the active file on this instance. If we
	     * should gzip the file then a zlib stream is returned.
	     *
	     * @param {ReadableStream} source –PassThrough to pipe to the file when open.
	     * @returns {WritableStream} Stream that writes to disk for the active file.
	     */
	  }, {
	    key: "_createStream",
	    value: function _createStream(source) {
	      var _this10 = this;
	      var fullpath = path.join(this.dirname, this.filename);
	      debug('create stream start', fullpath, this.options);
	      var dest = fs.createWriteStream(fullpath, this.options)
	      // TODO: What should we do with errors here?
	      .on('error', function (err) {
	        return debug(err);
	      }).on('close', function () {
	        return debug('close', dest.path, dest.bytesWritten);
	      }).on('open', function () {
	        debug('file open ok', fullpath);
	        _this10.emit('open', fullpath);
	        source.pipe(dest);

	        // If rotation occured during the open operation then we immediately
	        // start writing to a new PassThrough, begin opening the next file
	        // and cleanup the previous source and dest once the source has drained.
	        if (_this10.rotatedWhileOpening) {
	          _this10._stream = new PassThrough();
	          _this10._stream.setMaxListeners(30);
	          _this10._rotateFile();
	          _this10.rotatedWhileOpening = false;
	          _this10._cleanupStream(dest);
	          source.end();
	        }
	      });
	      debug('create stream ok', fullpath);
	      return dest;
	    }

	    /**
	     * TODO: add method description.
	     * @param {function} callback - TODO: add param description.
	     * @returns {undefined}
	     */
	  }, {
	    key: "_incFile",
	    value: function _incFile(callback) {
	      debug('_incFile', this.filename);
	      var ext = path.extname(this._basename);
	      var basename = path.basename(this._basename, ext);
	      var tasks = [];
	      if (this.zippedArchive) {
	        tasks.push(function (cb) {
	          var num = this._created > 0 && !this.tailable ? this._created : '';
	          this._compressFile(path.join(this.dirname, "".concat(basename).concat(num).concat(ext)), path.join(this.dirname, "".concat(basename).concat(num).concat(ext, ".gz")), cb);
	        }.bind(this));
	      }
	      tasks.push(function (cb) {
	        if (!this.tailable) {
	          this._created += 1;
	          this._checkMaxFilesIncrementing(ext, basename, cb);
	        } else {
	          this._checkMaxFilesTailable(ext, basename, cb);
	        }
	      }.bind(this));
	      asyncSeries(tasks, callback);
	    }

	    /**
	     * Gets the next filename to use for this instance in the case that log
	     * filesizes are being capped.
	     * @returns {string} - TODO: add return description.
	     * @private
	     */
	  }, {
	    key: "_getFile",
	    value: function _getFile() {
	      var ext = path.extname(this._basename);
	      var basename = path.basename(this._basename, ext);
	      var isRotation = this.rotationFormat ? this.rotationFormat() : this._created;

	      // Caveat emptor (indexzero): rotationFormat() was broken by design When
	      // combined with max files because the set of files to unlink is never
	      // stored.
	      return !this.tailable && this._created ? "".concat(basename).concat(isRotation).concat(ext) : "".concat(basename).concat(ext);
	    }

	    /**
	     * Increment the number of files created or checked by this instance.
	     * @param {mixed} ext - TODO: add param description.
	     * @param {mixed} basename - TODO: add param description.
	     * @param {mixed} callback - TODO: add param description.
	     * @returns {undefined}
	     * @private
	     */
	  }, {
	    key: "_checkMaxFilesIncrementing",
	    value: function _checkMaxFilesIncrementing(ext, basename, callback) {
	      // Check for maxFiles option and delete file.
	      if (!this.maxFiles || this._created < this.maxFiles) {
	        return setImmediate(callback);
	      }
	      var oldest = this._created - this.maxFiles;
	      var isOldest = oldest !== 0 ? oldest : '';
	      var isZipped = this.zippedArchive ? '.gz' : '';
	      var filePath = "".concat(basename).concat(isOldest).concat(ext).concat(isZipped);
	      var target = path.join(this.dirname, filePath);
	      fs.unlink(target, callback);
	    }

	    /**
	     * Roll files forward based on integer, up to maxFiles. e.g. if base if
	     * file.log and it becomes oversized, roll to file1.log, and allow file.log
	     * to be re-used. If file is oversized again, roll file1.log to file2.log,
	     * roll file.log to file1.log, and so on.
	     * @param {mixed} ext - TODO: add param description.
	     * @param {mixed} basename - TODO: add param description.
	     * @param {mixed} callback - TODO: add param description.
	     * @returns {undefined}
	     * @private
	     */
	  }, {
	    key: "_checkMaxFilesTailable",
	    value: function _checkMaxFilesTailable(ext, basename, callback) {
	      var _this12 = this;
	      var tasks = [];
	      if (!this.maxFiles) {
	        return;
	      }

	      // const isZipped = this.zippedArchive ? '.gz' : '';
	      var isZipped = this.zippedArchive ? '.gz' : '';
	      for (var x = this.maxFiles - 1; x > 1; x--) {
	        tasks.push(function (i, cb) {
	          var _this11 = this;
	          var fileName = "".concat(basename).concat(i - 1).concat(ext).concat(isZipped);
	          var tmppath = path.join(this.dirname, fileName);
	          fs.exists(tmppath, function (exists) {
	            if (!exists) {
	              return cb(null);
	            }
	            fileName = "".concat(basename).concat(i).concat(ext).concat(isZipped);
	            fs.rename(tmppath, path.join(_this11.dirname, fileName), cb);
	          });
	        }.bind(this, x));
	      }
	      asyncSeries(tasks, function () {
	        fs.rename(path.join(_this12.dirname, "".concat(basename).concat(ext).concat(isZipped)), path.join(_this12.dirname, "".concat(basename, "1").concat(ext).concat(isZipped)), callback);
	      });
	    }

	    /**
	     * Compresses src to dest with gzip and unlinks src
	     * @param {string} src - path to source file.
	     * @param {string} dest - path to zipped destination file.
	     * @param {Function} callback - callback called after file has been compressed.
	     * @returns {undefined}
	     * @private
	     */
	  }, {
	    key: "_compressFile",
	    value: function _compressFile(src, dest, callback) {
	      fs.access(src, fs.F_OK, function (err) {
	        if (err) {
	          return callback();
	        }
	        var gzip = zlib.createGzip();
	        var inp = fs.createReadStream(src);
	        var out = fs.createWriteStream(dest);
	        out.on('finish', function () {
	          fs.unlink(src, callback);
	        });
	        inp.pipe(gzip).pipe(out);
	      });
	    }
	  }, {
	    key: "_createLogDirIfNotExist",
	    value: function _createLogDirIfNotExist(dirPath) {
	      /* eslint-disable no-sync */
	      if (!fs.existsSync(dirPath)) {
	        fs.mkdirSync(dirPath, {
	          recursive: true
	        });
	      }
	      /* eslint-enable no-sync */
	    }
	  }]);
	}(TransportStream);
	return file;
}

/**
 * http.js: Transport for outputting to a json-rpcserver.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var http_1;
var hasRequiredHttp;

function requireHttp () {
	if (hasRequiredHttp) return http_1;
	hasRequiredHttp = 1;

	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
	function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
	function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
	function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
	function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
	function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
	function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
	function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
	function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
	function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: true, configurable: true } }), Object.defineProperty(t, "prototype", { writable: false }), e && _setPrototypeOf(t, e); }
	function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
	var http = require$$0$8;
	var https = https__default;
	var _require = requireReadableBrowser(),
	  Stream = _require.Stream;
	var TransportStream = requireDist();
	var _require2 = requireSafeStableStringify(),
	  configure = _require2.configure;

	/**
	 * Transport for outputting to a json-rpc server.
	 * @type {Stream}
	 * @extends {TransportStream}
	 */
	http_1 = /*#__PURE__*/function (_TransportStream) {
	  /**
	   * Constructor function for the Http transport object responsible for
	   * persisting log messages and metadata to a terminal or TTY.
	   * @param {!Object} [options={}] - Options for this instance.
	   */
	  // eslint-disable-next-line max-statements
	  function Http() {
	    var _this;
	    var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
	    _classCallCheck(this, Http);
	    _this = _callSuper(this, Http, [options]);
	    _this.options = options;
	    _this.name = options.name || 'http';
	    _this.ssl = !!options.ssl;
	    _this.host = options.host || 'localhost';
	    _this.port = options.port;
	    _this.auth = options.auth;
	    _this.path = options.path || '';
	    _this.maximumDepth = options.maximumDepth;
	    _this.agent = options.agent;
	    _this.headers = options.headers || {};
	    _this.headers['content-type'] = 'application/json';
	    _this.batch = options.batch || false;
	    _this.batchInterval = options.batchInterval || 5000;
	    _this.batchCount = options.batchCount || 10;
	    _this.batchOptions = [];
	    _this.batchTimeoutID = -1;
	    _this.batchCallback = {};
	    if (!_this.port) {
	      _this.port = _this.ssl ? 443 : 80;
	    }
	    return _this;
	  }

	  /**
	   * Core logging method exposed to Winston.
	   * @param {Object} info - TODO: add param description.
	   * @param {function} callback - TODO: add param description.
	   * @returns {undefined}
	   */
	  _inherits(Http, _TransportStream);
	  return _createClass(Http, [{
	    key: "log",
	    value: function log(info, callback) {
	      var _this2 = this;
	      this._request(info, null, null, function (err, res) {
	        if (res && res.statusCode !== 200) {
	          err = new Error("Invalid HTTP Status Code: ".concat(res.statusCode));
	        }
	        if (err) {
	          _this2.emit('warn', err);
	        } else {
	          _this2.emit('logged', info);
	        }
	      });

	      // Remark: (jcrugzz) Fire and forget here so requests dont cause buffering
	      // and block more requests from happening?
	      if (callback) {
	        setImmediate(callback);
	      }
	    }

	    /**
	     * Query the transport. Options object is optional.
	     * @param {Object} options -  Loggly-like query options for this instance.
	     * @param {function} callback - Continuation to respond to when complete.
	     * @returns {undefined}
	     */
	  }, {
	    key: "query",
	    value: function query(options, callback) {
	      if (typeof options === 'function') {
	        callback = options;
	        options = {};
	      }
	      options = {
	        method: 'query',
	        params: this.normalizeQuery(options)
	      };
	      var auth = options.params.auth || null;
	      delete options.params.auth;
	      var path = options.params.path || null;
	      delete options.params.path;
	      this._request(options, auth, path, function (err, res, body) {
	        if (res && res.statusCode !== 200) {
	          err = new Error("Invalid HTTP Status Code: ".concat(res.statusCode));
	        }
	        if (err) {
	          return callback(err);
	        }
	        if (typeof body === 'string') {
	          try {
	            body = JSON.parse(body);
	          } catch (e) {
	            return callback(e);
	          }
	        }
	        callback(null, body);
	      });
	    }

	    /**
	     * Returns a log stream for this transport. Options object is optional.
	     * @param {Object} options - Stream options for this instance.
	     * @returns {Stream} - TODO: add return description
	     */
	  }, {
	    key: "stream",
	    value: function stream() {
	      var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
	      var stream = new Stream();
	      options = {
	        method: 'stream',
	        params: options
	      };
	      var path = options.params.path || null;
	      delete options.params.path;
	      var auth = options.params.auth || null;
	      delete options.params.auth;
	      var buff = '';
	      var req = this._request(options, auth, path);
	      stream.destroy = function () {
	        return req.destroy();
	      };
	      req.on('data', function (data) {
	        data = (buff + data).split(/\n+/);
	        var l = data.length - 1;
	        var i = 0;
	        for (; i < l; i++) {
	          try {
	            stream.emit('log', JSON.parse(data[i]));
	          } catch (e) {
	            stream.emit('error', e);
	          }
	        }
	        buff = data[l];
	      });
	      req.on('error', function (err) {
	        return stream.emit('error', err);
	      });
	      return stream;
	    }

	    /**
	     * Make a request to a winstond server or any http server which can
	     * handle json-rpc.
	     * @param {function} options - Options to sent the request.
	     * @param {Object?} auth - authentication options
	     * @param {string} path - request path
	     * @param {function} callback - Continuation to respond to when complete.
	     */
	  }, {
	    key: "_request",
	    value: function _request(options, auth, path, callback) {
	      options = options || {};
	      auth = auth || this.auth;
	      path = path || this.path || '';
	      if (this.batch) {
	        this._doBatch(options, callback, auth, path);
	      } else {
	        this._doRequest(options, callback, auth, path);
	      }
	    }

	    /**
	     * Send or memorize the options according to batch configuration
	     * @param {function} options - Options to sent the request.
	     * @param {function} callback - Continuation to respond to when complete.
	     * @param {Object?} auth - authentication options
	     * @param {string} path - request path
	     */
	  }, {
	    key: "_doBatch",
	    value: function _doBatch(options, callback, auth, path) {
	      this.batchOptions.push(options);
	      if (this.batchOptions.length === 1) {
	        // First message stored, it's time to start the timeout!
	        var me = this;
	        this.batchCallback = callback;
	        this.batchTimeoutID = setTimeout(function () {
	          // timeout is reached, send all messages to endpoint
	          me.batchTimeoutID = -1;
	          me._doBatchRequest(me.batchCallback, auth, path);
	        }, this.batchInterval);
	      }
	      if (this.batchOptions.length === this.batchCount) {
	        // max batch count is reached, send all messages to endpoint
	        this._doBatchRequest(this.batchCallback, auth, path);
	      }
	    }

	    /**
	     * Initiate a request with the memorized batch options, stop the batch timeout
	     * @param {function} callback - Continuation to respond to when complete.
	     * @param {Object?} auth - authentication options
	     * @param {string} path - request path
	     */
	  }, {
	    key: "_doBatchRequest",
	    value: function _doBatchRequest(callback, auth, path) {
	      if (this.batchTimeoutID > 0) {
	        clearTimeout(this.batchTimeoutID);
	        this.batchTimeoutID = -1;
	      }
	      var batchOptionsCopy = this.batchOptions.slice();
	      this.batchOptions = [];
	      this._doRequest(batchOptionsCopy, callback, auth, path);
	    }

	    /**
	     * Make a request to a winstond server or any http server which can
	     * handle json-rpc.
	     * @param {function} options - Options to sent the request.
	     * @param {function} callback - Continuation to respond to when complete.
	     * @param {Object?} auth - authentication options
	     * @param {string} path - request path
	     */
	  }, {
	    key: "_doRequest",
	    value: function _doRequest(options, callback, auth, path) {
	      // Prepare options for outgoing HTTP request
	      var headers = Object.assign({}, this.headers);
	      if (auth && auth.bearer) {
	        headers.Authorization = "Bearer ".concat(auth.bearer);
	      }
	      var req = (this.ssl ? https : http).request(_objectSpread(_objectSpread({}, this.options), {}, {
	        method: 'POST',
	        host: this.host,
	        port: this.port,
	        path: "/".concat(path.replace(/^\//, '')),
	        headers: headers,
	        auth: auth && auth.username && auth.password ? "".concat(auth.username, ":").concat(auth.password) : '',
	        agent: this.agent
	      }));
	      req.on('error', callback);
	      req.on('response', function (res) {
	        return res.on('end', function () {
	          return callback(null, res);
	        }).resume();
	      });
	      var jsonStringify = configure(_objectSpread({}, this.maximumDepth && {
	        maximumDepth: this.maximumDepth
	      }));
	      req.end(Buffer.from(jsonStringify(options, this.options.replacer), 'utf8'));
	    }
	  }]);
	}(TransportStream);
	return http_1;
}

var isStream_1;
var hasRequiredIsStream;

function requireIsStream () {
	if (hasRequiredIsStream) return isStream_1;
	hasRequiredIsStream = 1;

	const isStream = stream =>
		stream !== null &&
		typeof stream === 'object' &&
		typeof stream.pipe === 'function';

	isStream.writable = stream =>
		isStream(stream) &&
		stream.writable !== false &&
		typeof stream._write === 'function' &&
		typeof stream._writableState === 'object';

	isStream.readable = stream =>
		isStream(stream) &&
		stream.readable !== false &&
		typeof stream._read === 'function' &&
		typeof stream._readableState === 'object';

	isStream.duplex = stream =>
		isStream.writable(stream) &&
		isStream.readable(stream);

	isStream.transform = stream =>
		isStream.duplex(stream) &&
		typeof stream._transform === 'function';

	isStream_1 = isStream;
	return isStream_1;
}

/**
 * stream.js: Transport for outputting to any arbitrary stream.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var stream;
var hasRequiredStream;

function requireStream () {
	if (hasRequiredStream) return stream;
	hasRequiredStream = 1;

	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
	function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
	function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
	function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
	function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
	function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
	function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
	function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: true, configurable: true } }), Object.defineProperty(t, "prototype", { writable: false }), e && _setPrototypeOf(t, e); }
	function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
	var isStream = requireIsStream();
	var _require = requireTripleBeam(),
	  MESSAGE = _require.MESSAGE;
	var os = os__default;
	var TransportStream = requireDist();

	/**
	 * Transport for outputting to any arbitrary stream.
	 * @type {Stream}
	 * @extends {TransportStream}
	 */
	stream = /*#__PURE__*/function (_TransportStream) {
	  /**
	   * Constructor function for the Console transport object responsible for
	   * persisting log messages and metadata to a terminal or TTY.
	   * @param {!Object} [options={}] - Options for this instance.
	   */
	  function Stream() {
	    var _this;
	    var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
	    _classCallCheck(this, Stream);
	    _this = _callSuper(this, Stream, [options]);
	    if (!options.stream || !isStream(options.stream)) {
	      throw new Error('options.stream is required.');
	    }

	    // We need to listen for drain events when write() returns false. This can
	    // make node mad at times.
	    _this._stream = options.stream;
	    _this._stream.setMaxListeners(Infinity);
	    _this.isObjectMode = options.stream._writableState.objectMode;
	    _this.eol = typeof options.eol === 'string' ? options.eol : os.EOL;
	    return _this;
	  }

	  /**
	   * Core logging method exposed to Winston.
	   * @param {Object} info - TODO: add param description.
	   * @param {Function} callback - TODO: add param description.
	   * @returns {undefined}
	   */
	  _inherits(Stream, _TransportStream);
	  return _createClass(Stream, [{
	    key: "log",
	    value: function log(info, callback) {
	      var _this2 = this;
	      setImmediate(function () {
	        return _this2.emit('logged', info);
	      });
	      if (this.isObjectMode) {
	        this._stream.write(info);
	        if (callback) {
	          callback(); // eslint-disable-line callback-return
	        }
	        return;
	      }
	      this._stream.write("".concat(info[MESSAGE]).concat(this.eol));
	      if (callback) {
	        callback(); // eslint-disable-line callback-return
	      }
	      return;
	    }
	  }]);
	}(TransportStream);
	return stream;
}

/**
 * transports.js: Set of all transports Winston knows about.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var hasRequiredTransports;

function requireTransports () {
	if (hasRequiredTransports) return transports;
	hasRequiredTransports = 1;
	(function (exports$1) {

		/**
		 * TODO: add property description.
		 * @type {Console}
		 */
		Object.defineProperty(exports$1, 'Console', {
		  configurable: true,
		  enumerable: true,
		  get: function get() {
		    return requireConsole$1();
		  }
		});

		/**
		 * TODO: add property description.
		 * @type {File}
		 */
		Object.defineProperty(exports$1, 'File', {
		  configurable: true,
		  enumerable: true,
		  get: function get() {
		    return requireFile();
		  }
		});

		/**
		 * TODO: add property description.
		 * @type {Http}
		 */
		Object.defineProperty(exports$1, 'Http', {
		  configurable: true,
		  enumerable: true,
		  get: function get() {
		    return requireHttp();
		  }
		});

		/**
		 * TODO: add property description.
		 * @type {Stream}
		 */
		Object.defineProperty(exports$1, 'Stream', {
		  configurable: true,
		  enumerable: true,
		  get: function get() {
		    return requireStream();
		  }
		}); 
	} (transports));
	return transports;
}

var config = {};

/**
 * index.js: Default settings for all levels that winston knows about.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var hasRequiredConfig;

function requireConfig () {
	if (hasRequiredConfig) return config;
	hasRequiredConfig = 1;

	var logform = requireBrowser$2();
	var _require = requireTripleBeam(),
	  configs = _require.configs;

	/**
	 * Export config set for the CLI.
	 * @type {Object}
	 */
	config.cli = logform.levels(configs.cli);

	/**
	 * Export config set for npm.
	 * @type {Object}
	 */
	config.npm = logform.levels(configs.npm);

	/**
	 * Export config set for the syslog.
	 * @type {Object}
	 */
	config.syslog = logform.levels(configs.syslog);

	/**
	 * Hoist addColors from logform where it was refactored into in winston@3.
	 * @type {Object}
	 */
	config.addColors = logform.levels;
	return config;
}

var forEach = {exports: {}};

var eachOf = {exports: {}};

var hasRequiredEachOf;

function requireEachOf () {
	if (hasRequiredEachOf) return eachOf.exports;
	hasRequiredEachOf = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});

		var _isArrayLike = requireIsArrayLike();

		var _isArrayLike2 = _interopRequireDefault(_isArrayLike);

		var _breakLoop = requireBreakLoop();

		var _breakLoop2 = _interopRequireDefault(_breakLoop);

		var _eachOfLimit = requireEachOfLimit();

		var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);

		var _once = requireOnce();

		var _once2 = _interopRequireDefault(_once);

		var _onlyOnce = requireOnlyOnce();

		var _onlyOnce2 = _interopRequireDefault(_onlyOnce);

		var _wrapAsync = requireWrapAsync();

		var _wrapAsync2 = _interopRequireDefault(_wrapAsync);

		var _awaitify = requireAwaitify();

		var _awaitify2 = _interopRequireDefault(_awaitify);

		function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

		// eachOf implementation optimized for array-likes
		function eachOfArrayLike(coll, iteratee, callback) {
		    callback = (0, _once2.default)(callback);
		    var index = 0,
		        completed = 0,
		        { length } = coll,
		        canceled = false;
		    if (length === 0) {
		        callback(null);
		    }

		    function iteratorCallback(err, value) {
		        if (err === false) {
		            canceled = true;
		        }
		        if (canceled === true) return;
		        if (err) {
		            callback(err);
		        } else if (++completed === length || value === _breakLoop2.default) {
		            callback(null);
		        }
		    }

		    for (; index < length; index++) {
		        iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback));
		    }
		}

		// a generic version of eachOf which can handle array, object, and iterator cases.
		function eachOfGeneric(coll, iteratee, callback) {
		    return (0, _eachOfLimit2.default)(coll, Infinity, iteratee, callback);
		}

		/**
		 * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument
		 * to the iteratee.
		 *
		 * @name eachOf
		 * @static
		 * @memberOf module:Collections
		 * @method
		 * @alias forEachOf
		 * @category Collection
		 * @see [async.each]{@link module:Collections.each}
		 * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
		 * @param {AsyncFunction} iteratee - A function to apply to each
		 * item in `coll`.
		 * The `key` is the item's key, or index in the case of an array.
		 * Invoked with (item, key, callback).
		 * @param {Function} [callback] - A callback which is called when all
		 * `iteratee` functions have finished, or an error occurs. Invoked with (err).
		 * @returns {Promise} a promise, if a callback is omitted
		 * @example
		 *
		 * // dev.json is a file containing a valid json object config for dev environment
		 * // dev.json is a file containing a valid json object config for test environment
		 * // prod.json is a file containing a valid json object config for prod environment
		 * // invalid.json is a file with a malformed json object
		 *
		 * let configs = {}; //global variable
		 * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'};
		 * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'};
		 *
		 * // asynchronous function that reads a json file and parses the contents as json object
		 * function parseFile(file, key, callback) {
		 *     fs.readFile(file, "utf8", function(err, data) {
		 *         if (err) return calback(err);
		 *         try {
		 *             configs[key] = JSON.parse(data);
		 *         } catch (e) {
		 *             return callback(e);
		 *         }
		 *         callback();
		 *     });
		 * }
		 *
		 * // Using callbacks
		 * async.forEachOf(validConfigFileMap, parseFile, function (err) {
		 *     if (err) {
		 *         console.error(err);
		 *     } else {
		 *         console.log(configs);
		 *         // configs is now a map of JSON data, e.g.
		 *         // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
		 *     }
		 * });
		 *
		 * //Error handing
		 * async.forEachOf(invalidConfigFileMap, parseFile, function (err) {
		 *     if (err) {
		 *         console.error(err);
		 *         // JSON parse error exception
		 *     } else {
		 *         console.log(configs);
		 *     }
		 * });
		 *
		 * // Using Promises
		 * async.forEachOf(validConfigFileMap, parseFile)
		 * .then( () => {
		 *     console.log(configs);
		 *     // configs is now a map of JSON data, e.g.
		 *     // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
		 * }).catch( err => {
		 *     console.error(err);
		 * });
		 *
		 * //Error handing
		 * async.forEachOf(invalidConfigFileMap, parseFile)
		 * .then( () => {
		 *     console.log(configs);
		 * }).catch( err => {
		 *     console.error(err);
		 *     // JSON parse error exception
		 * });
		 *
		 * // Using async/await
		 * async () => {
		 *     try {
		 *         let result = await async.forEachOf(validConfigFileMap, parseFile);
		 *         console.log(configs);
		 *         // configs is now a map of JSON data, e.g.
		 *         // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
		 *     }
		 *     catch (err) {
		 *         console.log(err);
		 *     }
		 * }
		 *
		 * //Error handing
		 * async () => {
		 *     try {
		 *         let result = await async.forEachOf(invalidConfigFileMap, parseFile);
		 *         console.log(configs);
		 *     }
		 *     catch (err) {
		 *         console.log(err);
		 *         // JSON parse error exception
		 *     }
		 * }
		 *
		 */
		function eachOf(coll, iteratee, callback) {
		    var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric;
		    return eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback);
		}

		exports$1.default = (0, _awaitify2.default)(eachOf, 3);
		module.exports = exports$1.default; 
	} (eachOf, eachOf.exports));
	return eachOf.exports;
}

var withoutIndex = {exports: {}};

var hasRequiredWithoutIndex;

function requireWithoutIndex () {
	if (hasRequiredWithoutIndex) return withoutIndex.exports;
	hasRequiredWithoutIndex = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});
		exports$1.default = _withoutIndex;
		function _withoutIndex(iteratee) {
		    return (value, index, callback) => iteratee(value, callback);
		}
		module.exports = exports$1.default; 
	} (withoutIndex, withoutIndex.exports));
	return withoutIndex.exports;
}

var hasRequiredForEach;

function requireForEach () {
	if (hasRequiredForEach) return forEach.exports;
	hasRequiredForEach = 1;
	(function (module, exports$1) {

		Object.defineProperty(exports$1, "__esModule", {
		    value: true
		});

		var _eachOf = requireEachOf();

		var _eachOf2 = _interopRequireDefault(_eachOf);

		var _withoutIndex = requireWithoutIndex();

		var _withoutIndex2 = _interopRequireDefault(_withoutIndex);

		var _wrapAsync = requireWrapAsync();

		var _wrapAsync2 = _interopRequireDefault(_wrapAsync);

		var _awaitify = requireAwaitify();

		var _awaitify2 = _interopRequireDefault(_awaitify);

		function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

		/**
		 * Applies the function `iteratee` to each item in `coll`, in parallel.
		 * The `iteratee` is called with an item from the list, and a callback for when
		 * it has finished. If the `iteratee` passes an error to its `callback`, the
		 * main `callback` (for the `each` function) is immediately called with the
		 * error.
		 *
		 * Note, that since this function applies `iteratee` to each item in parallel,
		 * there is no guarantee that the iteratee functions will complete in order.
		 *
		 * @name each
		 * @static
		 * @memberOf module:Collections
		 * @method
		 * @alias forEach
		 * @category Collection
		 * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
		 * @param {AsyncFunction} iteratee - An async function to apply to
		 * each item in `coll`. Invoked with (item, callback).
		 * The array index is not passed to the iteratee.
		 * If you need the index, use `eachOf`.
		 * @param {Function} [callback] - A callback which is called when all
		 * `iteratee` functions have finished, or an error occurs. Invoked with (err).
		 * @returns {Promise} a promise, if a callback is omitted
		 * @example
		 *
		 * // dir1 is a directory that contains file1.txt, file2.txt
		 * // dir2 is a directory that contains file3.txt, file4.txt
		 * // dir3 is a directory that contains file5.txt
		 * // dir4 does not exist
		 *
		 * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt'];
		 * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt'];
		 *
		 * // asynchronous function that deletes a file
		 * const deleteFile = function(file, callback) {
		 *     fs.unlink(file, callback);
		 * };
		 *
		 * // Using callbacks
		 * async.each(fileList, deleteFile, function(err) {
		 *     if( err ) {
		 *         console.log(err);
		 *     } else {
		 *         console.log('All files have been deleted successfully');
		 *     }
		 * });
		 *
		 * // Error Handling
		 * async.each(withMissingFileList, deleteFile, function(err){
		 *     console.log(err);
		 *     // [ Error: ENOENT: no such file or directory ]
		 *     // since dir4/file2.txt does not exist
		 *     // dir1/file1.txt could have been deleted
		 * });
		 *
		 * // Using Promises
		 * async.each(fileList, deleteFile)
		 * .then( () => {
		 *     console.log('All files have been deleted successfully');
		 * }).catch( err => {
		 *     console.log(err);
		 * });
		 *
		 * // Error Handling
		 * async.each(fileList, deleteFile)
		 * .then( () => {
		 *     console.log('All files have been deleted successfully');
		 * }).catch( err => {
		 *     console.log(err);
		 *     // [ Error: ENOENT: no such file or directory ]
		 *     // since dir4/file2.txt does not exist
		 *     // dir1/file1.txt could have been deleted
		 * });
		 *
		 * // Using async/await
		 * async () => {
		 *     try {
		 *         await async.each(files, deleteFile);
		 *     }
		 *     catch (err) {
		 *         console.log(err);
		 *     }
		 * }
		 *
		 * // Error Handling
		 * async () => {
		 *     try {
		 *         await async.each(withMissingFileList, deleteFile);
		 *     }
		 *     catch (err) {
		 *         console.log(err);
		 *         // [ Error: ENOENT: no such file or directory ]
		 *         // since dir4/file2.txt does not exist
		 *         // dir1/file1.txt could have been deleted
		 *     }
		 * }
		 *
		 */
		function eachLimit(coll, iteratee, callback) {
		    return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback);
		}

		exports$1.default = (0, _awaitify2.default)(eachLimit, 3);
		module.exports = exports$1.default; 
	} (forEach, forEach.exports));
	return forEach.exports;
}

var fn_name;
var hasRequiredFn_name;

function requireFn_name () {
	if (hasRequiredFn_name) return fn_name;
	hasRequiredFn_name = 1;

	var toString = Object.prototype.toString;

	/**
	 * Extract names from functions.
	 *
	 * @param {Function} fn The function who's name we need to extract.
	 * @returns {String} The name of the function.
	 * @public
	 */
	fn_name = function name(fn) {
	  if ('string' === typeof fn.displayName && fn.constructor.name) {
	    return fn.displayName;
	  } else if ('string' === typeof fn.name && fn.name) {
	    return fn.name;
	  }

	  //
	  // Check to see if the constructor has a name.
	  //
	  if (
	       'object' === typeof fn
	    && fn.constructor
	    && 'string' === typeof fn.constructor.name
	  ) return fn.constructor.name;

	  //
	  // toString the given function and attempt to parse it out of it, or determine
	  // the class.
	  //
	  var named = fn.toString()
	    , type = toString.call(fn).slice(8, -1);

	  if ('Function' === type) {
	    named = named.substring(named.indexOf('(') + 1, named.indexOf(')'));
	  } else {
	    named = type;
	  }

	  return named || 'anonymous';
	};
	return fn_name;
}

var oneTime;
var hasRequiredOneTime;

function requireOneTime () {
	if (hasRequiredOneTime) return oneTime;
	hasRequiredOneTime = 1;

	var name = requireFn_name();

	/**
	 * Wrap callbacks to prevent double execution.
	 *
	 * @param {Function} fn Function that should only be called once.
	 * @returns {Function} A wrapped callback which prevents multiple executions.
	 * @public
	 */
	oneTime = function one(fn) {
	  var called = 0
	    , value;

	  /**
	   * The function that prevents double execution.
	   *
	   * @private
	   */
	  function onetime() {
	    if (called) return value;

	    called = 1;
	    value = fn.apply(this, arguments);
	    fn = null;

	    return value;
	  }

	  //
	  // To make debugging more easy we want to use the name of the supplied
	  // function. So when you look at the functions that are assigned to event
	  // listeners you don't see a load of `onetime` functions but actually the
	  // names of the functions that this module will call.
	  //
	  // NOTE: We cannot override the `name` property, as that is `readOnly`
	  // property, so displayName will have to do.
	  //
	  onetime.displayName = name(fn);
	  return onetime;
	};
	return oneTime;
}

var stackTrace = {};

var hasRequiredStackTrace;

function requireStackTrace () {
	if (hasRequiredStackTrace) return stackTrace;
	hasRequiredStackTrace = 1;
	(function (exports$1) {
		exports$1.get = function(belowFn) {
		  var oldLimit = Error.stackTraceLimit;
		  Error.stackTraceLimit = Infinity;

		  var dummyObject = {};

		  var v8Handler = Error.prepareStackTrace;
		  Error.prepareStackTrace = function(dummyObject, v8StackTrace) {
		    return v8StackTrace;
		  };
		  Error.captureStackTrace(dummyObject, belowFn || exports$1.get);

		  var v8StackTrace = dummyObject.stack;
		  Error.prepareStackTrace = v8Handler;
		  Error.stackTraceLimit = oldLimit;

		  return v8StackTrace;
		};

		exports$1.parse = function(err) {
		  if (!err.stack) {
		    return [];
		  }

		  var self = this;
		  var lines = err.stack.split('\n').slice(1);

		  return lines
		    .map(function(line) {
		      if (line.match(/^\s*[-]{4,}$/)) {
		        return self._createParsedCallSite({
		          fileName: line,
		          lineNumber: null,
		          functionName: null,
		          typeName: null,
		          methodName: null,
		          columnNumber: null,
		          'native': null,
		        });
		      }

		      var lineMatch = line.match(/at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/);
		      if (!lineMatch) {
		        return;
		      }

		      var object = null;
		      var method = null;
		      var functionName = null;
		      var typeName = null;
		      var methodName = null;
		      var isNative = (lineMatch[5] === 'native');

		      if (lineMatch[1]) {
		        functionName = lineMatch[1];
		        var methodStart = functionName.lastIndexOf('.');
		        if (functionName[methodStart-1] == '.')
		          methodStart--;
		        if (methodStart > 0) {
		          object = functionName.substr(0, methodStart);
		          method = functionName.substr(methodStart + 1);
		          var objectEnd = object.indexOf('.Module');
		          if (objectEnd > 0) {
		            functionName = functionName.substr(objectEnd + 1);
		            object = object.substr(0, objectEnd);
		          }
		        }
		        typeName = null;
		      }

		      if (method) {
		        typeName = object;
		        methodName = method;
		      }

		      if (method === '<anonymous>') {
		        methodName = null;
		        functionName = null;
		      }

		      var properties = {
		        fileName: lineMatch[2] || null,
		        lineNumber: parseInt(lineMatch[3], 10) || null,
		        functionName: functionName,
		        typeName: typeName,
		        methodName: methodName,
		        columnNumber: parseInt(lineMatch[4], 10) || null,
		        'native': isNative,
		      };

		      return self._createParsedCallSite(properties);
		    })
		    .filter(function(callSite) {
		      return !!callSite;
		    });
		};

		function CallSite(properties) {
		  for (var property in properties) {
		    this[property] = properties[property];
		  }
		}

		var strProperties = [
		  'this',
		  'typeName',
		  'functionName',
		  'methodName',
		  'fileName',
		  'lineNumber',
		  'columnNumber',
		  'function',
		  'evalOrigin'
		];
		var boolProperties = [
		  'topLevel',
		  'eval',
		  'native',
		  'constructor'
		];
		strProperties.forEach(function (property) {
		  CallSite.prototype[property] = null;
		  CallSite.prototype['get' + property[0].toUpperCase() + property.substr(1)] = function () {
		    return this[property];
		  };
		});
		boolProperties.forEach(function (property) {
		  CallSite.prototype[property] = false;
		  CallSite.prototype['is' + property[0].toUpperCase() + property.substr(1)] = function () {
		    return this[property];
		  };
		});

		exports$1._createParsedCallSite = function(properties) {
		  return new CallSite(properties);
		}; 
	} (stackTrace));
	return stackTrace;
}

/**
 * exception-stream.js: TODO: add file header handler.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var exceptionStream;
var hasRequiredExceptionStream;

function requireExceptionStream () {
	if (hasRequiredExceptionStream) return exceptionStream;
	hasRequiredExceptionStream = 1;

	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
	function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
	function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
	function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
	function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
	function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
	function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
	function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: true, configurable: true } }), Object.defineProperty(t, "prototype", { writable: false }), e && _setPrototypeOf(t, e); }
	function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
	var _require = requireReadableBrowser(),
	  Writable = _require.Writable;

	/**
	 * TODO: add class description.
	 * @type {ExceptionStream}
	 * @extends {Writable}
	 */
	exceptionStream = /*#__PURE__*/function (_Writable) {
	  /**
	   * Constructor function for the ExceptionStream responsible for wrapping a
	   * TransportStream; only allowing writes of `info` objects with
	   * `info.exception` set to true.
	   * @param {!TransportStream} transport - Stream to filter to exceptions
	   */
	  function ExceptionStream(transport) {
	    var _this;
	    _classCallCheck(this, ExceptionStream);
	    _this = _callSuper(this, ExceptionStream, [{
	      objectMode: true
	    }]);
	    if (!transport) {
	      throw new Error('ExceptionStream requires a TransportStream instance.');
	    }

	    // Remark (indexzero): we set `handleExceptions` here because it's the
	    // predicate checked in ExceptionHandler.prototype.__getExceptionHandlers
	    _this.handleExceptions = true;
	    _this.transport = transport;
	    return _this;
	  }

	  /**
	   * Writes the info object to our transport instance if (and only if) the
	   * `exception` property is set on the info.
	   * @param {mixed} info - TODO: add param description.
	   * @param {mixed} enc - TODO: add param description.
	   * @param {mixed} callback - TODO: add param description.
	   * @returns {mixed} - TODO: add return description.
	   * @private
	   */
	  _inherits(ExceptionStream, _Writable);
	  return _createClass(ExceptionStream, [{
	    key: "_write",
	    value: function _write(info, enc, callback) {
	      if (info.exception) {
	        return this.transport.log(info, callback);
	      }
	      callback();
	      return true;
	    }
	  }]);
	}(Writable);
	return exceptionStream;
}

/**
 * exception-handler.js: Object for handling uncaughtException events.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var exceptionHandler;
var hasRequiredExceptionHandler;

function requireExceptionHandler () {
	if (hasRequiredExceptionHandler) return exceptionHandler;
	hasRequiredExceptionHandler = 1;

	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
	function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
	var os = os__default;
	var asyncForEach = requireForEach();
	var debug = requireBrowser$1()('winston:exception');
	var once = requireOneTime();
	var stackTrace = requireStackTrace();
	var ExceptionStream = requireExceptionStream();

	/**
	 * Object for handling uncaughtException events.
	 * @type {ExceptionHandler}
	 */
	exceptionHandler = /*#__PURE__*/function () {
	  /**
	   * TODO: add contructor description
	   * @param {!Logger} logger - TODO: add param description
	   */
	  function ExceptionHandler(logger) {
	    _classCallCheck(this, ExceptionHandler);
	    if (!logger) {
	      throw new Error('Logger is required to handle exceptions');
	    }
	    this.logger = logger;
	    this.handlers = new Map();
	  }

	  /**
	   * Handles `uncaughtException` events for the current process by adding any
	   * handlers passed in.
	   * @returns {undefined}
	   */
	  return _createClass(ExceptionHandler, [{
	    key: "handle",
	    value: function handle() {
	      var _this = this;
	      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
	        args[_key] = arguments[_key];
	      }
	      args.forEach(function (arg) {
	        if (Array.isArray(arg)) {
	          return arg.forEach(function (handler) {
	            return _this._addHandler(handler);
	          });
	        }
	        _this._addHandler(arg);
	      });
	      if (!this.catcher) {
	        this.catcher = this._uncaughtException.bind(this);
	        process.on('uncaughtException', this.catcher);
	      }
	    }

	    /**
	     * Removes any handlers to `uncaughtException` events for the current
	     * process. This does not modify the state of the `this.handlers` set.
	     * @returns {undefined}
	     */
	  }, {
	    key: "unhandle",
	    value: function unhandle() {
	      var _this2 = this;
	      if (this.catcher) {
	        process.removeListener('uncaughtException', this.catcher);
	        this.catcher = false;
	        Array.from(this.handlers.values()).forEach(function (wrapper) {
	          return _this2.logger.unpipe(wrapper);
	        });
	      }
	    }

	    /**
	     * TODO: add method description
	     * @param {Error} err - Error to get information about.
	     * @returns {mixed} - TODO: add return description.
	     */
	  }, {
	    key: "getAllInfo",
	    value: function getAllInfo(err) {
	      var message = null;
	      if (err) {
	        message = typeof err === 'string' ? err : err.message;
	      }
	      return {
	        error: err,
	        // TODO (indexzero): how do we configure this?
	        level: 'error',
	        message: ["uncaughtException: ".concat(message || '(no error message)'), err && err.stack || '  No stack trace'].join('\n'),
	        stack: err && err.stack,
	        exception: true,
	        date: new Date().toString(),
	        process: this.getProcessInfo(),
	        os: this.getOsInfo(),
	        trace: this.getTrace(err)
	      };
	    }

	    /**
	     * Gets all relevant process information for the currently running process.
	     * @returns {mixed} - TODO: add return description.
	     */
	  }, {
	    key: "getProcessInfo",
	    value: function getProcessInfo() {
	      return {
	        pid: process.pid,
	        uid: process.getuid ? process.getuid() : null,
	        gid: process.getgid ? process.getgid() : null,
	        cwd: process.cwd(),
	        execPath: process.execPath,
	        version: process.version,
	        argv: process.argv,
	        memoryUsage: process.memoryUsage()
	      };
	    }

	    /**
	     * Gets all relevant OS information for the currently running process.
	     * @returns {mixed} - TODO: add return description.
	     */
	  }, {
	    key: "getOsInfo",
	    value: function getOsInfo() {
	      return {
	        loadavg: os.loadavg(),
	        uptime: os.uptime()
	      };
	    }

	    /**
	     * Gets a stack trace for the specified error.
	     * @param {mixed} err - TODO: add param description.
	     * @returns {mixed} - TODO: add return description.
	     */
	  }, {
	    key: "getTrace",
	    value: function getTrace(err) {
	      var trace = err ? stackTrace.parse(err) : stackTrace.get();
	      return trace.map(function (site) {
	        return {
	          column: site.getColumnNumber(),
	          file: site.getFileName(),
	          "function": site.getFunctionName(),
	          line: site.getLineNumber(),
	          method: site.getMethodName(),
	          "native": site.isNative()
	        };
	      });
	    }

	    /**
	     * Helper method to add a transport as an exception handler.
	     * @param {Transport} handler - The transport to add as an exception handler.
	     * @returns {void}
	     */
	  }, {
	    key: "_addHandler",
	    value: function _addHandler(handler) {
	      if (!this.handlers.has(handler)) {
	        handler.handleExceptions = true;
	        var wrapper = new ExceptionStream(handler);
	        this.handlers.set(handler, wrapper);
	        this.logger.pipe(wrapper);
	      }
	    }

	    /**
	     * Logs all relevant information around the `err` and exits the current
	     * process.
	     * @param {Error} err - Error to handle
	     * @returns {mixed} - TODO: add return description.
	     * @private
	     */
	  }, {
	    key: "_uncaughtException",
	    value: function _uncaughtException(err) {
	      var info = this.getAllInfo(err);
	      var handlers = this._getExceptionHandlers();
	      // Calculate if we should exit on this error
	      var doExit = typeof this.logger.exitOnError === 'function' ? this.logger.exitOnError(err) : this.logger.exitOnError;
	      var timeout;
	      if (!handlers.length && doExit) {
	        // eslint-disable-next-line no-console
	        console.warn('winston: exitOnError cannot be true with no exception handlers.');
	        // eslint-disable-next-line no-console
	        console.warn('winston: not exiting process.');
	        doExit = false;
	      }
	      function gracefulExit() {
	        debug('doExit', doExit);
	        debug('process._exiting', process._exiting);
	        if (doExit && !process._exiting) {
	          // Remark: Currently ignoring any exceptions from transports when
	          // catching uncaught exceptions.
	          if (timeout) {
	            clearTimeout(timeout);
	          }
	          // eslint-disable-next-line no-process-exit
	          process.exit(1);
	        }
	      }
	      if (!handlers || handlers.length === 0) {
	        return process.nextTick(gracefulExit);
	      }

	      // Log to all transports attempting to listen for when they are completed.
	      asyncForEach(handlers, function (handler, next) {
	        var done = once(next);
	        var transport = handler.transport || handler;

	        // Debug wrapping so that we can inspect what's going on under the covers.
	        function onDone(event) {
	          return function () {
	            debug(event);
	            done();
	          };
	        }
	        transport._ending = true;
	        transport.once('finish', onDone('finished'));
	        transport.once('error', onDone('error'));
	      }, function () {
	        return doExit && gracefulExit();
	      });
	      this.logger.log(info);

	      // If exitOnError is true, then only allow the logging of exceptions to
	      // take up to `3000ms`.
	      if (doExit) {
	        timeout = setTimeout(gracefulExit, 3000);
	      }
	    }

	    /**
	     * Returns the list of transports and exceptionHandlers for this instance.
	     * @returns {Array} - List of transports and exceptionHandlers for this
	     * instance.
	     * @private
	     */
	  }, {
	    key: "_getExceptionHandlers",
	    value: function _getExceptionHandlers() {
	      // Remark (indexzero): since `logger.transports` returns all of the pipes
	      // from the _readableState of the stream we actually get the join of the
	      // explicit handlers and the implicit transports with
	      // `handleExceptions: true`
	      return this.logger.transports.filter(function (wrap) {
	        var transport = wrap.transport || wrap;
	        return transport.handleExceptions;
	      });
	    }
	  }]);
	}();
	return exceptionHandler;
}

/**
 * rejection-stream.js: TODO: add file header handler.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var rejectionStream;
var hasRequiredRejectionStream;

function requireRejectionStream () {
	if (hasRequiredRejectionStream) return rejectionStream;
	hasRequiredRejectionStream = 1;

	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
	function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
	function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
	function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
	function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
	function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
	function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
	function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: true, configurable: true } }), Object.defineProperty(t, "prototype", { writable: false }), e && _setPrototypeOf(t, e); }
	function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
	var _require = requireReadableBrowser(),
	  Writable = _require.Writable;

	/**
	 * TODO: add class description.
	 * @type {RejectionStream}
	 * @extends {Writable}
	 */
	rejectionStream = /*#__PURE__*/function (_Writable) {
	  /**
	   * Constructor function for the RejectionStream responsible for wrapping a
	   * TransportStream; only allowing writes of `info` objects with
	   * `info.rejection` set to true.
	   * @param {!TransportStream} transport - Stream to filter to rejections
	   */
	  function RejectionStream(transport) {
	    var _this;
	    _classCallCheck(this, RejectionStream);
	    _this = _callSuper(this, RejectionStream, [{
	      objectMode: true
	    }]);
	    if (!transport) {
	      throw new Error('RejectionStream requires a TransportStream instance.');
	    }
	    _this.handleRejections = true;
	    _this.transport = transport;
	    return _this;
	  }

	  /**
	   * Writes the info object to our transport instance if (and only if) the
	   * `rejection` property is set on the info.
	   * @param {mixed} info - TODO: add param description.
	   * @param {mixed} enc - TODO: add param description.
	   * @param {mixed} callback - TODO: add param description.
	   * @returns {mixed} - TODO: add return description.
	   * @private
	   */
	  _inherits(RejectionStream, _Writable);
	  return _createClass(RejectionStream, [{
	    key: "_write",
	    value: function _write(info, enc, callback) {
	      if (info.rejection) {
	        return this.transport.log(info, callback);
	      }
	      callback();
	      return true;
	    }
	  }]);
	}(Writable);
	return rejectionStream;
}

/**
 * exception-handler.js: Object for handling uncaughtException events.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var rejectionHandler;
var hasRequiredRejectionHandler;

function requireRejectionHandler () {
	if (hasRequiredRejectionHandler) return rejectionHandler;
	hasRequiredRejectionHandler = 1;

	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
	function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
	var os = os__default;
	var asyncForEach = requireForEach();
	var debug = requireBrowser$1()('winston:rejection');
	var once = requireOneTime();
	var stackTrace = requireStackTrace();
	var RejectionStream = requireRejectionStream();

	/**
	 * Object for handling unhandledRejection events.
	 * @type {RejectionHandler}
	 */
	rejectionHandler = /*#__PURE__*/function () {
	  /**
	   * TODO: add contructor description
	   * @param {!Logger} logger - TODO: add param description
	   */
	  function RejectionHandler(logger) {
	    _classCallCheck(this, RejectionHandler);
	    if (!logger) {
	      throw new Error('Logger is required to handle rejections');
	    }
	    this.logger = logger;
	    this.handlers = new Map();
	  }

	  /**
	   * Handles `unhandledRejection` events for the current process by adding any
	   * handlers passed in.
	   * @returns {undefined}
	   */
	  return _createClass(RejectionHandler, [{
	    key: "handle",
	    value: function handle() {
	      var _this = this;
	      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
	        args[_key] = arguments[_key];
	      }
	      args.forEach(function (arg) {
	        if (Array.isArray(arg)) {
	          return arg.forEach(function (handler) {
	            return _this._addHandler(handler);
	          });
	        }
	        _this._addHandler(arg);
	      });
	      if (!this.catcher) {
	        this.catcher = this._unhandledRejection.bind(this);
	        process.on('unhandledRejection', this.catcher);
	      }
	    }

	    /**
	     * Removes any handlers to `unhandledRejection` events for the current
	     * process. This does not modify the state of the `this.handlers` set.
	     * @returns {undefined}
	     */
	  }, {
	    key: "unhandle",
	    value: function unhandle() {
	      var _this2 = this;
	      if (this.catcher) {
	        process.removeListener('unhandledRejection', this.catcher);
	        this.catcher = false;
	        Array.from(this.handlers.values()).forEach(function (wrapper) {
	          return _this2.logger.unpipe(wrapper);
	        });
	      }
	    }

	    /**
	     * TODO: add method description
	     * @param {Error} err - Error to get information about.
	     * @returns {mixed} - TODO: add return description.
	     */
	  }, {
	    key: "getAllInfo",
	    value: function getAllInfo(err) {
	      var message = null;
	      if (err) {
	        message = typeof err === 'string' ? err : err.message;
	      }
	      return {
	        error: err,
	        // TODO (indexzero): how do we configure this?
	        level: 'error',
	        message: ["unhandledRejection: ".concat(message || '(no error message)'), err && err.stack || '  No stack trace'].join('\n'),
	        stack: err && err.stack,
	        rejection: true,
	        date: new Date().toString(),
	        process: this.getProcessInfo(),
	        os: this.getOsInfo(),
	        trace: this.getTrace(err)
	      };
	    }

	    /**
	     * Gets all relevant process information for the currently running process.
	     * @returns {mixed} - TODO: add return description.
	     */
	  }, {
	    key: "getProcessInfo",
	    value: function getProcessInfo() {
	      return {
	        pid: process.pid,
	        uid: process.getuid ? process.getuid() : null,
	        gid: process.getgid ? process.getgid() : null,
	        cwd: process.cwd(),
	        execPath: process.execPath,
	        version: process.version,
	        argv: process.argv,
	        memoryUsage: process.memoryUsage()
	      };
	    }

	    /**
	     * Gets all relevant OS information for the currently running process.
	     * @returns {mixed} - TODO: add return description.
	     */
	  }, {
	    key: "getOsInfo",
	    value: function getOsInfo() {
	      return {
	        loadavg: os.loadavg(),
	        uptime: os.uptime()
	      };
	    }

	    /**
	     * Gets a stack trace for the specified error.
	     * @param {mixed} err - TODO: add param description.
	     * @returns {mixed} - TODO: add return description.
	     */
	  }, {
	    key: "getTrace",
	    value: function getTrace(err) {
	      var trace = err ? stackTrace.parse(err) : stackTrace.get();
	      return trace.map(function (site) {
	        return {
	          column: site.getColumnNumber(),
	          file: site.getFileName(),
	          "function": site.getFunctionName(),
	          line: site.getLineNumber(),
	          method: site.getMethodName(),
	          "native": site.isNative()
	        };
	      });
	    }

	    /**
	     * Helper method to add a transport as an exception handler.
	     * @param {Transport} handler - The transport to add as an exception handler.
	     * @returns {void}
	     */
	  }, {
	    key: "_addHandler",
	    value: function _addHandler(handler) {
	      if (!this.handlers.has(handler)) {
	        handler.handleRejections = true;
	        var wrapper = new RejectionStream(handler);
	        this.handlers.set(handler, wrapper);
	        this.logger.pipe(wrapper);
	      }
	    }

	    /**
	     * Logs all relevant information around the `err` and exits the current
	     * process.
	     * @param {Error} err - Error to handle
	     * @returns {mixed} - TODO: add return description.
	     * @private
	     */
	  }, {
	    key: "_unhandledRejection",
	    value: function _unhandledRejection(err) {
	      var info = this.getAllInfo(err);
	      var handlers = this._getRejectionHandlers();
	      // Calculate if we should exit on this error
	      var doExit = typeof this.logger.exitOnError === 'function' ? this.logger.exitOnError(err) : this.logger.exitOnError;
	      var timeout;
	      if (!handlers.length && doExit) {
	        // eslint-disable-next-line no-console
	        console.warn('winston: exitOnError cannot be true with no rejection handlers.');
	        // eslint-disable-next-line no-console
	        console.warn('winston: not exiting process.');
	        doExit = false;
	      }
	      function gracefulExit() {
	        debug('doExit', doExit);
	        debug('process._exiting', process._exiting);
	        if (doExit && !process._exiting) {
	          // Remark: Currently ignoring any rejections from transports when
	          // catching unhandled rejections.
	          if (timeout) {
	            clearTimeout(timeout);
	          }
	          // eslint-disable-next-line no-process-exit
	          process.exit(1);
	        }
	      }
	      if (!handlers || handlers.length === 0) {
	        return process.nextTick(gracefulExit);
	      }

	      // Log to all transports attempting to listen for when they are completed.
	      asyncForEach(handlers, function (handler, next) {
	        var done = once(next);
	        var transport = handler.transport || handler;

	        // Debug wrapping so that we can inspect what's going on under the covers.
	        function onDone(event) {
	          return function () {
	            debug(event);
	            done();
	          };
	        }
	        transport._ending = true;
	        transport.once('finish', onDone('finished'));
	        transport.once('error', onDone('error'));
	      }, function () {
	        return doExit && gracefulExit();
	      });
	      this.logger.log(info);

	      // If exitOnError is true, then only allow the logging of exceptions to
	      // take up to `3000ms`.
	      if (doExit) {
	        timeout = setTimeout(gracefulExit, 3000);
	      }
	    }

	    /**
	     * Returns the list of transports and exceptionHandlers for this instance.
	     * @returns {Array} - List of transports and exceptionHandlers for this
	     * instance.
	     * @private
	     */
	  }, {
	    key: "_getRejectionHandlers",
	    value: function _getRejectionHandlers() {
	      // Remark (indexzero): since `logger.transports` returns all of the pipes
	      // from the _readableState of the stream we actually get the join of the
	      // explicit handlers and the implicit transports with
	      // `handleRejections: true`
	      return this.logger.transports.filter(function (wrap) {
	        var transport = wrap.transport || wrap;
	        return transport.handleRejections;
	      });
	    }
	  }]);
	}();
	return rejectionHandler;
}

var legacy = {exports: {}};

var modern = {exports: {}};

var hasRequiredModern;

function requireModern () {
	if (hasRequiredModern) return modern.exports;
	hasRequiredModern = 1;

	const util = require$$0$6;
	const Writable = require_stream_writable();
	const { LEVEL } = requireTripleBeam();

	/**
	 * Constructor function for the TransportStream. This is the base prototype
	 * that all `winston >= 3` transports should inherit from.
	 * @param {Object} options - Options for this TransportStream instance
	 * @param {String} options.level - Highest level according to RFC5424.
	 * @param {Boolean} options.handleExceptions - If true, info with
	 * { exception: true } will be written.
	 * @param {Function} options.log - Custom log function for simple Transport
	 * creation
	 * @param {Function} options.close - Called on "unpipe" from parent.
	 */
	const TransportStream = modern.exports = function TransportStream(options = {}) {
	  Writable.call(this, { objectMode: true, highWaterMark: options.highWaterMark });

	  this.format = options.format;
	  this.level = options.level;
	  this.handleExceptions = options.handleExceptions;
	  this.handleRejections = options.handleRejections;
	  this.silent = options.silent;

	  if (options.log) this.log = options.log;
	  if (options.logv) this.logv = options.logv;
	  if (options.close) this.close = options.close;

	  // Get the levels from the source we are piped from.
	  this.once('pipe', logger => {
	    // Remark (indexzero): this bookkeeping can only support multiple
	    // Logger parents with the same `levels`. This comes into play in
	    // the `winston.Container` code in which `container.add` takes
	    // a fully realized set of options with pre-constructed TransportStreams.
	    this.levels = logger.levels;
	    this.parent = logger;
	  });

	  // If and/or when the transport is removed from this instance
	  this.once('unpipe', src => {
	    // Remark (indexzero): this bookkeeping can only support multiple
	    // Logger parents with the same `levels`. This comes into play in
	    // the `winston.Container` code in which `container.add` takes
	    // a fully realized set of options with pre-constructed TransportStreams.
	    if (src === this.parent) {
	      this.parent = null;
	      if (this.close) {
	        this.close();
	      }
	    }
	  });
	};

	/*
	 * Inherit from Writeable using Node.js built-ins
	 */
	util.inherits(TransportStream, Writable);

	/**
	 * Writes the info object to our transport instance.
	 * @param {mixed} info - TODO: add param description.
	 * @param {mixed} enc - TODO: add param description.
	 * @param {function} callback - TODO: add param description.
	 * @returns {undefined}
	 * @private
	 */
	TransportStream.prototype._write = function _write(info, enc, callback) {
	  if (this.silent || (info.exception === true && !this.handleExceptions)) {
	    return callback(null);
	  }

	  // Remark: This has to be handled in the base transport now because we
	  // cannot conditionally write to our pipe targets as stream. We always
	  // prefer any explicit level set on the Transport itself falling back to
	  // any level set on the parent.
	  const level = this.level || (this.parent && this.parent.level);

	  if (!level || this.levels[level] >= this.levels[info[LEVEL]]) {
	    if (info && !this.format) {
	      return this.log(info, callback);
	    }

	    let errState;
	    let transformed;

	    // We trap(and re-throw) any errors generated by the user-provided format, but also
	    // guarantee that the streams callback is invoked so that we can continue flowing.
	    try {
	      transformed = this.format.transform(Object.assign({}, info), this.format.options);
	    } catch (err) {
	      errState = err;
	    }

	    if (errState || !transformed) {
	      // eslint-disable-next-line callback-return
	      callback();
	      if (errState) throw errState;
	      return;
	    }

	    return this.log(transformed, callback);
	  }
	  this._writableState.sync = false;
	  return callback(null);
	};

	/**
	 * Writes the batch of info objects (i.e. "object chunks") to our transport
	 * instance after performing any necessary filtering.
	 * @param {mixed} chunks - TODO: add params description.
	 * @param {function} callback - TODO: add params description.
	 * @returns {mixed} - TODO: add returns description.
	 * @private
	 */
	TransportStream.prototype._writev = function _writev(chunks, callback) {
	  if (this.logv) {
	    const infos = chunks.filter(this._accept, this);
	    if (!infos.length) {
	      return callback(null);
	    }

	    // Remark (indexzero): from a performance perspective if Transport
	    // implementers do choose to implement logv should we make it their
	    // responsibility to invoke their format?
	    return this.logv(infos, callback);
	  }

	  for (let i = 0; i < chunks.length; i++) {
	    if (!this._accept(chunks[i])) continue;

	    if (chunks[i].chunk && !this.format) {
	      this.log(chunks[i].chunk, chunks[i].callback);
	      continue;
	    }

	    let errState;
	    let transformed;

	    // We trap(and re-throw) any errors generated by the user-provided format, but also
	    // guarantee that the streams callback is invoked so that we can continue flowing.
	    try {
	      transformed = this.format.transform(
	        Object.assign({}, chunks[i].chunk),
	        this.format.options
	      );
	    } catch (err) {
	      errState = err;
	    }

	    if (errState || !transformed) {
	      // eslint-disable-next-line callback-return
	      chunks[i].callback();
	      if (errState) {
	        // eslint-disable-next-line callback-return
	        callback(null);
	        throw errState;
	      }
	    } else {
	      this.log(transformed, chunks[i].callback);
	    }
	  }

	  return callback(null);
	};

	/**
	 * Predicate function that returns true if the specfied `info` on the
	 * WriteReq, `write`, should be passed down into the derived
	 * TransportStream's I/O via `.log(info, callback)`.
	 * @param {WriteReq} write - winston@3 Node.js WriteReq for the `info` object
	 * representing the log message.
	 * @returns {Boolean} - Value indicating if the `write` should be accepted &
	 * logged.
	 */
	TransportStream.prototype._accept = function _accept(write) {
	  const info = write.chunk;
	  if (this.silent) {
	    return false;
	  }

	  // We always prefer any explicit level set on the Transport itself
	  // falling back to any level set on the parent.
	  const level = this.level || (this.parent && this.parent.level);

	  // Immediately check the average case: log level filtering.
	  if (
	    info.exception === true ||
	    !level ||
	    this.levels[level] >= this.levels[info[LEVEL]]
	  ) {
	    // Ensure the info object is valid based on `{ exception }`:
	    // 1. { handleExceptions: true }: all `info` objects are valid
	    // 2. { exception: false }: accepted by all transports.
	    if (this.handleExceptions || info.exception !== true) {
	      return true;
	    }
	  }

	  return false;
	};

	/**
	 * _nop is short for "No operation"
	 * @returns {Boolean} Intentionally false.
	 */
	TransportStream.prototype._nop = function _nop() {
	  // eslint-disable-next-line no-undefined
	  return void undefined;
	};
	return modern.exports;
}

var hasRequiredLegacy;

function requireLegacy () {
	if (hasRequiredLegacy) return legacy.exports;
	hasRequiredLegacy = 1;

	const util = require$$0$6;
	const { LEVEL } = requireTripleBeam();
	const TransportStream = requireModern();

	/**
	 * Constructor function for the LegacyTransportStream. This is an internal
	 * wrapper `winston >= 3` uses to wrap older transports implementing
	 * log(level, message, meta).
	 * @param {Object} options - Options for this TransportStream instance.
	 * @param {Transpot} options.transport - winston@2 or older Transport to wrap.
	 */

	const LegacyTransportStream = legacy.exports = function LegacyTransportStream(options = {}) {
	  TransportStream.call(this, options);
	  if (!options.transport || typeof options.transport.log !== 'function') {
	    throw new Error('Invalid transport, must be an object with a log method.');
	  }

	  this.transport = options.transport;
	  this.level = this.level || options.transport.level;
	  this.handleExceptions = this.handleExceptions || options.transport.handleExceptions;

	  // Display our deprecation notice.
	  this._deprecated();

	  // Properly bubble up errors from the transport to the
	  // LegacyTransportStream instance, but only once no matter how many times
	  // this transport is shared.
	  function transportError(err) {
	    this.emit('error', err, this.transport);
	  }

	  if (!this.transport.__winstonError) {
	    this.transport.__winstonError = transportError.bind(this);
	    this.transport.on('error', this.transport.__winstonError);
	  }
	};

	/*
	 * Inherit from TransportStream using Node.js built-ins
	 */
	util.inherits(LegacyTransportStream, TransportStream);

	/**
	 * Writes the info object to our transport instance.
	 * @param {mixed} info - TODO: add param description.
	 * @param {mixed} enc - TODO: add param description.
	 * @param {function} callback - TODO: add param description.
	 * @returns {undefined}
	 * @private
	 */
	LegacyTransportStream.prototype._write = function _write(info, enc, callback) {
	  if (this.silent || (info.exception === true && !this.handleExceptions)) {
	    return callback(null);
	  }

	  // Remark: This has to be handled in the base transport now because we
	  // cannot conditionally write to our pipe targets as stream.
	  if (!this.level || this.levels[this.level] >= this.levels[info[LEVEL]]) {
	    this.transport.log(info[LEVEL], info.message, info, this._nop);
	  }

	  callback(null);
	};

	/**
	 * Writes the batch of info objects (i.e. "object chunks") to our transport
	 * instance after performing any necessary filtering.
	 * @param {mixed} chunks - TODO: add params description.
	 * @param {function} callback - TODO: add params description.
	 * @returns {mixed} - TODO: add returns description.
	 * @private
	 */
	LegacyTransportStream.prototype._writev = function _writev(chunks, callback) {
	  for (let i = 0; i < chunks.length; i++) {
	    if (this._accept(chunks[i])) {
	      this.transport.log(
	        chunks[i].chunk[LEVEL],
	        chunks[i].chunk.message,
	        chunks[i].chunk,
	        this._nop
	      );
	      chunks[i].callback();
	    }
	  }

	  return callback(null);
	};

	/**
	 * Displays a deprecation notice. Defined as a function so it can be
	 * overriden in tests.
	 * @returns {undefined}
	 */
	LegacyTransportStream.prototype._deprecated = function _deprecated() {
	  // eslint-disable-next-line no-console
	  console.error([
	    `${this.transport.name} is a legacy winston transport. Consider upgrading: `,
	    '- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md'
	  ].join('\n'));
	};

	/**
	 * Clean up error handling state on the legacy transport associated
	 * with this instance.
	 * @returns {undefined}
	 */
	LegacyTransportStream.prototype.close = function close() {
	  if (this.transport.close) {
	    this.transport.close();
	  }

	  if (this.transport.__winstonError) {
	    this.transport.removeListener('error', this.transport.__winstonError);
	    this.transport.__winstonError = null;
	  }
	};
	return legacy.exports;
}

/**
 * profiler.js: TODO: add file header description.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var profiler;
var hasRequiredProfiler;

function requireProfiler () {
	if (hasRequiredProfiler) return profiler;
	hasRequiredProfiler = 1;

	/**
	 * TODO: add class description.
	 * @type {Profiler}
	 * @private
	 */
	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
	function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
	var Profiler = /*#__PURE__*/function () {
	  /**
	   * Constructor function for the Profiler instance used by
	   * `Logger.prototype.startTimer`. When done is called the timer will finish
	   * and log the duration.
	   * @param {!Logger} logger - TODO: add param description.
	   * @private
	   */
	  function Profiler(logger) {
	    _classCallCheck(this, Profiler);
	    var Logger = requireLogger();
	    if (_typeof(logger) !== 'object' || Array.isArray(logger) || !(logger instanceof Logger)) {
	      throw new Error('Logger is required for profiling');
	    } else {
	      this.logger = logger;
	      this.start = Date.now();
	    }
	  }

	  /**
	   * Ends the current timer (i.e. Profiler) instance and logs the `msg` along
	   * with the duration since creation.
	   * @returns {mixed} - TODO: add return description.
	   * @private
	   */
	  return _createClass(Profiler, [{
	    key: "done",
	    value: function done() {
	      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
	        args[_key] = arguments[_key];
	      }
	      if (typeof args[args.length - 1] === 'function') {
	        // eslint-disable-next-line no-console
	        console.warn('Callback function no longer supported as of winston@3.0.0');
	        args.pop();
	      }
	      var info = _typeof(args[args.length - 1]) === 'object' ? args.pop() : {};
	      info.level = info.level || 'info';
	      info.durationMs = Date.now() - this.start;
	      return this.logger.write(info);
	    }
	  }]);
	}();
	profiler = Profiler;
	return profiler;
}

var format$2;
var hasRequiredFormat$2;

function requireFormat$2 () {
	if (hasRequiredFormat$2) return format$2;
	hasRequiredFormat$2 = 1;

	/*
	 * Displays a helpful message and the source of
	 * the format when it is invalid.
	 */
	class InvalidFormatError extends Error {
	  constructor(formatFn) {
	    super(`Format functions must be synchronous taking a two arguments: (info, opts)
Found: ${formatFn.toString().split('\n')[0]}\n`);

	    Error.captureStackTrace(this, InvalidFormatError);
	  }
	}

	/*
	 * function format (formatFn)
	 * Returns a create function for the `formatFn`.
	 */
	format$2 = formatFn => {
	  if (formatFn.length > 2) {
	    throw new InvalidFormatError(formatFn);
	  }

	  /*
	   * function Format (options)
	   * Base prototype which calls a `_format`
	   * function and pushes the result.
	   */
	  function Format(options = {}) {
	    this.options = options;
	  }

	  Format.prototype.transform = formatFn;

	  //
	  // Create a function which returns new instances of
	  // FormatWrap for simple syntax like:
	  //
	  // require('winston').formats.json();
	  //
	  function createFormatWrap(opts) {
	    return new Format(opts);
	  }

	  //
	  // Expose the FormatWrap through the create function
	  // for testability.
	  //
	  createFormatWrap.Format = Format;
	  return createFormatWrap;
	};
	return format$2;
}

var json;
var hasRequiredJson;

function requireJson () {
	if (hasRequiredJson) return json;
	hasRequiredJson = 1;

	const format = requireFormat$2();
	const { MESSAGE } = requireTripleBeam();
	const stringify = requireSafeStableStringify();

	/*
	 * function replacer (key, value)
	 * Handles proper stringification of Buffer and bigint output.
	 */
	function replacer(key, value) {
	  // safe-stable-stringify does support BigInt, however, it doesn't wrap the value in quotes.
	  // Leading to a loss in fidelity if the resulting string is parsed.
	  // It would also be a breaking change for logform.
	  if (typeof value === 'bigint')
	    return value.toString();
	  return value;
	}

	/*
	 * function json (info)
	 * Returns a new instance of the JSON format that turns a log `info`
	 * object into pure JSON. This was previously exposed as { json: true }
	 * to transports in `winston < 3.0.0`.
	 */
	json = format((info, opts) => {
	  const jsonStringify = stringify.configure(opts);
	  info[MESSAGE] = jsonStringify(info, opts.replacer || replacer, opts.space);
	  return info;
	});
	return json;
}

/**
 * logger.js: TODO: add file header description.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var logger;
var hasRequiredLogger;

function requireLogger () {
	if (hasRequiredLogger) return logger;
	hasRequiredLogger = 1;

	function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; }
	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
	function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
	function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
	function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
	function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
	function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
	function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
	function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: true, configurable: true } }), Object.defineProperty(t, "prototype", { writable: false }), e && _setPrototypeOf(t, e); }
	function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
	var _require = requireReadableBrowser(),
	  Stream = _require.Stream,
	  Transform = _require.Transform;
	var asyncForEach = requireForEach();
	var _require2 = requireTripleBeam(),
	  LEVEL = _require2.LEVEL,
	  SPLAT = _require2.SPLAT;
	var isStream = requireIsStream();
	var ExceptionHandler = requireExceptionHandler();
	var RejectionHandler = requireRejectionHandler();
	var LegacyTransportStream = requireLegacy();
	var Profiler = requireProfiler();
	var _require3 = requireCommon(),
	  warn = _require3.warn;
	var config = requireConfig();

	/**
	 * Captures the number of format (i.e. %s strings) in a given string.
	 * Based on `util.format`, see Node.js source:
	 * https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230
	 * @type {RegExp}
	 */
	var formatRegExp = /%[scdjifoO%]/g;

	/**
	 * TODO: add class description.
	 * @type {Logger}
	 * @extends {Transform}
	 */
	var Logger = /*#__PURE__*/function (_Transform) {
	  /**
	   * Constructor function for the Logger object responsible for persisting log
	   * messages and metadata to one or more transports.
	   * @param {!Object} options - foo
	   */
	  function Logger(options) {
	    var _this;
	    _classCallCheck(this, Logger);
	    _this = _callSuper(this, Logger, [{
	      objectMode: true
	    }]);
	    _this.configure(options);
	    return _this;
	  }
	  _inherits(Logger, _Transform);
	  return _createClass(Logger, [{
	    key: "child",
	    value: function child(defaultRequestMetadata) {
	      var logger = this;
	      return Object.create(logger, {
	        write: {
	          value: function value(info) {
	            var infoClone = Object.assign({}, defaultRequestMetadata, info);

	            // Object.assign doesn't copy inherited Error
	            // properties so we have to do that explicitly
	            //
	            // Remark (indexzero): we should remove this
	            // since the errors format will handle this case.
	            //
	            if (info instanceof Error) {
	              infoClone.stack = info.stack;
	              infoClone.message = info.message;
	            }
	            logger.write(infoClone);
	          }
	        }
	      });
	    }

	    /**
	     * This will wholesale reconfigure this instance by:
	     * 1. Resetting all transports. Older transports will be removed implicitly.
	     * 2. Set all other options including levels, colors, rewriters, filters,
	     *    exceptionHandlers, etc.
	     * @param {!Object} options - TODO: add param description.
	     * @returns {undefined}
	     */
	  }, {
	    key: "configure",
	    value: function configure() {
	      var _this2 = this;
	      var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
	        silent = _ref.silent,
	        format = _ref.format,
	        defaultMeta = _ref.defaultMeta,
	        levels = _ref.levels,
	        _ref$level = _ref.level,
	        level = _ref$level === void 0 ? 'info' : _ref$level,
	        _ref$exitOnError = _ref.exitOnError,
	        exitOnError = _ref$exitOnError === void 0 ? true : _ref$exitOnError,
	        transports = _ref.transports,
	        colors = _ref.colors,
	        emitErrs = _ref.emitErrs,
	        formatters = _ref.formatters,
	        padLevels = _ref.padLevels,
	        rewriters = _ref.rewriters,
	        stripColors = _ref.stripColors,
	        exceptionHandlers = _ref.exceptionHandlers,
	        rejectionHandlers = _ref.rejectionHandlers;
	      // Reset transports if we already have them
	      if (this.transports.length) {
	        this.clear();
	      }
	      this.silent = silent;
	      this.format = format || this.format || requireJson()();
	      this.defaultMeta = defaultMeta || null;
	      // Hoist other options onto this instance.
	      this.levels = levels || this.levels || config.npm.levels;
	      this.level = level;
	      if (this.exceptions) {
	        this.exceptions.unhandle();
	      }
	      if (this.rejections) {
	        this.rejections.unhandle();
	      }
	      this.exceptions = new ExceptionHandler(this);
	      this.rejections = new RejectionHandler(this);
	      this.profilers = {};
	      this.exitOnError = exitOnError;

	      // Add all transports we have been provided.
	      if (transports) {
	        transports = Array.isArray(transports) ? transports : [transports];
	        transports.forEach(function (transport) {
	          return _this2.add(transport);
	        });
	      }
	      if (colors || emitErrs || formatters || padLevels || rewriters || stripColors) {
	        throw new Error(['{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.', 'Use a custom winston.format(function) instead.', 'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'].join('\n'));
	      }
	      if (exceptionHandlers) {
	        this.exceptions.handle(exceptionHandlers);
	      }
	      if (rejectionHandlers) {
	        this.rejections.handle(rejectionHandlers);
	      }
	    }

	    /* eslint-disable valid-jsdoc */
	    /**
	     * Helper method to get the highest logging level associated with a logger
	     *
	     * @returns { number | null } - The highest configured logging level, null
	     * for invalid configuration
	     */
	  }, {
	    key: "getHighestLogLevel",
	    value: function getHighestLogLevel() {
	      var _this3 = this;
	      // This can be null, if this.level has an invalid value
	      var configuredLevelValue = getLevelValue(this.levels, this.level);

	      // If there are no transports, return the level configured at the logger level
	      if (!this.transports || this.transports.length === 0) {
	        return configuredLevelValue;
	      }
	      return this.transports.reduce(function (max, transport) {
	        var levelValue = getLevelValue(_this3.levels, transport.level);
	        return levelValue !== null && levelValue > max ? levelValue : max;
	      }, configuredLevelValue);
	    }
	  }, {
	    key: "isLevelEnabled",
	    value: function isLevelEnabled(level) {
	      var _this4 = this;
	      var givenLevelValue = getLevelValue(this.levels, level);
	      if (givenLevelValue === null) {
	        return false;
	      }
	      var configuredLevelValue = getLevelValue(this.levels, this.level);
	      if (configuredLevelValue === null) {
	        return false;
	      }
	      if (!this.transports || this.transports.length === 0) {
	        return configuredLevelValue >= givenLevelValue;
	      }
	      var index = this.transports.findIndex(function (transport) {
	        var transportLevelValue = getLevelValue(_this4.levels, transport.level);
	        if (transportLevelValue === null) {
	          transportLevelValue = configuredLevelValue;
	        }
	        return transportLevelValue >= givenLevelValue;
	      });
	      return index !== -1;
	    }

	    /* eslint-disable valid-jsdoc */
	    /**
	     * Ensure backwards compatibility with a `log` method
	     * @param {mixed} level - Level the log message is written at.
	     * @param {mixed} msg - TODO: add param description.
	     * @param {mixed} meta - TODO: add param description.
	     * @returns {Logger} - TODO: add return description.
	     *
	     * @example
	     *    // Supports the existing API:
	     *    logger.log('info', 'Hello world', { custom: true });
	     *    logger.log('info', new Error('Yo, it\'s on fire'));
	     *
	     *    // Requires winston.format.splat()
	     *    logger.log('info', '%s %d%%', 'A string', 50, { thisIsMeta: true });
	     *
	     *    // And the new API with a single JSON literal:
	     *    logger.log({ level: 'info', message: 'Hello world', custom: true });
	     *    logger.log({ level: 'info', message: new Error('Yo, it\'s on fire') });
	     *
	     *    // Also requires winston.format.splat()
	     *    logger.log({
	     *      level: 'info',
	     *      message: '%s %d%%',
	     *      [SPLAT]: ['A string', 50],
	     *      meta: { thisIsMeta: true }
	     *    });
	     *
	     */
	    /* eslint-enable valid-jsdoc */
	  }, {
	    key: "log",
	    value: function log(level, msg) {
	      for (var _len = arguments.length, splat = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
	        splat[_key - 2] = arguments[_key];
	      }
	      // eslint-disable-line max-params
	      // Optimize for the hotpath of logging JSON literals
	      if (arguments.length === 1) {
	        // Yo dawg, I heard you like levels ... seriously ...
	        // In this context the LHS `level` here is actually the `info` so read
	        // this as: info[LEVEL] = info.level;
	        level[LEVEL] = level.level;
	        this._addDefaultMeta(level);
	        this.write(level);
	        return this;
	      }

	      // Slightly less hotpath, but worth optimizing for.
	      if (arguments.length === 2) {
	        if (msg && _typeof(msg) === 'object') {
	          msg[LEVEL] = msg.level = level;
	          this._addDefaultMeta(msg);
	          this.write(msg);
	          return this;
	        }
	        msg = _defineProperty(_defineProperty(_defineProperty({}, LEVEL, level), "level", level), "message", msg);
	        this._addDefaultMeta(msg);
	        this.write(msg);
	        return this;
	      }
	      var meta = splat[0];
	      if (_typeof(meta) === 'object' && meta !== null) {
	        // Extract tokens, if none available default to empty array to
	        // ensure consistancy in expected results
	        var tokens = msg && msg.match && msg.match(formatRegExp);
	        if (!tokens) {
	          var info = Object.assign({}, this.defaultMeta, meta, _defineProperty(_defineProperty(_defineProperty(_defineProperty({}, LEVEL, level), SPLAT, splat), "level", level), "message", msg));
	          if (meta.message) info.message = "".concat(info.message, " ").concat(meta.message);
	          if (meta.stack) info.stack = meta.stack;
	          if (meta.cause) info.cause = meta.cause;
	          this.write(info);
	          return this;
	        }
	      }
	      this.write(Object.assign({}, this.defaultMeta, _defineProperty(_defineProperty(_defineProperty(_defineProperty({}, LEVEL, level), SPLAT, splat), "level", level), "message", msg)));
	      return this;
	    }

	    /**
	     * Pushes data so that it can be picked up by all of our pipe targets.
	     * @param {mixed} info - TODO: add param description.
	     * @param {mixed} enc - TODO: add param description.
	     * @param {mixed} callback - Continues stream processing.
	     * @returns {undefined}
	     * @private
	     */
	  }, {
	    key: "_transform",
	    value: function _transform(info, enc, callback) {
	      if (this.silent) {
	        return callback();
	      }

	      // [LEVEL] is only soft guaranteed to be set here since we are a proper
	      // stream. It is likely that `info` came in through `.log(info)` or
	      // `.info(info)`. If it is not defined, however, define it.
	      // This LEVEL symbol is provided by `triple-beam` and also used in:
	      // - logform
	      // - winston-transport
	      // - abstract-winston-transport
	      if (!info[LEVEL]) {
	        info[LEVEL] = info.level;
	      }

	      // Remark: really not sure what to do here, but this has been reported as
	      // very confusing by pre winston@2.0.0 users as quite confusing when using
	      // custom levels.
	      if (!this.levels[info[LEVEL]] && this.levels[info[LEVEL]] !== 0) {
	        // eslint-disable-next-line no-console
	        console.error('[winston] Unknown logger level: %s', info[LEVEL]);
	      }

	      // Remark: not sure if we should simply error here.
	      if (!this._readableState.pipes) {
	        // eslint-disable-next-line no-console
	        console.error('[winston] Attempt to write logs with no transports, which can increase memory usage: %j', info);
	      }

	      // Here we write to the `format` pipe-chain, which on `readable` above will
	      // push the formatted `info` Object onto the buffer for this instance. We trap
	      // (and re-throw) any errors generated by the user-provided format, but also
	      // guarantee that the streams callback is invoked so that we can continue flowing.
	      try {
	        this.push(this.format.transform(info, this.format.options));
	      } finally {
	        this._writableState.sync = false;
	        // eslint-disable-next-line callback-return
	        callback();
	      }
	    }

	    /**
	     * Delays the 'finish' event until all transport pipe targets have
	     * also emitted 'finish' or are already finished.
	     * @param {mixed} callback - Continues stream processing.
	     */
	  }, {
	    key: "_final",
	    value: function _final(callback) {
	      var transports = this.transports.slice();
	      asyncForEach(transports, function (transport, next) {
	        if (!transport || transport.finished) return setImmediate(next);
	        transport.once('finish', next);
	        transport.end();
	      }, callback);
	    }

	    /**
	     * Adds the transport to this logger instance by piping to it.
	     * @param {mixed} transport - TODO: add param description.
	     * @returns {Logger} - TODO: add return description.
	     */
	  }, {
	    key: "add",
	    value: function add(transport) {
	      // Support backwards compatibility with all existing `winston < 3.x.x`
	      // transports which meet one of two criteria:
	      // 1. They inherit from winston.Transport in  < 3.x.x which is NOT a stream.
	      // 2. They expose a log method which has a length greater than 2 (i.e. more then
	      //    just `log(info, callback)`.
	      var target = !isStream(transport) || transport.log.length > 2 ? new LegacyTransportStream({
	        transport: transport
	      }) : transport;
	      if (!target._writableState || !target._writableState.objectMode) {
	        throw new Error('Transports must WritableStreams in objectMode. Set { objectMode: true }.');
	      }

	      // Listen for the `error` event and the `warn` event on the new Transport.
	      this._onEvent('error', target);
	      this._onEvent('warn', target);
	      this.pipe(target);
	      if (transport.handleExceptions) {
	        this.exceptions.handle();
	      }
	      if (transport.handleRejections) {
	        this.rejections.handle();
	      }
	      return this;
	    }

	    /**
	     * Removes the transport from this logger instance by unpiping from it.
	     * @param {mixed} transport - TODO: add param description.
	     * @returns {Logger} - TODO: add return description.
	     */
	  }, {
	    key: "remove",
	    value: function remove(transport) {
	      if (!transport) return this;
	      var target = transport;
	      if (!isStream(transport) || transport.log.length > 2) {
	        target = this.transports.filter(function (match) {
	          return match.transport === transport;
	        })[0];
	      }
	      if (target) {
	        this.unpipe(target);
	      }
	      return this;
	    }

	    /**
	     * Removes all transports from this logger instance.
	     * @returns {Logger} - TODO: add return description.
	     */
	  }, {
	    key: "clear",
	    value: function clear() {
	      this.unpipe();
	      return this;
	    }

	    /**
	     * Cleans up resources (streams, event listeners) for all transports
	     * associated with this instance (if necessary).
	     * @returns {Logger} - TODO: add return description.
	     */
	  }, {
	    key: "close",
	    value: function close() {
	      this.exceptions.unhandle();
	      this.rejections.unhandle();
	      this.clear();
	      this.emit('close');
	      return this;
	    }

	    /**
	     * Sets the `target` levels specified on this instance.
	     * @param {Object} Target levels to use on this instance.
	     */
	  }, {
	    key: "setLevels",
	    value: function setLevels() {
	      warn.deprecated('setLevels');
	    }

	    /**
	     * Queries the all transports for this instance with the specified `options`.
	     * This will aggregate each transport's results into one object containing
	     * a property per transport.
	     * @param {Object} options - Query options for this instance.
	     * @param {function} callback - Continuation to respond to when complete.
	     */
	  }, {
	    key: "query",
	    value: function query(options, callback) {
	      if (typeof options === 'function') {
	        callback = options;
	        options = {};
	      }
	      options = options || {};
	      var results = {};
	      var queryObject = Object.assign({}, options.query || {});

	      // Helper function to query a single transport
	      function queryTransport(transport, next) {
	        if (options.query && typeof transport.formatQuery === 'function') {
	          options.query = transport.formatQuery(queryObject);
	        }
	        transport.query(options, function (err, res) {
	          if (err) {
	            return next(err);
	          }
	          if (typeof transport.formatResults === 'function') {
	            res = transport.formatResults(res, options.format);
	          }
	          next(null, res);
	        });
	      }

	      // Helper function to accumulate the results from `queryTransport` into
	      // the `results`.
	      function addResults(transport, next) {
	        queryTransport(transport, function (err, result) {
	          // queryTransport could potentially invoke the callback multiple times
	          // since Transport code can be unpredictable.
	          if (next) {
	            result = err || result;
	            if (result) {
	              results[transport.name] = result;
	            }

	            // eslint-disable-next-line callback-return
	            next();
	          }
	          next = null;
	        });
	      }

	      // Iterate over the transports in parallel setting the appropriate key in
	      // the `results`.
	      asyncForEach(this.transports.filter(function (transport) {
	        return !!transport.query;
	      }), addResults, function () {
	        return callback(null, results);
	      });
	    }

	    /**
	     * Returns a log stream for all transports. Options object is optional.
	     * @param{Object} options={} - Stream options for this instance.
	     * @returns {Stream} - TODO: add return description.
	     */
	  }, {
	    key: "stream",
	    value: function stream() {
	      var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
	      var out = new Stream();
	      var streams = [];
	      out._streams = streams;
	      out.destroy = function () {
	        var i = streams.length;
	        while (i--) {
	          streams[i].destroy();
	        }
	      };

	      // Create a list of all transports for this instance.
	      this.transports.filter(function (transport) {
	        return !!transport.stream;
	      }).forEach(function (transport) {
	        var str = transport.stream(options);
	        if (!str) {
	          return;
	        }
	        streams.push(str);
	        str.on('log', function (log) {
	          log.transport = log.transport || [];
	          log.transport.push(transport.name);
	          out.emit('log', log);
	        });
	        str.on('error', function (err) {
	          err.transport = err.transport || [];
	          err.transport.push(transport.name);
	          out.emit('error', err);
	        });
	      });
	      return out;
	    }

	    /**
	     * Returns an object corresponding to a specific timing. When done is called
	     * the timer will finish and log the duration. e.g.:
	     * @returns {Profile} - TODO: add return description.
	     * @example
	     *    const timer = winston.startTimer()
	     *    setTimeout(() => {
	     *      timer.done({
	     *        message: 'Logging message'
	     *      });
	     *    }, 1000);
	     */
	  }, {
	    key: "startTimer",
	    value: function startTimer() {
	      return new Profiler(this);
	    }

	    /**
	     * Tracks the time inbetween subsequent calls to this method with the same
	     * `id` parameter. The second call to this method will log the difference in
	     * milliseconds along with the message.
	     * @param {string} id Unique id of the profiler
	     * @returns {Logger} - TODO: add return description.
	     */
	  }, {
	    key: "profile",
	    value: function profile(id) {
	      var time = Date.now();
	      if (this.profilers[id]) {
	        var timeEnd = this.profilers[id];
	        delete this.profilers[id];

	        // Attempt to be kind to users if they are still using older APIs.
	        for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
	          args[_key2 - 1] = arguments[_key2];
	        }
	        if (typeof args[args.length - 2] === 'function') {
	          // eslint-disable-next-line no-console
	          console.warn('Callback function no longer supported as of winston@3.0.0');
	          args.pop();
	        }

	        // Set the duration property of the metadata
	        var info = _typeof(args[args.length - 1]) === 'object' ? args.pop() : {};
	        info.level = info.level || 'info';
	        info.durationMs = time - timeEnd;
	        info.message = info.message || id;
	        return this.write(info);
	      }
	      this.profilers[id] = time;
	      return this;
	    }

	    /**
	     * Backwards compatibility to `exceptions.handle` in winston < 3.0.0.
	     * @returns {undefined}
	     * @deprecated
	     */
	  }, {
	    key: "handleExceptions",
	    value: function handleExceptions() {
	      var _this$exceptions;
	      // eslint-disable-next-line no-console
	      console.warn('Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()');
	      (_this$exceptions = this.exceptions).handle.apply(_this$exceptions, arguments);
	    }

	    /**
	     * Backwards compatibility to `exceptions.handle` in winston < 3.0.0.
	     * @returns {undefined}
	     * @deprecated
	     */
	  }, {
	    key: "unhandleExceptions",
	    value: function unhandleExceptions() {
	      var _this$exceptions2;
	      // eslint-disable-next-line no-console
	      console.warn('Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()');
	      (_this$exceptions2 = this.exceptions).unhandle.apply(_this$exceptions2, arguments);
	    }

	    /**
	     * Throw a more meaningful deprecation notice
	     * @throws {Error} - TODO: add throws description.
	     */
	  }, {
	    key: "cli",
	    value: function cli() {
	      throw new Error(['Logger.cli() was removed in winston@3.0.0', 'Use a custom winston.formats.cli() instead.', 'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'].join('\n'));
	    }

	    /**
	     * Bubbles the `event` that occured on the specified `transport` up
	     * from this instance.
	     * @param {string} event - The event that occured
	     * @param {Object} transport - Transport on which the event occured
	     * @private
	     */
	  }, {
	    key: "_onEvent",
	    value: function _onEvent(event, transport) {
	      function transportEvent(err) {
	        // https://github.com/winstonjs/winston/issues/1364
	        if (event === 'error' && !this.transports.includes(transport)) {
	          this.add(transport);
	        }
	        this.emit(event, err, transport);
	      }
	      if (!transport['__winston' + event]) {
	        transport['__winston' + event] = transportEvent.bind(this);
	        transport.on(event, transport['__winston' + event]);
	      }
	    }
	  }, {
	    key: "_addDefaultMeta",
	    value: function _addDefaultMeta(msg) {
	      if (this.defaultMeta) {
	        Object.assign(msg, this.defaultMeta);
	      }
	    }
	  }]);
	}(Transform);
	function getLevelValue(levels, level) {
	  var value = levels[level];
	  if (!value && value !== 0) {
	    return null;
	  }
	  return value;
	}

	/**
	 * Represents the current readableState pipe targets for this Logger instance.
	 * @type {Array|Object}
	 */
	Object.defineProperty(Logger.prototype, 'transports', {
	  configurable: false,
	  enumerable: true,
	  get: function get() {
	    var pipes = this._readableState.pipes;
	    return !Array.isArray(pipes) ? [pipes].filter(Boolean) : pipes;
	  }
	});
	logger = Logger;
	return logger;
}

/**
 * create-logger.js: Logger factory for winston logger instances.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var createLogger;
var hasRequiredCreateLogger;

function requireCreateLogger () {
	if (hasRequiredCreateLogger) return createLogger;
	hasRequiredCreateLogger = 1;

	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _createClass(e, r, t) { return Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
	function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
	function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
	function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
	function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
	function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: true, configurable: true } }), Object.defineProperty(t, "prototype", { writable: false }), e && _setPrototypeOf(t, e); }
	function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
	var _require = requireTripleBeam(),
	  LEVEL = _require.LEVEL;
	var config = requireConfig();
	var Logger = requireLogger();
	var debug = requireBrowser$1()('winston:create-logger');
	function isLevelEnabledFunctionName(level) {
	  return 'is' + level.charAt(0).toUpperCase() + level.slice(1) + 'Enabled';
	}

	/**
	 * Create a new instance of a winston Logger. Creates a new
	 * prototype for each instance.
	 * @param {!Object} opts - Options for the created logger.
	 * @returns {Logger} - A newly created logger instance.
	 */
	createLogger = function () {
	  var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
	  //
	  // Default levels: npm
	  //
	  opts.levels = opts.levels || config.npm.levels;

	  /**
	   * DerivedLogger to attach the logs level methods.
	   * @type {DerivedLogger}
	   * @extends {Logger}
	   */
	  var DerivedLogger = /*#__PURE__*/function (_Logger) {
	    /**
	     * Create a new class derived logger for which the levels can be attached to
	     * the prototype of. This is a V8 optimization that is well know to increase
	     * performance of prototype functions.
	     * @param {!Object} options - Options for the created logger.
	     */
	    function DerivedLogger(options) {
	      _classCallCheck(this, DerivedLogger);
	      return _callSuper(this, DerivedLogger, [options]);
	    }
	    _inherits(DerivedLogger, _Logger);
	    return _createClass(DerivedLogger);
	  }(Logger);
	  var logger = new DerivedLogger(opts);

	  //
	  // Create the log level methods for the derived logger.
	  //
	  Object.keys(opts.levels).forEach(function (level) {
	    debug('Define prototype method for "%s"', level);
	    if (level === 'log') {
	      // eslint-disable-next-line no-console
	      console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.');
	      return;
	    }

	    //
	    // Define prototype methods for each log level e.g.:
	    // logger.log('info', msg) implies these methods are defined:
	    // - logger.info(msg)
	    // - logger.isInfoEnabled()
	    //
	    // Remark: to support logger.child this **MUST** be a function
	    // so it'll always be called on the instance instead of a fixed
	    // place in the prototype chain.
	    //
	    DerivedLogger.prototype[level] = function () {
	      // Prefer any instance scope, but default to "root" logger
	      var self = this || logger;

	      // Optimize the hot-path which is the single object.
	      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
	        args[_key] = arguments[_key];
	      }
	      if (args.length === 1) {
	        var msg = args[0];
	        var info = msg && msg.message && msg || {
	          message: msg
	        };
	        info.level = info[LEVEL] = level;
	        self._addDefaultMeta(info);
	        self.write(info);
	        return this || logger;
	      }

	      // When provided nothing assume the empty string
	      if (args.length === 0) {
	        self.log(level, '');
	        return self;
	      }

	      // Otherwise build argument list which could potentially conform to
	      // either:
	      // . v3 API: log(obj)
	      // 2. v1/v2 API: log(level, msg, ... [string interpolate], [{metadata}], [callback])
	      return self.log.apply(self, [level].concat(args));
	    };
	    DerivedLogger.prototype[isLevelEnabledFunctionName(level)] = function () {
	      return (this || logger).isLevelEnabled(level);
	    };
	  });
	  return logger;
	};
	return createLogger;
}

/**
 * container.js: Inversion of control container for winston logger instances.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var container$1;
var hasRequiredContainer;

function requireContainer () {
	if (hasRequiredContainer) return container$1;
	hasRequiredContainer = 1;

	function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
	function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
	function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
	function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
	function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
	function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
	var createLogger = requireCreateLogger();

	/**
	 * Inversion of control container for winston logger instances.
	 * @type {Container}
	 */
	container$1 = /*#__PURE__*/function () {
	  /**
	   * Constructor function for the Container object responsible for managing a
	   * set of `winston.Logger` instances based on string ids.
	   * @param {!Object} [options={}] - Default pass-thru options for Loggers.
	   */
	  function Container() {
	    var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
	    _classCallCheck(this, Container);
	    this.loggers = new Map();
	    this.options = options;
	  }

	  /**
	   * Retrieves a `winston.Logger` instance for the specified `id`. If an
	   * instance does not exist, one is created.
	   * @param {!string} id - The id of the Logger to get.
	   * @param {?Object} [options] - Options for the Logger instance.
	   * @returns {Logger} - A configured Logger instance with a specified id.
	   */
	  return _createClass(Container, [{
	    key: "add",
	    value: function add(id, options) {
	      var _this = this;
	      if (!this.loggers.has(id)) {
	        // Remark: Simple shallow clone for configuration options in case we pass
	        // in instantiated protoypal objects
	        options = Object.assign({}, options || this.options);
	        var existing = options.transports || this.options.transports;

	        // Remark: Make sure if we have an array of transports we slice it to
	        // make copies of those references.
	        if (existing) {
	          options.transports = Array.isArray(existing) ? existing.slice() : [existing];
	        } else {
	          options.transports = [];
	        }
	        var logger = createLogger(options);
	        logger.on('close', function () {
	          return _this._delete(id);
	        });
	        this.loggers.set(id, logger);
	      }
	      return this.loggers.get(id);
	    }

	    /**
	     * Retreives a `winston.Logger` instance for the specified `id`. If
	     * an instance does not exist, one is created.
	     * @param {!string} id - The id of the Logger to get.
	     * @param {?Object} [options] - Options for the Logger instance.
	     * @returns {Logger} - A configured Logger instance with a specified id.
	     */
	  }, {
	    key: "get",
	    value: function get(id, options) {
	      return this.add(id, options);
	    }

	    /**
	     * Check if the container has a logger with the id.
	     * @param {?string} id - The id of the Logger instance to find.
	     * @returns {boolean} - Boolean value indicating if this instance has a
	     * logger with the specified `id`.
	     */
	  }, {
	    key: "has",
	    value: function has(id) {
	      return !!this.loggers.has(id);
	    }

	    /**
	     * Closes a `Logger` instance with the specified `id` if it exists.
	     * If no `id` is supplied then all Loggers are closed.
	     * @param {?string} id - The id of the Logger instance to close.
	     * @returns {undefined}
	     */
	  }, {
	    key: "close",
	    value: function close(id) {
	      var _this2 = this;
	      if (id) {
	        return this._removeLogger(id);
	      }
	      this.loggers.forEach(function (val, key) {
	        return _this2._removeLogger(key);
	      });
	    }

	    /**
	     * Remove a logger based on the id.
	     * @param {!string} id - The id of the logger to remove.
	     * @returns {undefined}
	     * @private
	     */
	  }, {
	    key: "_removeLogger",
	    value: function _removeLogger(id) {
	      if (!this.loggers.has(id)) {
	        return;
	      }
	      var logger = this.loggers.get(id);
	      logger.close();
	      this._delete(id);
	    }

	    /**
	     * Deletes a `Logger` instance with the specified `id`.
	     * @param {!string} id - The id of the Logger instance to delete from
	     * container.
	     * @returns {undefined}
	     * @private
	     */
	  }, {
	    key: "_delete",
	    value: function _delete(id) {
	      this.loggers["delete"](id);
	    }
	  }]);
	}();
	return container$1;
}

/**
 * winston.js: Top-level include defining Winston.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */

var hasRequiredWinston;

function requireWinston () {
	if (hasRequiredWinston) return winston$1;
	hasRequiredWinston = 1;
	(function (exports$1) {

		var logform = requireBrowser$2();
		var _require = requireCommon(),
		  warn = _require.warn;

		/**
		 * Expose version. Use `require` method for `webpack` support.
		 * @type {string}
		 */
		exports$1.version = require$$2.version;
		/**
		 * Include transports defined by default by winston
		 * @type {Array}
		 */
		exports$1.transports = requireTransports();
		/**
		 * Expose utility methods
		 * @type {Object}
		 */
		exports$1.config = requireConfig();
		/**
		 * Hoist format-related functionality from logform.
		 * @type {Object}
		 */
		exports$1.addColors = logform.levels;
		/**
		 * Hoist format-related functionality from logform.
		 * @type {Object}
		 */
		exports$1.format = logform.format;
		/**
		 * Expose core Logging-related prototypes.
		 * @type {function}
		 */
		exports$1.createLogger = requireCreateLogger();
		/**
		 * Expose core Logging-related prototypes.
		 * @type {function}
		 */
		exports$1.Logger = requireLogger();
		/**
		 * Expose core Logging-related prototypes.
		 * @type {Object}
		 */
		exports$1.ExceptionHandler = requireExceptionHandler();
		/**
		 * Expose core Logging-related prototypes.
		 * @type {Object}
		 */
		exports$1.RejectionHandler = requireRejectionHandler();
		/**
		 * Expose core Logging-related prototypes.
		 * @type {Container}
		 */
		exports$1.Container = requireContainer();
		/**
		 * Expose core Logging-related prototypes.
		 * @type {Object}
		 */
		exports$1.Transport = requireDist();
		/**
		 * We create and expose a default `Container` to `winston.loggers` so that the
		 * programmer may manage multiple `winston.Logger` instances without any
		 * additional overhead.
		 * @example
		 *   // some-file1.js
		 *   const logger = require('winston').loggers.get('something');
		 *
		 *   // some-file2.js
		 *   const logger = require('winston').loggers.get('something');
		 */
		exports$1.loggers = new exports$1.Container();

		/**
		 * We create and expose a 'defaultLogger' so that the programmer may do the
		 * following without the need to create an instance of winston.Logger directly:
		 * @example
		 *   const winston = require('winston');
		 *   winston.log('info', 'some message');
		 *   winston.error('some error');
		 */
		var defaultLogger = exports$1.createLogger();

		// Pass through the target methods onto `winston.
		Object.keys(exports$1.config.npm.levels).concat(['log', 'query', 'stream', 'add', 'remove', 'clear', 'profile', 'startTimer', 'handleExceptions', 'unhandleExceptions', 'handleRejections', 'unhandleRejections', 'configure', 'child']).forEach(function (method) {
		  return exports$1[method] = function () {
		    return defaultLogger[method].apply(defaultLogger, arguments);
		  };
		});

		/**
		 * Define getter / setter for the default logger level which need to be exposed
		 * by winston.
		 * @type {string}
		 */
		Object.defineProperty(exports$1, 'level', {
		  get: function get() {
		    return defaultLogger.level;
		  },
		  set: function set(val) {
		    defaultLogger.level = val;
		  }
		});

		/**
		 * Define getter for `exceptions` which replaces `handleExceptions` and
		 * `unhandleExceptions`.
		 * @type {Object}
		 */
		Object.defineProperty(exports$1, 'exceptions', {
		  get: function get() {
		    return defaultLogger.exceptions;
		  }
		});

		/**
		 * Define getter for `rejections` which replaces `handleRejections` and
		 * `unhandleRejections`.
		 * @type {Object}
		 */
		Object.defineProperty(exports$1, 'rejections', {
		  get: function get() {
		    return defaultLogger.rejections;
		  }
		});

		/**
		 * Define getters / setters for appropriate properties of the default logger
		 * which need to be exposed by winston.
		 * @type {Logger}
		 */
		['exitOnError'].forEach(function (prop) {
		  Object.defineProperty(exports$1, prop, {
		    get: function get() {
		      return defaultLogger[prop];
		    },
		    set: function set(val) {
		      defaultLogger[prop] = val;
		    }
		  });
		});

		/**
		 * The default transports and exceptionHandlers for the default winston logger.
		 * @type {Object}
		 */
		Object.defineProperty(exports$1, 'default', {
		  get: function get() {
		    return {
		      exceptionHandlers: defaultLogger.exceptionHandlers,
		      rejectionHandlers: defaultLogger.rejectionHandlers,
		      transports: defaultLogger.transports
		    };
		  }
		});

		// Have friendlier breakage notices for properties that were exposed by default
		// on winston < 3.0.
		warn.deprecated(exports$1, 'setLevels');
		warn.forFunctions(exports$1, 'useFormat', ['cli']);
		warn.forProperties(exports$1, 'useFormat', ['padLevels', 'stripColors']);
		warn.forFunctions(exports$1, 'deprecated', ['addRewriter', 'addFilter', 'clone', 'extend']);
		warn.forProperties(exports$1, 'deprecated', ['emitErrs', 'levelLength']); 
	} (winston$1));
	return winston$1;
}

var winstonExports = requireWinston();
const winston = /*@__PURE__*/getDefaultExportFromCjs(winstonExports);

var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
  LogLevel2["DEBUG"] = "debug";
  LogLevel2["INFO"] = "info";
  LogLevel2["WARN"] = "warn";
  LogLevel2["ERROR"] = "error";
  LogLevel2["FATAL"] = "fatal";
  return LogLevel2;
})(LogLevel || {});
function getFormattedTimestamp() {
  const now = /* @__PURE__ */ new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, "0");
  const day = now.getDate().toString().padStart(2, "0");
  const hours = now.getHours().toString().padStart(2, "0");
  const minutes = now.getMinutes().toString().padStart(2, "0");
  const seconds = now.getSeconds().toString().padStart(2, "0");
  const milliseconds = now.getMilliseconds().toString().padStart(3, "0");
  return `${year}-${month}-${day}_${hours}-${minutes}-${seconds}.${milliseconds}`;
}
const logEmitter = new EventEmitter();
class Subscription {
  static MAX_HISTORY = 100;
  static history = [];
  subscribe(listener) {
    for (const history of Subscription.history) {
      try {
        listener(history);
      } catch {
      }
    }
    logEmitter.on("log", listener);
  }
  unsubscribe(listener) {
    logEmitter.off("log", listener);
  }
  notify(msg) {
    logEmitter.emit("log", msg);
    if (Subscription.history.length >= Subscription.MAX_HISTORY) {
      Subscription.history.shift();
    }
    Subscription.history.push(msg);
  }
}
const logSubscription$1 = new Subscription();
class LogWrapper {
  fileLogEnabled = true;
  consoleLogEnabled = true;
  logger;
  constructor(logDir) {
    const filename = `${getFormattedTimestamp()}.log`;
    const logPath = path$1.join(logDir, filename);
    this.logger = winston.createLogger({
      level: "debug",
      format: winstonExports.format.combine(
        winstonExports.format.timestamp({ format: "MM-DD HH:mm:ss" }),
        winstonExports.format.printf(({ timestamp, level, message, ...meta }) => {
          const userInfo = meta["userInfo"] ? `${meta["userInfo"]} | ` : "";
          return `${timestamp} [${level}] ${userInfo}${message}`;
        })
      ),
      transports: [
        new winstonExports.transports.File({
          filename: logPath,
          level: "debug",
          maxsize: 5 * 1024 * 1024,
          // 5MB
          maxFiles: 5
        }),
        new winstonExports.transports.Console({
          format: winstonExports.format.combine(
            winstonExports.format.colorize(),
            winstonExports.format.printf(({ timestamp, level, message, ...meta }) => {
              const userInfo = meta["userInfo"] ? `${meta["userInfo"]} | ` : "";
              return `${timestamp} [${level}] ${userInfo}${message}`;
            })
          )
        })
      ]
    });
    this.setLogSelfInfo({ nick: "", uid: "" });
    this.cleanOldLogs(logDir);
  }
  cleanOldLogs(logDir) {
    const oneWeekAgo = Date.now() - 7 * 24 * 60 * 60 * 1e3;
    fs$1.readdir(logDir).then((files) => {
      files.forEach((file) => {
        const filePath = path$1.join(logDir, file);
        this.deleteOldLogFile(filePath, oneWeekAgo);
      });
    }).catch((err) => {
      this.logger.error("Failed to read log directory", err);
    });
  }
  deleteOldLogFile(filePath, oneWeekAgo) {
    fs$1.stat(filePath).then((stats) => {
      if (stats.mtime.getTime() < oneWeekAgo) {
        fs$1.unlink(filePath).catch((err) => {
          if (err) {
            if (err.code === "ENOENT") {
              this.logger.warn(`File already deleted: ${filePath}`);
            } else {
              this.logger.error("Failed to delete old log file", err);
            }
          } else {
            this.logger.info(`Deleted old log file: ${filePath}`);
          }
        });
      }
    }).catch((err) => {
      this.logger.error("Failed to get file stats", err);
    });
  }
  setFileAndConsoleLogLevel(fileLogLevel, consoleLogLevel) {
    this.logger.transports.forEach((transport) => {
      if (transport instanceof winstonExports.transports.File) {
        transport.level = fileLogLevel;
      } else if (transport instanceof winstonExports.transports.Console) {
        transport.level = consoleLogLevel;
      }
    });
  }
  setLogSelfInfo(selfInfo) {
    const userInfo = `${selfInfo.nick}`;
    this.logger.defaultMeta = { userInfo };
  }
  setFileLogEnabled(isEnabled) {
    this.fileLogEnabled = isEnabled;
    this.logger.transports.forEach((transport) => {
      if (transport instanceof winstonExports.transports.File) {
        transport.silent = !isEnabled;
      }
    });
  }
  setConsoleLogEnabled(isEnabled) {
    this.consoleLogEnabled = isEnabled;
    this.logger.transports.forEach((transport) => {
      if (transport instanceof winstonExports.transports.Console) {
        transport.silent = !isEnabled;
      }
    });
  }
  formatMsg(msg) {
    return msg.map((msgItem) => {
      if (msgItem instanceof Error) {
        return msgItem.stack;
      } else if (typeof msgItem === "object") {
        return JSON.stringify(truncateString(JSON.parse(JSON.stringify(msgItem, null, 2))));
      }
      return msgItem;
    }).join(" ");
  }
  _log(level, ...args) {
    const message = this.formatMsg(args);
    if (this.consoleLogEnabled && this.fileLogEnabled) {
      this.logger.log(level, message);
    } else if (this.consoleLogEnabled) {
      this.logger.log(level, message);
    } else if (this.fileLogEnabled) {
      this.logger.log(level, message.replace(/\x1B[@-_][0-?]*[ -/]*[@-~]/g, ""));
    }
    logSubscription$1.notify(JSON.stringify({ level, message }));
  }
  log(...args) {
    this._log("info" /* INFO */, ...args);
  }
  logDebug(...args) {
    this._log("debug" /* DEBUG */, ...args);
  }
  logError(...args) {
    this._log("error" /* ERROR */, ...args);
  }
  logWarn(...args) {
    this._log("warn" /* WARN */, ...args);
  }
  logFatal(...args) {
    this._log("fatal" /* FATAL */, ...args);
  }
  logMessage(msg, selfInfo) {
    const isSelfSent = msg.senderUin === selfInfo.uin;
    if (msg.elements[0]?.elementType === ElementType.GreyTip) {
      return;
    }
    this.log(`${isSelfSent ? "发送 ->" : "接收 <-"} ${rawMessageToText(msg)}`);
  }
}
function rawMessageToText(msg, recursiveLevel = 0) {
  if (recursiveLevel > 2) {
    return "...";
  }
  const tokens = [];
  if (msg.chatType === ChatType.KCHATTYPEC2C) {
    tokens.push(`私聊 (${msg.peerUin})`);
  } else if (msg.chatType === ChatType.KCHATTYPEGROUP) {
    if (recursiveLevel < 1) {
      tokens.push(`群聊 [${msg.peerName}(${msg.peerUin})]`);
    }
    if (msg.senderUin !== "0") {
      tokens.push(`[${msg.sendMemberName || msg.sendRemarkName || msg.sendNickName}(${msg.senderUin})]`);
    }
  } else if (msg.chatType === ChatType.KCHATTYPEDATALINE) {
    tokens.push("移动设备");
  } else {
    tokens.push(`临时消息 (${msg.peerUin})`);
  }
  for (const element of msg.elements) {
    tokens.push(msgElementToText(element, msg, recursiveLevel));
  }
  return tokens.join(" ");
}
function msgElementToText(element, msg, recursiveLevel) {
  if (element.textElement) {
    return textElementToText(element.textElement);
  }
  if (element.replyElement) {
    return replyElementToText(element.replyElement, msg, recursiveLevel);
  }
  if (element.picElement) {
    return "[图片]";
  }
  if (element.fileElement) {
    return `[文件 ${element.fileElement.fileName}]`;
  }
  if (element.videoElement) {
    return "[视频]";
  }
  if (element.pttElement) {
    return `[语音 ${element.pttElement.duration}s]`;
  }
  if (element.arkElement) {
    return "[卡片消息]";
  }
  if (element.faceElement) {
    return `[表情 ${element.faceElement.faceText ?? ""}]`;
  }
  if (element.marketFaceElement) {
    return element.marketFaceElement.faceName;
  }
  if (element.markdownElement) {
    return "[Markdown 消息]";
  }
  if (element.multiForwardMsgElement) {
    return "[转发消息]";
  }
  if (element.elementType === ElementType.GreyTip) {
    return "[灰条消息]";
  }
  return `[未实现 (ElementType = ${element.elementType})]`;
}
function textElementToText(textElement) {
  if (textElement.atType === NTMsgAtType.ATTYPEUNKNOWN) {
    const originalContentLines = textElement.content.split("\n");
    return `${originalContentLines[0]}${originalContentLines.length > 1 ? " ..." : ""}`;
  } else if (textElement.atType === NTMsgAtType.ATTYPEALL) {
    return "@全体成员";
  } else if (textElement.atType === NTMsgAtType.ATTYPEONE) {
    return `${textElement.content} (${textElement.atUid})`;
  }
  return "";
}
function replyElementToText(replyElement, msg, recursiveLevel) {
  const recordMsgOrNull = msg.records.find((record) => replyElement.sourceMsgIdInRecords === record.msgId);
  return `[回复消息 ${recordMsgOrNull && recordMsgOrNull.peerUin !== "284840486" && recordMsgOrNull.peerUin !== "1094950020" ? rawMessageToText(recordMsgOrNull, recursiveLevel + 1) : `未找到消息记录 (MsgId = ${replyElement.sourceMsgIdInRecords})`}]`;
}

class PacketLogger {
  napLogger;
  constructor(napcore) {
    this.napLogger = napcore.logger;
  }
  _log(level, ...msg) {
    this.napLogger._log(level, "[Core] [Packet] " + msg);
  }
  debug(...msg) {
    this._log(LogLevel.DEBUG, msg);
  }
  info(...msg) {
    this._log(LogLevel.INFO, msg);
  }
  warn(...msg) {
    this._log(LogLevel.WARN, msg);
  }
  error(...msg) {
    this._log(LogLevel.ERROR, msg);
  }
  fatal(...msg) {
    this._log(LogLevel.FATAL, msg);
  }
}

class NapCoreContext {
  core;
  constructor(core) {
    this.core = core;
  }
  get logger() {
    return this.core.context.logger;
  }
  get basicInfo() {
    return {
      requireMinNTQQBuild: (buildVer) => this.core.context.basicInfoWrapper.requireMinNTQQBuild(buildVer),
      uin: +this.core.selfInfo.uin,
      uid: this.core.selfInfo.uid,
      uin2uid: (uin) => this.core.apis.UserApi.getUidByUinV2(String(uin)).then((res) => res ?? ""),
      uid2uin: (uid) => this.core.apis.UserApi.getUinByUidV2(uid).then((res) => +res)
    };
  }
  get config() {
    return this.core.configLoader.configData;
  }
  sendSsoCmdReqByContend = (cmd, data) => this.core.context.session.getMsgService().sendSsoCmdReqByContend(cmd, data);
}

class NativePacketClient {
  napcore;
  logger;
  cb = /* @__PURE__ */ new Map();
  // hash-type callback
  logStack;
  available = false;
  supportedPlatforms = ["win32.x64", "linux.x64", "linux.arm64", "darwin.x64", "darwin.arm64"];
  MoeHooExport = { exports: {} };
  constructor(napCore, logger, logStack) {
    this.napcore = napCore;
    this.logger = logger;
    this.logStack = logStack;
  }
  check() {
    const platform = process.platform + "." + process.arch;
    if (!this.supportedPlatforms.includes(platform)) {
      this.logStack.pushLogWarn(`NativePacketClient: 不支持的平台: ${platform}`);
      return false;
    }
    const moehoo_path = path__default.join(dirname(fileURLToPath(import.meta.url)), "./native/napi2native/napi2native." + platform + ".node");
    if (!fs__default.existsSync(moehoo_path)) {
      this.logStack.pushLogWarn(`NativePacketClient: 缺失运行时文件: ${moehoo_path}`);
      return false;
    }
    return true;
  }
  async init(_pid, recv, send) {
    const platform = process.platform + "." + process.arch;
    const isNewQQ = this.napcore.basicInfo.requireMinNTQQBuild("40824");
    if (isNewQQ) {
      const moehoo_path = path__default.join(dirname(fileURLToPath(import.meta.url)), "./native/napi2native/napi2native." + platform + ".node");
      process.dlopen(this.MoeHooExport, moehoo_path, constants.dlopen.RTLD_LAZY);
      this.MoeHooExport?.exports.initHook?.(send, recv);
      this.available = true;
    }
  }
  async sendPacket(cmd, data, rsp = false, timeout = 5e3) {
    if (!rsp) {
      this.napcore.sendSsoCmdReqByContend(cmd, data).catch(
        (err) => this.logger.error(
          `[PacketClient] sendPacket 无响应命令发送失败 cmd=${cmd} err=${err}`
        )
      );
      return { seq: 0, cmd, data: Buffer.alloc(0) };
    }
    const sendPromise = this.napcore.sendSsoCmdReqByContend(cmd, data).then((ret) => ({
      seq: 0,
      cmd,
      data: ret.rspbuffer
    }));
    const timeoutPromise = new Promise((_resolve, reject) => {
      setTimeout(
        () => reject(
          new Error(
            `[PacketClient] sendPacket 超时 cmd=${cmd} timeout=${timeout}ms`
          )
        ),
        timeout
      );
    });
    return Promise.race([sendPromise, timeoutPromise]);
  }
  async sendOidbPacket(pkt, rsp = false, timeout = 5e3) {
    return await this.sendPacket(pkt.cmd, pkt.data, rsp, timeout);
  }
}

class LogStack {
  stack = [];
  logger;
  constructor(logger) {
    this.logger = logger;
  }
  push(msg) {
    this.stack.push(msg);
  }
  pushLogInfo(msg) {
    this.logger.info(msg);
    this.stack.push(`${(/* @__PURE__ */ new Date()).toISOString()} [INFO] ${msg}`);
  }
  pushLogWarn(msg) {
    this.logger.warn(msg);
    this.stack.push(`${(/* @__PURE__ */ new Date()).toISOString()} [WARN] ${msg}`);
  }
  pushLogError(msg) {
    this.logger.error(msg);
    this.stack.push(`${(/* @__PURE__ */ new Date()).toISOString()} [ERROR] ${msg}`);
  }
  clear() {
    this.stack = [];
  }
  content() {
    return this.stack.join("\n");
  }
}
class PacketClientContext {
  napCore;
  logger;
  logStack;
  _client;
  constructor(napCore, logger) {
    this.napCore = napCore;
    this.logger = logger;
    this.logStack = new LogStack(logger);
    this._client = this.newClient();
  }
  get available() {
    return this._client.available;
  }
  get clientLogStack() {
    return this._client.logStack.content();
  }
  async init(pid, recv, send) {
    await this._client.init(pid, recv, send);
  }
  async sendOidbPacket(pkt, rsp, timeout) {
    const raw = await this._client.sendOidbPacket(pkt, rsp, timeout);
    return raw.data;
  }
  newClient() {
    this.logger.info("使用 NativePacketClient 作为后端");
    const client = new NativePacketClient(this.napCore, this.logger, this.logStack);
    if (!client.check()) {
      throw new Error("[Core] [Packet] NativePacketClient 不可用，NapCat.Packet将不会加载！");
    }
    return client;
  }
}

const SupportedElementTypes = [
  ElementType.TEXT,
  ElementType.PIC,
  ElementType.REPLY,
  ElementType.FACE,
  ElementType.MFACE,
  ElementType.VIDEO,
  ElementType.FILE,
  ElementType.PTT,
  ElementType.ARK,
  ElementType.MARKDOWN,
  ElementType.MULTIFORWARD
];
class PacketMsgConverter {
  isValidElementType(type) {
    return SupportedElementTypes.includes(type);
  }
  rawToPacketMsgConverters = {
    [ElementType.TEXT]: (element) => {
      if (element.textElement?.atType) {
        return new PacketMsgAtElement(element);
      }
      return new PacketMsgTextElement(element);
    },
    [ElementType.PIC]: (element) => {
      return new PacketMsgPicElement(element);
    },
    [ElementType.REPLY]: (element) => {
      return new PacketMsgReplyElement(element);
    },
    [ElementType.FACE]: (element) => {
      return new PacketMsgFaceElement(element);
    },
    [ElementType.MFACE]: (element) => {
      return new PacketMsgMarkFaceElement(element);
    },
    [ElementType.VIDEO]: (element) => {
      return new PacketMsgVideoElement(element);
    },
    [ElementType.FILE]: (element) => {
      return new PacketMsgFileElement(element);
    },
    [ElementType.PTT]: (element) => {
      return new PacketMsgPttElement(element);
    },
    [ElementType.ARK]: (element) => {
      return new PacketMsgLightAppElement(element);
    },
    [ElementType.MARKDOWN]: (element) => {
      return new PacketMsgMarkDownElement(element);
    },
    [ElementType.MULTIFORWARD]: (element) => {
      return new PacketMultiMsgElement(element);
    }
  };
  rawMsgWithSendMsgToPacketMsg(msg) {
    return {
      senderUid: msg.senderUid ?? "",
      senderUin: msg.senderUin,
      senderName: msg.senderName,
      groupId: msg.groupId,
      time: msg.time,
      msg: msg.msg.map((element) => {
        if (!this.isValidElementType(element.elementType)) return null;
        return this.rawToPacketMsgConverters[element.elementType](element);
      }).filter((e) => e !== null)
    };
  }
  rawMsgToPacketMsg(msg, ctxPeer) {
    return {
      seq: +msg.msgSeq,
      groupId: ctxPeer.chatType === ChatType.KCHATTYPEGROUP ? +msg.peerUid : void 0,
      senderUid: msg.senderUid,
      senderUin: +msg.senderUin,
      senderName: msg.sendMemberName && msg.sendMemberName !== "" ? msg.sendMemberName : msg.sendNickName && msg.sendNickName !== "" ? msg.sendNickName : "QQ用户",
      time: +msg.msgTime,
      msg: msg.elements.map((element) => {
        if (!this.isValidElementType(element.elementType)) return null;
        return this.rawToPacketMsgConverters[element.elementType](element);
      }).filter((e) => e !== null)
    };
  }
  packetMsgToRaw(msg) {
    const converters = [
      PacketMsgTextElement.parseElement,
      PacketMsgAtElement.parseElement,
      PacketMsgReplyElement.parseElement,
      PacketMsgPicElement.parseElement
    ];
    return msg.map((element) => {
      for (const converter of converters) {
        const result = converter(element);
        if (result) return result;
      }
      return null;
    }).filter((e) => e !== null);
  }
}

class PacketOperationContext {
  context;
  constructor(context) {
    this.context = context;
  }
  async sendPacket(pkt, rsp) {
    return await this.context.client.sendOidbPacket(pkt, rsp);
  }
  async SendPoke(is_group, peer, target) {
    const req = SendPoke_default.build(is_group, peer, target ?? peer);
    await this.context.client.sendOidbPacket(req);
  }
  async SetGroupTodo(groupUin, msgSeq) {
    const req = SetGroupTodo_default.build(groupUin, msgSeq);
    await this.context.client.sendOidbPacket(req, true);
  }
  async FetchRkey(timeout = 1e4) {
    const req = FetchRkey_default.build();
    const resp = await this.context.client.sendOidbPacket(req, true, timeout);
    const res = FetchRkey_default.parse(resp);
    return res.data.rkeyList;
  }
  async GroupSign(groupUin) {
    const req = GroupSign_default.build(this.context.napcore.basicInfo.uin, groupUin);
    await this.context.client.sendOidbPacket(req);
  }
  async GetStrangerStatus(uin) {
    let status = 0;
    try {
      const req = GetStrangerInfo_default.build(uin);
      const resp = await this.context.client.sendOidbPacket(req, true);
      const res = GetStrangerInfo_default.parse(resp);
      const extBigInt = BigInt(res.data.status.value);
      if (extBigInt <= 10n) {
        return { status: Number(extBigInt) * 10, ext_status: 0 };
      }
      status = Number((extBigInt & 0xff00n) + (extBigInt >> 16n & 0xffn));
      return { status: 10, ext_status: status };
    } catch {
      return void 0;
    }
  }
  async SetGroupSpecialTitle(groupUin, uid, title) {
    const req = SetSpecialTitle_default.build(groupUin, uid, title);
    await this.context.client.sendOidbPacket(req);
  }
  async UploadResources(msg, groupUin = 0) {
    const chatType = groupUin ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C;
    const peerUid = groupUin ? String(groupUin) : this.context.napcore.basicInfo.uid;
    const reqList = msg.flatMap(
      (m) => m.msg.map((e) => {
        if (e instanceof PacketMsgPicElement) {
          return this.context.highway.uploadImage({ chatType, peerUid }, e);
        } else if (e instanceof PacketMsgVideoElement) {
          return this.context.highway.uploadVideo({ chatType, peerUid }, e);
        } else if (e instanceof PacketMsgPttElement) {
          return this.context.highway.uploadPtt({ chatType, peerUid }, e);
        } else if (e instanceof PacketMsgFileElement) {
          return this.context.highway.uploadFile({ chatType, peerUid }, e);
        }
        return null;
      }).filter(Boolean)
    );
    const res = await Promise.allSettled(reqList);
    this.context.logger.info(`上传资源${res.length}个，失败${res.filter((r) => r.status === "rejected").length}个`);
    res.forEach((result, index) => {
      if (result.status === "rejected") {
        this.context.logger.error(`上传第${index + 1}个资源失败：${result.reason.stack}`);
      }
    });
  }
  async UploadImage(img) {
    await this.context.highway.uploadImage(
      {
        chatType: ChatType.KCHATTYPEC2C,
        peerUid: this.context.napcore.basicInfo.uid
      },
      img
    );
    const index = img.msgInfo?.msgInfoBody?.at(0)?.index;
    if (!index) {
      throw new Error("img.msgInfo?.msgInfoBody![0].index! is undefined");
    }
    return await this.GetImageUrl(this.context.napcore.basicInfo.uid, index);
  }
  async GetImageUrl(selfUid, node) {
    const req = DownloadImage_default.build(selfUid, node);
    const resp = await this.context.client.sendOidbPacket(req, true);
    const res = DownloadImage_default.parse(resp);
    return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
  }
  async GetPttUrl(selfUid, node, timeout) {
    const req = DownloadPtt_default.build(selfUid, node);
    const resp = await this.context.client.sendOidbPacket(req, true, timeout);
    const res = DownloadPtt_default.parse(resp);
    return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
  }
  async GetVideoUrl(selfUid, node, timeout) {
    const req = DownloadVideo_default.build(selfUid, node);
    const resp = await this.context.client.sendOidbPacket(req, true, timeout);
    const res = DownloadVideo_default.parse(resp);
    return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
  }
  async GetGroupImageUrl(groupUin, node, timeout) {
    const req = DownloadGroupImage_default.build(groupUin, node);
    const resp = await this.context.client.sendOidbPacket(req, true, timeout);
    const res = DownloadImage_default.parse(resp);
    return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
  }
  async GetGroupPttUrl(groupUin, node, timeout) {
    const req = DownloadGroupPtt_default.build(groupUin, node);
    const resp = await this.context.client.sendOidbPacket(req, true, timeout);
    const res = DownloadImage_default.parse(resp);
    return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
  }
  async GetGroupVideoUrl(groupUin, node, timeout = 2e4) {
    const req = DownloadGroupVideo_default.build(groupUin, node);
    const resp = await this.context.client.sendOidbPacket(req, true, timeout);
    const res = DownloadImage_default.parse(resp);
    return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
  }
  async ImageOCR(imgUrl) {
    const req = ImageOCR_default.build(imgUrl);
    const resp = await this.context.client.sendOidbPacket(req, true);
    const res = ImageOCR_default.parse(resp);
    return {
      texts: res.ocrRspBody.textDetections.map((item) => {
        return {
          text: item.detectedText,
          confidence: item.confidence,
          coordinates: item.polygon.coordinates.map((c) => {
            return {
              x: c.x,
              y: c.y
            };
          })
        };
      }),
      language: res.ocrRspBody.language
    };
  }
  async SendPreprocess(msg, groupUin = 0) {
    const ps = msg.map((m) => {
      return m.msg.map(async (e) => {
        if (e instanceof PacketMsgReplyElement && !e.targetElems) {
          this.context.logger.debug("Cannot find reply element's targetElems, prepare to fetch it...");
          if (!e.targetPeer?.peerUid) {
            this.context.logger.error("targetPeer is undefined!");
          }
          let targetMsg;
          if (e.isGroupReply) {
            targetMsg = await this.FetchGroupMessage(+(e.targetPeer?.peerUid ?? 0), e.targetMessageSeq, e.targetMessageSeq);
          } else {
            targetMsg = await this.FetchC2CMessage(await this.context.napcore.basicInfo.uin2uid(e.targetUin), e.targetMessageSeq, e.targetMessageSeq);
          }
          e.targetElems = targetMsg.at(0)?.body?.richText?.elems;
          e.targetSourceMsg = targetMsg.at(0);
        }
      });
    }).flat();
    await Promise.all(ps);
    await this.UploadResources(msg, groupUin);
  }
  async FetchGroupMessage(groupUin, startSeq, endSeq) {
    const req = FetchGroupMessage_default.build(groupUin, startSeq, endSeq);
    const resp = await this.context.client.sendOidbPacket(req, true);
    const res = FetchGroupMessage_default.parse(resp);
    return res.body.messages;
  }
  async FetchC2CMessage(targetUid, startSeq, endSeq) {
    const req = FetchC2CMessage_default.build(targetUid, startSeq, endSeq);
    const resp = await this.context.client.sendOidbPacket(req, true);
    const res = FetchC2CMessage_default.parse(resp);
    return res.messages;
  }
  async UploadForwardMsg(msg, groupUin = 0) {
    await this.SendPreprocess(msg, groupUin);
    const req = UploadForwardMsg_default.build(this.context.napcore.basicInfo.uid, msg, groupUin);
    const resp = await this.context.client.sendOidbPacket(req, true);
    const res = UploadForwardMsg_default.parse(resp);
    return res.result.resId;
  }
  async MoveGroupFile(groupUin, fileUUID, currentParentDirectory, targetParentDirectory) {
    const req = MoveGroupFile_default.build(groupUin, fileUUID, currentParentDirectory, targetParentDirectory);
    const resp = await this.context.client.sendOidbPacket(req, true);
    const res = MoveGroupFile_default.parse(resp);
    return res.move.retCode;
  }
  async RenameGroupFile(groupUin, fileUUID, currentParentDirectory, newName) {
    const req = RenameGroupFile_default.build(groupUin, fileUUID, currentParentDirectory, newName);
    const resp = await this.context.client.sendOidbPacket(req, true);
    const res = RenameGroupFile_default.parse(resp);
    return res.rename.retCode;
  }
  async GetGroupFileUrl(groupUin, fileUUID, timeout) {
    const req = DownloadGroupFile_default.build(groupUin, fileUUID);
    const resp = await this.context.client.sendOidbPacket(req, true, timeout);
    const res = DownloadGroupFile_default.parse(resp);
    return `https://${res.download.downloadDns}/ftn_handler/${Buffer.from(res.download.downloadUrl).toString("hex")}/?fname=`;
  }
  async GetPrivateFileUrl(self_id, fileUUID, md5, timeout) {
    const req = DownloadPrivateFile_default.build(self_id, fileUUID, md5);
    const resp = await this.context.client.sendOidbPacket(req, true, timeout);
    const res = DownloadPrivateFile_default.parse(resp);
    return `http://${res.body?.result?.server}:${res.body?.result?.port}${res.body?.result?.url?.slice(8)}&isthumb=0`;
  }
  async GetMiniAppAdaptShareInfo(param) {
    const req = GetMiniAppAdaptShareInfo_default.build(param);
    const resp = await this.context.client.sendOidbPacket(req, true);
    const res = GetMiniAppAdaptShareInfo_default.parse(resp);
    return JSON.parse(res.content.jsonContent);
  }
  async FetchAiVoiceList(groupUin, chatType) {
    const req = FetchAiVoiceList_default.build(groupUin, chatType);
    const resp = await this.context.client.sendOidbPacket(req, true);
    const res = FetchAiVoiceList_default.parse(resp);
    if (!res.content) return null;
    return res.content.map((item) => {
      return {
        category: item.category,
        voices: item.voices
      };
    });
  }
  async GetAiVoice(groupUin, voiceId, text, chatType) {
    let reqTime = 0;
    const reqMaxTime = 30;
    const sessionId = crypto$2.randomBytes(4).readUInt32BE(0);
    while (true) {
      if (reqTime >= reqMaxTime) {
        throw new Error(`sendAiVoiceChatReq failed after ${reqMaxTime} times`);
      }
      reqTime++;
      const req = GetAiVoice_default.build(groupUin, voiceId, text, sessionId, chatType);
      const resp = await this.context.client.sendOidbPacket(req, true);
      const res = GetAiVoice_default.parse(resp);
      if (!res.msgInfo) continue;
      return res.msgInfo;
    }
  }
  async FetchForwardMsg(res_id) {
    const req = DownloadForwardMsg_default.build(this.context.napcore.basicInfo.uid, res_id);
    const resp = await this.context.client.sendOidbPacket(req, true);
    const res = DownloadForwardMsg_default.parse(resp);
    const inflate = gunzipSync$1(res.result.payload);
    const result = new NapProtoMsg(LongMsgResult).decode(inflate);
    const main = result.action.find((r) => r.actionCommand === "MultiMsg");
    if (!main?.actionData.msgBody) {
      throw new Error("msgBody is empty");
    }
    this.context.logger.debug("rawChains ", inflate.toString("hex"));
    const messagesPromises = main.actionData.msgBody.map(async (msg) => {
      if (!msg?.body?.richText?.elems) {
        throw new Error("msg.body.richText.elems is empty");
      }
      const rawChains = new PacketMsgConverter().packetMsgToRaw(msg?.body?.richText?.elems);
      const elements = await Promise.all(
        rawChains.map(async ([element, rawElem]) => {
          if (element.picElement && rawElem?.commonElem?.pbElem) {
            const extra = new NapProtoMsg(MsgInfo).decode(rawElem.commonElem.pbElem);
            const index = extra?.msgInfoBody[0]?.index;
            if (msg?.responseHead.grp !== void 0) {
              const groupUin = msg?.responseHead.grp?.groupUin ?? 0;
              element.picElement = {
                ...element.picElement,
                originImageUrl: await this.GetGroupImageUrl(groupUin, index)
              };
            } else {
              element.picElement = {
                ...element.picElement,
                originImageUrl: await this.GetImageUrl(this.context.napcore.basicInfo.uid, index)
              };
            }
            return element;
          }
          return element;
        })
      );
      return {
        chatType: ChatType.KCHATTYPEGROUP,
        elements,
        guildId: "",
        isOnlineMsg: false,
        msgId: "7467703692092974645",
        // TODO: no necessary
        msgRandom: "0",
        msgSeq: String(msg.contentHead.sequence ?? 0),
        msgTime: String(msg.contentHead.timeStamp ?? 0),
        msgType: NTMsgType.KMSGTYPEMIX,
        parentMsgIdList: [],
        parentMsgPeer: {
          chatType: ChatType.KCHATTYPEGROUP,
          peerUid: String(msg?.responseHead.grp?.groupUin ?? 0)
        },
        peerName: "",
        peerUid: "1094950020",
        peerUin: "1094950020",
        recallTime: "0",
        records: [],
        sendNickName: msg?.responseHead.grp?.memberName ?? "",
        sendRemarkName: msg?.responseHead.grp?.memberName ?? "",
        senderUid: "",
        senderUin: "1094950020",
        sourceType: MsgSourceType.K_DOWN_SOURCETYPE_UNKNOWN,
        subMsgType: 1
      };
    });
    return await Promise.all(messagesPromises);
  }
}

class PacketContext {
  msgConverter;
  napcore;
  logger;
  client;
  highway;
  operation;
  constructor(core) {
    this.msgConverter = new PacketMsgConverter();
    this.napcore = new NapCoreContext(core);
    this.logger = new PacketLogger(this.napcore);
    this.client = new PacketClientContext(this.napcore, this.logger);
    this.highway = new PacketHighwayContext(this.napcore, this.logger, this.client);
    this.operation = new PacketOperationContext(this);
  }
}

class PacketClientSession {
  context;
  constructor(core) {
    this.context = new PacketContext(core);
  }
  init(pid, recv, send) {
    return this.context.client.init(pid, recv, send);
  }
  get clientLogStack() {
    return this.context.client.clientLogStack;
  }
  get available() {
    return this.context.client.available;
  }
  get operation() {
    return this.context.operation;
  }
  // TODO: global message element adapter (?
  get msgConverter() {
    return this.context.msgConverter;
  }
}

const __vite_import_meta_env__ = {};
const napCatVersion = typeof (__vite_import_meta_env__) !== "undefined" && ".4.9.100" || "alpha";

const typedOffset$1 = offset$1;
class NTQQPacketApi {
  context;
  core;
  logger;
  qqVersion;
  pkt;
  errStack = [];
  packetStatus = false;
  constructor(context, core) {
    this.context = context;
    this.core = core;
    this.logger = core.context.logger;
  }
  async initApi() {
    this.packetStatus = await this.InitSendPacket(this.context.basicInfoWrapper.getFullQQVersion()).then((result) => {
      return result;
    }).catch((err) => {
      this.logger.logError(err);
      this.errStack.push(err);
      return false;
    }) && this.pkt?.available;
  }
  get available() {
    return this.pkt?.available ?? false;
  }
  get clientLogStack() {
    return this.pkt?.clientLogStack + "\n" + this.errStack.join("\n");
  }
  async InitSendPacket(qqVer) {
    this.qqVersion = qqVer;
    const table = typedOffset$1[qqVer + "-" + os.arch()];
    if (!table) {
      const err = `[Core] [Packet] PacketBackend 不支持当前QQ版本架构：${qqVer}-${os.arch()}，
            请参照 https://github.com/NapNeko/NapCatQQ/releases/tag/v${napCatVersion} 配置正确的QQ版本！`;
      this.logger.logError(err);
      this.errStack.push(err);
      return false;
    }
    if (this.core.configLoader.configData.packetBackend === "disable") {
      const err = "[Core] [Packet] 已禁用PacketBackend，NapCat.Packet将不会加载！";
      this.logger.logError(err);
      this.errStack.push(err);
      return false;
    }
    this.pkt = new PacketClientSession(this.core);
    await this.pkt.init(process.pid, table.recv, table.send);
    try {
      await this.pkt.operation.FetchRkey(1500);
    } catch (error) {
      this.logger.logError("测试Packet状态异常", error);
      return false;
    }
    return true;
  }
}

class NTQQCollectionApi {
  context;
  core;
  constructor(context, core) {
    this.context = context;
    this.core = core;
  }
  async createCollection(authorUin, authorUid, authorName, brief, rawData) {
    return this.context.session.getCollectionService().createNewCollectionItem({
      commInfo: {
        bid: 1,
        category: 2,
        author: {
          type: 1,
          numId: authorUin,
          strId: authorName,
          groupId: "0",
          groupName: "",
          uid: authorUid
        },
        customGroupId: "0",
        createTime: Date.now().toString(),
        sequence: Date.now().toString()
      },
      richMediaSummary: {
        originalUri: "",
        publisher: "",
        richMediaVersion: 0,
        subTitle: "",
        title: "",
        brief,
        picList: [],
        contentType: 1
      },
      richMediaContent: {
        rawData,
        bizDataList: [],
        picList: [],
        fileList: []
      },
      need_share_url: false
    });
  }
  async getAllCollection(category = 0, count = 50) {
    return this.context.session.getCollectionService().getCollectionItemList({
      category,
      groupId: -1,
      forceSync: true,
      forceFromDb: false,
      timeStamp: "0",
      count,
      searchDown: true
    });
  }
}

var PlatformType = /* @__PURE__ */ ((PlatformType2) => {
  PlatformType2[PlatformType2["KUNKNOWN"] = 0] = "KUNKNOWN";
  PlatformType2[PlatformType2["KANDROID"] = 1] = "KANDROID";
  PlatformType2[PlatformType2["KIOS"] = 2] = "KIOS";
  PlatformType2[PlatformType2["KWINDOWS"] = 3] = "KWINDOWS";
  PlatformType2[PlatformType2["KMAC"] = 4] = "KMAC";
  PlatformType2[PlatformType2["KLINUX"] = 5] = "KLINUX";
  return PlatformType2;
})(PlatformType || {});
var VendorType = /* @__PURE__ */ ((VendorType2) => {
  VendorType2[VendorType2["KNOSETONIOS"] = 0] = "KNOSETONIOS";
  VendorType2[VendorType2["KSUPPORTGOOGLEPUSH"] = 99] = "KSUPPORTGOOGLEPUSH";
  VendorType2[VendorType2["KSUPPORTHMS"] = 3] = "KSUPPORTHMS";
  VendorType2[VendorType2["KSUPPORTOPPOPUSH"] = 4] = "KSUPPORTOPPOPUSH";
  VendorType2[VendorType2["KSUPPORTTPNS"] = 2] = "KSUPPORTTPNS";
  VendorType2[VendorType2["KSUPPORTVIVOPUSH"] = 5] = "KSUPPORTVIVOPUSH";
  VendorType2[VendorType2["KUNSUPPORTANDROIDPUSH"] = 1] = "KUNSUPPORTANDROIDPUSH";
  return VendorType2;
})(VendorType || {});

let osName;
try {
  osName = os$1.hostname();
} catch {
  osName = "NapCat";
}
const homeDir = os$1.homedir();
const systemPlatform = os$1.platform();
os$1.arch();
const systemVersion = os$1.release();
const hostname = osName;
path$1.join(homeDir, "Downloads");
const systemName = os$1.type();

class NTEventWrapper {
  WrapperSession;
  // WrapperSession
  listenerManager = /* @__PURE__ */ new Map();
  // ListenerName-Unique -> Listener实例
  EventTask = /* @__PURE__ */ new Map();
  // tasks ListenerMainName -> ListenerSubName-> uuid -> {timeout,createtime,func}
  constructor(wrapperSession) {
    this.WrapperSession = wrapperSession;
  }
  createProxyDispatch(ListenerMainName) {
    const dispatcherListenerFunc = this.dispatcherListener.bind(this);
    return new Proxy(
      {},
      {
        get(target, prop, receiver) {
          if (typeof target[prop] === "undefined") {
            return (...args) => {
              dispatcherListenerFunc(ListenerMainName, prop, ...args).then();
            };
          }
          return Reflect.get(target, prop, receiver);
        }
      }
    );
  }
  createEventFunction(eventName) {
    const eventNameArr = eventName.split("/");
    if (eventNameArr.length > 1) {
      const serviceName = "get" + (eventNameArr[0]?.replace("NodeIKernel", "") ?? "");
      const eventName2 = eventNameArr[1];
      const services = this.WrapperSession[serviceName]?.();
      if (!services || !eventName2) {
        return void 0;
      }
      let event = services[eventName2];
      event = event?.bind(services);
      if (event) {
        return event;
      }
      return void 0;
    }
    return void 0;
  }
  createListenerFunction(listenerMainName, uniqueCode = "") {
    const existListener = this.listenerManager.get(listenerMainName + uniqueCode);
    if (!existListener) {
      const Listener = this.createProxyDispatch(listenerMainName);
      const ServiceSubName = /^NodeIKernel(.*?)Listener$/.exec(listenerMainName)[1];
      const Service = `NodeIKernel${ServiceSubName}Service/addKernel${ServiceSubName}Listener`;
      this.createEventFunction(Service)(Listener);
      this.listenerManager.set(listenerMainName + uniqueCode, Listener);
      return Listener;
    }
    return existListener;
  }
  // 统一回调清理事件
  async dispatcherListener(ListenerMainName, ListenerSubName, ...args) {
    this.EventTask.get(ListenerMainName)?.get(ListenerSubName)?.forEach((task, uuid) => {
      if (task.createtime + task.timeout < Date.now()) {
        this.EventTask.get(ListenerMainName)?.get(ListenerSubName)?.delete(uuid);
        return;
      }
      if (task?.checker?.(...args)) {
        task.func(...args);
      }
    });
  }
  async callNoListenerEvent(serviceAndMethod, ...args) {
    return this.createEventFunction(serviceAndMethod)(...args);
  }
  async registerListen(listenerAndMethod, checker, waitTimes = 1, timeout = 5e3) {
    return new Promise((resolve, reject) => {
      const ListenerNameList = listenerAndMethod.split("/");
      const ListenerMainName = ListenerNameList[0] ?? "";
      const ListenerSubName = ListenerNameList[1] ?? "";
      const id = randomUUID();
      let complete = 0;
      let retData;
      function sendDataCallback() {
        if (complete === 0) {
          reject(new Error(" ListenerName:" + listenerAndMethod + " timeout"));
        } else {
          resolve(retData);
        }
      }
      const timeoutRef = setTimeout(sendDataCallback, timeout);
      const eventCallback = {
        timeout,
        createtime: Date.now(),
        checker,
        func: (...args) => {
          complete++;
          retData = args;
          if (complete >= waitTimes) {
            clearTimeout(timeoutRef);
            sendDataCallback();
          }
        }
      };
      if (!this.EventTask.get(ListenerMainName)) {
        this.EventTask.set(ListenerMainName, /* @__PURE__ */ new Map());
      }
      if (!this.EventTask.get(ListenerMainName)?.get(ListenerSubName)) {
        this.EventTask.get(ListenerMainName)?.set(ListenerSubName, /* @__PURE__ */ new Map());
      }
      this.EventTask.get(ListenerMainName)?.get(ListenerSubName)?.set(id, eventCallback);
      this.createListenerFunction(ListenerMainName);
    });
  }
  async callNormalEventV2(serviceAndMethod, listenerAndMethod, args, checkerEvent = () => true, checkerListener = () => true, callbackTimesToWait = 1, timeout = 5e3) {
    const id = randomUUID();
    let complete = 0;
    let retData;
    let retEvent = {};
    function sendDataCallback(resolve, reject) {
      if (complete === 0) {
        reject(
          new Error(
            "Timeout: NTEvent serviceAndMethod:" + serviceAndMethod + " ListenerName:" + listenerAndMethod + " EventRet:\n" + JSON.stringify(retEvent, null, 4) + "\n"
          )
        );
      } else {
        resolve([retEvent, ...retData]);
      }
    }
    const ListenerNameList = listenerAndMethod.split("/");
    const ListenerMainName = ListenerNameList[0] ?? "";
    const ListenerSubName = ListenerNameList[1] ?? "";
    return new Promise(
      (resolve, reject) => {
        const timeoutRef = setTimeout(() => sendDataCallback(resolve, reject), timeout);
        const eventCallback = {
          timeout,
          createtime: Date.now(),
          checker: checkerListener,
          func: (...args2) => {
            complete++;
            retData = args2;
            if (complete >= callbackTimesToWait) {
              clearTimeout(timeoutRef);
              sendDataCallback(resolve, reject);
            }
          }
        };
        if (!this.EventTask.get(ListenerMainName)) {
          this.EventTask.set(ListenerMainName, /* @__PURE__ */ new Map());
        }
        if (!this.EventTask.get(ListenerMainName)?.get(ListenerSubName)) {
          this.EventTask.get(ListenerMainName)?.set(ListenerSubName, /* @__PURE__ */ new Map());
        }
        this.EventTask.get(ListenerMainName)?.get(ListenerSubName)?.set(id, eventCallback);
        this.createListenerFunction(ListenerMainName);
        const eventResult = this.createEventFunction(serviceAndMethod)(...args);
        const eventRetHandle = (eventData) => {
          retEvent = eventData;
          if (!checkerEvent(retEvent) && timeoutRef.hasRef()) {
            clearTimeout(timeoutRef);
            reject(
              new Error(
                "EventChecker Failed: NTEvent serviceAndMethod:" + serviceAndMethod + " ListenerName:" + listenerAndMethod + " EventRet:\n" + JSON.stringify(retEvent, null, 4) + "\n"
              )
            );
          }
        };
        if (eventResult instanceof Promise) {
          eventResult.then((eventResult2) => {
            eventRetHandle(eventResult2);
          }).catch(reject);
        } else {
          eventRetHandle(eventResult);
        }
      }
    );
  }
}

// This is a generated file. Do not edit.
var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/;
var ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;
var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/;

var unicode = {
	Space_Separator: Space_Separator,
	ID_Start: ID_Start,
	ID_Continue: ID_Continue
};

var util$2 = {
    isSpaceSeparator (c) {
        return typeof c === 'string' && unicode.Space_Separator.test(c)
    },

    isIdStartChar (c) {
        return typeof c === 'string' && (
            (c >= 'a' && c <= 'z') ||
        (c >= 'A' && c <= 'Z') ||
        (c === '$') || (c === '_') ||
        unicode.ID_Start.test(c)
        )
    },

    isIdContinueChar (c) {
        return typeof c === 'string' && (
            (c >= 'a' && c <= 'z') ||
        (c >= 'A' && c <= 'Z') ||
        (c >= '0' && c <= '9') ||
        (c === '$') || (c === '_') ||
        (c === '\u200C') || (c === '\u200D') ||
        unicode.ID_Continue.test(c)
        )
    },

    isDigit (c) {
        return typeof c === 'string' && /[0-9]/.test(c)
    },

    isHexDigit (c) {
        return typeof c === 'string' && /[0-9A-Fa-f]/.test(c)
    },
};

let source;
let parseState;
let stack;
let pos;
let line;
let column;
let token;
let key;
let root;

var parse = function parse (text, reviver) {
    source = String(text);
    parseState = 'start';
    stack = [];
    pos = 0;
    line = 1;
    column = 0;
    token = undefined;
    key = undefined;
    root = undefined;

    do {
        token = lex();

        // This code is unreachable.
        // if (!parseStates[parseState]) {
        //     throw invalidParseState()
        // }

        parseStates[parseState]();
    } while (token.type !== 'eof')

    if (typeof reviver === 'function') {
        return internalize({'': root}, '', reviver)
    }

    return root
};

function internalize (holder, name, reviver) {
    const value = holder[name];
    if (value != null && typeof value === 'object') {
        if (Array.isArray(value)) {
            for (let i = 0; i < value.length; i++) {
                const key = String(i);
                const replacement = internalize(value, key, reviver);
                if (replacement === undefined) {
                    delete value[key];
                } else {
                    Object.defineProperty(value, key, {
                        value: replacement,
                        writable: true,
                        enumerable: true,
                        configurable: true,
                    });
                }
            }
        } else {
            for (const key in value) {
                const replacement = internalize(value, key, reviver);
                if (replacement === undefined) {
                    delete value[key];
                } else {
                    Object.defineProperty(value, key, {
                        value: replacement,
                        writable: true,
                        enumerable: true,
                        configurable: true,
                    });
                }
            }
        }
    }

    return reviver.call(holder, name, value)
}

let lexState;
let buffer;
let doubleQuote;
let sign;
let c;

function lex () {
    lexState = 'default';
    buffer = '';
    doubleQuote = false;
    sign = 1;

    for (;;) {
        c = peek();

        // This code is unreachable.
        // if (!lexStates[lexState]) {
        //     throw invalidLexState(lexState)
        // }

        const token = lexStates[lexState]();
        if (token) {
            return token
        }
    }
}

function peek () {
    if (source[pos]) {
        return String.fromCodePoint(source.codePointAt(pos))
    }
}

function read () {
    const c = peek();

    if (c === '\n') {
        line++;
        column = 0;
    } else if (c) {
        column += c.length;
    } else {
        column++;
    }

    if (c) {
        pos += c.length;
    }

    return c
}

const lexStates = {
    default () {
        switch (c) {
        case '\t':
        case '\v':
        case '\f':
        case ' ':
        case '\u00A0':
        case '\uFEFF':
        case '\n':
        case '\r':
        case '\u2028':
        case '\u2029':
            read();
            return

        case '/':
            read();
            lexState = 'comment';
            return

        case undefined:
            read();
            return newToken('eof')
        }

        if (util$2.isSpaceSeparator(c)) {
            read();
            return
        }

        // This code is unreachable.
        // if (!lexStates[parseState]) {
        //     throw invalidLexState(parseState)
        // }

        return lexStates[parseState]()
    },

    comment () {
        switch (c) {
        case '*':
            read();
            lexState = 'multiLineComment';
            return

        case '/':
            read();
            lexState = 'singleLineComment';
            return
        }

        throw invalidChar(read())
    },

    multiLineComment () {
        switch (c) {
        case '*':
            read();
            lexState = 'multiLineCommentAsterisk';
            return

        case undefined:
            throw invalidChar(read())
        }

        read();
    },

    multiLineCommentAsterisk () {
        switch (c) {
        case '*':
            read();
            return

        case '/':
            read();
            lexState = 'default';
            return

        case undefined:
            throw invalidChar(read())
        }

        read();
        lexState = 'multiLineComment';
    },

    singleLineComment () {
        switch (c) {
        case '\n':
        case '\r':
        case '\u2028':
        case '\u2029':
            read();
            lexState = 'default';
            return

        case undefined:
            read();
            return newToken('eof')
        }

        read();
    },

    value () {
        switch (c) {
        case '{':
        case '[':
            return newToken('punctuator', read())

        case 'n':
            read();
            literal('ull');
            return newToken('null', null)

        case 't':
            read();
            literal('rue');
            return newToken('boolean', true)

        case 'f':
            read();
            literal('alse');
            return newToken('boolean', false)

        case '-':
        case '+':
            if (read() === '-') {
                sign = -1;
            }

            lexState = 'sign';
            return

        case '.':
            buffer = read();
            lexState = 'decimalPointLeading';
            return

        case '0':
            buffer = read();
            lexState = 'zero';
            return

        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
            buffer = read();
            lexState = 'decimalInteger';
            return

        case 'I':
            read();
            literal('nfinity');
            return newToken('numeric', Infinity)

        case 'N':
            read();
            literal('aN');
            return newToken('numeric', NaN)

        case '"':
        case "'":
            doubleQuote = (read() === '"');
            buffer = '';
            lexState = 'string';
            return
        }

        throw invalidChar(read())
    },

    identifierNameStartEscape () {
        if (c !== 'u') {
            throw invalidChar(read())
        }

        read();
        const u = unicodeEscape();
        switch (u) {
        case '$':
        case '_':
            break

        default:
            if (!util$2.isIdStartChar(u)) {
                throw invalidIdentifier()
            }

            break
        }

        buffer += u;
        lexState = 'identifierName';
    },

    identifierName () {
        switch (c) {
        case '$':
        case '_':
        case '\u200C':
        case '\u200D':
            buffer += read();
            return

        case '\\':
            read();
            lexState = 'identifierNameEscape';
            return
        }

        if (util$2.isIdContinueChar(c)) {
            buffer += read();
            return
        }

        return newToken('identifier', buffer)
    },

    identifierNameEscape () {
        if (c !== 'u') {
            throw invalidChar(read())
        }

        read();
        const u = unicodeEscape();
        switch (u) {
        case '$':
        case '_':
        case '\u200C':
        case '\u200D':
            break

        default:
            if (!util$2.isIdContinueChar(u)) {
                throw invalidIdentifier()
            }

            break
        }

        buffer += u;
        lexState = 'identifierName';
    },

    sign () {
        switch (c) {
        case '.':
            buffer = read();
            lexState = 'decimalPointLeading';
            return

        case '0':
            buffer = read();
            lexState = 'zero';
            return

        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
            buffer = read();
            lexState = 'decimalInteger';
            return

        case 'I':
            read();
            literal('nfinity');
            return newToken('numeric', sign * Infinity)

        case 'N':
            read();
            literal('aN');
            return newToken('numeric', NaN)
        }

        throw invalidChar(read())
    },

    zero () {
        switch (c) {
        case '.':
            buffer += read();
            lexState = 'decimalPoint';
            return

        case 'e':
        case 'E':
            buffer += read();
            lexState = 'decimalExponent';
            return

        case 'x':
        case 'X':
            buffer += read();
            lexState = 'hexadecimal';
            return
        }

        return newToken('numeric', sign * 0)
    },

    decimalInteger () {
        switch (c) {
        case '.':
            buffer += read();
            lexState = 'decimalPoint';
            return

        case 'e':
        case 'E':
            buffer += read();
            lexState = 'decimalExponent';
            return
        }

        if (util$2.isDigit(c)) {
            buffer += read();
            return
        }

        return newToken('numeric', sign * Number(buffer))
    },

    decimalPointLeading () {
        if (util$2.isDigit(c)) {
            buffer += read();
            lexState = 'decimalFraction';
            return
        }

        throw invalidChar(read())
    },

    decimalPoint () {
        switch (c) {
        case 'e':
        case 'E':
            buffer += read();
            lexState = 'decimalExponent';
            return
        }

        if (util$2.isDigit(c)) {
            buffer += read();
            lexState = 'decimalFraction';
            return
        }

        return newToken('numeric', sign * Number(buffer))
    },

    decimalFraction () {
        switch (c) {
        case 'e':
        case 'E':
            buffer += read();
            lexState = 'decimalExponent';
            return
        }

        if (util$2.isDigit(c)) {
            buffer += read();
            return
        }

        return newToken('numeric', sign * Number(buffer))
    },

    decimalExponent () {
        switch (c) {
        case '+':
        case '-':
            buffer += read();
            lexState = 'decimalExponentSign';
            return
        }

        if (util$2.isDigit(c)) {
            buffer += read();
            lexState = 'decimalExponentInteger';
            return
        }

        throw invalidChar(read())
    },

    decimalExponentSign () {
        if (util$2.isDigit(c)) {
            buffer += read();
            lexState = 'decimalExponentInteger';
            return
        }

        throw invalidChar(read())
    },

    decimalExponentInteger () {
        if (util$2.isDigit(c)) {
            buffer += read();
            return
        }

        return newToken('numeric', sign * Number(buffer))
    },

    hexadecimal () {
        if (util$2.isHexDigit(c)) {
            buffer += read();
            lexState = 'hexadecimalInteger';
            return
        }

        throw invalidChar(read())
    },

    hexadecimalInteger () {
        if (util$2.isHexDigit(c)) {
            buffer += read();
            return
        }

        return newToken('numeric', sign * Number(buffer))
    },

    string () {
        switch (c) {
        case '\\':
            read();
            buffer += escape$2();
            return

        case '"':
            if (doubleQuote) {
                read();
                return newToken('string', buffer)
            }

            buffer += read();
            return

        case "'":
            if (!doubleQuote) {
                read();
                return newToken('string', buffer)
            }

            buffer += read();
            return

        case '\n':
        case '\r':
            throw invalidChar(read())

        case '\u2028':
        case '\u2029':
            separatorChar(c);
            break

        case undefined:
            throw invalidChar(read())
        }

        buffer += read();
    },

    start () {
        switch (c) {
        case '{':
        case '[':
            return newToken('punctuator', read())

        // This code is unreachable since the default lexState handles eof.
        // case undefined:
        //     return newToken('eof')
        }

        lexState = 'value';
    },

    beforePropertyName () {
        switch (c) {
        case '$':
        case '_':
            buffer = read();
            lexState = 'identifierName';
            return

        case '\\':
            read();
            lexState = 'identifierNameStartEscape';
            return

        case '}':
            return newToken('punctuator', read())

        case '"':
        case "'":
            doubleQuote = (read() === '"');
            lexState = 'string';
            return
        }

        if (util$2.isIdStartChar(c)) {
            buffer += read();
            lexState = 'identifierName';
            return
        }

        throw invalidChar(read())
    },

    afterPropertyName () {
        if (c === ':') {
            return newToken('punctuator', read())
        }

        throw invalidChar(read())
    },

    beforePropertyValue () {
        lexState = 'value';
    },

    afterPropertyValue () {
        switch (c) {
        case ',':
        case '}':
            return newToken('punctuator', read())
        }

        throw invalidChar(read())
    },

    beforeArrayValue () {
        if (c === ']') {
            return newToken('punctuator', read())
        }

        lexState = 'value';
    },

    afterArrayValue () {
        switch (c) {
        case ',':
        case ']':
            return newToken('punctuator', read())
        }

        throw invalidChar(read())
    },

    end () {
        // This code is unreachable since it's handled by the default lexState.
        // if (c === undefined) {
        //     read()
        //     return newToken('eof')
        // }

        throw invalidChar(read())
    },
};

function newToken (type, value) {
    return {
        type,
        value,
        line,
        column,
    }
}

function literal (s) {
    for (const c of s) {
        const p = peek();

        if (p !== c) {
            throw invalidChar(read())
        }

        read();
    }
}

function escape$2 () {
    const c = peek();
    switch (c) {
    case 'b':
        read();
        return '\b'

    case 'f':
        read();
        return '\f'

    case 'n':
        read();
        return '\n'

    case 'r':
        read();
        return '\r'

    case 't':
        read();
        return '\t'

    case 'v':
        read();
        return '\v'

    case '0':
        read();
        if (util$2.isDigit(peek())) {
            throw invalidChar(read())
        }

        return '\0'

    case 'x':
        read();
        return hexEscape()

    case 'u':
        read();
        return unicodeEscape()

    case '\n':
    case '\u2028':
    case '\u2029':
        read();
        return ''

    case '\r':
        read();
        if (peek() === '\n') {
            read();
        }

        return ''

    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
        throw invalidChar(read())

    case undefined:
        throw invalidChar(read())
    }

    return read()
}

function hexEscape () {
    let buffer = '';
    let c = peek();

    if (!util$2.isHexDigit(c)) {
        throw invalidChar(read())
    }

    buffer += read();

    c = peek();
    if (!util$2.isHexDigit(c)) {
        throw invalidChar(read())
    }

    buffer += read();

    return String.fromCodePoint(parseInt(buffer, 16))
}

function unicodeEscape () {
    let buffer = '';
    let count = 4;

    while (count-- > 0) {
        const c = peek();
        if (!util$2.isHexDigit(c)) {
            throw invalidChar(read())
        }

        buffer += read();
    }

    return String.fromCodePoint(parseInt(buffer, 16))
}

const parseStates = {
    start () {
        if (token.type === 'eof') {
            throw invalidEOF()
        }

        push();
    },

    beforePropertyName () {
        switch (token.type) {
        case 'identifier':
        case 'string':
            key = token.value;
            parseState = 'afterPropertyName';
            return

        case 'punctuator':
            // This code is unreachable since it's handled by the lexState.
            // if (token.value !== '}') {
            //     throw invalidToken()
            // }

            pop();
            return

        case 'eof':
            throw invalidEOF()
        }

        // This code is unreachable since it's handled by the lexState.
        // throw invalidToken()
    },

    afterPropertyName () {
        // This code is unreachable since it's handled by the lexState.
        // if (token.type !== 'punctuator' || token.value !== ':') {
        //     throw invalidToken()
        // }

        if (token.type === 'eof') {
            throw invalidEOF()
        }

        parseState = 'beforePropertyValue';
    },

    beforePropertyValue () {
        if (token.type === 'eof') {
            throw invalidEOF()
        }

        push();
    },

    beforeArrayValue () {
        if (token.type === 'eof') {
            throw invalidEOF()
        }

        if (token.type === 'punctuator' && token.value === ']') {
            pop();
            return
        }

        push();
    },

    afterPropertyValue () {
        // This code is unreachable since it's handled by the lexState.
        // if (token.type !== 'punctuator') {
        //     throw invalidToken()
        // }

        if (token.type === 'eof') {
            throw invalidEOF()
        }

        switch (token.value) {
        case ',':
            parseState = 'beforePropertyName';
            return

        case '}':
            pop();
        }

        // This code is unreachable since it's handled by the lexState.
        // throw invalidToken()
    },

    afterArrayValue () {
        // This code is unreachable since it's handled by the lexState.
        // if (token.type !== 'punctuator') {
        //     throw invalidToken()
        // }

        if (token.type === 'eof') {
            throw invalidEOF()
        }

        switch (token.value) {
        case ',':
            parseState = 'beforeArrayValue';
            return

        case ']':
            pop();
        }

        // This code is unreachable since it's handled by the lexState.
        // throw invalidToken()
    },

    end () {
        // This code is unreachable since it's handled by the lexState.
        // if (token.type !== 'eof') {
        //     throw invalidToken()
        // }
    },
};

function push () {
    let value;

    switch (token.type) {
    case 'punctuator':
        switch (token.value) {
        case '{':
            value = {};
            break

        case '[':
            value = [];
            break
        }

        break

    case 'null':
    case 'boolean':
    case 'numeric':
    case 'string':
        value = token.value;
        break

    // This code is unreachable.
    // default:
    //     throw invalidToken()
    }

    if (root === undefined) {
        root = value;
    } else {
        const parent = stack[stack.length - 1];
        if (Array.isArray(parent)) {
            parent.push(value);
        } else {
            Object.defineProperty(parent, key, {
                value,
                writable: true,
                enumerable: true,
                configurable: true,
            });
        }
    }

    if (value !== null && typeof value === 'object') {
        stack.push(value);

        if (Array.isArray(value)) {
            parseState = 'beforeArrayValue';
        } else {
            parseState = 'beforePropertyName';
        }
    } else {
        const current = stack[stack.length - 1];
        if (current == null) {
            parseState = 'end';
        } else if (Array.isArray(current)) {
            parseState = 'afterArrayValue';
        } else {
            parseState = 'afterPropertyValue';
        }
    }
}

function pop () {
    stack.pop();

    const current = stack[stack.length - 1];
    if (current == null) {
        parseState = 'end';
    } else if (Array.isArray(current)) {
        parseState = 'afterArrayValue';
    } else {
        parseState = 'afterPropertyValue';
    }
}

// This code is unreachable.
// function invalidParseState () {
//     return new Error(`JSON5: invalid parse state '${parseState}'`)
// }

// This code is unreachable.
// function invalidLexState (state) {
//     return new Error(`JSON5: invalid lex state '${state}'`)
// }

function invalidChar (c) {
    if (c === undefined) {
        return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
    }

    return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
}

function invalidEOF () {
    return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
}

// This code is unreachable.
// function invalidToken () {
//     if (token.type === 'eof') {
//         return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
//     }

//     const c = String.fromCodePoint(token.value.codePointAt(0))
//     return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
// }

function invalidIdentifier () {
    column -= 5;
    return syntaxError(`JSON5: invalid identifier character at ${line}:${column}`)
}

function separatorChar (c) {
    console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`);
}

function formatChar (c) {
    const replacements = {
        "'": "\\'",
        '"': '\\"',
        '\\': '\\\\',
        '\b': '\\b',
        '\f': '\\f',
        '\n': '\\n',
        '\r': '\\r',
        '\t': '\\t',
        '\v': '\\v',
        '\0': '\\0',
        '\u2028': '\\u2028',
        '\u2029': '\\u2029',
    };

    if (replacements[c]) {
        return replacements[c]
    }

    if (c < ' ') {
        const hexString = c.charCodeAt(0).toString(16);
        return '\\x' + ('00' + hexString).substring(hexString.length)
    }

    return c
}

function syntaxError (message) {
    const err = new SyntaxError(message);
    err.lineNumber = line;
    err.columnNumber = column;
    return err
}

var stringify = function stringify (value, replacer, space) {
    const stack = [];
    let indent = '';
    let propertyList;
    let replacerFunc;
    let gap = '';
    let quote;

    if (
        replacer != null &&
        typeof replacer === 'object' &&
        !Array.isArray(replacer)
    ) {
        space = replacer.space;
        quote = replacer.quote;
        replacer = replacer.replacer;
    }

    if (typeof replacer === 'function') {
        replacerFunc = replacer;
    } else if (Array.isArray(replacer)) {
        propertyList = [];
        for (const v of replacer) {
            let item;

            if (typeof v === 'string') {
                item = v;
            } else if (
                typeof v === 'number' ||
                v instanceof String ||
                v instanceof Number
            ) {
                item = String(v);
            }

            if (item !== undefined && propertyList.indexOf(item) < 0) {
                propertyList.push(item);
            }
        }
    }

    if (space instanceof Number) {
        space = Number(space);
    } else if (space instanceof String) {
        space = String(space);
    }

    if (typeof space === 'number') {
        if (space > 0) {
            space = Math.min(10, Math.floor(space));
            gap = '          '.substr(0, space);
        }
    } else if (typeof space === 'string') {
        gap = space.substr(0, 10);
    }

    return serializeProperty('', {'': value})

    function serializeProperty (key, holder) {
        let value = holder[key];
        if (value != null) {
            if (typeof value.toJSON5 === 'function') {
                value = value.toJSON5(key);
            } else if (typeof value.toJSON === 'function') {
                value = value.toJSON(key);
            }
        }

        if (replacerFunc) {
            value = replacerFunc.call(holder, key, value);
        }

        if (value instanceof Number) {
            value = Number(value);
        } else if (value instanceof String) {
            value = String(value);
        } else if (value instanceof Boolean) {
            value = value.valueOf();
        }

        switch (value) {
        case null: return 'null'
        case true: return 'true'
        case false: return 'false'
        }

        if (typeof value === 'string') {
            return quoteString(value)
        }

        if (typeof value === 'number') {
            return String(value)
        }

        if (typeof value === 'object') {
            return Array.isArray(value) ? serializeArray(value) : serializeObject(value)
        }

        return undefined
    }

    function quoteString (value) {
        const quotes = {
            "'": 0.1,
            '"': 0.2,
        };

        const replacements = {
            "'": "\\'",
            '"': '\\"',
            '\\': '\\\\',
            '\b': '\\b',
            '\f': '\\f',
            '\n': '\\n',
            '\r': '\\r',
            '\t': '\\t',
            '\v': '\\v',
            '\0': '\\0',
            '\u2028': '\\u2028',
            '\u2029': '\\u2029',
        };

        let product = '';

        for (let i = 0; i < value.length; i++) {
            const c = value[i];
            switch (c) {
            case "'":
            case '"':
                quotes[c]++;
                product += c;
                continue

            case '\0':
                if (util$2.isDigit(value[i + 1])) {
                    product += '\\x00';
                    continue
                }
            }

            if (replacements[c]) {
                product += replacements[c];
                continue
            }

            if (c < ' ') {
                let hexString = c.charCodeAt(0).toString(16);
                product += '\\x' + ('00' + hexString).substring(hexString.length);
                continue
            }

            product += c;
        }

        const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b);

        product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]);

        return quoteChar + product + quoteChar
    }

    function serializeObject (value) {
        if (stack.indexOf(value) >= 0) {
            throw TypeError('Converting circular structure to JSON5')
        }

        stack.push(value);

        let stepback = indent;
        indent = indent + gap;

        let keys = propertyList || Object.keys(value);
        let partial = [];
        for (const key of keys) {
            const propertyString = serializeProperty(key, value);
            if (propertyString !== undefined) {
                let member = serializeKey(key) + ':';
                if (gap !== '') {
                    member += ' ';
                }
                member += propertyString;
                partial.push(member);
            }
        }

        let final;
        if (partial.length === 0) {
            final = '{}';
        } else {
            let properties;
            if (gap === '') {
                properties = partial.join(',');
                final = '{' + properties + '}';
            } else {
                let separator = ',\n' + indent;
                properties = partial.join(separator);
                final = '{\n' + indent + properties + ',\n' + stepback + '}';
            }
        }

        stack.pop();
        indent = stepback;
        return final
    }

    function serializeKey (key) {
        if (key.length === 0) {
            return quoteString(key)
        }

        const firstChar = String.fromCodePoint(key.codePointAt(0));
        if (!util$2.isIdStartChar(firstChar)) {
            return quoteString(key)
        }

        for (let i = firstChar.length; i < key.length; i++) {
            if (!util$2.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) {
                return quoteString(key)
            }
        }

        return key
    }

    function serializeArray (value) {
        if (stack.indexOf(value) >= 0) {
            throw TypeError('Converting circular structure to JSON5')
        }

        stack.push(value);

        let stepback = indent;
        indent = indent + gap;

        let partial = [];
        for (let i = 0; i < value.length; i++) {
            const propertyString = serializeProperty(String(i), value);
            partial.push((propertyString !== undefined) ? propertyString : 'null');
        }

        let final;
        if (partial.length === 0) {
            final = '[]';
        } else {
            if (gap === '') {
                let properties = partial.join(',');
                final = '[' + properties + ']';
            } else {
                let separator = ',\n' + indent;
                let properties = partial.join(separator);
                final = '[\n' + indent + properties + ',\n' + stepback + ']';
            }
        }

        stack.pop();
        indent = stepback;
        return final
    }
};

const JSON5 = {
    parse,
    stringify,
};

var lib$2 = JSON5;

var ajv = {exports: {}};

var core$1 = {};

var validate = {};

var boolSchema = {};

var errors = {};

var codegen = {};

var code$1 = {};

var hasRequiredCode$1;

function requireCode$1 () {
	if (hasRequiredCode$1) return code$1;
	hasRequiredCode$1 = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.regexpCode = exports$1.getEsmExportName = exports$1.getProperty = exports$1.safeStringify = exports$1.stringify = exports$1.strConcat = exports$1.addCodeArg = exports$1.str = exports$1._ = exports$1.nil = exports$1._Code = exports$1.Name = exports$1.IDENTIFIER = exports$1._CodeOrName = void 0;
		// eslint-disable-next-line @typescript-eslint/no-extraneous-class
		class _CodeOrName {
		}
		exports$1._CodeOrName = _CodeOrName;
		exports$1.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
		class Name extends _CodeOrName {
		    constructor(s) {
		        super();
		        if (!exports$1.IDENTIFIER.test(s))
		            throw new Error("CodeGen: name must be a valid identifier");
		        this.str = s;
		    }
		    toString() {
		        return this.str;
		    }
		    emptyStr() {
		        return false;
		    }
		    get names() {
		        return { [this.str]: 1 };
		    }
		}
		exports$1.Name = Name;
		class _Code extends _CodeOrName {
		    constructor(code) {
		        super();
		        this._items = typeof code === "string" ? [code] : code;
		    }
		    toString() {
		        return this.str;
		    }
		    emptyStr() {
		        if (this._items.length > 1)
		            return false;
		        const item = this._items[0];
		        return item === "" || item === '""';
		    }
		    get str() {
		        var _a;
		        return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, "")));
		    }
		    get names() {
		        var _a;
		        return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => {
		            if (c instanceof Name)
		                names[c.str] = (names[c.str] || 0) + 1;
		            return names;
		        }, {})));
		    }
		}
		exports$1._Code = _Code;
		exports$1.nil = new _Code("");
		function _(strs, ...args) {
		    const code = [strs[0]];
		    let i = 0;
		    while (i < args.length) {
		        addCodeArg(code, args[i]);
		        code.push(strs[++i]);
		    }
		    return new _Code(code);
		}
		exports$1._ = _;
		const plus = new _Code("+");
		function str(strs, ...args) {
		    const expr = [safeStringify(strs[0])];
		    let i = 0;
		    while (i < args.length) {
		        expr.push(plus);
		        addCodeArg(expr, args[i]);
		        expr.push(plus, safeStringify(strs[++i]));
		    }
		    optimize(expr);
		    return new _Code(expr);
		}
		exports$1.str = str;
		function addCodeArg(code, arg) {
		    if (arg instanceof _Code)
		        code.push(...arg._items);
		    else if (arg instanceof Name)
		        code.push(arg);
		    else
		        code.push(interpolate(arg));
		}
		exports$1.addCodeArg = addCodeArg;
		function optimize(expr) {
		    let i = 1;
		    while (i < expr.length - 1) {
		        if (expr[i] === plus) {
		            const res = mergeExprItems(expr[i - 1], expr[i + 1]);
		            if (res !== undefined) {
		                expr.splice(i - 1, 3, res);
		                continue;
		            }
		            expr[i++] = "+";
		        }
		        i++;
		    }
		}
		function mergeExprItems(a, b) {
		    if (b === '""')
		        return a;
		    if (a === '""')
		        return b;
		    if (typeof a == "string") {
		        if (b instanceof Name || a[a.length - 1] !== '"')
		            return;
		        if (typeof b != "string")
		            return `${a.slice(0, -1)}${b}"`;
		        if (b[0] === '"')
		            return a.slice(0, -1) + b.slice(1);
		        return;
		    }
		    if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))
		        return `"${a}${b.slice(1)}`;
		    return;
		}
		function strConcat(c1, c2) {
		    return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`;
		}
		exports$1.strConcat = strConcat;
		// TODO do not allow arrays here
		function interpolate(x) {
		    return typeof x == "number" || typeof x == "boolean" || x === null
		        ? x
		        : safeStringify(Array.isArray(x) ? x.join(",") : x);
		}
		function stringify(x) {
		    return new _Code(safeStringify(x));
		}
		exports$1.stringify = stringify;
		function safeStringify(x) {
		    return JSON.stringify(x)
		        .replace(/\u2028/g, "\\u2028")
		        .replace(/\u2029/g, "\\u2029");
		}
		exports$1.safeStringify = safeStringify;
		function getProperty(key) {
		    return typeof key == "string" && exports$1.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`;
		}
		exports$1.getProperty = getProperty;
		//Does best effort to format the name properly
		function getEsmExportName(key) {
		    if (typeof key == "string" && exports$1.IDENTIFIER.test(key)) {
		        return new _Code(`${key}`);
		    }
		    throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
		}
		exports$1.getEsmExportName = getEsmExportName;
		function regexpCode(rx) {
		    return new _Code(rx.toString());
		}
		exports$1.regexpCode = regexpCode;
		
	} (code$1));
	return code$1;
}

var scope = {};

var hasRequiredScope;

function requireScope () {
	if (hasRequiredScope) return scope;
	hasRequiredScope = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.ValueScope = exports$1.ValueScopeName = exports$1.Scope = exports$1.varKinds = exports$1.UsedValueState = void 0;
		const code_1 = requireCode$1();
		class ValueError extends Error {
		    constructor(name) {
		        super(`CodeGen: "code" for ${name} not defined`);
		        this.value = name.value;
		    }
		}
		var UsedValueState;
		(function (UsedValueState) {
		    UsedValueState[UsedValueState["Started"] = 0] = "Started";
		    UsedValueState[UsedValueState["Completed"] = 1] = "Completed";
		})(UsedValueState || (exports$1.UsedValueState = UsedValueState = {}));
		exports$1.varKinds = {
		    const: new code_1.Name("const"),
		    let: new code_1.Name("let"),
		    var: new code_1.Name("var"),
		};
		class Scope {
		    constructor({ prefixes, parent } = {}) {
		        this._names = {};
		        this._prefixes = prefixes;
		        this._parent = parent;
		    }
		    toName(nameOrPrefix) {
		        return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
		    }
		    name(prefix) {
		        return new code_1.Name(this._newName(prefix));
		    }
		    _newName(prefix) {
		        const ng = this._names[prefix] || this._nameGroup(prefix);
		        return `${prefix}${ng.index++}`;
		    }
		    _nameGroup(prefix) {
		        var _a, _b;
		        if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) {
		            throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
		        }
		        return (this._names[prefix] = { prefix, index: 0 });
		    }
		}
		exports$1.Scope = Scope;
		class ValueScopeName extends code_1.Name {
		    constructor(prefix, nameStr) {
		        super(nameStr);
		        this.prefix = prefix;
		    }
		    setValue(value, { property, itemIndex }) {
		        this.value = value;
		        this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`;
		    }
		}
		exports$1.ValueScopeName = ValueScopeName;
		const line = (0, code_1._) `\n`;
		class ValueScope extends Scope {
		    constructor(opts) {
		        super(opts);
		        this._values = {};
		        this._scope = opts.scope;
		        this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
		    }
		    get() {
		        return this._scope;
		    }
		    name(prefix) {
		        return new ValueScopeName(prefix, this._newName(prefix));
		    }
		    value(nameOrPrefix, value) {
		        var _a;
		        if (value.ref === undefined)
		            throw new Error("CodeGen: ref must be passed in value");
		        const name = this.toName(nameOrPrefix);
		        const { prefix } = name;
		        const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;
		        let vs = this._values[prefix];
		        if (vs) {
		            const _name = vs.get(valueKey);
		            if (_name)
		                return _name;
		        }
		        else {
		            vs = this._values[prefix] = new Map();
		        }
		        vs.set(valueKey, name);
		        const s = this._scope[prefix] || (this._scope[prefix] = []);
		        const itemIndex = s.length;
		        s[itemIndex] = value.ref;
		        name.setValue(value, { property: prefix, itemIndex });
		        return name;
		    }
		    getValue(prefix, keyOrRef) {
		        const vs = this._values[prefix];
		        if (!vs)
		            return;
		        return vs.get(keyOrRef);
		    }
		    scopeRefs(scopeName, values = this._values) {
		        return this._reduceValues(values, (name) => {
		            if (name.scopePath === undefined)
		                throw new Error(`CodeGen: name "${name}" has no value`);
		            return (0, code_1._) `${scopeName}${name.scopePath}`;
		        });
		    }
		    scopeCode(values = this._values, usedValues, getCode) {
		        return this._reduceValues(values, (name) => {
		            if (name.value === undefined)
		                throw new Error(`CodeGen: name "${name}" has no value`);
		            return name.value.code;
		        }, usedValues, getCode);
		    }
		    _reduceValues(values, valueCode, usedValues = {}, getCode) {
		        let code = code_1.nil;
		        for (const prefix in values) {
		            const vs = values[prefix];
		            if (!vs)
		                continue;
		            const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map());
		            vs.forEach((name) => {
		                if (nameSet.has(name))
		                    return;
		                nameSet.set(name, UsedValueState.Started);
		                let c = valueCode(name);
		                if (c) {
		                    const def = this.opts.es5 ? exports$1.varKinds.var : exports$1.varKinds.const;
		                    code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`;
		                }
		                else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) {
		                    code = (0, code_1._) `${code}${c}${this.opts._n}`;
		                }
		                else {
		                    throw new ValueError(name);
		                }
		                nameSet.set(name, UsedValueState.Completed);
		            });
		        }
		        return code;
		    }
		}
		exports$1.ValueScope = ValueScope;
		
	} (scope));
	return scope;
}

var hasRequiredCodegen;

function requireCodegen () {
	if (hasRequiredCodegen) return codegen;
	hasRequiredCodegen = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.or = exports$1.and = exports$1.not = exports$1.CodeGen = exports$1.operators = exports$1.varKinds = exports$1.ValueScopeName = exports$1.ValueScope = exports$1.Scope = exports$1.Name = exports$1.regexpCode = exports$1.stringify = exports$1.getProperty = exports$1.nil = exports$1.strConcat = exports$1.str = exports$1._ = void 0;
		const code_1 = requireCode$1();
		const scope_1 = requireScope();
		var code_2 = requireCode$1();
		Object.defineProperty(exports$1, "_", { enumerable: true, get: function () { return code_2._; } });
		Object.defineProperty(exports$1, "str", { enumerable: true, get: function () { return code_2.str; } });
		Object.defineProperty(exports$1, "strConcat", { enumerable: true, get: function () { return code_2.strConcat; } });
		Object.defineProperty(exports$1, "nil", { enumerable: true, get: function () { return code_2.nil; } });
		Object.defineProperty(exports$1, "getProperty", { enumerable: true, get: function () { return code_2.getProperty; } });
		Object.defineProperty(exports$1, "stringify", { enumerable: true, get: function () { return code_2.stringify; } });
		Object.defineProperty(exports$1, "regexpCode", { enumerable: true, get: function () { return code_2.regexpCode; } });
		Object.defineProperty(exports$1, "Name", { enumerable: true, get: function () { return code_2.Name; } });
		var scope_2 = requireScope();
		Object.defineProperty(exports$1, "Scope", { enumerable: true, get: function () { return scope_2.Scope; } });
		Object.defineProperty(exports$1, "ValueScope", { enumerable: true, get: function () { return scope_2.ValueScope; } });
		Object.defineProperty(exports$1, "ValueScopeName", { enumerable: true, get: function () { return scope_2.ValueScopeName; } });
		Object.defineProperty(exports$1, "varKinds", { enumerable: true, get: function () { return scope_2.varKinds; } });
		exports$1.operators = {
		    GT: new code_1._Code(">"),
		    GTE: new code_1._Code(">="),
		    LT: new code_1._Code("<"),
		    LTE: new code_1._Code("<="),
		    EQ: new code_1._Code("==="),
		    NEQ: new code_1._Code("!=="),
		    NOT: new code_1._Code("!"),
		    OR: new code_1._Code("||"),
		    AND: new code_1._Code("&&"),
		    ADD: new code_1._Code("+"),
		};
		class Node {
		    optimizeNodes() {
		        return this;
		    }
		    optimizeNames(_names, _constants) {
		        return this;
		    }
		}
		class Def extends Node {
		    constructor(varKind, name, rhs) {
		        super();
		        this.varKind = varKind;
		        this.name = name;
		        this.rhs = rhs;
		    }
		    render({ es5, _n }) {
		        const varKind = es5 ? scope_1.varKinds.var : this.varKind;
		        const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`;
		        return `${varKind} ${this.name}${rhs};` + _n;
		    }
		    optimizeNames(names, constants) {
		        if (!names[this.name.str])
		            return;
		        if (this.rhs)
		            this.rhs = optimizeExpr(this.rhs, names, constants);
		        return this;
		    }
		    get names() {
		        return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
		    }
		}
		class Assign extends Node {
		    constructor(lhs, rhs, sideEffects) {
		        super();
		        this.lhs = lhs;
		        this.rhs = rhs;
		        this.sideEffects = sideEffects;
		    }
		    render({ _n }) {
		        return `${this.lhs} = ${this.rhs};` + _n;
		    }
		    optimizeNames(names, constants) {
		        if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
		            return;
		        this.rhs = optimizeExpr(this.rhs, names, constants);
		        return this;
		    }
		    get names() {
		        const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
		        return addExprNames(names, this.rhs);
		    }
		}
		class AssignOp extends Assign {
		    constructor(lhs, op, rhs, sideEffects) {
		        super(lhs, rhs, sideEffects);
		        this.op = op;
		    }
		    render({ _n }) {
		        return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
		    }
		}
		class Label extends Node {
		    constructor(label) {
		        super();
		        this.label = label;
		        this.names = {};
		    }
		    render({ _n }) {
		        return `${this.label}:` + _n;
		    }
		}
		class Break extends Node {
		    constructor(label) {
		        super();
		        this.label = label;
		        this.names = {};
		    }
		    render({ _n }) {
		        const label = this.label ? ` ${this.label}` : "";
		        return `break${label};` + _n;
		    }
		}
		class Throw extends Node {
		    constructor(error) {
		        super();
		        this.error = error;
		    }
		    render({ _n }) {
		        return `throw ${this.error};` + _n;
		    }
		    get names() {
		        return this.error.names;
		    }
		}
		class AnyCode extends Node {
		    constructor(code) {
		        super();
		        this.code = code;
		    }
		    render({ _n }) {
		        return `${this.code};` + _n;
		    }
		    optimizeNodes() {
		        return `${this.code}` ? this : undefined;
		    }
		    optimizeNames(names, constants) {
		        this.code = optimizeExpr(this.code, names, constants);
		        return this;
		    }
		    get names() {
		        return this.code instanceof code_1._CodeOrName ? this.code.names : {};
		    }
		}
		class ParentNode extends Node {
		    constructor(nodes = []) {
		        super();
		        this.nodes = nodes;
		    }
		    render(opts) {
		        return this.nodes.reduce((code, n) => code + n.render(opts), "");
		    }
		    optimizeNodes() {
		        const { nodes } = this;
		        let i = nodes.length;
		        while (i--) {
		            const n = nodes[i].optimizeNodes();
		            if (Array.isArray(n))
		                nodes.splice(i, 1, ...n);
		            else if (n)
		                nodes[i] = n;
		            else
		                nodes.splice(i, 1);
		        }
		        return nodes.length > 0 ? this : undefined;
		    }
		    optimizeNames(names, constants) {
		        const { nodes } = this;
		        let i = nodes.length;
		        while (i--) {
		            // iterating backwards improves 1-pass optimization
		            const n = nodes[i];
		            if (n.optimizeNames(names, constants))
		                continue;
		            subtractNames(names, n.names);
		            nodes.splice(i, 1);
		        }
		        return nodes.length > 0 ? this : undefined;
		    }
		    get names() {
		        return this.nodes.reduce((names, n) => addNames(names, n.names), {});
		    }
		}
		class BlockNode extends ParentNode {
		    render(opts) {
		        return "{" + opts._n + super.render(opts) + "}" + opts._n;
		    }
		}
		class Root extends ParentNode {
		}
		class Else extends BlockNode {
		}
		Else.kind = "else";
		class If extends BlockNode {
		    constructor(condition, nodes) {
		        super(nodes);
		        this.condition = condition;
		    }
		    render(opts) {
		        let code = `if(${this.condition})` + super.render(opts);
		        if (this.else)
		            code += "else " + this.else.render(opts);
		        return code;
		    }
		    optimizeNodes() {
		        super.optimizeNodes();
		        const cond = this.condition;
		        if (cond === true)
		            return this.nodes; // else is ignored here
		        let e = this.else;
		        if (e) {
		            const ns = e.optimizeNodes();
		            e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
		        }
		        if (e) {
		            if (cond === false)
		                return e instanceof If ? e : e.nodes;
		            if (this.nodes.length)
		                return this;
		            return new If(not(cond), e instanceof If ? [e] : e.nodes);
		        }
		        if (cond === false || !this.nodes.length)
		            return undefined;
		        return this;
		    }
		    optimizeNames(names, constants) {
		        var _a;
		        this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
		        if (!(super.optimizeNames(names, constants) || this.else))
		            return;
		        this.condition = optimizeExpr(this.condition, names, constants);
		        return this;
		    }
		    get names() {
		        const names = super.names;
		        addExprNames(names, this.condition);
		        if (this.else)
		            addNames(names, this.else.names);
		        return names;
		    }
		}
		If.kind = "if";
		class For extends BlockNode {
		}
		For.kind = "for";
		class ForLoop extends For {
		    constructor(iteration) {
		        super();
		        this.iteration = iteration;
		    }
		    render(opts) {
		        return `for(${this.iteration})` + super.render(opts);
		    }
		    optimizeNames(names, constants) {
		        if (!super.optimizeNames(names, constants))
		            return;
		        this.iteration = optimizeExpr(this.iteration, names, constants);
		        return this;
		    }
		    get names() {
		        return addNames(super.names, this.iteration.names);
		    }
		}
		class ForRange extends For {
		    constructor(varKind, name, from, to) {
		        super();
		        this.varKind = varKind;
		        this.name = name;
		        this.from = from;
		        this.to = to;
		    }
		    render(opts) {
		        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
		        const { name, from, to } = this;
		        return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
		    }
		    get names() {
		        const names = addExprNames(super.names, this.from);
		        return addExprNames(names, this.to);
		    }
		}
		class ForIter extends For {
		    constructor(loop, varKind, name, iterable) {
		        super();
		        this.loop = loop;
		        this.varKind = varKind;
		        this.name = name;
		        this.iterable = iterable;
		    }
		    render(opts) {
		        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
		    }
		    optimizeNames(names, constants) {
		        if (!super.optimizeNames(names, constants))
		            return;
		        this.iterable = optimizeExpr(this.iterable, names, constants);
		        return this;
		    }
		    get names() {
		        return addNames(super.names, this.iterable.names);
		    }
		}
		class Func extends BlockNode {
		    constructor(name, args, async) {
		        super();
		        this.name = name;
		        this.args = args;
		        this.async = async;
		    }
		    render(opts) {
		        const _async = this.async ? "async " : "";
		        return `${_async}function ${this.name}(${this.args})` + super.render(opts);
		    }
		}
		Func.kind = "func";
		class Return extends ParentNode {
		    render(opts) {
		        return "return " + super.render(opts);
		    }
		}
		Return.kind = "return";
		class Try extends BlockNode {
		    render(opts) {
		        let code = "try" + super.render(opts);
		        if (this.catch)
		            code += this.catch.render(opts);
		        if (this.finally)
		            code += this.finally.render(opts);
		        return code;
		    }
		    optimizeNodes() {
		        var _a, _b;
		        super.optimizeNodes();
		        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();
		        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
		        return this;
		    }
		    optimizeNames(names, constants) {
		        var _a, _b;
		        super.optimizeNames(names, constants);
		        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
		        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
		        return this;
		    }
		    get names() {
		        const names = super.names;
		        if (this.catch)
		            addNames(names, this.catch.names);
		        if (this.finally)
		            addNames(names, this.finally.names);
		        return names;
		    }
		}
		class Catch extends BlockNode {
		    constructor(error) {
		        super();
		        this.error = error;
		    }
		    render(opts) {
		        return `catch(${this.error})` + super.render(opts);
		    }
		}
		Catch.kind = "catch";
		class Finally extends BlockNode {
		    render(opts) {
		        return "finally" + super.render(opts);
		    }
		}
		Finally.kind = "finally";
		class CodeGen {
		    constructor(extScope, opts = {}) {
		        this._values = {};
		        this._blockStarts = [];
		        this._constants = {};
		        this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
		        this._extScope = extScope;
		        this._scope = new scope_1.Scope({ parent: extScope });
		        this._nodes = [new Root()];
		    }
		    toString() {
		        return this._root.render(this.opts);
		    }
		    // returns unique name in the internal scope
		    name(prefix) {
		        return this._scope.name(prefix);
		    }
		    // reserves unique name in the external scope
		    scopeName(prefix) {
		        return this._extScope.name(prefix);
		    }
		    // reserves unique name in the external scope and assigns value to it
		    scopeValue(prefixOrName, value) {
		        const name = this._extScope.value(prefixOrName, value);
		        const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set());
		        vs.add(name);
		        return name;
		    }
		    getScopeValue(prefix, keyOrRef) {
		        return this._extScope.getValue(prefix, keyOrRef);
		    }
		    // return code that assigns values in the external scope to the names that are used internally
		    // (same names that were returned by gen.scopeName or gen.scopeValue)
		    scopeRefs(scopeName) {
		        return this._extScope.scopeRefs(scopeName, this._values);
		    }
		    scopeCode() {
		        return this._extScope.scopeCode(this._values);
		    }
		    _def(varKind, nameOrPrefix, rhs, constant) {
		        const name = this._scope.toName(nameOrPrefix);
		        if (rhs !== undefined && constant)
		            this._constants[name.str] = rhs;
		        this._leafNode(new Def(varKind, name, rhs));
		        return name;
		    }
		    // `const` declaration (`var` in es5 mode)
		    const(nameOrPrefix, rhs, _constant) {
		        return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
		    }
		    // `let` declaration with optional assignment (`var` in es5 mode)
		    let(nameOrPrefix, rhs, _constant) {
		        return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
		    }
		    // `var` declaration with optional assignment
		    var(nameOrPrefix, rhs, _constant) {
		        return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
		    }
		    // assignment code
		    assign(lhs, rhs, sideEffects) {
		        return this._leafNode(new Assign(lhs, rhs, sideEffects));
		    }
		    // `+=` code
		    add(lhs, rhs) {
		        return this._leafNode(new AssignOp(lhs, exports$1.operators.ADD, rhs));
		    }
		    // appends passed SafeExpr to code or executes Block
		    code(c) {
		        if (typeof c == "function")
		            c();
		        else if (c !== code_1.nil)
		            this._leafNode(new AnyCode(c));
		        return this;
		    }
		    // returns code for object literal for the passed argument list of key-value pairs
		    object(...keyValues) {
		        const code = ["{"];
		        for (const [key, value] of keyValues) {
		            if (code.length > 1)
		                code.push(",");
		            code.push(key);
		            if (key !== value || this.opts.es5) {
		                code.push(":");
		                (0, code_1.addCodeArg)(code, value);
		            }
		        }
		        code.push("}");
		        return new code_1._Code(code);
		    }
		    // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
		    if(condition, thenBody, elseBody) {
		        this._blockNode(new If(condition));
		        if (thenBody && elseBody) {
		            this.code(thenBody).else().code(elseBody).endIf();
		        }
		        else if (thenBody) {
		            this.code(thenBody).endIf();
		        }
		        else if (elseBody) {
		            throw new Error('CodeGen: "else" body without "then" body');
		        }
		        return this;
		    }
		    // `else if` clause - invalid without `if` or after `else` clauses
		    elseIf(condition) {
		        return this._elseNode(new If(condition));
		    }
		    // `else` clause - only valid after `if` or `else if` clauses
		    else() {
		        return this._elseNode(new Else());
		    }
		    // end `if` statement (needed if gen.if was used only with condition)
		    endIf() {
		        return this._endBlockNode(If, Else);
		    }
		    _for(node, forBody) {
		        this._blockNode(node);
		        if (forBody)
		            this.code(forBody).endFor();
		        return this;
		    }
		    // a generic `for` clause (or statement if `forBody` is passed)
		    for(iteration, forBody) {
		        return this._for(new ForLoop(iteration), forBody);
		    }
		    // `for` statement for a range of values
		    forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
		        const name = this._scope.toName(nameOrPrefix);
		        return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
		    }
		    // `for-of` statement (in es5 mode replace with a normal for loop)
		    forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
		        const name = this._scope.toName(nameOrPrefix);
		        if (this.opts.es5) {
		            const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
		            return this.forRange("_i", 0, (0, code_1._) `${arr}.length`, (i) => {
		                this.var(name, (0, code_1._) `${arr}[${i}]`);
		                forBody(name);
		            });
		        }
		        return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
		    }
		    // `for-in` statement.
		    // With option `ownProperties` replaced with a `for-of` loop for object keys
		    forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
		        if (this.opts.ownProperties) {
		            return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody);
		        }
		        const name = this._scope.toName(nameOrPrefix);
		        return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
		    }
		    // end `for` loop
		    endFor() {
		        return this._endBlockNode(For);
		    }
		    // `label` statement
		    label(label) {
		        return this._leafNode(new Label(label));
		    }
		    // `break` statement
		    break(label) {
		        return this._leafNode(new Break(label));
		    }
		    // `return` statement
		    return(value) {
		        const node = new Return();
		        this._blockNode(node);
		        this.code(value);
		        if (node.nodes.length !== 1)
		            throw new Error('CodeGen: "return" should have one node');
		        return this._endBlockNode(Return);
		    }
		    // `try` statement
		    try(tryBody, catchCode, finallyCode) {
		        if (!catchCode && !finallyCode)
		            throw new Error('CodeGen: "try" without "catch" and "finally"');
		        const node = new Try();
		        this._blockNode(node);
		        this.code(tryBody);
		        if (catchCode) {
		            const error = this.name("e");
		            this._currNode = node.catch = new Catch(error);
		            catchCode(error);
		        }
		        if (finallyCode) {
		            this._currNode = node.finally = new Finally();
		            this.code(finallyCode);
		        }
		        return this._endBlockNode(Catch, Finally);
		    }
		    // `throw` statement
		    throw(error) {
		        return this._leafNode(new Throw(error));
		    }
		    // start self-balancing block
		    block(body, nodeCount) {
		        this._blockStarts.push(this._nodes.length);
		        if (body)
		            this.code(body).endBlock(nodeCount);
		        return this;
		    }
		    // end the current self-balancing block
		    endBlock(nodeCount) {
		        const len = this._blockStarts.pop();
		        if (len === undefined)
		            throw new Error("CodeGen: not in self-balancing block");
		        const toClose = this._nodes.length - len;
		        if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
		            throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
		        }
		        this._nodes.length = len;
		        return this;
		    }
		    // `function` heading (or definition if funcBody is passed)
		    func(name, args = code_1.nil, async, funcBody) {
		        this._blockNode(new Func(name, args, async));
		        if (funcBody)
		            this.code(funcBody).endFunc();
		        return this;
		    }
		    // end function definition
		    endFunc() {
		        return this._endBlockNode(Func);
		    }
		    optimize(n = 1) {
		        while (n-- > 0) {
		            this._root.optimizeNodes();
		            this._root.optimizeNames(this._root.names, this._constants);
		        }
		    }
		    _leafNode(node) {
		        this._currNode.nodes.push(node);
		        return this;
		    }
		    _blockNode(node) {
		        this._currNode.nodes.push(node);
		        this._nodes.push(node);
		    }
		    _endBlockNode(N1, N2) {
		        const n = this._currNode;
		        if (n instanceof N1 || (N2 && n instanceof N2)) {
		            this._nodes.pop();
		            return this;
		        }
		        throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
		    }
		    _elseNode(node) {
		        const n = this._currNode;
		        if (!(n instanceof If)) {
		            throw new Error('CodeGen: "else" without "if"');
		        }
		        this._currNode = n.else = node;
		        return this;
		    }
		    get _root() {
		        return this._nodes[0];
		    }
		    get _currNode() {
		        const ns = this._nodes;
		        return ns[ns.length - 1];
		    }
		    set _currNode(node) {
		        const ns = this._nodes;
		        ns[ns.length - 1] = node;
		    }
		}
		exports$1.CodeGen = CodeGen;
		function addNames(names, from) {
		    for (const n in from)
		        names[n] = (names[n] || 0) + (from[n] || 0);
		    return names;
		}
		function addExprNames(names, from) {
		    return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
		}
		function optimizeExpr(expr, names, constants) {
		    if (expr instanceof code_1.Name)
		        return replaceName(expr);
		    if (!canOptimize(expr))
		        return expr;
		    return new code_1._Code(expr._items.reduce((items, c) => {
		        if (c instanceof code_1.Name)
		            c = replaceName(c);
		        if (c instanceof code_1._Code)
		            items.push(...c._items);
		        else
		            items.push(c);
		        return items;
		    }, []));
		    function replaceName(n) {
		        const c = constants[n.str];
		        if (c === undefined || names[n.str] !== 1)
		            return n;
		        delete names[n.str];
		        return c;
		    }
		    function canOptimize(e) {
		        return (e instanceof code_1._Code &&
		            e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined));
		    }
		}
		function subtractNames(names, from) {
		    for (const n in from)
		        names[n] = (names[n] || 0) - (from[n] || 0);
		}
		function not(x) {
		    return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._) `!${par(x)}`;
		}
		exports$1.not = not;
		const andCode = mappend(exports$1.operators.AND);
		// boolean AND (&&) expression with the passed arguments
		function and(...args) {
		    return args.reduce(andCode);
		}
		exports$1.and = and;
		const orCode = mappend(exports$1.operators.OR);
		// boolean OR (||) expression with the passed arguments
		function or(...args) {
		    return args.reduce(orCode);
		}
		exports$1.or = or;
		function mappend(op) {
		    return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`);
		}
		function par(x) {
		    return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`;
		}
		
	} (codegen));
	return codegen;
}

var util$1 = {};

var hasRequiredUtil$1;

function requireUtil$1 () {
	if (hasRequiredUtil$1) return util$1;
	hasRequiredUtil$1 = 1;
	Object.defineProperty(util$1, "__esModule", { value: true });
	util$1.checkStrictMode = util$1.getErrorPath = util$1.Type = util$1.useFunc = util$1.setEvaluated = util$1.evaluatedPropsToName = util$1.mergeEvaluated = util$1.eachItem = util$1.unescapeJsonPointer = util$1.escapeJsonPointer = util$1.escapeFragment = util$1.unescapeFragment = util$1.schemaRefOrVal = util$1.schemaHasRulesButRef = util$1.schemaHasRules = util$1.checkUnknownRules = util$1.alwaysValidSchema = util$1.toHash = void 0;
	const codegen_1 = requireCodegen();
	const code_1 = requireCode$1();
	// TODO refactor to use Set
	function toHash(arr) {
	    const hash = {};
	    for (const item of arr)
	        hash[item] = true;
	    return hash;
	}
	util$1.toHash = toHash;
	function alwaysValidSchema(it, schema) {
	    if (typeof schema == "boolean")
	        return schema;
	    if (Object.keys(schema).length === 0)
	        return true;
	    checkUnknownRules(it, schema);
	    return !schemaHasRules(schema, it.self.RULES.all);
	}
	util$1.alwaysValidSchema = alwaysValidSchema;
	function checkUnknownRules(it, schema = it.schema) {
	    const { opts, self } = it;
	    if (!opts.strictSchema)
	        return;
	    if (typeof schema === "boolean")
	        return;
	    const rules = self.RULES.keywords;
	    for (const key in schema) {
	        if (!rules[key])
	            checkStrictMode(it, `unknown keyword: "${key}"`);
	    }
	}
	util$1.checkUnknownRules = checkUnknownRules;
	function schemaHasRules(schema, rules) {
	    if (typeof schema == "boolean")
	        return !schema;
	    for (const key in schema)
	        if (rules[key])
	            return true;
	    return false;
	}
	util$1.schemaHasRules = schemaHasRules;
	function schemaHasRulesButRef(schema, RULES) {
	    if (typeof schema == "boolean")
	        return !schema;
	    for (const key in schema)
	        if (key !== "$ref" && RULES.all[key])
	            return true;
	    return false;
	}
	util$1.schemaHasRulesButRef = schemaHasRulesButRef;
	function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {
	    if (!$data) {
	        if (typeof schema == "number" || typeof schema == "boolean")
	            return schema;
	        if (typeof schema == "string")
	            return (0, codegen_1._) `${schema}`;
	    }
	    return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;
	}
	util$1.schemaRefOrVal = schemaRefOrVal;
	function unescapeFragment(str) {
	    return unescapeJsonPointer(decodeURIComponent(str));
	}
	util$1.unescapeFragment = unescapeFragment;
	function escapeFragment(str) {
	    return encodeURIComponent(escapeJsonPointer(str));
	}
	util$1.escapeFragment = escapeFragment;
	function escapeJsonPointer(str) {
	    if (typeof str == "number")
	        return `${str}`;
	    return str.replace(/~/g, "~0").replace(/\//g, "~1");
	}
	util$1.escapeJsonPointer = escapeJsonPointer;
	function unescapeJsonPointer(str) {
	    return str.replace(/~1/g, "/").replace(/~0/g, "~");
	}
	util$1.unescapeJsonPointer = unescapeJsonPointer;
	function eachItem(xs, f) {
	    if (Array.isArray(xs)) {
	        for (const x of xs)
	            f(x);
	    }
	    else {
	        f(xs);
	    }
	}
	util$1.eachItem = eachItem;
	function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) {
	    return (gen, from, to, toName) => {
	        const res = to === undefined
	            ? from
	            : to instanceof codegen_1.Name
	                ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)
	                : from instanceof codegen_1.Name
	                    ? (mergeToName(gen, to, from), from)
	                    : mergeValues(from, to);
	        return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
	    };
	}
	util$1.mergeEvaluated = {
	    props: makeMergeEvaluated({
	        mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => {
	            gen.if((0, codegen_1._) `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._) `${to} || {}`).code((0, codegen_1._) `Object.assign(${to}, ${from})`));
	        }),
	        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => {
	            if (from === true) {
	                gen.assign(to, true);
	            }
	            else {
	                gen.assign(to, (0, codegen_1._) `${to} || {}`);
	                setEvaluated(gen, to, from);
	            }
	        }),
	        mergeValues: (from, to) => (from === true ? true : { ...from, ...to }),
	        resultToName: evaluatedPropsToName,
	    }),
	    items: makeMergeEvaluated({
	        mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._) `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
	        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)),
	        mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),
	        resultToName: (gen, items) => gen.var("items", items),
	    }),
	};
	function evaluatedPropsToName(gen, ps) {
	    if (ps === true)
	        return gen.var("props", true);
	    const props = gen.var("props", (0, codegen_1._) `{}`);
	    if (ps !== undefined)
	        setEvaluated(gen, props, ps);
	    return props;
	}
	util$1.evaluatedPropsToName = evaluatedPropsToName;
	function setEvaluated(gen, props, ps) {
	    Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true));
	}
	util$1.setEvaluated = setEvaluated;
	const snippets = {};
	function useFunc(gen, f) {
	    return gen.scopeValue("func", {
	        ref: f,
	        code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)),
	    });
	}
	util$1.useFunc = useFunc;
	var Type;
	(function (Type) {
	    Type[Type["Num"] = 0] = "Num";
	    Type[Type["Str"] = 1] = "Str";
	})(Type || (util$1.Type = Type = {}));
	function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
	    // let path
	    if (dataProp instanceof codegen_1.Name) {
	        const isNumber = dataPropType === Type.Num;
	        return jsPropertySyntax
	            ? isNumber
	                ? (0, codegen_1._) `"[" + ${dataProp} + "]"`
	                : (0, codegen_1._) `"['" + ${dataProp} + "']"`
	            : isNumber
	                ? (0, codegen_1._) `"/" + ${dataProp}`
	                : (0, codegen_1._) `"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; // TODO maybe use global escapePointer
	    }
	    return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
	}
	util$1.getErrorPath = getErrorPath;
	function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
	    if (!mode)
	        return;
	    msg = `strict mode: ${msg}`;
	    if (mode === true)
	        throw new Error(msg);
	    it.self.logger.warn(msg);
	}
	util$1.checkStrictMode = checkStrictMode;
	
	return util$1;
}

var names$1 = {};

var hasRequiredNames;

function requireNames () {
	if (hasRequiredNames) return names$1;
	hasRequiredNames = 1;
	Object.defineProperty(names$1, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const names = {
	    // validation function arguments
	    data: new codegen_1.Name("data"), // data passed to validation function
	    // args passed from referencing schema
	    valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below
	    instancePath: new codegen_1.Name("instancePath"),
	    parentData: new codegen_1.Name("parentData"),
	    parentDataProperty: new codegen_1.Name("parentDataProperty"),
	    rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function
	    dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef
	    // function scoped variables
	    vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors
	    errors: new codegen_1.Name("errors"), // counter of validation errors
	    this: new codegen_1.Name("this"),
	    // "globals"
	    self: new codegen_1.Name("self"),
	    scope: new codegen_1.Name("scope"),
	    // JTD serialize/parse name for JSON string and position
	    json: new codegen_1.Name("json"),
	    jsonPos: new codegen_1.Name("jsonPos"),
	    jsonLen: new codegen_1.Name("jsonLen"),
	    jsonPart: new codegen_1.Name("jsonPart"),
	};
	names$1.default = names;
	
	return names$1;
}

var hasRequiredErrors;

function requireErrors () {
	if (hasRequiredErrors) return errors;
	hasRequiredErrors = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.extendErrors = exports$1.resetErrorsCount = exports$1.reportExtraError = exports$1.reportError = exports$1.keyword$DataError = exports$1.keywordError = void 0;
		const codegen_1 = requireCodegen();
		const util_1 = requireUtil$1();
		const names_1 = requireNames();
		exports$1.keywordError = {
		    message: ({ keyword }) => (0, codegen_1.str) `must pass "${keyword}" keyword validation`,
		};
		exports$1.keyword$DataError = {
		    message: ({ keyword, schemaType }) => schemaType
		        ? (0, codegen_1.str) `"${keyword}" keyword must be ${schemaType} ($data)`
		        : (0, codegen_1.str) `"${keyword}" keyword is invalid ($data)`,
		};
		function reportError(cxt, error = exports$1.keywordError, errorPaths, overrideAllErrors) {
		    const { it } = cxt;
		    const { gen, compositeRule, allErrors } = it;
		    const errObj = errorObjectCode(cxt, error, errorPaths);
		    if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) {
		        addError(gen, errObj);
		    }
		    else {
		        returnErrors(it, (0, codegen_1._) `[${errObj}]`);
		    }
		}
		exports$1.reportError = reportError;
		function reportExtraError(cxt, error = exports$1.keywordError, errorPaths) {
		    const { it } = cxt;
		    const { gen, compositeRule, allErrors } = it;
		    const errObj = errorObjectCode(cxt, error, errorPaths);
		    addError(gen, errObj);
		    if (!(compositeRule || allErrors)) {
		        returnErrors(it, names_1.default.vErrors);
		    }
		}
		exports$1.reportExtraError = reportExtraError;
		function resetErrorsCount(gen, errsCount) {
		    gen.assign(names_1.default.errors, errsCount);
		    gen.if((0, codegen_1._) `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._) `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
		}
		exports$1.resetErrorsCount = resetErrorsCount;
		function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) {
		    /* istanbul ignore if */
		    if (errsCount === undefined)
		        throw new Error("ajv implementation error");
		    const err = gen.name("err");
		    gen.forRange("i", errsCount, names_1.default.errors, (i) => {
		        gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`);
		        gen.if((0, codegen_1._) `${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._) `${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
		        gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`);
		        if (it.opts.verbose) {
		            gen.assign((0, codegen_1._) `${err}.schema`, schemaValue);
		            gen.assign((0, codegen_1._) `${err}.data`, data);
		        }
		    });
		}
		exports$1.extendErrors = extendErrors;
		function addError(gen, errObj) {
		    const err = gen.const("err", errObj);
		    gen.if((0, codegen_1._) `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._) `[${err}]`), (0, codegen_1._) `${names_1.default.vErrors}.push(${err})`);
		    gen.code((0, codegen_1._) `${names_1.default.errors}++`);
		}
		function returnErrors(it, errs) {
		    const { gen, validateName, schemaEnv } = it;
		    if (schemaEnv.$async) {
		        gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`);
		    }
		    else {
		        gen.assign((0, codegen_1._) `${validateName}.errors`, errs);
		        gen.return(false);
		    }
		}
		const E = {
		    keyword: new codegen_1.Name("keyword"),
		    schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors
		    params: new codegen_1.Name("params"),
		    propertyName: new codegen_1.Name("propertyName"),
		    message: new codegen_1.Name("message"),
		    schema: new codegen_1.Name("schema"),
		    parentSchema: new codegen_1.Name("parentSchema"),
		};
		function errorObjectCode(cxt, error, errorPaths) {
		    const { createErrors } = cxt.it;
		    if (createErrors === false)
		        return (0, codegen_1._) `{}`;
		    return errorObject(cxt, error, errorPaths);
		}
		function errorObject(cxt, error, errorPaths = {}) {
		    const { gen, it } = cxt;
		    const keyValues = [
		        errorInstancePath(it, errorPaths),
		        errorSchemaPath(cxt, errorPaths),
		    ];
		    extraErrorProps(cxt, error, keyValues);
		    return gen.object(...keyValues);
		}
		function errorInstancePath({ errorPath }, { instancePath }) {
		    const instPath = instancePath
		        ? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}`
		        : errorPath;
		    return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
		}
		function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
		    let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`;
		    if (schemaPath) {
		        schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
		    }
		    return [E.schemaPath, schPath];
		}
		function extraErrorProps(cxt, { params, message }, keyValues) {
		    const { keyword, data, schemaValue, it } = cxt;
		    const { opts, propertyName, topSchemaRef, schemaPath } = it;
		    keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._) `{}`]);
		    if (opts.messages) {
		        keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
		    }
		    if (opts.verbose) {
		        keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
		    }
		    if (propertyName)
		        keyValues.push([E.propertyName, propertyName]);
		}
		
	} (errors));
	return errors;
}

var hasRequiredBoolSchema;

function requireBoolSchema () {
	if (hasRequiredBoolSchema) return boolSchema;
	hasRequiredBoolSchema = 1;
	Object.defineProperty(boolSchema, "__esModule", { value: true });
	boolSchema.boolOrEmptySchema = boolSchema.topBoolOrEmptySchema = void 0;
	const errors_1 = requireErrors();
	const codegen_1 = requireCodegen();
	const names_1 = requireNames();
	const boolError = {
	    message: "boolean schema is false",
	};
	function topBoolOrEmptySchema(it) {
	    const { gen, schema, validateName } = it;
	    if (schema === false) {
	        falseSchemaError(it, false);
	    }
	    else if (typeof schema == "object" && schema.$async === true) {
	        gen.return(names_1.default.data);
	    }
	    else {
	        gen.assign((0, codegen_1._) `${validateName}.errors`, null);
	        gen.return(true);
	    }
	}
	boolSchema.topBoolOrEmptySchema = topBoolOrEmptySchema;
	function boolOrEmptySchema(it, valid) {
	    const { gen, schema } = it;
	    if (schema === false) {
	        gen.var(valid, false); // TODO var
	        falseSchemaError(it);
	    }
	    else {
	        gen.var(valid, true); // TODO var
	    }
	}
	boolSchema.boolOrEmptySchema = boolOrEmptySchema;
	function falseSchemaError(it, overrideAllErrors) {
	    const { gen, data } = it;
	    // TODO maybe some other interface should be used for non-keyword validation errors...
	    const cxt = {
	        gen,
	        keyword: "false schema",
	        data,
	        schema: false,
	        schemaCode: false,
	        schemaValue: false,
	        params: {},
	        it,
	    };
	    (0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors);
	}
	
	return boolSchema;
}

var dataType = {};

var rules = {};

var hasRequiredRules;

function requireRules () {
	if (hasRequiredRules) return rules;
	hasRequiredRules = 1;
	Object.defineProperty(rules, "__esModule", { value: true });
	rules.getRules = rules.isJSONType = void 0;
	const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
	const jsonTypes = new Set(_jsonTypes);
	function isJSONType(x) {
	    return typeof x == "string" && jsonTypes.has(x);
	}
	rules.isJSONType = isJSONType;
	function getRules() {
	    const groups = {
	        number: { type: "number", rules: [] },
	        string: { type: "string", rules: [] },
	        array: { type: "array", rules: [] },
	        object: { type: "object", rules: [] },
	    };
	    return {
	        types: { ...groups, integer: true, boolean: true, null: true },
	        rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
	        post: { rules: [] },
	        all: {},
	        keywords: {},
	    };
	}
	rules.getRules = getRules;
	
	return rules;
}

var applicability = {};

var hasRequiredApplicability;

function requireApplicability () {
	if (hasRequiredApplicability) return applicability;
	hasRequiredApplicability = 1;
	Object.defineProperty(applicability, "__esModule", { value: true });
	applicability.shouldUseRule = applicability.shouldUseGroup = applicability.schemaHasRulesForType = void 0;
	function schemaHasRulesForType({ schema, self }, type) {
	    const group = self.RULES.types[type];
	    return group && group !== true && shouldUseGroup(schema, group);
	}
	applicability.schemaHasRulesForType = schemaHasRulesForType;
	function shouldUseGroup(schema, group) {
	    return group.rules.some((rule) => shouldUseRule(schema, rule));
	}
	applicability.shouldUseGroup = shouldUseGroup;
	function shouldUseRule(schema, rule) {
	    var _a;
	    return (schema[rule.keyword] !== undefined ||
	        ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined)));
	}
	applicability.shouldUseRule = shouldUseRule;
	
	return applicability;
}

var hasRequiredDataType;

function requireDataType () {
	if (hasRequiredDataType) return dataType;
	hasRequiredDataType = 1;
	Object.defineProperty(dataType, "__esModule", { value: true });
	dataType.reportTypeError = dataType.checkDataTypes = dataType.checkDataType = dataType.coerceAndCheckDataType = dataType.getJSONTypes = dataType.getSchemaTypes = dataType.DataType = void 0;
	const rules_1 = requireRules();
	const applicability_1 = requireApplicability();
	const errors_1 = requireErrors();
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$1();
	var DataType;
	(function (DataType) {
	    DataType[DataType["Correct"] = 0] = "Correct";
	    DataType[DataType["Wrong"] = 1] = "Wrong";
	})(DataType || (dataType.DataType = DataType = {}));
	function getSchemaTypes(schema) {
	    const types = getJSONTypes(schema.type);
	    const hasNull = types.includes("null");
	    if (hasNull) {
	        if (schema.nullable === false)
	            throw new Error("type: null contradicts nullable: false");
	    }
	    else {
	        if (!types.length && schema.nullable !== undefined) {
	            throw new Error('"nullable" cannot be used without "type"');
	        }
	        if (schema.nullable === true)
	            types.push("null");
	    }
	    return types;
	}
	dataType.getSchemaTypes = getSchemaTypes;
	// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
	function getJSONTypes(ts) {
	    const types = Array.isArray(ts) ? ts : ts ? [ts] : [];
	    if (types.every(rules_1.isJSONType))
	        return types;
	    throw new Error("type must be JSONType or JSONType[]: " + types.join(","));
	}
	dataType.getJSONTypes = getJSONTypes;
	function coerceAndCheckDataType(it, types) {
	    const { gen, data, opts } = it;
	    const coerceTo = coerceToTypes(types, opts.coerceTypes);
	    const checkTypes = types.length > 0 &&
	        !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));
	    if (checkTypes) {
	        const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);
	        gen.if(wrongType, () => {
	            if (coerceTo.length)
	                coerceData(it, types, coerceTo);
	            else
	                reportTypeError(it);
	        });
	    }
	    return checkTypes;
	}
	dataType.coerceAndCheckDataType = coerceAndCheckDataType;
	const COERCIBLE = new Set(["string", "number", "integer", "boolean", "null"]);
	function coerceToTypes(types, coerceTypes) {
	    return coerceTypes
	        ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array"))
	        : [];
	}
	function coerceData(it, types, coerceTo) {
	    const { gen, data, opts } = it;
	    const dataType = gen.let("dataType", (0, codegen_1._) `typeof ${data}`);
	    const coerced = gen.let("coerced", (0, codegen_1._) `undefined`);
	    if (opts.coerceTypes === "array") {
	        gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen
	            .assign(data, (0, codegen_1._) `${data}[0]`)
	            .assign(dataType, (0, codegen_1._) `typeof ${data}`)
	            .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));
	    }
	    gen.if((0, codegen_1._) `${coerced} !== undefined`);
	    for (const t of coerceTo) {
	        if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) {
	            coerceSpecificType(t);
	        }
	    }
	    gen.else();
	    reportTypeError(it);
	    gen.endIf();
	    gen.if((0, codegen_1._) `${coerced} !== undefined`, () => {
	        gen.assign(data, coerced);
	        assignParentData(it, coerced);
	    });
	    function coerceSpecificType(t) {
	        switch (t) {
	            case "string":
	                gen
	                    .elseIf((0, codegen_1._) `${dataType} == "number" || ${dataType} == "boolean"`)
	                    .assign(coerced, (0, codegen_1._) `"" + ${data}`)
	                    .elseIf((0, codegen_1._) `${data} === null`)
	                    .assign(coerced, (0, codegen_1._) `""`);
	                return;
	            case "number":
	                gen
	                    .elseIf((0, codegen_1._) `${dataType} == "boolean" || ${data} === null
              || (${dataType} == "string" && ${data} && ${data} == +${data})`)
	                    .assign(coerced, (0, codegen_1._) `+${data}`);
	                return;
	            case "integer":
	                gen
	                    .elseIf((0, codegen_1._) `${dataType} === "boolean" || ${data} === null
              || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`)
	                    .assign(coerced, (0, codegen_1._) `+${data}`);
	                return;
	            case "boolean":
	                gen
	                    .elseIf((0, codegen_1._) `${data} === "false" || ${data} === 0 || ${data} === null`)
	                    .assign(coerced, false)
	                    .elseIf((0, codegen_1._) `${data} === "true" || ${data} === 1`)
	                    .assign(coerced, true);
	                return;
	            case "null":
	                gen.elseIf((0, codegen_1._) `${data} === "" || ${data} === 0 || ${data} === false`);
	                gen.assign(coerced, null);
	                return;
	            case "array":
	                gen
	                    .elseIf((0, codegen_1._) `${dataType} === "string" || ${dataType} === "number"
              || ${dataType} === "boolean" || ${data} === null`)
	                    .assign(coerced, (0, codegen_1._) `[${data}]`);
	        }
	    }
	}
	function assignParentData({ gen, parentData, parentDataProperty }, expr) {
	    // TODO use gen.property
	    gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr));
	}
	function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
	    const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
	    let cond;
	    switch (dataType) {
	        case "null":
	            return (0, codegen_1._) `${data} ${EQ} null`;
	        case "array":
	            cond = (0, codegen_1._) `Array.isArray(${data})`;
	            break;
	        case "object":
	            cond = (0, codegen_1._) `${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
	            break;
	        case "integer":
	            cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`);
	            break;
	        case "number":
	            cond = numCond();
	            break;
	        default:
	            return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`;
	    }
	    return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
	    function numCond(_cond = codegen_1.nil) {
	        return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil);
	    }
	}
	dataType.checkDataType = checkDataType;
	function checkDataTypes(dataTypes, data, strictNums, correct) {
	    if (dataTypes.length === 1) {
	        return checkDataType(dataTypes[0], data, strictNums, correct);
	    }
	    let cond;
	    const types = (0, util_1.toHash)(dataTypes);
	    if (types.array && types.object) {
	        const notObj = (0, codegen_1._) `typeof ${data} != "object"`;
	        cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`;
	        delete types.null;
	        delete types.array;
	        delete types.object;
	    }
	    else {
	        cond = codegen_1.nil;
	    }
	    if (types.number)
	        delete types.integer;
	    for (const t in types)
	        cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));
	    return cond;
	}
	dataType.checkDataTypes = checkDataTypes;
	const typeError = {
	    message: ({ schema }) => `must be ${schema}`,
	    params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`,
	};
	function reportTypeError(it) {
	    const cxt = getTypeErrorContext(it);
	    (0, errors_1.reportError)(cxt, typeError);
	}
	dataType.reportTypeError = reportTypeError;
	function getTypeErrorContext(it) {
	    const { gen, data, schema } = it;
	    const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
	    return {
	        gen,
	        keyword: "type",
	        data,
	        schema: schema.type,
	        schemaCode,
	        schemaValue: schemaCode,
	        parentSchema: schema,
	        params: {},
	        it,
	    };
	}
	
	return dataType;
}

var defaults = {};

var hasRequiredDefaults;

function requireDefaults () {
	if (hasRequiredDefaults) return defaults;
	hasRequiredDefaults = 1;
	Object.defineProperty(defaults, "__esModule", { value: true });
	defaults.assignDefaults = void 0;
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$1();
	function assignDefaults(it, ty) {
	    const { properties, items } = it.schema;
	    if (ty === "object" && properties) {
	        for (const key in properties) {
	            assignDefault(it, key, properties[key].default);
	        }
	    }
	    else if (ty === "array" && Array.isArray(items)) {
	        items.forEach((sch, i) => assignDefault(it, i, sch.default));
	    }
	}
	defaults.assignDefaults = assignDefaults;
	function assignDefault(it, prop, defaultValue) {
	    const { gen, compositeRule, data, opts } = it;
	    if (defaultValue === undefined)
	        return;
	    const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`;
	    if (compositeRule) {
	        (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);
	        return;
	    }
	    let condition = (0, codegen_1._) `${childData} === undefined`;
	    if (opts.useDefaults === "empty") {
	        condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === ""`;
	    }
	    // `${childData} === undefined` +
	    // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "")
	    gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
	}
	
	return defaults;
}

var keyword = {};

var code = {};

var hasRequiredCode;

function requireCode () {
	if (hasRequiredCode) return code;
	hasRequiredCode = 1;
	Object.defineProperty(code, "__esModule", { value: true });
	code.validateUnion = code.validateArray = code.usePattern = code.callValidateCode = code.schemaProperties = code.allSchemaProperties = code.noPropertyInData = code.propertyInData = code.isOwnProperty = code.hasPropFunc = code.reportMissingProp = code.checkMissingProp = code.checkReportMissingProp = void 0;
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$1();
	const names_1 = requireNames();
	const util_2 = requireUtil$1();
	function checkReportMissingProp(cxt, prop) {
	    const { gen, data, it } = cxt;
	    gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
	        cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true);
	        cxt.error();
	    });
	}
	code.checkReportMissingProp = checkReportMissingProp;
	function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
	    return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`)));
	}
	code.checkMissingProp = checkMissingProp;
	function reportMissingProp(cxt, missing) {
	    cxt.setParams({ missingProperty: missing }, true);
	    cxt.error();
	}
	code.reportMissingProp = reportMissingProp;
	function hasPropFunc(gen) {
	    return gen.scopeValue("func", {
	        // eslint-disable-next-line @typescript-eslint/unbound-method
	        ref: Object.prototype.hasOwnProperty,
	        code: (0, codegen_1._) `Object.prototype.hasOwnProperty`,
	    });
	}
	code.hasPropFunc = hasPropFunc;
	function isOwnProperty(gen, data, property) {
	    return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`;
	}
	code.isOwnProperty = isOwnProperty;
	function propertyInData(gen, data, property, ownProperties) {
	    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
	    return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond;
	}
	code.propertyInData = propertyInData;
	function noPropertyInData(gen, data, property, ownProperties) {
	    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`;
	    return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
	}
	code.noPropertyInData = noPropertyInData;
	function allSchemaProperties(schemaMap) {
	    return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
	}
	code.allSchemaProperties = allSchemaProperties;
	function schemaProperties(it, schemaMap) {
	    return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
	}
	code.schemaProperties = schemaProperties;
	function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
	    const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
	    const valCxt = [
	        [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
	        [names_1.default.parentData, it.parentData],
	        [names_1.default.parentDataProperty, it.parentDataProperty],
	        [names_1.default.rootData, names_1.default.rootData],
	    ];
	    if (it.opts.dynamicRef)
	        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
	    const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`;
	    return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`;
	}
	code.callValidateCode = callValidateCode;
	const newRegExp = (0, codegen_1._) `new RegExp`;
	function usePattern({ gen, it: { opts } }, pattern) {
	    const u = opts.unicodeRegExp ? "u" : "";
	    const { regExp } = opts.code;
	    const rx = regExp(pattern, u);
	    return gen.scopeValue("pattern", {
	        key: rx.toString(),
	        ref: rx,
	        code: (0, codegen_1._) `${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`,
	    });
	}
	code.usePattern = usePattern;
	function validateArray(cxt) {
	    const { gen, data, keyword, it } = cxt;
	    const valid = gen.name("valid");
	    if (it.allErrors) {
	        const validArr = gen.let("valid", true);
	        validateItems(() => gen.assign(validArr, false));
	        return validArr;
	    }
	    gen.var(valid, true);
	    validateItems(() => gen.break());
	    return valid;
	    function validateItems(notValid) {
	        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
	        gen.forRange("i", 0, len, (i) => {
	            cxt.subschema({
	                keyword,
	                dataProp: i,
	                dataPropType: util_1.Type.Num,
	            }, valid);
	            gen.if((0, codegen_1.not)(valid), notValid);
	        });
	    }
	}
	code.validateArray = validateArray;
	function validateUnion(cxt) {
	    const { gen, schema, keyword, it } = cxt;
	    /* istanbul ignore if */
	    if (!Array.isArray(schema))
	        throw new Error("ajv implementation error");
	    const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
	    if (alwaysValid && !it.opts.unevaluated)
	        return;
	    const valid = gen.let("valid", false);
	    const schValid = gen.name("_valid");
	    gen.block(() => schema.forEach((_sch, i) => {
	        const schCxt = cxt.subschema({
	            keyword,
	            schemaProp: i,
	            compositeRule: true,
	        }, schValid);
	        gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`);
	        const merged = cxt.mergeValidEvaluated(schCxt, schValid);
	        // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)
	        // or if all properties and items were evaluated (it.props === true && it.items === true)
	        if (!merged)
	            gen.if((0, codegen_1.not)(valid));
	    }));
	    cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
	}
	code.validateUnion = validateUnion;
	
	return code;
}

var hasRequiredKeyword;

function requireKeyword () {
	if (hasRequiredKeyword) return keyword;
	hasRequiredKeyword = 1;
	Object.defineProperty(keyword, "__esModule", { value: true });
	keyword.validateKeywordUsage = keyword.validSchemaType = keyword.funcKeywordCode = keyword.macroKeywordCode = void 0;
	const codegen_1 = requireCodegen();
	const names_1 = requireNames();
	const code_1 = requireCode();
	const errors_1 = requireErrors();
	function macroKeywordCode(cxt, def) {
	    const { gen, keyword, schema, parentSchema, it } = cxt;
	    const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
	    const schemaRef = useKeyword(gen, keyword, macroSchema);
	    if (it.opts.validateSchema !== false)
	        it.self.validateSchema(macroSchema, true);
	    const valid = gen.name("valid");
	    cxt.subschema({
	        schema: macroSchema,
	        schemaPath: codegen_1.nil,
	        errSchemaPath: `${it.errSchemaPath}/${keyword}`,
	        topSchemaRef: schemaRef,
	        compositeRule: true,
	    }, valid);
	    cxt.pass(valid, () => cxt.error(true));
	}
	keyword.macroKeywordCode = macroKeywordCode;
	function funcKeywordCode(cxt, def) {
	    var _a;
	    const { gen, keyword, schema, parentSchema, $data, it } = cxt;
	    checkAsyncKeyword(it, def);
	    const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
	    const validateRef = useKeyword(gen, keyword, validate);
	    const valid = gen.let("valid");
	    cxt.block$data(valid, validateKeyword);
	    cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);
	    function validateKeyword() {
	        if (def.errors === false) {
	            assignValid();
	            if (def.modifying)
	                modifyData(cxt);
	            reportErrs(() => cxt.error());
	        }
	        else {
	            const ruleErrs = def.async ? validateAsync() : validateSync();
	            if (def.modifying)
	                modifyData(cxt);
	            reportErrs(() => addErrs(cxt, ruleErrs));
	        }
	    }
	    function validateAsync() {
	        const ruleErrs = gen.let("ruleErrs", null);
	        gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e)));
	        return ruleErrs;
	    }
	    function validateSync() {
	        const validateErrs = (0, codegen_1._) `${validateRef}.errors`;
	        gen.assign(validateErrs, null);
	        assignValid(codegen_1.nil);
	        return validateErrs;
	    }
	    function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) {
	        const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
	        const passSchema = !(("compile" in def && !$data) || def.schema === false);
	        gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
	    }
	    function reportErrs(errors) {
	        var _a;
	        gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors);
	    }
	}
	keyword.funcKeywordCode = funcKeywordCode;
	function modifyData(cxt) {
	    const { gen, data, it } = cxt;
	    gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`));
	}
	function addErrs(cxt, errs) {
	    const { gen } = cxt;
	    gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => {
	        gen
	            .assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`)
	            .assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
	        (0, errors_1.extendErrors)(cxt);
	    }, () => cxt.error());
	}
	function checkAsyncKeyword({ schemaEnv }, def) {
	    if (def.async && !schemaEnv.$async)
	        throw new Error("async keyword in sync schema");
	}
	function useKeyword(gen, keyword, result) {
	    if (result === undefined)
	        throw new Error(`keyword "${keyword}" failed to compile`);
	    return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
	}
	function validSchemaType(schema, schemaType, allowUndefined = false) {
	    // TODO add tests
	    return (!schemaType.length ||
	        schemaType.some((st) => st === "array"
	            ? Array.isArray(schema)
	            : st === "object"
	                ? schema && typeof schema == "object" && !Array.isArray(schema)
	                : typeof schema == st || (allowUndefined && typeof schema == "undefined")));
	}
	keyword.validSchemaType = validSchemaType;
	function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {
	    /* istanbul ignore if */
	    if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
	        throw new Error("ajv implementation error");
	    }
	    const deps = def.dependencies;
	    if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
	        throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
	    }
	    if (def.validateSchema) {
	        const valid = def.validateSchema(schema[keyword]);
	        if (!valid) {
	            const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` +
	                self.errorsText(def.validateSchema.errors);
	            if (opts.validateSchema === "log")
	                self.logger.error(msg);
	            else
	                throw new Error(msg);
	        }
	    }
	}
	keyword.validateKeywordUsage = validateKeywordUsage;
	
	return keyword;
}

var subschema = {};

var hasRequiredSubschema;

function requireSubschema () {
	if (hasRequiredSubschema) return subschema;
	hasRequiredSubschema = 1;
	Object.defineProperty(subschema, "__esModule", { value: true });
	subschema.extendSubschemaMode = subschema.extendSubschemaData = subschema.getSubschema = void 0;
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$1();
	function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
	    if (keyword !== undefined && schema !== undefined) {
	        throw new Error('both "keyword" and "schema" passed, only one allowed');
	    }
	    if (keyword !== undefined) {
	        const sch = it.schema[keyword];
	        return schemaProp === undefined
	            ? {
	                schema: sch,
	                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
	                errSchemaPath: `${it.errSchemaPath}/${keyword}`,
	            }
	            : {
	                schema: sch[schemaProp],
	                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
	                errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`,
	            };
	    }
	    if (schema !== undefined) {
	        if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
	            throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
	        }
	        return {
	            schema,
	            schemaPath,
	            topSchemaRef,
	            errSchemaPath,
	        };
	    }
	    throw new Error('either "keyword" or "schema" must be passed');
	}
	subschema.getSubschema = getSubschema;
	function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
	    if (data !== undefined && dataProp !== undefined) {
	        throw new Error('both "data" and "dataProp" passed, only one allowed');
	    }
	    const { gen } = it;
	    if (dataProp !== undefined) {
	        const { errorPath, dataPathArr, opts } = it;
	        const nextData = gen.let("data", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
	        dataContextProps(nextData);
	        subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
	        subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`;
	        subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
	    }
	    if (data !== undefined) {
	        const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); // replaceable if used once?
	        dataContextProps(nextData);
	        if (propertyName !== undefined)
	            subschema.propertyName = propertyName;
	        // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
	    }
	    if (dataTypes)
	        subschema.dataTypes = dataTypes;
	    function dataContextProps(_nextData) {
	        subschema.data = _nextData;
	        subschema.dataLevel = it.dataLevel + 1;
	        subschema.dataTypes = [];
	        it.definedProperties = new Set();
	        subschema.parentData = it.data;
	        subschema.dataNames = [...it.dataNames, _nextData];
	    }
	}
	subschema.extendSubschemaData = extendSubschemaData;
	function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
	    if (compositeRule !== undefined)
	        subschema.compositeRule = compositeRule;
	    if (createErrors !== undefined)
	        subschema.createErrors = createErrors;
	    if (allErrors !== undefined)
	        subschema.allErrors = allErrors;
	    subschema.jtdDiscriminator = jtdDiscriminator; // not inherited
	    subschema.jtdMetadata = jtdMetadata; // not inherited
	}
	subschema.extendSubschemaMode = extendSubschemaMode;
	
	return subschema;
}

var resolve = {};

var fastDeepEqual;
var hasRequiredFastDeepEqual;

function requireFastDeepEqual () {
	if (hasRequiredFastDeepEqual) return fastDeepEqual;
	hasRequiredFastDeepEqual = 1;

	// do not edit .js files directly - edit src/index.jst



	fastDeepEqual = function equal(a, b) {
	  if (a === b) return true;

	  if (a && b && typeof a == 'object' && typeof b == 'object') {
	    if (a.constructor !== b.constructor) return false;

	    var length, i, keys;
	    if (Array.isArray(a)) {
	      length = a.length;
	      if (length != b.length) return false;
	      for (i = length; i-- !== 0;)
	        if (!equal(a[i], b[i])) return false;
	      return true;
	    }



	    if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
	    if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
	    if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();

	    keys = Object.keys(a);
	    length = keys.length;
	    if (length !== Object.keys(b).length) return false;

	    for (i = length; i-- !== 0;)
	      if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;

	    for (i = length; i-- !== 0;) {
	      var key = keys[i];

	      if (!equal(a[key], b[key])) return false;
	    }

	    return true;
	  }

	  // true if both NaN, false otherwise
	  return a!==a && b!==b;
	};
	return fastDeepEqual;
}

var jsonSchemaTraverse = {exports: {}};

var hasRequiredJsonSchemaTraverse;

function requireJsonSchemaTraverse () {
	if (hasRequiredJsonSchemaTraverse) return jsonSchemaTraverse.exports;
	hasRequiredJsonSchemaTraverse = 1;

	var traverse = jsonSchemaTraverse.exports = function (schema, opts, cb) {
	  // Legacy support for v0.3.1 and earlier.
	  if (typeof opts == 'function') {
	    cb = opts;
	    opts = {};
	  }

	  cb = opts.cb || cb;
	  var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
	  var post = cb.post || function() {};

	  _traverse(opts, pre, post, schema, '', schema);
	};


	traverse.keywords = {
	  additionalItems: true,
	  items: true,
	  contains: true,
	  additionalProperties: true,
	  propertyNames: true,
	  not: true,
	  if: true,
	  then: true,
	  else: true
	};

	traverse.arrayKeywords = {
	  items: true,
	  allOf: true,
	  anyOf: true,
	  oneOf: true
	};

	traverse.propsKeywords = {
	  $defs: true,
	  definitions: true,
	  properties: true,
	  patternProperties: true,
	  dependencies: true
	};

	traverse.skipKeywords = {
	  default: true,
	  enum: true,
	  const: true,
	  required: true,
	  maximum: true,
	  minimum: true,
	  exclusiveMaximum: true,
	  exclusiveMinimum: true,
	  multipleOf: true,
	  maxLength: true,
	  minLength: true,
	  pattern: true,
	  format: true,
	  maxItems: true,
	  minItems: true,
	  uniqueItems: true,
	  maxProperties: true,
	  minProperties: true
	};


	function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
	  if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
	    pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
	    for (var key in schema) {
	      var sch = schema[key];
	      if (Array.isArray(sch)) {
	        if (key in traverse.arrayKeywords) {
	          for (var i=0; i<sch.length; i++)
	            _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
	        }
	      } else if (key in traverse.propsKeywords) {
	        if (sch && typeof sch == 'object') {
	          for (var prop in sch)
	            _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
	        }
	      } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
	        _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
	      }
	    }
	    post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
	  }
	}


	function escapeJsonPtr(str) {
	  return str.replace(/~/g, '~0').replace(/\//g, '~1');
	}
	return jsonSchemaTraverse.exports;
}

var hasRequiredResolve;

function requireResolve () {
	if (hasRequiredResolve) return resolve;
	hasRequiredResolve = 1;
	Object.defineProperty(resolve, "__esModule", { value: true });
	resolve.getSchemaRefs = resolve.resolveUrl = resolve.normalizeId = resolve._getFullPath = resolve.getFullPath = resolve.inlineRef = void 0;
	const util_1 = requireUtil$1();
	const equal = requireFastDeepEqual();
	const traverse = requireJsonSchemaTraverse();
	// TODO refactor to use keyword definitions
	const SIMPLE_INLINED = new Set([
	    "type",
	    "format",
	    "pattern",
	    "maxLength",
	    "minLength",
	    "maxProperties",
	    "minProperties",
	    "maxItems",
	    "minItems",
	    "maximum",
	    "minimum",
	    "uniqueItems",
	    "multipleOf",
	    "required",
	    "enum",
	    "const",
	]);
	function inlineRef(schema, limit = true) {
	    if (typeof schema == "boolean")
	        return true;
	    if (limit === true)
	        return !hasRef(schema);
	    if (!limit)
	        return false;
	    return countKeys(schema) <= limit;
	}
	resolve.inlineRef = inlineRef;
	const REF_KEYWORDS = new Set([
	    "$ref",
	    "$recursiveRef",
	    "$recursiveAnchor",
	    "$dynamicRef",
	    "$dynamicAnchor",
	]);
	function hasRef(schema) {
	    for (const key in schema) {
	        if (REF_KEYWORDS.has(key))
	            return true;
	        const sch = schema[key];
	        if (Array.isArray(sch) && sch.some(hasRef))
	            return true;
	        if (typeof sch == "object" && hasRef(sch))
	            return true;
	    }
	    return false;
	}
	function countKeys(schema) {
	    let count = 0;
	    for (const key in schema) {
	        if (key === "$ref")
	            return Infinity;
	        count++;
	        if (SIMPLE_INLINED.has(key))
	            continue;
	        if (typeof schema[key] == "object") {
	            (0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch)));
	        }
	        if (count === Infinity)
	            return Infinity;
	    }
	    return count;
	}
	function getFullPath(resolver, id = "", normalize) {
	    if (normalize !== false)
	        id = normalizeId(id);
	    const p = resolver.parse(id);
	    return _getFullPath(resolver, p);
	}
	resolve.getFullPath = getFullPath;
	function _getFullPath(resolver, p) {
	    const serialized = resolver.serialize(p);
	    return serialized.split("#")[0] + "#";
	}
	resolve._getFullPath = _getFullPath;
	const TRAILING_SLASH_HASH = /#\/?$/;
	function normalizeId(id) {
	    return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
	}
	resolve.normalizeId = normalizeId;
	function resolveUrl(resolver, baseId, id) {
	    id = normalizeId(id);
	    return resolver.resolve(baseId, id);
	}
	resolve.resolveUrl = resolveUrl;
	const ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
	function getSchemaRefs(schema, baseId) {
	    if (typeof schema == "boolean")
	        return {};
	    const { schemaId, uriResolver } = this.opts;
	    const schId = normalizeId(schema[schemaId] || baseId);
	    const baseIds = { "": schId };
	    const pathPrefix = getFullPath(uriResolver, schId, false);
	    const localRefs = {};
	    const schemaRefs = new Set();
	    traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
	        if (parentJsonPtr === undefined)
	            return;
	        const fullPath = pathPrefix + jsonPtr;
	        let innerBaseId = baseIds[parentJsonPtr];
	        if (typeof sch[schemaId] == "string")
	            innerBaseId = addRef.call(this, sch[schemaId]);
	        addAnchor.call(this, sch.$anchor);
	        addAnchor.call(this, sch.$dynamicAnchor);
	        baseIds[jsonPtr] = innerBaseId;
	        function addRef(ref) {
	            // eslint-disable-next-line @typescript-eslint/unbound-method
	            const _resolve = this.opts.uriResolver.resolve;
	            ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
	            if (schemaRefs.has(ref))
	                throw ambiguos(ref);
	            schemaRefs.add(ref);
	            let schOrRef = this.refs[ref];
	            if (typeof schOrRef == "string")
	                schOrRef = this.refs[schOrRef];
	            if (typeof schOrRef == "object") {
	                checkAmbiguosRef(sch, schOrRef.schema, ref);
	            }
	            else if (ref !== normalizeId(fullPath)) {
	                if (ref[0] === "#") {
	                    checkAmbiguosRef(sch, localRefs[ref], ref);
	                    localRefs[ref] = sch;
	                }
	                else {
	                    this.refs[ref] = fullPath;
	                }
	            }
	            return ref;
	        }
	        function addAnchor(anchor) {
	            if (typeof anchor == "string") {
	                if (!ANCHOR.test(anchor))
	                    throw new Error(`invalid anchor "${anchor}"`);
	                addRef.call(this, `#${anchor}`);
	            }
	        }
	    });
	    return localRefs;
	    function checkAmbiguosRef(sch1, sch2, ref) {
	        if (sch2 !== undefined && !equal(sch1, sch2))
	            throw ambiguos(ref);
	    }
	    function ambiguos(ref) {
	        return new Error(`reference "${ref}" resolves to more than one schema`);
	    }
	}
	resolve.getSchemaRefs = getSchemaRefs;
	
	return resolve;
}

var hasRequiredValidate;

function requireValidate () {
	if (hasRequiredValidate) return validate;
	hasRequiredValidate = 1;
	Object.defineProperty(validate, "__esModule", { value: true });
	validate.getData = validate.KeywordCxt = validate.validateFunctionCode = void 0;
	const boolSchema_1 = requireBoolSchema();
	const dataType_1 = requireDataType();
	const applicability_1 = requireApplicability();
	const dataType_2 = requireDataType();
	const defaults_1 = requireDefaults();
	const keyword_1 = requireKeyword();
	const subschema_1 = requireSubschema();
	const codegen_1 = requireCodegen();
	const names_1 = requireNames();
	const resolve_1 = requireResolve();
	const util_1 = requireUtil$1();
	const errors_1 = requireErrors();
	// schema compilation - generates validation function, subschemaCode (below) is used for subschemas
	function validateFunctionCode(it) {
	    if (isSchemaObj(it)) {
	        checkKeywords(it);
	        if (schemaCxtHasRules(it)) {
	            topSchemaObjCode(it);
	            return;
	        }
	    }
	    validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
	}
	validate.validateFunctionCode = validateFunctionCode;
	function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
	    if (opts.code.es5) {
	        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
	            gen.code((0, codegen_1._) `"use strict"; ${funcSourceUrl(schema, opts)}`);
	            destructureValCxtES5(gen, opts);
	            gen.code(body);
	        });
	    }
	    else {
	        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
	    }
	}
	function destructureValCxt(opts) {
	    return (0, codegen_1._) `{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._) `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
	}
	function destructureValCxtES5(gen, opts) {
	    gen.if(names_1.default.valCxt, () => {
	        gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`);
	        gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`);
	        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
	        gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`);
	        if (opts.dynamicRef)
	            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
	    }, () => {
	        gen.var(names_1.default.instancePath, (0, codegen_1._) `""`);
	        gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`);
	        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`);
	        gen.var(names_1.default.rootData, names_1.default.data);
	        if (opts.dynamicRef)
	            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`);
	    });
	}
	function topSchemaObjCode(it) {
	    const { schema, opts, gen } = it;
	    validateFunction(it, () => {
	        if (opts.$comment && schema.$comment)
	            commentKeyword(it);
	        checkNoDefault(it);
	        gen.let(names_1.default.vErrors, null);
	        gen.let(names_1.default.errors, 0);
	        if (opts.unevaluated)
	            resetEvaluated(it);
	        typeAndKeywords(it);
	        returnResults(it);
	    });
	    return;
	}
	function resetEvaluated(it) {
	    // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated
	    const { gen, validateName } = it;
	    it.evaluated = gen.const("evaluated", (0, codegen_1._) `${validateName}.evaluated`);
	    gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`));
	    gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`));
	}
	function funcSourceUrl(schema, opts) {
	    const schId = typeof schema == "object" && schema[opts.schemaId];
	    return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil;
	}
	// schema compilation - this function is used recursively to generate code for sub-schemas
	function subschemaCode(it, valid) {
	    if (isSchemaObj(it)) {
	        checkKeywords(it);
	        if (schemaCxtHasRules(it)) {
	            subSchemaObjCode(it, valid);
	            return;
	        }
	    }
	    (0, boolSchema_1.boolOrEmptySchema)(it, valid);
	}
	function schemaCxtHasRules({ schema, self }) {
	    if (typeof schema == "boolean")
	        return !schema;
	    for (const key in schema)
	        if (self.RULES.all[key])
	            return true;
	    return false;
	}
	function isSchemaObj(it) {
	    return typeof it.schema != "boolean";
	}
	function subSchemaObjCode(it, valid) {
	    const { schema, gen, opts } = it;
	    if (opts.$comment && schema.$comment)
	        commentKeyword(it);
	    updateContext(it);
	    checkAsyncSchema(it);
	    const errsCount = gen.const("_errs", names_1.default.errors);
	    typeAndKeywords(it, errsCount);
	    // TODO var
	    gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
	}
	function checkKeywords(it) {
	    (0, util_1.checkUnknownRules)(it);
	    checkRefsAndKeywords(it);
	}
	function typeAndKeywords(it, errsCount) {
	    if (it.opts.jtd)
	        return schemaKeywords(it, [], false, errsCount);
	    const types = (0, dataType_1.getSchemaTypes)(it.schema);
	    const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);
	    schemaKeywords(it, types, !checkedTypes, errsCount);
	}
	function checkRefsAndKeywords(it) {
	    const { schema, errSchemaPath, opts, self } = it;
	    if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {
	        self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
	    }
	}
	function checkNoDefault(it) {
	    const { schema, opts } = it;
	    if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {
	        (0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
	    }
	}
	function updateContext(it) {
	    const schId = it.schema[it.opts.schemaId];
	    if (schId)
	        it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
	}
	function checkAsyncSchema(it) {
	    if (it.schema.$async && !it.schemaEnv.$async)
	        throw new Error("async schema in sync schema");
	}
	function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
	    const msg = schema.$comment;
	    if (opts.$comment === true) {
	        gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`);
	    }
	    else if (typeof opts.$comment == "function") {
	        const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`;
	        const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
	        gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
	    }
	}
	function returnResults(it) {
	    const { gen, schemaEnv, validateName, ValidationError, opts } = it;
	    if (schemaEnv.$async) {
	        // TODO assign unevaluated
	        gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`));
	    }
	    else {
	        gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors);
	        if (opts.unevaluated)
	            assignEvaluated(it);
	        gen.return((0, codegen_1._) `${names_1.default.errors} === 0`);
	    }
	}
	function assignEvaluated({ gen, evaluated, props, items }) {
	    if (props instanceof codegen_1.Name)
	        gen.assign((0, codegen_1._) `${evaluated}.props`, props);
	    if (items instanceof codegen_1.Name)
	        gen.assign((0, codegen_1._) `${evaluated}.items`, items);
	}
	function schemaKeywords(it, types, typeErrors, errsCount) {
	    const { gen, schema, data, allErrors, opts, self } = it;
	    const { RULES } = self;
	    if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
	        gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); // TODO typecast
	        return;
	    }
	    if (!opts.jtd)
	        checkStrictTypes(it, types);
	    gen.block(() => {
	        for (const group of RULES.rules)
	            groupKeywords(group);
	        groupKeywords(RULES.post);
	    });
	    function groupKeywords(group) {
	        if (!(0, applicability_1.shouldUseGroup)(schema, group))
	            return;
	        if (group.type) {
	            gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
	            iterateKeywords(it, group);
	            if (types.length === 1 && types[0] === group.type && typeErrors) {
	                gen.else();
	                (0, dataType_2.reportTypeError)(it);
	            }
	            gen.endIf();
	        }
	        else {
	            iterateKeywords(it, group);
	        }
	        // TODO make it "ok" call?
	        if (!allErrors)
	            gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`);
	    }
	}
	function iterateKeywords(it, group) {
	    const { gen, schema, opts: { useDefaults }, } = it;
	    if (useDefaults)
	        (0, defaults_1.assignDefaults)(it, group.type);
	    gen.block(() => {
	        for (const rule of group.rules) {
	            if ((0, applicability_1.shouldUseRule)(schema, rule)) {
	                keywordCode(it, rule.keyword, rule.definition, group.type);
	            }
	        }
	    });
	}
	function checkStrictTypes(it, types) {
	    if (it.schemaEnv.meta || !it.opts.strictTypes)
	        return;
	    checkContextTypes(it, types);
	    if (!it.opts.allowUnionTypes)
	        checkMultipleTypes(it, types);
	    checkKeywordTypes(it, it.dataTypes);
	}
	function checkContextTypes(it, types) {
	    if (!types.length)
	        return;
	    if (!it.dataTypes.length) {
	        it.dataTypes = types;
	        return;
	    }
	    types.forEach((t) => {
	        if (!includesType(it.dataTypes, t)) {
	            strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);
	        }
	    });
	    narrowSchemaTypes(it, types);
	}
	function checkMultipleTypes(it, ts) {
	    if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
	        strictTypesError(it, "use allowUnionTypes to allow union type keyword");
	    }
	}
	function checkKeywordTypes(it, ts) {
	    const rules = it.self.RULES.all;
	    for (const keyword in rules) {
	        const rule = rules[keyword];
	        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
	            const { type } = rule.definition;
	            if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
	                strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
	            }
	        }
	    }
	}
	function hasApplicableType(schTs, kwdT) {
	    return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"));
	}
	function includesType(ts, t) {
	    return ts.includes(t) || (t === "integer" && ts.includes("number"));
	}
	function narrowSchemaTypes(it, withTypes) {
	    const ts = [];
	    for (const t of it.dataTypes) {
	        if (includesType(withTypes, t))
	            ts.push(t);
	        else if (withTypes.includes("integer") && t === "number")
	            ts.push("integer");
	    }
	    it.dataTypes = ts;
	}
	function strictTypesError(it, msg) {
	    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
	    msg += ` at "${schemaPath}" (strictTypes)`;
	    (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
	}
	class KeywordCxt {
	    constructor(it, def, keyword) {
	        (0, keyword_1.validateKeywordUsage)(it, def, keyword);
	        this.gen = it.gen;
	        this.allErrors = it.allErrors;
	        this.keyword = keyword;
	        this.data = it.data;
	        this.schema = it.schema[keyword];
	        this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
	        this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
	        this.schemaType = def.schemaType;
	        this.parentSchema = it.schema;
	        this.params = {};
	        this.it = it;
	        this.def = def;
	        if (this.$data) {
	            this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
	        }
	        else {
	            this.schemaCode = this.schemaValue;
	            if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
	                throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
	            }
	        }
	        if ("code" in def ? def.trackErrors : def.errors !== false) {
	            this.errsCount = it.gen.const("_errs", names_1.default.errors);
	        }
	    }
	    result(condition, successAction, failAction) {
	        this.failResult((0, codegen_1.not)(condition), successAction, failAction);
	    }
	    failResult(condition, successAction, failAction) {
	        this.gen.if(condition);
	        if (failAction)
	            failAction();
	        else
	            this.error();
	        if (successAction) {
	            this.gen.else();
	            successAction();
	            if (this.allErrors)
	                this.gen.endIf();
	        }
	        else {
	            if (this.allErrors)
	                this.gen.endIf();
	            else
	                this.gen.else();
	        }
	    }
	    pass(condition, failAction) {
	        this.failResult((0, codegen_1.not)(condition), undefined, failAction);
	    }
	    fail(condition) {
	        if (condition === undefined) {
	            this.error();
	            if (!this.allErrors)
	                this.gen.if(false); // this branch will be removed by gen.optimize
	            return;
	        }
	        this.gen.if(condition);
	        this.error();
	        if (this.allErrors)
	            this.gen.endIf();
	        else
	            this.gen.else();
	    }
	    fail$data(condition) {
	        if (!this.$data)
	            return this.fail(condition);
	        const { schemaCode } = this;
	        this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
	    }
	    error(append, errorParams, errorPaths) {
	        if (errorParams) {
	            this.setParams(errorParams);
	            this._error(append, errorPaths);
	            this.setParams({});
	            return;
	        }
	        this._error(append, errorPaths);
	    }
	    _error(append, errorPaths) {
	        (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
	    }
	    $dataError() {
	        (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
	    }
	    reset() {
	        if (this.errsCount === undefined)
	            throw new Error('add "trackErrors" to keyword definition');
	        (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
	    }
	    ok(cond) {
	        if (!this.allErrors)
	            this.gen.if(cond);
	    }
	    setParams(obj, assign) {
	        if (assign)
	            Object.assign(this.params, obj);
	        else
	            this.params = obj;
	    }
	    block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
	        this.gen.block(() => {
	            this.check$data(valid, $dataValid);
	            codeBlock();
	        });
	    }
	    check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
	        if (!this.$data)
	            return;
	        const { gen, schemaCode, schemaType, def } = this;
	        gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid));
	        if (valid !== codegen_1.nil)
	            gen.assign(valid, true);
	        if (schemaType.length || def.validateSchema) {
	            gen.elseIf(this.invalid$data());
	            this.$dataError();
	            if (valid !== codegen_1.nil)
	                gen.assign(valid, false);
	        }
	        gen.else();
	    }
	    invalid$data() {
	        const { gen, schemaCode, schemaType, def, it } = this;
	        return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
	        function wrong$DataType() {
	            if (schemaType.length) {
	                /* istanbul ignore if */
	                if (!(schemaCode instanceof codegen_1.Name))
	                    throw new Error("ajv implementation error");
	                const st = Array.isArray(schemaType) ? schemaType : [schemaType];
	                return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
	            }
	            return codegen_1.nil;
	        }
	        function invalid$DataSchema() {
	            if (def.validateSchema) {
	                const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); // TODO value.code for standalone
	                return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`;
	            }
	            return codegen_1.nil;
	        }
	    }
	    subschema(appl, valid) {
	        const subschema = (0, subschema_1.getSubschema)(this.it, appl);
	        (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
	        (0, subschema_1.extendSubschemaMode)(subschema, appl);
	        const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined };
	        subschemaCode(nextContext, valid);
	        return nextContext;
	    }
	    mergeEvaluated(schemaCxt, toName) {
	        const { it, gen } = this;
	        if (!it.opts.unevaluated)
	            return;
	        if (it.props !== true && schemaCxt.props !== undefined) {
	            it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
	        }
	        if (it.items !== true && schemaCxt.items !== undefined) {
	            it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
	        }
	    }
	    mergeValidEvaluated(schemaCxt, valid) {
	        const { it, gen } = this;
	        if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
	            gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
	            return true;
	        }
	    }
	}
	validate.KeywordCxt = KeywordCxt;
	function keywordCode(it, keyword, def, ruleType) {
	    const cxt = new KeywordCxt(it, def, keyword);
	    if ("code" in def) {
	        def.code(cxt, ruleType);
	    }
	    else if (cxt.$data && def.validate) {
	        (0, keyword_1.funcKeywordCode)(cxt, def);
	    }
	    else if ("macro" in def) {
	        (0, keyword_1.macroKeywordCode)(cxt, def);
	    }
	    else if (def.compile || def.validate) {
	        (0, keyword_1.funcKeywordCode)(cxt, def);
	    }
	}
	const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
	const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
	function getData($data, { dataLevel, dataNames, dataPathArr }) {
	    let jsonPointer;
	    let data;
	    if ($data === "")
	        return names_1.default.rootData;
	    if ($data[0] === "/") {
	        if (!JSON_POINTER.test($data))
	            throw new Error(`Invalid JSON-pointer: ${$data}`);
	        jsonPointer = $data;
	        data = names_1.default.rootData;
	    }
	    else {
	        const matches = RELATIVE_JSON_POINTER.exec($data);
	        if (!matches)
	            throw new Error(`Invalid JSON-pointer: ${$data}`);
	        const up = +matches[1];
	        jsonPointer = matches[2];
	        if (jsonPointer === "#") {
	            if (up >= dataLevel)
	                throw new Error(errorMsg("property/index", up));
	            return dataPathArr[dataLevel - up];
	        }
	        if (up > dataLevel)
	            throw new Error(errorMsg("data", up));
	        data = dataNames[dataLevel - up];
	        if (!jsonPointer)
	            return data;
	    }
	    let expr = data;
	    const segments = jsonPointer.split("/");
	    for (const segment of segments) {
	        if (segment) {
	            data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
	            expr = (0, codegen_1._) `${expr} && ${data}`;
	        }
	    }
	    return expr;
	    function errorMsg(pointerType, up) {
	        return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
	    }
	}
	validate.getData = getData;
	
	return validate;
}

var validation_error = {};

var hasRequiredValidation_error;

function requireValidation_error () {
	if (hasRequiredValidation_error) return validation_error;
	hasRequiredValidation_error = 1;
	Object.defineProperty(validation_error, "__esModule", { value: true });
	class ValidationError extends Error {
	    constructor(errors) {
	        super("validation failed");
	        this.errors = errors;
	        this.ajv = this.validation = true;
	    }
	}
	validation_error.default = ValidationError;
	
	return validation_error;
}

var ref_error = {};

var hasRequiredRef_error;

function requireRef_error () {
	if (hasRequiredRef_error) return ref_error;
	hasRequiredRef_error = 1;
	Object.defineProperty(ref_error, "__esModule", { value: true });
	const resolve_1 = requireResolve();
	class MissingRefError extends Error {
	    constructor(resolver, baseId, ref, msg) {
	        super(msg || `can't resolve reference ${ref} from id ${baseId}`);
	        this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
	        this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
	    }
	}
	ref_error.default = MissingRefError;
	
	return ref_error;
}

var compile = {};

var hasRequiredCompile;

function requireCompile () {
	if (hasRequiredCompile) return compile;
	hasRequiredCompile = 1;
	Object.defineProperty(compile, "__esModule", { value: true });
	compile.resolveSchema = compile.getCompilingSchema = compile.resolveRef = compile.compileSchema = compile.SchemaEnv = void 0;
	const codegen_1 = requireCodegen();
	const validation_error_1 = requireValidation_error();
	const names_1 = requireNames();
	const resolve_1 = requireResolve();
	const util_1 = requireUtil$1();
	const validate_1 = requireValidate();
	class SchemaEnv {
	    constructor(env) {
	        var _a;
	        this.refs = {};
	        this.dynamicAnchors = {};
	        let schema;
	        if (typeof env.schema == "object")
	            schema = env.schema;
	        this.schema = env.schema;
	        this.schemaId = env.schemaId;
	        this.root = env.root || this;
	        this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
	        this.schemaPath = env.schemaPath;
	        this.localRefs = env.localRefs;
	        this.meta = env.meta;
	        this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
	        this.refs = {};
	    }
	}
	compile.SchemaEnv = SchemaEnv;
	// let codeSize = 0
	// let nodeCount = 0
	// Compiles schema in SchemaEnv
	function compileSchema(sch) {
	    // TODO refactor - remove compilations
	    const _sch = getCompilingSchema.call(this, sch);
	    if (_sch)
	        return _sch;
	    const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails
	    const { es5, lines } = this.opts.code;
	    const { ownProperties } = this.opts;
	    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
	    let _ValidationError;
	    if (sch.$async) {
	        _ValidationError = gen.scopeValue("Error", {
	            ref: validation_error_1.default,
	            code: (0, codegen_1._) `require("ajv/dist/runtime/validation_error").default`,
	        });
	    }
	    const validateName = gen.scopeName("validate");
	    sch.validateName = validateName;
	    const schemaCxt = {
	        gen,
	        allErrors: this.opts.allErrors,
	        data: names_1.default.data,
	        parentData: names_1.default.parentData,
	        parentDataProperty: names_1.default.parentDataProperty,
	        dataNames: [names_1.default.data],
	        dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed?
	        dataLevel: 0,
	        dataTypes: [],
	        definedProperties: new Set(),
	        topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true
	            ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) }
	            : { ref: sch.schema }),
	        validateName,
	        ValidationError: _ValidationError,
	        schema: sch.schema,
	        schemaEnv: sch,
	        rootId,
	        baseId: sch.baseId || rootId,
	        schemaPath: codegen_1.nil,
	        errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
	        errorPath: (0, codegen_1._) `""`,
	        opts: this.opts,
	        self: this,
	    };
	    let sourceCode;
	    try {
	        this._compilations.add(sch);
	        (0, validate_1.validateFunctionCode)(schemaCxt);
	        gen.optimize(this.opts.code.optimize);
	        // gen.optimize(1)
	        const validateCode = gen.toString();
	        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
	        // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))
	        if (this.opts.code.process)
	            sourceCode = this.opts.code.process(sourceCode, sch);
	        // console.log("\n\n\n *** \n", sourceCode)
	        const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
	        const validate = makeValidate(this, this.scope.get());
	        this.scope.value(validateName, { ref: validate });
	        validate.errors = null;
	        validate.schema = sch.schema;
	        validate.schemaEnv = sch;
	        if (sch.$async)
	            validate.$async = true;
	        if (this.opts.code.source === true) {
	            validate.source = { validateName, validateCode, scopeValues: gen._values };
	        }
	        if (this.opts.unevaluated) {
	            const { props, items } = schemaCxt;
	            validate.evaluated = {
	                props: props instanceof codegen_1.Name ? undefined : props,
	                items: items instanceof codegen_1.Name ? undefined : items,
	                dynamicProps: props instanceof codegen_1.Name,
	                dynamicItems: items instanceof codegen_1.Name,
	            };
	            if (validate.source)
	                validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
	        }
	        sch.validate = validate;
	        return sch;
	    }
	    catch (e) {
	        delete sch.validate;
	        delete sch.validateName;
	        if (sourceCode)
	            this.logger.error("Error compiling schema, function code:", sourceCode);
	        // console.log("\n\n\n *** \n", sourceCode, this.opts)
	        throw e;
	    }
	    finally {
	        this._compilations.delete(sch);
	    }
	}
	compile.compileSchema = compileSchema;
	function resolveRef(root, baseId, ref) {
	    var _a;
	    ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
	    const schOrFunc = root.refs[ref];
	    if (schOrFunc)
	        return schOrFunc;
	    let _sch = resolve.call(this, root, ref);
	    if (_sch === undefined) {
	        const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv
	        const { schemaId } = this.opts;
	        if (schema)
	            _sch = new SchemaEnv({ schema, schemaId, root, baseId });
	    }
	    if (_sch === undefined)
	        return;
	    return (root.refs[ref] = inlineOrCompile.call(this, _sch));
	}
	compile.resolveRef = resolveRef;
	function inlineOrCompile(sch) {
	    if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
	        return sch.schema;
	    return sch.validate ? sch : compileSchema.call(this, sch);
	}
	// Index of schema compilation in the currently compiled list
	function getCompilingSchema(schEnv) {
	    for (const sch of this._compilations) {
	        if (sameSchemaEnv(sch, schEnv))
	            return sch;
	    }
	}
	compile.getCompilingSchema = getCompilingSchema;
	function sameSchemaEnv(s1, s2) {
	    return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
	}
	// resolve and compile the references ($ref)
	// TODO returns AnySchemaObject (if the schema can be inlined) or validation function
	function resolve(root, // information about the root schema for the current schema
	ref // reference to resolve
	) {
	    let sch;
	    while (typeof (sch = this.refs[ref]) == "string")
	        ref = sch;
	    return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
	}
	// Resolve schema, its root and baseId
	function resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
	ref // reference to resolve
	) {
	    const p = this.opts.uriResolver.parse(ref);
	    const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
	    let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined);
	    // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
	    if (Object.keys(root.schema).length > 0 && refPath === baseId) {
	        return getJsonPointer.call(this, p, root);
	    }
	    const id = (0, resolve_1.normalizeId)(refPath);
	    const schOrRef = this.refs[id] || this.schemas[id];
	    if (typeof schOrRef == "string") {
	        const sch = resolveSchema.call(this, root, schOrRef);
	        if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
	            return;
	        return getJsonPointer.call(this, p, sch);
	    }
	    if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
	        return;
	    if (!schOrRef.validate)
	        compileSchema.call(this, schOrRef);
	    if (id === (0, resolve_1.normalizeId)(ref)) {
	        const { schema } = schOrRef;
	        const { schemaId } = this.opts;
	        const schId = schema[schemaId];
	        if (schId)
	            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
	        return new SchemaEnv({ schema, schemaId, root, baseId });
	    }
	    return getJsonPointer.call(this, p, schOrRef);
	}
	compile.resolveSchema = resolveSchema;
	const PREVENT_SCOPE_CHANGE = new Set([
	    "properties",
	    "patternProperties",
	    "enum",
	    "dependencies",
	    "definitions",
	]);
	function getJsonPointer(parsedRef, { baseId, schema, root }) {
	    var _a;
	    if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/")
	        return;
	    for (const part of parsedRef.fragment.slice(1).split("/")) {
	        if (typeof schema === "boolean")
	            return;
	        const partSchema = schema[(0, util_1.unescapeFragment)(part)];
	        if (partSchema === undefined)
	            return;
	        schema = partSchema;
	        // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
	        const schId = typeof schema === "object" && schema[this.opts.schemaId];
	        if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
	            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
	        }
	    }
	    let env;
	    if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
	        const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
	        env = resolveSchema.call(this, root, $ref);
	    }
	    // even though resolution failed we need to return SchemaEnv to throw exception
	    // so that compileAsync loads missing schema.
	    const { schemaId } = this.opts;
	    env = env || new SchemaEnv({ schema, schemaId, root, baseId });
	    if (env.schema !== env.root.schema)
	        return env;
	    return undefined;
	}
	
	return compile;
}

const $id$1 = "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#";
const description = "Meta-schema for $data reference (JSON AnySchema extension proposal)";
const type$1 = "object";
const required$1 = ["$data"];
const properties$2 = {"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}};
const additionalProperties$1 = false;
const require$$9 = {
  $id: $id$1,
  description,
  type: type$1,
  required: required$1,
  properties: properties$2,
  additionalProperties: additionalProperties$1,
};

var uri = {};

var fastUri = {exports: {}};

var utils$1;
var hasRequiredUtils$1;

function requireUtils$1 () {
	if (hasRequiredUtils$1) return utils$1;
	hasRequiredUtils$1 = 1;

	/** @type {(value: string) => boolean} */
	const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);

	/** @type {(value: string) => boolean} */
	const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);

	/**
	 * @param {Array<string>} input
	 * @returns {string}
	 */
	function stringArrayToHexStripped (input) {
	  let acc = '';
	  let code = 0;
	  let i = 0;

	  for (i = 0; i < input.length; i++) {
	    code = input[i].charCodeAt(0);
	    if (code === 48) {
	      continue
	    }
	    if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {
	      return ''
	    }
	    acc += input[i];
	    break
	  }

	  for (i += 1; i < input.length; i++) {
	    code = input[i].charCodeAt(0);
	    if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {
	      return ''
	    }
	    acc += input[i];
	  }
	  return acc
	}

	/**
	 * @typedef {Object} GetIPV6Result
	 * @property {boolean} error - Indicates if there was an error parsing the IPv6 address.
	 * @property {string} address - The parsed IPv6 address.
	 * @property {string} [zone] - The zone identifier, if present.
	 */

	/**
	 * @param {string} value
	 * @returns {boolean}
	 */
	const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);

	/**
	 * @param {Array<string>} buffer
	 * @returns {boolean}
	 */
	function consumeIsZone (buffer) {
	  buffer.length = 0;
	  return true
	}

	/**
	 * @param {Array<string>} buffer
	 * @param {Array<string>} address
	 * @param {GetIPV6Result} output
	 * @returns {boolean}
	 */
	function consumeHextets (buffer, address, output) {
	  if (buffer.length) {
	    const hex = stringArrayToHexStripped(buffer);
	    if (hex !== '') {
	      address.push(hex);
	    } else {
	      output.error = true;
	      return false
	    }
	    buffer.length = 0;
	  }
	  return true
	}

	/**
	 * @param {string} input
	 * @returns {GetIPV6Result}
	 */
	function getIPV6 (input) {
	  let tokenCount = 0;
	  const output = { error: false, address: '', zone: '' };
	  /** @type {Array<string>} */
	  const address = [];
	  /** @type {Array<string>} */
	  const buffer = [];
	  let endipv6Encountered = false;
	  let endIpv6 = false;

	  let consume = consumeHextets;

	  for (let i = 0; i < input.length; i++) {
	    const cursor = input[i];
	    if (cursor === '[' || cursor === ']') { continue }
	    if (cursor === ':') {
	      if (endipv6Encountered === true) {
	        endIpv6 = true;
	      }
	      if (!consume(buffer, address, output)) { break }
	      if (++tokenCount > 7) {
	        // not valid
	        output.error = true;
	        break
	      }
	      if (i > 0 && input[i - 1] === ':') {
	        endipv6Encountered = true;
	      }
	      address.push(':');
	      continue
	    } else if (cursor === '%') {
	      if (!consume(buffer, address, output)) { break }
	      // switch to zone detection
	      consume = consumeIsZone;
	    } else {
	      buffer.push(cursor);
	      continue
	    }
	  }
	  if (buffer.length) {
	    if (consume === consumeIsZone) {
	      output.zone = buffer.join('');
	    } else if (endIpv6) {
	      address.push(buffer.join(''));
	    } else {
	      address.push(stringArrayToHexStripped(buffer));
	    }
	  }
	  output.address = address.join('');
	  return output
	}

	/**
	 * @typedef {Object} NormalizeIPv6Result
	 * @property {string} host - The normalized host.
	 * @property {string} [escapedHost] - The escaped host.
	 * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address.
	 */

	/**
	 * @param {string} host
	 * @returns {NormalizeIPv6Result}
	 */
	function normalizeIPv6 (host) {
	  if (findToken(host, ':') < 2) { return { host, isIPV6: false } }
	  const ipv6 = getIPV6(host);

	  if (!ipv6.error) {
	    let newHost = ipv6.address;
	    let escapedHost = ipv6.address;
	    if (ipv6.zone) {
	      newHost += '%' + ipv6.zone;
	      escapedHost += '%25' + ipv6.zone;
	    }
	    return { host: newHost, isIPV6: true, escapedHost }
	  } else {
	    return { host, isIPV6: false }
	  }
	}

	/**
	 * @param {string} str
	 * @param {string} token
	 * @returns {number}
	 */
	function findToken (str, token) {
	  let ind = 0;
	  for (let i = 0; i < str.length; i++) {
	    if (str[i] === token) ind++;
	  }
	  return ind
	}

	/**
	 * @param {string} path
	 * @returns {string}
	 *
	 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4
	 */
	function removeDotSegments (path) {
	  let input = path;
	  const output = [];
	  let nextSlash = -1;
	  let len = 0;

	  // eslint-disable-next-line no-cond-assign
	  while (len = input.length) {
	    if (len === 1) {
	      if (input === '.') {
	        break
	      } else if (input === '/') {
	        output.push('/');
	        break
	      } else {
	        output.push(input);
	        break
	      }
	    } else if (len === 2) {
	      if (input[0] === '.') {
	        if (input[1] === '.') {
	          break
	        } else if (input[1] === '/') {
	          input = input.slice(2);
	          continue
	        }
	      } else if (input[0] === '/') {
	        if (input[1] === '.' || input[1] === '/') {
	          output.push('/');
	          break
	        }
	      }
	    } else if (len === 3) {
	      if (input === '/..') {
	        if (output.length !== 0) {
	          output.pop();
	        }
	        output.push('/');
	        break
	      }
	    }
	    if (input[0] === '.') {
	      if (input[1] === '.') {
	        if (input[2] === '/') {
	          input = input.slice(3);
	          continue
	        }
	      } else if (input[1] === '/') {
	        input = input.slice(2);
	        continue
	      }
	    } else if (input[0] === '/') {
	      if (input[1] === '.') {
	        if (input[2] === '/') {
	          input = input.slice(2);
	          continue
	        } else if (input[2] === '.') {
	          if (input[3] === '/') {
	            input = input.slice(3);
	            if (output.length !== 0) {
	              output.pop();
	            }
	            continue
	          }
	        }
	      }
	    }

	    // Rule 2E: Move normal path segment to output
	    if ((nextSlash = input.indexOf('/', 1)) === -1) {
	      output.push(input);
	      break
	    } else {
	      output.push(input.slice(0, nextSlash));
	      input = input.slice(nextSlash);
	    }
	  }

	  return output.join('')
	}

	/**
	 * @param {import('../types/index').URIComponent} component
	 * @param {boolean} esc
	 * @returns {import('../types/index').URIComponent}
	 */
	function normalizeComponentEncoding (component, esc) {
	  const func = esc !== true ? escape : unescape;
	  if (component.scheme !== undefined) {
	    component.scheme = func(component.scheme);
	  }
	  if (component.userinfo !== undefined) {
	    component.userinfo = func(component.userinfo);
	  }
	  if (component.host !== undefined) {
	    component.host = func(component.host);
	  }
	  if (component.path !== undefined) {
	    component.path = func(component.path);
	  }
	  if (component.query !== undefined) {
	    component.query = func(component.query);
	  }
	  if (component.fragment !== undefined) {
	    component.fragment = func(component.fragment);
	  }
	  return component
	}

	/**
	 * @param {import('../types/index').URIComponent} component
	 * @returns {string|undefined}
	 */
	function recomposeAuthority (component) {
	  const uriTokens = [];

	  if (component.userinfo !== undefined) {
	    uriTokens.push(component.userinfo);
	    uriTokens.push('@');
	  }

	  if (component.host !== undefined) {
	    let host = unescape(component.host);
	    if (!isIPv4(host)) {
	      const ipV6res = normalizeIPv6(host);
	      if (ipV6res.isIPV6 === true) {
	        host = `[${ipV6res.escapedHost}]`;
	      } else {
	        host = component.host;
	      }
	    }
	    uriTokens.push(host);
	  }

	  if (typeof component.port === 'number' || typeof component.port === 'string') {
	    uriTokens.push(':');
	    uriTokens.push(String(component.port));
	  }

	  return uriTokens.length ? uriTokens.join('') : undefined
	}
	utils$1 = {
	  nonSimpleDomain,
	  recomposeAuthority,
	  normalizeComponentEncoding,
	  removeDotSegments,
	  isIPv4,
	  isUUID,
	  normalizeIPv6,
	  stringArrayToHexStripped
	};
	return utils$1;
}

var schemes;
var hasRequiredSchemes;

function requireSchemes () {
	if (hasRequiredSchemes) return schemes;
	hasRequiredSchemes = 1;

	const { isUUID } = requireUtils$1();
	const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;

	const supportedSchemeNames = /** @type {const} */ (['http', 'https', 'ws',
	  'wss', 'urn', 'urn:uuid']);

	/** @typedef {supportedSchemeNames[number]} SchemeName */

	/**
	 * @param {string} name
	 * @returns {name is SchemeName}
	 */
	function isValidSchemeName (name) {
	  return supportedSchemeNames.indexOf(/** @type {*} */ (name)) !== -1
	}

	/**
	 * @callback SchemeFn
	 * @param {import('../types/index').URIComponent} component
	 * @param {import('../types/index').Options} options
	 * @returns {import('../types/index').URIComponent}
	 */

	/**
	 * @typedef {Object} SchemeHandler
	 * @property {SchemeName} scheme - The scheme name.
	 * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts.
	 * @property {SchemeFn} parse - Function to parse the URI component for this scheme.
	 * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme.
	 * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme.
	 * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths.
	 * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode.
	 */

	/**
	 * @param {import('../types/index').URIComponent} wsComponent
	 * @returns {boolean}
	 */
	function wsIsSecure (wsComponent) {
	  if (wsComponent.secure === true) {
	    return true
	  } else if (wsComponent.secure === false) {
	    return false
	  } else if (wsComponent.scheme) {
	    return (
	      wsComponent.scheme.length === 3 &&
	      (wsComponent.scheme[0] === 'w' || wsComponent.scheme[0] === 'W') &&
	      (wsComponent.scheme[1] === 's' || wsComponent.scheme[1] === 'S') &&
	      (wsComponent.scheme[2] === 's' || wsComponent.scheme[2] === 'S')
	    )
	  } else {
	    return false
	  }
	}

	/** @type {SchemeFn} */
	function httpParse (component) {
	  if (!component.host) {
	    component.error = component.error || 'HTTP URIs must have a host.';
	  }

	  return component
	}

	/** @type {SchemeFn} */
	function httpSerialize (component) {
	  const secure = String(component.scheme).toLowerCase() === 'https';

	  // normalize the default port
	  if (component.port === (secure ? 443 : 80) || component.port === '') {
	    component.port = undefined;
	  }

	  // normalize the empty path
	  if (!component.path) {
	    component.path = '/';
	  }

	  // NOTE: We do not parse query strings for HTTP URIs
	  // as WWW Form Url Encoded query strings are part of the HTML4+ spec,
	  // and not the HTTP spec.

	  return component
	}

	/** @type {SchemeFn} */
	function wsParse (wsComponent) {
	// indicate if the secure flag is set
	  wsComponent.secure = wsIsSecure(wsComponent);

	  // construct resouce name
	  wsComponent.resourceName = (wsComponent.path || '/') + (wsComponent.query ? '?' + wsComponent.query : '');
	  wsComponent.path = undefined;
	  wsComponent.query = undefined;

	  return wsComponent
	}

	/** @type {SchemeFn} */
	function wsSerialize (wsComponent) {
	// normalize the default port
	  if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === '') {
	    wsComponent.port = undefined;
	  }

	  // ensure scheme matches secure flag
	  if (typeof wsComponent.secure === 'boolean') {
	    wsComponent.scheme = (wsComponent.secure ? 'wss' : 'ws');
	    wsComponent.secure = undefined;
	  }

	  // reconstruct path from resource name
	  if (wsComponent.resourceName) {
	    const [path, query] = wsComponent.resourceName.split('?');
	    wsComponent.path = (path && path !== '/' ? path : undefined);
	    wsComponent.query = query;
	    wsComponent.resourceName = undefined;
	  }

	  // forbid fragment component
	  wsComponent.fragment = undefined;

	  return wsComponent
	}

	/** @type {SchemeFn} */
	function urnParse (urnComponent, options) {
	  if (!urnComponent.path) {
	    urnComponent.error = 'URN can not be parsed';
	    return urnComponent
	  }
	  const matches = urnComponent.path.match(URN_REG);
	  if (matches) {
	    const scheme = options.scheme || urnComponent.scheme || 'urn';
	    urnComponent.nid = matches[1].toLowerCase();
	    urnComponent.nss = matches[2];
	    const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`;
	    const schemeHandler = getSchemeHandler(urnScheme);
	    urnComponent.path = undefined;

	    if (schemeHandler) {
	      urnComponent = schemeHandler.parse(urnComponent, options);
	    }
	  } else {
	    urnComponent.error = urnComponent.error || 'URN can not be parsed.';
	  }

	  return urnComponent
	}

	/** @type {SchemeFn} */
	function urnSerialize (urnComponent, options) {
	  if (urnComponent.nid === undefined) {
	    throw new Error('URN without nid cannot be serialized')
	  }
	  const scheme = options.scheme || urnComponent.scheme || 'urn';
	  const nid = urnComponent.nid.toLowerCase();
	  const urnScheme = `${scheme}:${options.nid || nid}`;
	  const schemeHandler = getSchemeHandler(urnScheme);

	  if (schemeHandler) {
	    urnComponent = schemeHandler.serialize(urnComponent, options);
	  }

	  const uriComponent = urnComponent;
	  const nss = urnComponent.nss;
	  uriComponent.path = `${nid || options.nid}:${nss}`;

	  options.skipEscape = true;
	  return uriComponent
	}

	/** @type {SchemeFn} */
	function urnuuidParse (urnComponent, options) {
	  const uuidComponent = urnComponent;
	  uuidComponent.uuid = uuidComponent.nss;
	  uuidComponent.nss = undefined;

	  if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {
	    uuidComponent.error = uuidComponent.error || 'UUID is not valid.';
	  }

	  return uuidComponent
	}

	/** @type {SchemeFn} */
	function urnuuidSerialize (uuidComponent) {
	  const urnComponent = uuidComponent;
	  // normalize UUID
	  urnComponent.nss = (uuidComponent.uuid || '').toLowerCase();
	  return urnComponent
	}

	const http = /** @type {SchemeHandler} */ ({
	  scheme: 'http',
	  domainHost: true,
	  parse: httpParse,
	  serialize: httpSerialize
	});

	const https = /** @type {SchemeHandler} */ ({
	  scheme: 'https',
	  domainHost: http.domainHost,
	  parse: httpParse,
	  serialize: httpSerialize
	});

	const ws = /** @type {SchemeHandler} */ ({
	  scheme: 'ws',
	  domainHost: true,
	  parse: wsParse,
	  serialize: wsSerialize
	});

	const wss = /** @type {SchemeHandler} */ ({
	  scheme: 'wss',
	  domainHost: ws.domainHost,
	  parse: ws.parse,
	  serialize: ws.serialize
	});

	const urn = /** @type {SchemeHandler} */ ({
	  scheme: 'urn',
	  parse: urnParse,
	  serialize: urnSerialize,
	  skipNormalize: true
	});

	const urnuuid = /** @type {SchemeHandler} */ ({
	  scheme: 'urn:uuid',
	  parse: urnuuidParse,
	  serialize: urnuuidSerialize,
	  skipNormalize: true
	});

	const SCHEMES = /** @type {Record<SchemeName, SchemeHandler>} */ ({
	  http,
	  https,
	  ws,
	  wss,
	  urn,
	  'urn:uuid': urnuuid
	});

	Object.setPrototypeOf(SCHEMES, null);

	/**
	 * @param {string|undefined} scheme
	 * @returns {SchemeHandler|undefined}
	 */
	function getSchemeHandler (scheme) {
	  return (
	    scheme && (
	      SCHEMES[/** @type {SchemeName} */ (scheme)] ||
	      SCHEMES[/** @type {SchemeName} */(scheme.toLowerCase())])
	  ) ||
	    undefined
	}

	schemes = {
	  wsIsSecure,
	  SCHEMES,
	  isValidSchemeName,
	  getSchemeHandler,
	};
	return schemes;
}

var hasRequiredFastUri;

function requireFastUri () {
	if (hasRequiredFastUri) return fastUri.exports;
	hasRequiredFastUri = 1;

	const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = requireUtils$1();
	const { SCHEMES, getSchemeHandler } = requireSchemes();

	/**
	 * @template {import('./types/index').URIComponent|string} T
	 * @param {T} uri
	 * @param {import('./types/index').Options} [options]
	 * @returns {T}
	 */
	function normalize (uri, options) {
	  if (typeof uri === 'string') {
	    uri = /** @type {T} */ (serialize(parse(uri, options), options));
	  } else if (typeof uri === 'object') {
	    uri = /** @type {T} */ (parse(serialize(uri, options), options));
	  }
	  return uri
	}

	/**
	 * @param {string} baseURI
	 * @param {string} relativeURI
	 * @param {import('./types/index').Options} [options]
	 * @returns {string}
	 */
	function resolve (baseURI, relativeURI, options) {
	  const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' };
	  const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true);
	  schemelessOptions.skipEscape = true;
	  return serialize(resolved, schemelessOptions)
	}

	/**
	 * @param {import ('./types/index').URIComponent} base
	 * @param {import ('./types/index').URIComponent} relative
	 * @param {import('./types/index').Options} [options]
	 * @param {boolean} [skipNormalization=false]
	 * @returns {import ('./types/index').URIComponent}
	 */
	function resolveComponent (base, relative, options, skipNormalization) {
	  /** @type {import('./types/index').URIComponent} */
	  const target = {};
	  if (!skipNormalization) {
	    base = parse(serialize(base, options), options); // normalize base component
	    relative = parse(serialize(relative, options), options); // normalize relative component
	  }
	  options = options || {};

	  if (!options.tolerant && relative.scheme) {
	    target.scheme = relative.scheme;
	    // target.authority = relative.authority;
	    target.userinfo = relative.userinfo;
	    target.host = relative.host;
	    target.port = relative.port;
	    target.path = removeDotSegments(relative.path || '');
	    target.query = relative.query;
	  } else {
	    if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {
	      // target.authority = relative.authority;
	      target.userinfo = relative.userinfo;
	      target.host = relative.host;
	      target.port = relative.port;
	      target.path = removeDotSegments(relative.path || '');
	      target.query = relative.query;
	    } else {
	      if (!relative.path) {
	        target.path = base.path;
	        if (relative.query !== undefined) {
	          target.query = relative.query;
	        } else {
	          target.query = base.query;
	        }
	      } else {
	        if (relative.path[0] === '/') {
	          target.path = removeDotSegments(relative.path);
	        } else {
	          if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {
	            target.path = '/' + relative.path;
	          } else if (!base.path) {
	            target.path = relative.path;
	          } else {
	            target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path;
	          }
	          target.path = removeDotSegments(target.path);
	        }
	        target.query = relative.query;
	      }
	      // target.authority = base.authority;
	      target.userinfo = base.userinfo;
	      target.host = base.host;
	      target.port = base.port;
	    }
	    target.scheme = base.scheme;
	  }

	  target.fragment = relative.fragment;

	  return target
	}

	/**
	 * @param {import ('./types/index').URIComponent|string} uriA
	 * @param {import ('./types/index').URIComponent|string} uriB
	 * @param {import ('./types/index').Options} options
	 * @returns {boolean}
	 */
	function equal (uriA, uriB, options) {
	  if (typeof uriA === 'string') {
	    uriA = unescape(uriA);
	    uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { ...options, skipEscape: true });
	  } else if (typeof uriA === 'object') {
	    uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true });
	  }

	  if (typeof uriB === 'string') {
	    uriB = unescape(uriB);
	    uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { ...options, skipEscape: true });
	  } else if (typeof uriB === 'object') {
	    uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true });
	  }

	  return uriA.toLowerCase() === uriB.toLowerCase()
	}

	/**
	 * @param {Readonly<import('./types/index').URIComponent>} cmpts
	 * @param {import('./types/index').Options} [opts]
	 * @returns {string}
	 */
	function serialize (cmpts, opts) {
	  const component = {
	    host: cmpts.host,
	    scheme: cmpts.scheme,
	    userinfo: cmpts.userinfo,
	    port: cmpts.port,
	    path: cmpts.path,
	    query: cmpts.query,
	    nid: cmpts.nid,
	    nss: cmpts.nss,
	    uuid: cmpts.uuid,
	    fragment: cmpts.fragment,
	    reference: cmpts.reference,
	    resourceName: cmpts.resourceName,
	    secure: cmpts.secure,
	    error: ''
	  };
	  const options = Object.assign({}, opts);
	  const uriTokens = [];

	  // find scheme handler
	  const schemeHandler = getSchemeHandler(options.scheme || component.scheme);

	  // perform scheme specific serialization
	  if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);

	  if (component.path !== undefined) {
	    if (!options.skipEscape) {
	      component.path = escape(component.path);

	      if (component.scheme !== undefined) {
	        component.path = component.path.split('%3A').join(':');
	      }
	    } else {
	      component.path = unescape(component.path);
	    }
	  }

	  if (options.reference !== 'suffix' && component.scheme) {
	    uriTokens.push(component.scheme, ':');
	  }

	  const authority = recomposeAuthority(component);
	  if (authority !== undefined) {
	    if (options.reference !== 'suffix') {
	      uriTokens.push('//');
	    }

	    uriTokens.push(authority);

	    if (component.path && component.path[0] !== '/') {
	      uriTokens.push('/');
	    }
	  }
	  if (component.path !== undefined) {
	    let s = component.path;

	    if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
	      s = removeDotSegments(s);
	    }

	    if (
	      authority === undefined &&
	      s[0] === '/' &&
	      s[1] === '/'
	    ) {
	      // don't allow the path to start with "//"
	      s = '/%2F' + s.slice(2);
	    }

	    uriTokens.push(s);
	  }

	  if (component.query !== undefined) {
	    uriTokens.push('?', component.query);
	  }

	  if (component.fragment !== undefined) {
	    uriTokens.push('#', component.fragment);
	  }
	  return uriTokens.join('')
	}

	const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;

	/**
	 * @param {string} uri
	 * @param {import('./types/index').Options} [opts]
	 * @returns
	 */
	function parse (uri, opts) {
	  const options = Object.assign({}, opts);
	  /** @type {import('./types/index').URIComponent} */
	  const parsed = {
	    scheme: undefined,
	    userinfo: undefined,
	    host: '',
	    port: undefined,
	    path: '',
	    query: undefined,
	    fragment: undefined
	  };

	  let isIP = false;
	  if (options.reference === 'suffix') {
	    if (options.scheme) {
	      uri = options.scheme + ':' + uri;
	    } else {
	      uri = '//' + uri;
	    }
	  }

	  const matches = uri.match(URI_PARSE);

	  if (matches) {
	    // store each component
	    parsed.scheme = matches[1];
	    parsed.userinfo = matches[3];
	    parsed.host = matches[4];
	    parsed.port = parseInt(matches[5], 10);
	    parsed.path = matches[6] || '';
	    parsed.query = matches[7];
	    parsed.fragment = matches[8];

	    // fix port number
	    if (isNaN(parsed.port)) {
	      parsed.port = matches[5];
	    }
	    if (parsed.host) {
	      const ipv4result = isIPv4(parsed.host);
	      if (ipv4result === false) {
	        const ipv6result = normalizeIPv6(parsed.host);
	        parsed.host = ipv6result.host.toLowerCase();
	        isIP = ipv6result.isIPV6;
	      } else {
	        isIP = true;
	      }
	    }
	    if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) {
	      parsed.reference = 'same-document';
	    } else if (parsed.scheme === undefined) {
	      parsed.reference = 'relative';
	    } else if (parsed.fragment === undefined) {
	      parsed.reference = 'absolute';
	    } else {
	      parsed.reference = 'uri';
	    }

	    // check for reference errors
	    if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) {
	      parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.';
	    }

	    // find scheme handler
	    const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);

	    // check if scheme can't handle IRIs
	    if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
	      // if host component is a domain name
	      if (parsed.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && isIP === false && nonSimpleDomain(parsed.host)) {
	        // convert Unicode IDN -> ASCII IDN
	        try {
	          parsed.host = URL.domainToASCII(parsed.host.toLowerCase());
	        } catch (e) {
	          parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
	        }
	      }
	      // convert IRI -> URI
	    }

	    if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {
	      if (uri.indexOf('%') !== -1) {
	        if (parsed.scheme !== undefined) {
	          parsed.scheme = unescape(parsed.scheme);
	        }
	        if (parsed.host !== undefined) {
	          parsed.host = unescape(parsed.host);
	        }
	      }
	      if (parsed.path) {
	        parsed.path = escape(unescape(parsed.path));
	      }
	      if (parsed.fragment) {
	        parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment));
	      }
	    }

	    // perform scheme specific parsing
	    if (schemeHandler && schemeHandler.parse) {
	      schemeHandler.parse(parsed, options);
	    }
	  } else {
	    parsed.error = parsed.error || 'URI can not be parsed.';
	  }
	  return parsed
	}

	const fastUri$1 = {
	  SCHEMES,
	  normalize,
	  resolve,
	  resolveComponent,
	  equal,
	  serialize,
	  parse
	};

	fastUri.exports = fastUri$1;
	fastUri.exports.default = fastUri$1;
	fastUri.exports.fastUri = fastUri$1;
	return fastUri.exports;
}

var hasRequiredUri;

function requireUri () {
	if (hasRequiredUri) return uri;
	hasRequiredUri = 1;
	Object.defineProperty(uri, "__esModule", { value: true });
	const uri$1 = requireFastUri();
	uri$1.code = 'require("ajv/dist/runtime/uri").default';
	uri.default = uri$1;
	
	return uri;
}

var hasRequiredCore$1;

function requireCore$1 () {
	if (hasRequiredCore$1) return core$1;
	hasRequiredCore$1 = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.CodeGen = exports$1.Name = exports$1.nil = exports$1.stringify = exports$1.str = exports$1._ = exports$1.KeywordCxt = void 0;
		var validate_1 = requireValidate();
		Object.defineProperty(exports$1, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
		var codegen_1 = requireCodegen();
		Object.defineProperty(exports$1, "_", { enumerable: true, get: function () { return codegen_1._; } });
		Object.defineProperty(exports$1, "str", { enumerable: true, get: function () { return codegen_1.str; } });
		Object.defineProperty(exports$1, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
		Object.defineProperty(exports$1, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
		Object.defineProperty(exports$1, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
		Object.defineProperty(exports$1, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
		const validation_error_1 = requireValidation_error();
		const ref_error_1 = requireRef_error();
		const rules_1 = requireRules();
		const compile_1 = requireCompile();
		const codegen_2 = requireCodegen();
		const resolve_1 = requireResolve();
		const dataType_1 = requireDataType();
		const util_1 = requireUtil$1();
		const $dataRefSchema = require$$9;
		const uri_1 = requireUri();
		const defaultRegExp = (str, flags) => new RegExp(str, flags);
		defaultRegExp.code = "new RegExp";
		const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
		const EXT_SCOPE_NAMES = new Set([
		    "validate",
		    "serialize",
		    "parse",
		    "wrapper",
		    "root",
		    "schema",
		    "keyword",
		    "pattern",
		    "formats",
		    "validate$data",
		    "func",
		    "obj",
		    "Error",
		]);
		const removedOptions = {
		    errorDataPath: "",
		    format: "`validateFormats: false` can be used instead.",
		    nullable: '"nullable" keyword is supported by default.',
		    jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
		    extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
		    missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
		    processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
		    sourceCode: "Use option `code: {source: true}`",
		    strictDefaults: "It is default now, see option `strict`.",
		    strictKeywords: "It is default now, see option `strict`.",
		    uniqueItems: '"uniqueItems" keyword is always validated.',
		    unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
		    cache: "Map is used as cache, schema object as key.",
		    serialize: "Map is used as cache, schema object as key.",
		    ajvErrors: "It is default now.",
		};
		const deprecatedOptions = {
		    ignoreKeywordsWithRef: "",
		    jsPropertySyntax: "",
		    unicode: '"minLength"/"maxLength" account for unicode characters by default.',
		};
		const MAX_EXPRESSION = 200;
		// eslint-disable-next-line complexity
		function requiredOptions(o) {
		    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
		    const s = o.strict;
		    const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
		    const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
		    const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
		    const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
		    return {
		        strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
		        strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
		        strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
		        strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
		        strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
		        code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
		        loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
		        loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
		        meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
		        messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
		        inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
		        schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
		        addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
		        validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
		        validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
		        unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
		        int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
		        uriResolver: uriResolver,
		    };
		}
		class Ajv {
		    constructor(opts = {}) {
		        this.schemas = {};
		        this.refs = {};
		        this.formats = {};
		        this._compilations = new Set();
		        this._loading = {};
		        this._cache = new Map();
		        opts = this.opts = { ...opts, ...requiredOptions(opts) };
		        const { es5, lines } = this.opts.code;
		        this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
		        this.logger = getLogger(opts.logger);
		        const formatOpt = opts.validateFormats;
		        opts.validateFormats = false;
		        this.RULES = (0, rules_1.getRules)();
		        checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
		        checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
		        this._metaOpts = getMetaSchemaOptions.call(this);
		        if (opts.formats)
		            addInitialFormats.call(this);
		        this._addVocabularies();
		        this._addDefaultMetaSchema();
		        if (opts.keywords)
		            addInitialKeywords.call(this, opts.keywords);
		        if (typeof opts.meta == "object")
		            this.addMetaSchema(opts.meta);
		        addInitialSchemas.call(this);
		        opts.validateFormats = formatOpt;
		    }
		    _addVocabularies() {
		        this.addKeyword("$async");
		    }
		    _addDefaultMetaSchema() {
		        const { $data, meta, schemaId } = this.opts;
		        let _dataRefSchema = $dataRefSchema;
		        if (schemaId === "id") {
		            _dataRefSchema = { ...$dataRefSchema };
		            _dataRefSchema.id = _dataRefSchema.$id;
		            delete _dataRefSchema.$id;
		        }
		        if (meta && $data)
		            this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
		    }
		    defaultMeta() {
		        const { meta, schemaId } = this.opts;
		        return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined);
		    }
		    validate(schemaKeyRef, // key, ref or schema object
		    // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
		    data // to be validated
		    ) {
		        let v;
		        if (typeof schemaKeyRef == "string") {
		            v = this.getSchema(schemaKeyRef);
		            if (!v)
		                throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
		        }
		        else {
		            v = this.compile(schemaKeyRef);
		        }
		        const valid = v(data);
		        if (!("$async" in v))
		            this.errors = v.errors;
		        return valid;
		    }
		    compile(schema, _meta) {
		        const sch = this._addSchema(schema, _meta);
		        return (sch.validate || this._compileSchemaEnv(sch));
		    }
		    compileAsync(schema, meta) {
		        if (typeof this.opts.loadSchema != "function") {
		            throw new Error("options.loadSchema should be a function");
		        }
		        const { loadSchema } = this.opts;
		        return runCompileAsync.call(this, schema, meta);
		        async function runCompileAsync(_schema, _meta) {
		            await loadMetaSchema.call(this, _schema.$schema);
		            const sch = this._addSchema(_schema, _meta);
		            return sch.validate || _compileAsync.call(this, sch);
		        }
		        async function loadMetaSchema($ref) {
		            if ($ref && !this.getSchema($ref)) {
		                await runCompileAsync.call(this, { $ref }, true);
		            }
		        }
		        async function _compileAsync(sch) {
		            try {
		                return this._compileSchemaEnv(sch);
		            }
		            catch (e) {
		                if (!(e instanceof ref_error_1.default))
		                    throw e;
		                checkLoaded.call(this, e);
		                await loadMissingSchema.call(this, e.missingSchema);
		                return _compileAsync.call(this, sch);
		            }
		        }
		        function checkLoaded({ missingSchema: ref, missingRef }) {
		            if (this.refs[ref]) {
		                throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
		            }
		        }
		        async function loadMissingSchema(ref) {
		            const _schema = await _loadSchema.call(this, ref);
		            if (!this.refs[ref])
		                await loadMetaSchema.call(this, _schema.$schema);
		            if (!this.refs[ref])
		                this.addSchema(_schema, ref, meta);
		        }
		        async function _loadSchema(ref) {
		            const p = this._loading[ref];
		            if (p)
		                return p;
		            try {
		                return await (this._loading[ref] = loadSchema(ref));
		            }
		            finally {
		                delete this._loading[ref];
		            }
		        }
		    }
		    // Adds schema to the instance
		    addSchema(schema, // If array is passed, `key` will be ignored
		    key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
		    _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
		    _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
		    ) {
		        if (Array.isArray(schema)) {
		            for (const sch of schema)
		                this.addSchema(sch, undefined, _meta, _validateSchema);
		            return this;
		        }
		        let id;
		        if (typeof schema === "object") {
		            const { schemaId } = this.opts;
		            id = schema[schemaId];
		            if (id !== undefined && typeof id != "string") {
		                throw new Error(`schema ${schemaId} must be string`);
		            }
		        }
		        key = (0, resolve_1.normalizeId)(key || id);
		        this._checkUnique(key);
		        this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
		        return this;
		    }
		    // Add schema that will be used to validate other schemas
		    // options in META_IGNORE_OPTIONS are alway set to false
		    addMetaSchema(schema, key, // schema key
		    _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
		    ) {
		        this.addSchema(schema, key, true, _validateSchema);
		        return this;
		    }
		    //  Validate schema against its meta-schema
		    validateSchema(schema, throwOrLogError) {
		        if (typeof schema == "boolean")
		            return true;
		        let $schema;
		        $schema = schema.$schema;
		        if ($schema !== undefined && typeof $schema != "string") {
		            throw new Error("$schema must be a string");
		        }
		        $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
		        if (!$schema) {
		            this.logger.warn("meta-schema not available");
		            this.errors = null;
		            return true;
		        }
		        const valid = this.validate($schema, schema);
		        if (!valid && throwOrLogError) {
		            const message = "schema is invalid: " + this.errorsText();
		            if (this.opts.validateSchema === "log")
		                this.logger.error(message);
		            else
		                throw new Error(message);
		        }
		        return valid;
		    }
		    // Get compiled schema by `key` or `ref`.
		    // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
		    getSchema(keyRef) {
		        let sch;
		        while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
		            keyRef = sch;
		        if (sch === undefined) {
		            const { schemaId } = this.opts;
		            const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
		            sch = compile_1.resolveSchema.call(this, root, keyRef);
		            if (!sch)
		                return;
		            this.refs[keyRef] = sch;
		        }
		        return (sch.validate || this._compileSchemaEnv(sch));
		    }
		    // Remove cached schema(s).
		    // If no parameter is passed all schemas but meta-schemas are removed.
		    // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
		    // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
		    removeSchema(schemaKeyRef) {
		        if (schemaKeyRef instanceof RegExp) {
		            this._removeAllSchemas(this.schemas, schemaKeyRef);
		            this._removeAllSchemas(this.refs, schemaKeyRef);
		            return this;
		        }
		        switch (typeof schemaKeyRef) {
		            case "undefined":
		                this._removeAllSchemas(this.schemas);
		                this._removeAllSchemas(this.refs);
		                this._cache.clear();
		                return this;
		            case "string": {
		                const sch = getSchEnv.call(this, schemaKeyRef);
		                if (typeof sch == "object")
		                    this._cache.delete(sch.schema);
		                delete this.schemas[schemaKeyRef];
		                delete this.refs[schemaKeyRef];
		                return this;
		            }
		            case "object": {
		                const cacheKey = schemaKeyRef;
		                this._cache.delete(cacheKey);
		                let id = schemaKeyRef[this.opts.schemaId];
		                if (id) {
		                    id = (0, resolve_1.normalizeId)(id);
		                    delete this.schemas[id];
		                    delete this.refs[id];
		                }
		                return this;
		            }
		            default:
		                throw new Error("ajv.removeSchema: invalid parameter");
		        }
		    }
		    // add "vocabulary" - a collection of keywords
		    addVocabulary(definitions) {
		        for (const def of definitions)
		            this.addKeyword(def);
		        return this;
		    }
		    addKeyword(kwdOrDef, def // deprecated
		    ) {
		        let keyword;
		        if (typeof kwdOrDef == "string") {
		            keyword = kwdOrDef;
		            if (typeof def == "object") {
		                this.logger.warn("these parameters are deprecated, see docs for addKeyword");
		                def.keyword = keyword;
		            }
		        }
		        else if (typeof kwdOrDef == "object" && def === undefined) {
		            def = kwdOrDef;
		            keyword = def.keyword;
		            if (Array.isArray(keyword) && !keyword.length) {
		                throw new Error("addKeywords: keyword must be string or non-empty array");
		            }
		        }
		        else {
		            throw new Error("invalid addKeywords parameters");
		        }
		        checkKeyword.call(this, keyword, def);
		        if (!def) {
		            (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
		            return this;
		        }
		        keywordMetaschema.call(this, def);
		        const definition = {
		            ...def,
		            type: (0, dataType_1.getJSONTypes)(def.type),
		            schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),
		        };
		        (0, util_1.eachItem)(keyword, definition.type.length === 0
		            ? (k) => addRule.call(this, k, definition)
		            : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
		        return this;
		    }
		    getKeyword(keyword) {
		        const rule = this.RULES.all[keyword];
		        return typeof rule == "object" ? rule.definition : !!rule;
		    }
		    // Remove keyword
		    removeKeyword(keyword) {
		        // TODO return type should be Ajv
		        const { RULES } = this;
		        delete RULES.keywords[keyword];
		        delete RULES.all[keyword];
		        for (const group of RULES.rules) {
		            const i = group.rules.findIndex((rule) => rule.keyword === keyword);
		            if (i >= 0)
		                group.rules.splice(i, 1);
		        }
		        return this;
		    }
		    // Add format
		    addFormat(name, format) {
		        if (typeof format == "string")
		            format = new RegExp(format);
		        this.formats[name] = format;
		        return this;
		    }
		    errorsText(errors = this.errors, // optional array of validation errors
		    { separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar`
		    ) {
		        if (!errors || errors.length === 0)
		            return "No errors";
		        return errors
		            .map((e) => `${dataVar}${e.instancePath} ${e.message}`)
		            .reduce((text, msg) => text + separator + msg);
		    }
		    $dataMetaSchema(metaSchema, keywordsJsonPointers) {
		        const rules = this.RULES.all;
		        metaSchema = JSON.parse(JSON.stringify(metaSchema));
		        for (const jsonPointer of keywordsJsonPointers) {
		            const segments = jsonPointer.split("/").slice(1); // first segment is an empty string
		            let keywords = metaSchema;
		            for (const seg of segments)
		                keywords = keywords[seg];
		            for (const key in rules) {
		                const rule = rules[key];
		                if (typeof rule != "object")
		                    continue;
		                const { $data } = rule.definition;
		                const schema = keywords[key];
		                if ($data && schema)
		                    keywords[key] = schemaOrData(schema);
		            }
		        }
		        return metaSchema;
		    }
		    _removeAllSchemas(schemas, regex) {
		        for (const keyRef in schemas) {
		            const sch = schemas[keyRef];
		            if (!regex || regex.test(keyRef)) {
		                if (typeof sch == "string") {
		                    delete schemas[keyRef];
		                }
		                else if (sch && !sch.meta) {
		                    this._cache.delete(sch.schema);
		                    delete schemas[keyRef];
		                }
		            }
		        }
		    }
		    _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
		        let id;
		        const { schemaId } = this.opts;
		        if (typeof schema == "object") {
		            id = schema[schemaId];
		        }
		        else {
		            if (this.opts.jtd)
		                throw new Error("schema must be object");
		            else if (typeof schema != "boolean")
		                throw new Error("schema must be object or boolean");
		        }
		        let sch = this._cache.get(schema);
		        if (sch !== undefined)
		            return sch;
		        baseId = (0, resolve_1.normalizeId)(id || baseId);
		        const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
		        sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
		        this._cache.set(sch.schema, sch);
		        if (addSchema && !baseId.startsWith("#")) {
		            // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
		            if (baseId)
		                this._checkUnique(baseId);
		            this.refs[baseId] = sch;
		        }
		        if (validateSchema)
		            this.validateSchema(schema, true);
		        return sch;
		    }
		    _checkUnique(id) {
		        if (this.schemas[id] || this.refs[id]) {
		            throw new Error(`schema with key or id "${id}" already exists`);
		        }
		    }
		    _compileSchemaEnv(sch) {
		        if (sch.meta)
		            this._compileMetaSchema(sch);
		        else
		            compile_1.compileSchema.call(this, sch);
		        /* istanbul ignore if */
		        if (!sch.validate)
		            throw new Error("ajv implementation error");
		        return sch.validate;
		    }
		    _compileMetaSchema(sch) {
		        const currentOpts = this.opts;
		        this.opts = this._metaOpts;
		        try {
		            compile_1.compileSchema.call(this, sch);
		        }
		        finally {
		            this.opts = currentOpts;
		        }
		    }
		}
		Ajv.ValidationError = validation_error_1.default;
		Ajv.MissingRefError = ref_error_1.default;
		exports$1.default = Ajv;
		function checkOptions(checkOpts, options, msg, log = "error") {
		    for (const key in checkOpts) {
		        const opt = key;
		        if (opt in options)
		            this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
		    }
		}
		function getSchEnv(keyRef) {
		    keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line
		    return this.schemas[keyRef] || this.refs[keyRef];
		}
		function addInitialSchemas() {
		    const optsSchemas = this.opts.schemas;
		    if (!optsSchemas)
		        return;
		    if (Array.isArray(optsSchemas))
		        this.addSchema(optsSchemas);
		    else
		        for (const key in optsSchemas)
		            this.addSchema(optsSchemas[key], key);
		}
		function addInitialFormats() {
		    for (const name in this.opts.formats) {
		        const format = this.opts.formats[name];
		        if (format)
		            this.addFormat(name, format);
		    }
		}
		function addInitialKeywords(defs) {
		    if (Array.isArray(defs)) {
		        this.addVocabulary(defs);
		        return;
		    }
		    this.logger.warn("keywords option as map is deprecated, pass array");
		    for (const keyword in defs) {
		        const def = defs[keyword];
		        if (!def.keyword)
		            def.keyword = keyword;
		        this.addKeyword(def);
		    }
		}
		function getMetaSchemaOptions() {
		    const metaOpts = { ...this.opts };
		    for (const opt of META_IGNORE_OPTIONS)
		        delete metaOpts[opt];
		    return metaOpts;
		}
		const noLogs = { log() { }, warn() { }, error() { } };
		function getLogger(logger) {
		    if (logger === false)
		        return noLogs;
		    if (logger === undefined)
		        return console;
		    if (logger.log && logger.warn && logger.error)
		        return logger;
		    throw new Error("logger must implement log, warn and error methods");
		}
		const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
		function checkKeyword(keyword, def) {
		    const { RULES } = this;
		    (0, util_1.eachItem)(keyword, (kwd) => {
		        if (RULES.keywords[kwd])
		            throw new Error(`Keyword ${kwd} is already defined`);
		        if (!KEYWORD_NAME.test(kwd))
		            throw new Error(`Keyword ${kwd} has invalid name`);
		    });
		    if (!def)
		        return;
		    if (def.$data && !("code" in def || "validate" in def)) {
		        throw new Error('$data keyword must have "code" or "validate" function');
		    }
		}
		function addRule(keyword, definition, dataType) {
		    var _a;
		    const post = definition === null || definition === void 0 ? void 0 : definition.post;
		    if (dataType && post)
		        throw new Error('keyword with "post" flag cannot have "type"');
		    const { RULES } = this;
		    let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
		    if (!ruleGroup) {
		        ruleGroup = { type: dataType, rules: [] };
		        RULES.rules.push(ruleGroup);
		    }
		    RULES.keywords[keyword] = true;
		    if (!definition)
		        return;
		    const rule = {
		        keyword,
		        definition: {
		            ...definition,
		            type: (0, dataType_1.getJSONTypes)(definition.type),
		            schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),
		        },
		    };
		    if (definition.before)
		        addBeforeRule.call(this, ruleGroup, rule, definition.before);
		    else
		        ruleGroup.rules.push(rule);
		    RULES.all[keyword] = rule;
		    (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
		}
		function addBeforeRule(ruleGroup, rule, before) {
		    const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
		    if (i >= 0) {
		        ruleGroup.rules.splice(i, 0, rule);
		    }
		    else {
		        ruleGroup.rules.push(rule);
		        this.logger.warn(`rule ${before} is not defined`);
		    }
		}
		function keywordMetaschema(def) {
		    let { metaSchema } = def;
		    if (metaSchema === undefined)
		        return;
		    if (def.$data && this.opts.$data)
		        metaSchema = schemaOrData(metaSchema);
		    def.validateSchema = this.compile(metaSchema, true);
		}
		const $dataRef = {
		    $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
		};
		function schemaOrData(schema) {
		    return { anyOf: [schema, $dataRef] };
		}
		
	} (core$1));
	return core$1;
}

var draft7 = {};

var core = {};

var id = {};

var hasRequiredId;

function requireId () {
	if (hasRequiredId) return id;
	hasRequiredId = 1;
	Object.defineProperty(id, "__esModule", { value: true });
	const def = {
	    keyword: "id",
	    code() {
	        throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
	    },
	};
	id.default = def;
	
	return id;
}

var ref = {};

var hasRequiredRef;

function requireRef () {
	if (hasRequiredRef) return ref;
	hasRequiredRef = 1;
	Object.defineProperty(ref, "__esModule", { value: true });
	ref.callRef = ref.getValidate = void 0;
	const ref_error_1 = requireRef_error();
	const code_1 = requireCode();
	const codegen_1 = requireCodegen();
	const names_1 = requireNames();
	const compile_1 = requireCompile();
	const util_1 = requireUtil$1();
	const def = {
	    keyword: "$ref",
	    schemaType: "string",
	    code(cxt) {
	        const { gen, schema: $ref, it } = cxt;
	        const { baseId, schemaEnv: env, validateName, opts, self } = it;
	        const { root } = env;
	        if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
	            return callRootRef();
	        const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);
	        if (schOrEnv === undefined)
	            throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
	        if (schOrEnv instanceof compile_1.SchemaEnv)
	            return callValidate(schOrEnv);
	        return inlineRefSchema(schOrEnv);
	        function callRootRef() {
	            if (env === root)
	                return callRef(cxt, validateName, env, env.$async);
	            const rootName = gen.scopeValue("root", { ref: root });
	            return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async);
	        }
	        function callValidate(sch) {
	            const v = getValidate(cxt, sch);
	            callRef(cxt, v, sch, sch.$async);
	        }
	        function inlineRefSchema(sch) {
	            const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
	            const valid = gen.name("valid");
	            const schCxt = cxt.subschema({
	                schema: sch,
	                dataTypes: [],
	                schemaPath: codegen_1.nil,
	                topSchemaRef: schName,
	                errSchemaPath: $ref,
	            }, valid);
	            cxt.mergeEvaluated(schCxt);
	            cxt.ok(valid);
	        }
	    },
	};
	function getValidate(cxt, sch) {
	    const { gen } = cxt;
	    return sch.validate
	        ? gen.scopeValue("validate", { ref: sch.validate })
	        : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.validate`;
	}
	ref.getValidate = getValidate;
	function callRef(cxt, v, sch, $async) {
	    const { gen, it } = cxt;
	    const { allErrors, schemaEnv: env, opts } = it;
	    const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
	    if ($async)
	        callAsyncRef();
	    else
	        callSyncRef();
	    function callAsyncRef() {
	        if (!env.$async)
	            throw new Error("async schema referenced by sync schema");
	        const valid = gen.let("valid");
	        gen.try(() => {
	            gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);
	            addEvaluatedFrom(v); // TODO will not work with async, it has to be returned with the result
	            if (!allErrors)
	                gen.assign(valid, true);
	        }, (e) => {
	            gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));
	            addErrorsFrom(e);
	            if (!allErrors)
	                gen.assign(valid, false);
	        });
	        cxt.ok(valid);
	    }
	    function callSyncRef() {
	        cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
	    }
	    function addErrorsFrom(source) {
	        const errs = (0, codegen_1._) `${source}.errors`;
	        gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); // TODO tagged
	        gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
	    }
	    function addEvaluatedFrom(source) {
	        var _a;
	        if (!it.opts.unevaluated)
	            return;
	        const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;
	        // TODO refactor
	        if (it.props !== true) {
	            if (schEvaluated && !schEvaluated.dynamicProps) {
	                if (schEvaluated.props !== undefined) {
	                    it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
	                }
	            }
	            else {
	                const props = gen.var("props", (0, codegen_1._) `${source}.evaluated.props`);
	                it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
	            }
	        }
	        if (it.items !== true) {
	            if (schEvaluated && !schEvaluated.dynamicItems) {
	                if (schEvaluated.items !== undefined) {
	                    it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
	                }
	            }
	            else {
	                const items = gen.var("items", (0, codegen_1._) `${source}.evaluated.items`);
	                it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
	            }
	        }
	    }
	}
	ref.callRef = callRef;
	ref.default = def;
	
	return ref;
}

var hasRequiredCore;

function requireCore () {
	if (hasRequiredCore) return core;
	hasRequiredCore = 1;
	Object.defineProperty(core, "__esModule", { value: true });
	const id_1 = requireId();
	const ref_1 = requireRef();
	const core$1 = [
	    "$schema",
	    "$id",
	    "$defs",
	    "$vocabulary",
	    { keyword: "$comment" },
	    "definitions",
	    id_1.default,
	    ref_1.default,
	];
	core.default = core$1;
	
	return core;
}

var validation = {};

var limitNumber = {};

var hasRequiredLimitNumber;

function requireLimitNumber () {
	if (hasRequiredLimitNumber) return limitNumber;
	hasRequiredLimitNumber = 1;
	Object.defineProperty(limitNumber, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const ops = codegen_1.operators;
	const KWDs = {
	    maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
	    minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
	    exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
	    exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE },
	};
	const error = {
	    message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`,
	    params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,
	};
	const def = {
	    keyword: Object.keys(KWDs),
	    type: "number",
	    schemaType: "number",
	    $data: true,
	    error,
	    code(cxt) {
	        const { keyword, data, schemaCode } = cxt;
	        cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
	    },
	};
	limitNumber.default = def;
	
	return limitNumber;
}

var multipleOf = {};

var hasRequiredMultipleOf;

function requireMultipleOf () {
	if (hasRequiredMultipleOf) return multipleOf;
	hasRequiredMultipleOf = 1;
	Object.defineProperty(multipleOf, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const error = {
	    message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`,
	    params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`,
	};
	const def = {
	    keyword: "multipleOf",
	    type: "number",
	    schemaType: "number",
	    $data: true,
	    error,
	    code(cxt) {
	        const { gen, data, schemaCode, it } = cxt;
	        // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)
	        const prec = it.opts.multipleOfPrecision;
	        const res = gen.let("res");
	        const invalid = prec
	            ? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`
	            : (0, codegen_1._) `${res} !== parseInt(${res})`;
	        cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
	    },
	};
	multipleOf.default = def;
	
	return multipleOf;
}

var limitLength = {};

var ucs2length = {};

var hasRequiredUcs2length;

function requireUcs2length () {
	if (hasRequiredUcs2length) return ucs2length;
	hasRequiredUcs2length = 1;
	Object.defineProperty(ucs2length, "__esModule", { value: true });
	// https://mathiasbynens.be/notes/javascript-encoding
	// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
	function ucs2length$1(str) {
	    const len = str.length;
	    let length = 0;
	    let pos = 0;
	    let value;
	    while (pos < len) {
	        length++;
	        value = str.charCodeAt(pos++);
	        if (value >= 0xd800 && value <= 0xdbff && pos < len) {
	            // high surrogate, and there is a next character
	            value = str.charCodeAt(pos);
	            if ((value & 0xfc00) === 0xdc00)
	                pos++; // low surrogate
	        }
	    }
	    return length;
	}
	ucs2length.default = ucs2length$1;
	ucs2length$1.code = 'require("ajv/dist/runtime/ucs2length").default';
	
	return ucs2length;
}

var hasRequiredLimitLength;

function requireLimitLength () {
	if (hasRequiredLimitLength) return limitLength;
	hasRequiredLimitLength = 1;
	Object.defineProperty(limitLength, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$1();
	const ucs2length_1 = requireUcs2length();
	const error = {
	    message({ keyword, schemaCode }) {
	        const comp = keyword === "maxLength" ? "more" : "fewer";
	        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`;
	    },
	    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
	};
	const def = {
	    keyword: ["maxLength", "minLength"],
	    type: "string",
	    schemaType: "number",
	    $data: true,
	    error,
	    code(cxt) {
	        const { keyword, data, schemaCode, it } = cxt;
	        const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
	        const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
	        cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`);
	    },
	};
	limitLength.default = def;
	
	return limitLength;
}

var pattern$1 = {};

var hasRequiredPattern;

function requirePattern () {
	if (hasRequiredPattern) return pattern$1;
	hasRequiredPattern = 1;
	Object.defineProperty(pattern$1, "__esModule", { value: true });
	const code_1 = requireCode();
	const codegen_1 = requireCodegen();
	const error = {
	    message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern "${schemaCode}"`,
	    params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`,
	};
	const def = {
	    keyword: "pattern",
	    type: "string",
	    schemaType: "string",
	    $data: true,
	    error,
	    code(cxt) {
	        const { data, $data, schema, schemaCode, it } = cxt;
	        // TODO regexp should be wrapped in try/catchs
	        const u = it.opts.unicodeRegExp ? "u" : "";
	        const regExp = $data ? (0, codegen_1._) `(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema);
	        cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`);
	    },
	};
	pattern$1.default = def;
	
	return pattern$1;
}

var limitProperties = {};

var hasRequiredLimitProperties;

function requireLimitProperties () {
	if (hasRequiredLimitProperties) return limitProperties;
	hasRequiredLimitProperties = 1;
	Object.defineProperty(limitProperties, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const error = {
	    message({ keyword, schemaCode }) {
	        const comp = keyword === "maxProperties" ? "more" : "fewer";
	        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`;
	    },
	    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
	};
	const def = {
	    keyword: ["maxProperties", "minProperties"],
	    type: "object",
	    schemaType: "number",
	    $data: true,
	    error,
	    code(cxt) {
	        const { keyword, data, schemaCode } = cxt;
	        const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
	        cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`);
	    },
	};
	limitProperties.default = def;
	
	return limitProperties;
}

var required = {};

var hasRequiredRequired;

function requireRequired () {
	if (hasRequiredRequired) return required;
	hasRequiredRequired = 1;
	Object.defineProperty(required, "__esModule", { value: true });
	const code_1 = requireCode();
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$1();
	const error = {
	    message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`,
	    params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`,
	};
	const def = {
	    keyword: "required",
	    type: "object",
	    schemaType: "array",
	    $data: true,
	    error,
	    code(cxt) {
	        const { gen, schema, schemaCode, data, $data, it } = cxt;
	        const { opts } = it;
	        if (!$data && schema.length === 0)
	            return;
	        const useLoop = schema.length >= opts.loopRequired;
	        if (it.allErrors)
	            allErrorsMode();
	        else
	            exitOnErrorMode();
	        if (opts.strictRequired) {
	            const props = cxt.parentSchema.properties;
	            const { definedProperties } = cxt.it;
	            for (const requiredKey of schema) {
	                if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) {
	                    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
	                    const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
	                    (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);
	                }
	            }
	        }
	        function allErrorsMode() {
	            if (useLoop || $data) {
	                cxt.block$data(codegen_1.nil, loopAllRequired);
	            }
	            else {
	                for (const prop of schema) {
	                    (0, code_1.checkReportMissingProp)(cxt, prop);
	                }
	            }
	        }
	        function exitOnErrorMode() {
	            const missing = gen.let("missing");
	            if (useLoop || $data) {
	                const valid = gen.let("valid", true);
	                cxt.block$data(valid, () => loopUntilMissing(missing, valid));
	                cxt.ok(valid);
	            }
	            else {
	                gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
	                (0, code_1.reportMissingProp)(cxt, missing);
	                gen.else();
	            }
	        }
	        function loopAllRequired() {
	            gen.forOf("prop", schemaCode, (prop) => {
	                cxt.setParams({ missingProperty: prop });
	                gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
	            });
	        }
	        function loopUntilMissing(missing, valid) {
	            cxt.setParams({ missingProperty: missing });
	            gen.forOf(missing, schemaCode, () => {
	                gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
	                gen.if((0, codegen_1.not)(valid), () => {
	                    cxt.error();
	                    gen.break();
	                });
	            }, codegen_1.nil);
	        }
	    },
	};
	required.default = def;
	
	return required;
}

var limitItems = {};

var hasRequiredLimitItems;

function requireLimitItems () {
	if (hasRequiredLimitItems) return limitItems;
	hasRequiredLimitItems = 1;
	Object.defineProperty(limitItems, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const error = {
	    message({ keyword, schemaCode }) {
	        const comp = keyword === "maxItems" ? "more" : "fewer";
	        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`;
	    },
	    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
	};
	const def = {
	    keyword: ["maxItems", "minItems"],
	    type: "array",
	    schemaType: "number",
	    $data: true,
	    error,
	    code(cxt) {
	        const { keyword, data, schemaCode } = cxt;
	        const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
	        cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`);
	    },
	};
	limitItems.default = def;
	
	return limitItems;
}

var uniqueItems = {};

var equal = {};

var hasRequiredEqual;

function requireEqual () {
	if (hasRequiredEqual) return equal;
	hasRequiredEqual = 1;
	Object.defineProperty(equal, "__esModule", { value: true });
	// https://github.com/ajv-validator/ajv/issues/889
	const equal$1 = requireFastDeepEqual();
	equal$1.code = 'require("ajv/dist/runtime/equal").default';
	equal.default = equal$1;
	
	return equal;
}

var hasRequiredUniqueItems;

function requireUniqueItems () {
	if (hasRequiredUniqueItems) return uniqueItems;
	hasRequiredUniqueItems = 1;
	Object.defineProperty(uniqueItems, "__esModule", { value: true });
	const dataType_1 = requireDataType();
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$1();
	const equal_1 = requireEqual();
	const error = {
	    message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
	    params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`,
	};
	const def = {
	    keyword: "uniqueItems",
	    type: "array",
	    schemaType: "boolean",
	    $data: true,
	    error,
	    code(cxt) {
	        const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
	        if (!$data && !schema)
	            return;
	        const valid = gen.let("valid");
	        const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
	        cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`);
	        cxt.ok(valid);
	        function validateUniqueItems() {
	            const i = gen.let("i", (0, codegen_1._) `${data}.length`);
	            const j = gen.let("j");
	            cxt.setParams({ i, j });
	            gen.assign(valid, true);
	            gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
	        }
	        function canOptimize() {
	            return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
	        }
	        function loopN(i, j) {
	            const item = gen.name("item");
	            const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
	            const indices = gen.const("indices", (0, codegen_1._) `{}`);
	            gen.for((0, codegen_1._) `;${i}--;`, () => {
	                gen.let(item, (0, codegen_1._) `${data}[${i}]`);
	                gen.if(wrongType, (0, codegen_1._) `continue`);
	                if (itemTypes.length > 1)
	                    gen.if((0, codegen_1._) `typeof ${item} == "string"`, (0, codegen_1._) `${item} += "_"`);
	                gen
	                    .if((0, codegen_1._) `typeof ${indices}[${item}] == "number"`, () => {
	                    gen.assign(j, (0, codegen_1._) `${indices}[${item}]`);
	                    cxt.error();
	                    gen.assign(valid, false).break();
	                })
	                    .code((0, codegen_1._) `${indices}[${item}] = ${i}`);
	            });
	        }
	        function loopN2(i, j) {
	            const eql = (0, util_1.useFunc)(gen, equal_1.default);
	            const outer = gen.name("outer");
	            gen.label(outer).for((0, codegen_1._) `;${i}--;`, () => gen.for((0, codegen_1._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._) `${eql}(${data}[${i}], ${data}[${j}])`, () => {
	                cxt.error();
	                gen.assign(valid, false).break(outer);
	            })));
	        }
	    },
	};
	uniqueItems.default = def;
	
	return uniqueItems;
}

var _const = {};

var hasRequired_const;

function require_const () {
	if (hasRequired_const) return _const;
	hasRequired_const = 1;
	Object.defineProperty(_const, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$1();
	const equal_1 = requireEqual();
	const error = {
	    message: "must be equal to constant",
	    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`,
	};
	const def = {
	    keyword: "const",
	    $data: true,
	    error,
	    code(cxt) {
	        const { gen, data, $data, schemaCode, schema } = cxt;
	        if ($data || (schema && typeof schema == "object")) {
	            cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
	        }
	        else {
	            cxt.fail((0, codegen_1._) `${schema} !== ${data}`);
	        }
	    },
	};
	_const.default = def;
	
	return _const;
}

var _enum = {};

var hasRequired_enum;

function require_enum () {
	if (hasRequired_enum) return _enum;
	hasRequired_enum = 1;
	Object.defineProperty(_enum, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$1();
	const equal_1 = requireEqual();
	const error = {
	    message: "must be equal to one of the allowed values",
	    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,
	};
	const def = {
	    keyword: "enum",
	    schemaType: "array",
	    $data: true,
	    error,
	    code(cxt) {
	        const { gen, data, $data, schema, schemaCode, it } = cxt;
	        if (!$data && schema.length === 0)
	            throw new Error("enum must have non-empty array");
	        const useLoop = schema.length >= it.opts.loopEnum;
	        let eql;
	        const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default)));
	        let valid;
	        if (useLoop || $data) {
	            valid = gen.let("valid");
	            cxt.block$data(valid, loopEnum);
	        }
	        else {
	            /* istanbul ignore if */
	            if (!Array.isArray(schema))
	                throw new Error("ajv implementation error");
	            const vSchema = gen.const("vSchema", schemaCode);
	            valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
	        }
	        cxt.pass(valid);
	        function loopEnum() {
	            gen.assign(valid, false);
	            gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
	        }
	        function equalCode(vSchema, i) {
	            const sch = schema[i];
	            return typeof sch === "object" && sch !== null
	                ? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])`
	                : (0, codegen_1._) `${data} === ${sch}`;
	        }
	    },
	};
	_enum.default = def;
	
	return _enum;
}

var hasRequiredValidation;

function requireValidation () {
	if (hasRequiredValidation) return validation;
	hasRequiredValidation = 1;
	Object.defineProperty(validation, "__esModule", { value: true });
	const limitNumber_1 = requireLimitNumber();
	const multipleOf_1 = requireMultipleOf();
	const limitLength_1 = requireLimitLength();
	const pattern_1 = requirePattern();
	const limitProperties_1 = requireLimitProperties();
	const required_1 = requireRequired();
	const limitItems_1 = requireLimitItems();
	const uniqueItems_1 = requireUniqueItems();
	const const_1 = require_const();
	const enum_1 = require_enum();
	const validation$1 = [
	    // number
	    limitNumber_1.default,
	    multipleOf_1.default,
	    // string
	    limitLength_1.default,
	    pattern_1.default,
	    // object
	    limitProperties_1.default,
	    required_1.default,
	    // array
	    limitItems_1.default,
	    uniqueItems_1.default,
	    // any
	    { keyword: "type", schemaType: ["string", "array"] },
	    { keyword: "nullable", schemaType: "boolean" },
	    const_1.default,
	    enum_1.default,
	];
	validation.default = validation$1;
	
	return validation;
}

var applicator = {};

var additionalItems = {};

var hasRequiredAdditionalItems;

function requireAdditionalItems () {
	if (hasRequiredAdditionalItems) return additionalItems;
	hasRequiredAdditionalItems = 1;
	Object.defineProperty(additionalItems, "__esModule", { value: true });
	additionalItems.validateAdditionalItems = void 0;
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$1();
	const error = {
	    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
	    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
	};
	const def = {
	    keyword: "additionalItems",
	    type: "array",
	    schemaType: ["boolean", "object"],
	    before: "uniqueItems",
	    error,
	    code(cxt) {
	        const { parentSchema, it } = cxt;
	        const { items } = parentSchema;
	        if (!Array.isArray(items)) {
	            (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
	            return;
	        }
	        validateAdditionalItems(cxt, items);
	    },
	};
	function validateAdditionalItems(cxt, items) {
	    const { gen, schema, data, keyword, it } = cxt;
	    it.items = true;
	    const len = gen.const("len", (0, codegen_1._) `${data}.length`);
	    if (schema === false) {
	        cxt.setParams({ len: items.length });
	        cxt.pass((0, codegen_1._) `${len} <= ${items.length}`);
	    }
	    else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
	        const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items.length}`); // TODO var
	        gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
	        cxt.ok(valid);
	    }
	    function validateItems(valid) {
	        gen.forRange("i", items.length, len, (i) => {
	            cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);
	            if (!it.allErrors)
	                gen.if((0, codegen_1.not)(valid), () => gen.break());
	        });
	    }
	}
	additionalItems.validateAdditionalItems = validateAdditionalItems;
	additionalItems.default = def;
	
	return additionalItems;
}

var prefixItems = {};

var items = {};

var hasRequiredItems;

function requireItems () {
	if (hasRequiredItems) return items;
	hasRequiredItems = 1;
	Object.defineProperty(items, "__esModule", { value: true });
	items.validateTuple = void 0;
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$1();
	const code_1 = requireCode();
	const def = {
	    keyword: "items",
	    type: "array",
	    schemaType: ["object", "array", "boolean"],
	    before: "uniqueItems",
	    code(cxt) {
	        const { schema, it } = cxt;
	        if (Array.isArray(schema))
	            return validateTuple(cxt, "additionalItems", schema);
	        it.items = true;
	        if ((0, util_1.alwaysValidSchema)(it, schema))
	            return;
	        cxt.ok((0, code_1.validateArray)(cxt));
	    },
	};
	function validateTuple(cxt, extraItems, schArr = cxt.schema) {
	    const { gen, parentSchema, data, keyword, it } = cxt;
	    checkStrictTuple(parentSchema);
	    if (it.opts.unevaluated && schArr.length && it.items !== true) {
	        it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
	    }
	    const valid = gen.name("valid");
	    const len = gen.const("len", (0, codegen_1._) `${data}.length`);
	    schArr.forEach((sch, i) => {
	        if ((0, util_1.alwaysValidSchema)(it, sch))
	            return;
	        gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({
	            keyword,
	            schemaProp: i,
	            dataProp: i,
	        }, valid));
	        cxt.ok(valid);
	    });
	    function checkStrictTuple(sch) {
	        const { opts, errSchemaPath } = it;
	        const l = schArr.length;
	        const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);
	        if (opts.strictTuples && !fullTuple) {
	            const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
	            (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
	        }
	    }
	}
	items.validateTuple = validateTuple;
	items.default = def;
	
	return items;
}

var hasRequiredPrefixItems;

function requirePrefixItems () {
	if (hasRequiredPrefixItems) return prefixItems;
	hasRequiredPrefixItems = 1;
	Object.defineProperty(prefixItems, "__esModule", { value: true });
	const items_1 = requireItems();
	const def = {
	    keyword: "prefixItems",
	    type: "array",
	    schemaType: ["array"],
	    before: "uniqueItems",
	    code: (cxt) => (0, items_1.validateTuple)(cxt, "items"),
	};
	prefixItems.default = def;
	
	return prefixItems;
}

var items2020 = {};

var hasRequiredItems2020;

function requireItems2020 () {
	if (hasRequiredItems2020) return items2020;
	hasRequiredItems2020 = 1;
	Object.defineProperty(items2020, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$1();
	const code_1 = requireCode();
	const additionalItems_1 = requireAdditionalItems();
	const error = {
	    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
	    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
	};
	const def = {
	    keyword: "items",
	    type: "array",
	    schemaType: ["object", "boolean"],
	    before: "uniqueItems",
	    error,
	    code(cxt) {
	        const { schema, parentSchema, it } = cxt;
	        const { prefixItems } = parentSchema;
	        it.items = true;
	        if ((0, util_1.alwaysValidSchema)(it, schema))
	            return;
	        if (prefixItems)
	            (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
	        else
	            cxt.ok((0, code_1.validateArray)(cxt));
	    },
	};
	items2020.default = def;
	
	return items2020;
}

var contains = {};

var hasRequiredContains;

function requireContains () {
	if (hasRequiredContains) return contains;
	hasRequiredContains = 1;
	Object.defineProperty(contains, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$1();
	const error = {
	    message: ({ params: { min, max } }) => max === undefined
	        ? (0, codegen_1.str) `must contain at least ${min} valid item(s)`
	        : (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`,
	    params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`,
	};
	const def = {
	    keyword: "contains",
	    type: "array",
	    schemaType: ["object", "boolean"],
	    before: "uniqueItems",
	    trackErrors: true,
	    error,
	    code(cxt) {
	        const { gen, schema, parentSchema, data, it } = cxt;
	        let min;
	        let max;
	        const { minContains, maxContains } = parentSchema;
	        if (it.opts.next) {
	            min = minContains === undefined ? 1 : minContains;
	            max = maxContains;
	        }
	        else {
	            min = 1;
	        }
	        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
	        cxt.setParams({ min, max });
	        if (max === undefined && min === 0) {
	            (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
	            return;
	        }
	        if (max !== undefined && min > max) {
	            (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
	            cxt.fail();
	            return;
	        }
	        if ((0, util_1.alwaysValidSchema)(it, schema)) {
	            let cond = (0, codegen_1._) `${len} >= ${min}`;
	            if (max !== undefined)
	                cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`;
	            cxt.pass(cond);
	            return;
	        }
	        it.items = true;
	        const valid = gen.name("valid");
	        if (max === undefined && min === 1) {
	            validateItems(valid, () => gen.if(valid, () => gen.break()));
	        }
	        else if (min === 0) {
	            gen.let(valid, true);
	            if (max !== undefined)
	                gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount);
	        }
	        else {
	            gen.let(valid, false);
	            validateItemsWithCount();
	        }
	        cxt.result(valid, () => cxt.reset());
	        function validateItemsWithCount() {
	            const schValid = gen.name("_valid");
	            const count = gen.let("count", 0);
	            validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
	        }
	        function validateItems(_valid, block) {
	            gen.forRange("i", 0, len, (i) => {
	                cxt.subschema({
	                    keyword: "contains",
	                    dataProp: i,
	                    dataPropType: util_1.Type.Num,
	                    compositeRule: true,
	                }, _valid);
	                block();
	            });
	        }
	        function checkLimits(count) {
	            gen.code((0, codegen_1._) `${count}++`);
	            if (max === undefined) {
	                gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break());
	            }
	            else {
	                gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break());
	                if (min === 1)
	                    gen.assign(valid, true);
	                else
	                    gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true));
	            }
	        }
	    },
	};
	contains.default = def;
	
	return contains;
}

var dependencies = {};

var hasRequiredDependencies;

function requireDependencies () {
	if (hasRequiredDependencies) return dependencies;
	hasRequiredDependencies = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.validateSchemaDeps = exports$1.validatePropertyDeps = exports$1.error = void 0;
		const codegen_1 = requireCodegen();
		const util_1 = requireUtil$1();
		const code_1 = requireCode();
		exports$1.error = {
		    message: ({ params: { property, depsCount, deps } }) => {
		        const property_ies = depsCount === 1 ? "property" : "properties";
		        return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`;
		    },
		    params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`, // TODO change to reference
		};
		const def = {
		    keyword: "dependencies",
		    type: "object",
		    schemaType: "object",
		    error: exports$1.error,
		    code(cxt) {
		        const [propDeps, schDeps] = splitDependencies(cxt);
		        validatePropertyDeps(cxt, propDeps);
		        validateSchemaDeps(cxt, schDeps);
		    },
		};
		function splitDependencies({ schema }) {
		    const propertyDeps = {};
		    const schemaDeps = {};
		    for (const key in schema) {
		        if (key === "__proto__")
		            continue;
		        const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
		        deps[key] = schema[key];
		    }
		    return [propertyDeps, schemaDeps];
		}
		function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
		    const { gen, data, it } = cxt;
		    if (Object.keys(propertyDeps).length === 0)
		        return;
		    const missing = gen.let("missing");
		    for (const prop in propertyDeps) {
		        const deps = propertyDeps[prop];
		        if (deps.length === 0)
		            continue;
		        const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
		        cxt.setParams({
		            property: prop,
		            depsCount: deps.length,
		            deps: deps.join(", "),
		        });
		        if (it.allErrors) {
		            gen.if(hasProperty, () => {
		                for (const depProp of deps) {
		                    (0, code_1.checkReportMissingProp)(cxt, depProp);
		                }
		            });
		        }
		        else {
		            gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
		            (0, code_1.reportMissingProp)(cxt, missing);
		            gen.else();
		        }
		    }
		}
		exports$1.validatePropertyDeps = validatePropertyDeps;
		function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
		    const { gen, data, keyword, it } = cxt;
		    const valid = gen.name("valid");
		    for (const prop in schemaDeps) {
		        if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
		            continue;
		        gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => {
		            const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
		            cxt.mergeValidEvaluated(schCxt, valid);
		        }, () => gen.var(valid, true) // TODO var
		        );
		        cxt.ok(valid);
		    }
		}
		exports$1.validateSchemaDeps = validateSchemaDeps;
		exports$1.default = def;
		
	} (dependencies));
	return dependencies;
}

var propertyNames = {};

var hasRequiredPropertyNames;

function requirePropertyNames () {
	if (hasRequiredPropertyNames) return propertyNames;
	hasRequiredPropertyNames = 1;
	Object.defineProperty(propertyNames, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$1();
	const error = {
	    message: "property name must be valid",
	    params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`,
	};
	const def = {
	    keyword: "propertyNames",
	    type: "object",
	    schemaType: ["object", "boolean"],
	    error,
	    code(cxt) {
	        const { gen, schema, data, it } = cxt;
	        if ((0, util_1.alwaysValidSchema)(it, schema))
	            return;
	        const valid = gen.name("valid");
	        gen.forIn("key", data, (key) => {
	            cxt.setParams({ propertyName: key });
	            cxt.subschema({
	                keyword: "propertyNames",
	                data: key,
	                dataTypes: ["string"],
	                propertyName: key,
	                compositeRule: true,
	            }, valid);
	            gen.if((0, codegen_1.not)(valid), () => {
	                cxt.error(true);
	                if (!it.allErrors)
	                    gen.break();
	            });
	        });
	        cxt.ok(valid);
	    },
	};
	propertyNames.default = def;
	
	return propertyNames;
}

var additionalProperties = {};

var hasRequiredAdditionalProperties;

function requireAdditionalProperties () {
	if (hasRequiredAdditionalProperties) return additionalProperties;
	hasRequiredAdditionalProperties = 1;
	Object.defineProperty(additionalProperties, "__esModule", { value: true });
	const code_1 = requireCode();
	const codegen_1 = requireCodegen();
	const names_1 = requireNames();
	const util_1 = requireUtil$1();
	const error = {
	    message: "must NOT have additional properties",
	    params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`,
	};
	const def = {
	    keyword: "additionalProperties",
	    type: ["object"],
	    schemaType: ["boolean", "object"],
	    allowUndefined: true,
	    trackErrors: true,
	    error,
	    code(cxt) {
	        const { gen, schema, parentSchema, data, errsCount, it } = cxt;
	        /* istanbul ignore if */
	        if (!errsCount)
	            throw new Error("ajv implementation error");
	        const { allErrors, opts } = it;
	        it.props = true;
	        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))
	            return;
	        const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
	        const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
	        checkAdditionalProperties();
	        cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
	        function checkAdditionalProperties() {
	            gen.forIn("key", data, (key) => {
	                if (!props.length && !patProps.length)
	                    additionalPropertyCode(key);
	                else
	                    gen.if(isAdditional(key), () => additionalPropertyCode(key));
	            });
	        }
	        function isAdditional(key) {
	            let definedProp;
	            if (props.length > 8) {
	                // TODO maybe an option instead of hard-coded 8?
	                const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
	                definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
	            }
	            else if (props.length) {
	                definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`));
	            }
	            else {
	                definedProp = codegen_1.nil;
	            }
	            if (patProps.length) {
	                definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
	            }
	            return (0, codegen_1.not)(definedProp);
	        }
	        function deleteAdditional(key) {
	            gen.code((0, codegen_1._) `delete ${data}[${key}]`);
	        }
	        function additionalPropertyCode(key) {
	            if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) {
	                deleteAdditional(key);
	                return;
	            }
	            if (schema === false) {
	                cxt.setParams({ additionalProperty: key });
	                cxt.error();
	                if (!allErrors)
	                    gen.break();
	                return;
	            }
	            if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
	                const valid = gen.name("valid");
	                if (opts.removeAdditional === "failing") {
	                    applyAdditionalSchema(key, valid, false);
	                    gen.if((0, codegen_1.not)(valid), () => {
	                        cxt.reset();
	                        deleteAdditional(key);
	                    });
	                }
	                else {
	                    applyAdditionalSchema(key, valid);
	                    if (!allErrors)
	                        gen.if((0, codegen_1.not)(valid), () => gen.break());
	                }
	            }
	        }
	        function applyAdditionalSchema(key, valid, errors) {
	            const subschema = {
	                keyword: "additionalProperties",
	                dataProp: key,
	                dataPropType: util_1.Type.Str,
	            };
	            if (errors === false) {
	                Object.assign(subschema, {
	                    compositeRule: true,
	                    createErrors: false,
	                    allErrors: false,
	                });
	            }
	            cxt.subschema(subschema, valid);
	        }
	    },
	};
	additionalProperties.default = def;
	
	return additionalProperties;
}

var properties$1 = {};

var hasRequiredProperties;

function requireProperties () {
	if (hasRequiredProperties) return properties$1;
	hasRequiredProperties = 1;
	Object.defineProperty(properties$1, "__esModule", { value: true });
	const validate_1 = requireValidate();
	const code_1 = requireCode();
	const util_1 = requireUtil$1();
	const additionalProperties_1 = requireAdditionalProperties();
	const def = {
	    keyword: "properties",
	    type: "object",
	    schemaType: "object",
	    code(cxt) {
	        const { gen, schema, parentSchema, data, it } = cxt;
	        if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) {
	            additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
	        }
	        const allProps = (0, code_1.allSchemaProperties)(schema);
	        for (const prop of allProps) {
	            it.definedProperties.add(prop);
	        }
	        if (it.opts.unevaluated && allProps.length && it.props !== true) {
	            it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
	        }
	        const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
	        if (properties.length === 0)
	            return;
	        const valid = gen.name("valid");
	        for (const prop of properties) {
	            if (hasDefault(prop)) {
	                applyPropertySchema(prop);
	            }
	            else {
	                gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
	                applyPropertySchema(prop);
	                if (!it.allErrors)
	                    gen.else().var(valid, true);
	                gen.endIf();
	            }
	            cxt.it.definedProperties.add(prop);
	            cxt.ok(valid);
	        }
	        function hasDefault(prop) {
	            return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined;
	        }
	        function applyPropertySchema(prop) {
	            cxt.subschema({
	                keyword: "properties",
	                schemaProp: prop,
	                dataProp: prop,
	            }, valid);
	        }
	    },
	};
	properties$1.default = def;
	
	return properties$1;
}

var patternProperties = {};

var hasRequiredPatternProperties;

function requirePatternProperties () {
	if (hasRequiredPatternProperties) return patternProperties;
	hasRequiredPatternProperties = 1;
	Object.defineProperty(patternProperties, "__esModule", { value: true });
	const code_1 = requireCode();
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$1();
	const util_2 = requireUtil$1();
	const def = {
	    keyword: "patternProperties",
	    type: "object",
	    schemaType: "object",
	    code(cxt) {
	        const { gen, schema, data, parentSchema, it } = cxt;
	        const { opts } = it;
	        const patterns = (0, code_1.allSchemaProperties)(schema);
	        const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
	        if (patterns.length === 0 ||
	            (alwaysValidPatterns.length === patterns.length &&
	                (!it.opts.unevaluated || it.props === true))) {
	            return;
	        }
	        const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
	        const valid = gen.name("valid");
	        if (it.props !== true && !(it.props instanceof codegen_1.Name)) {
	            it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
	        }
	        const { props } = it;
	        validatePatternProperties();
	        function validatePatternProperties() {
	            for (const pat of patterns) {
	                if (checkProperties)
	                    checkMatchingProperties(pat);
	                if (it.allErrors) {
	                    validateProperties(pat);
	                }
	                else {
	                    gen.var(valid, true); // TODO var
	                    validateProperties(pat);
	                    gen.if(valid);
	                }
	            }
	        }
	        function checkMatchingProperties(pat) {
	            for (const prop in checkProperties) {
	                if (new RegExp(pat).test(prop)) {
	                    (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
	                }
	            }
	        }
	        function validateProperties(pat) {
	            gen.forIn("key", data, (key) => {
	                gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
	                    const alwaysValid = alwaysValidPatterns.includes(pat);
	                    if (!alwaysValid) {
	                        cxt.subschema({
	                            keyword: "patternProperties",
	                            schemaProp: pat,
	                            dataProp: key,
	                            dataPropType: util_2.Type.Str,
	                        }, valid);
	                    }
	                    if (it.opts.unevaluated && props !== true) {
	                        gen.assign((0, codegen_1._) `${props}[${key}]`, true);
	                    }
	                    else if (!alwaysValid && !it.allErrors) {
	                        // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)
	                        // or if all properties were evaluated (props === true)
	                        gen.if((0, codegen_1.not)(valid), () => gen.break());
	                    }
	                });
	            });
	        }
	    },
	};
	patternProperties.default = def;
	
	return patternProperties;
}

var not = {};

var hasRequiredNot;

function requireNot () {
	if (hasRequiredNot) return not;
	hasRequiredNot = 1;
	Object.defineProperty(not, "__esModule", { value: true });
	const util_1 = requireUtil$1();
	const def = {
	    keyword: "not",
	    schemaType: ["object", "boolean"],
	    trackErrors: true,
	    code(cxt) {
	        const { gen, schema, it } = cxt;
	        if ((0, util_1.alwaysValidSchema)(it, schema)) {
	            cxt.fail();
	            return;
	        }
	        const valid = gen.name("valid");
	        cxt.subschema({
	            keyword: "not",
	            compositeRule: true,
	            createErrors: false,
	            allErrors: false,
	        }, valid);
	        cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
	    },
	    error: { message: "must NOT be valid" },
	};
	not.default = def;
	
	return not;
}

var anyOf = {};

var hasRequiredAnyOf;

function requireAnyOf () {
	if (hasRequiredAnyOf) return anyOf;
	hasRequiredAnyOf = 1;
	Object.defineProperty(anyOf, "__esModule", { value: true });
	const code_1 = requireCode();
	const def = {
	    keyword: "anyOf",
	    schemaType: "array",
	    trackErrors: true,
	    code: code_1.validateUnion,
	    error: { message: "must match a schema in anyOf" },
	};
	anyOf.default = def;
	
	return anyOf;
}

var oneOf = {};

var hasRequiredOneOf;

function requireOneOf () {
	if (hasRequiredOneOf) return oneOf;
	hasRequiredOneOf = 1;
	Object.defineProperty(oneOf, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$1();
	const error = {
	    message: "must match exactly one schema in oneOf",
	    params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`,
	};
	const def = {
	    keyword: "oneOf",
	    schemaType: "array",
	    trackErrors: true,
	    error,
	    code(cxt) {
	        const { gen, schema, parentSchema, it } = cxt;
	        /* istanbul ignore if */
	        if (!Array.isArray(schema))
	            throw new Error("ajv implementation error");
	        if (it.opts.discriminator && parentSchema.discriminator)
	            return;
	        const schArr = schema;
	        const valid = gen.let("valid", false);
	        const passing = gen.let("passing", null);
	        const schValid = gen.name("_valid");
	        cxt.setParams({ passing });
	        // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas
	        gen.block(validateOneOf);
	        cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
	        function validateOneOf() {
	            schArr.forEach((sch, i) => {
	                let schCxt;
	                if ((0, util_1.alwaysValidSchema)(it, sch)) {
	                    gen.var(schValid, true);
	                }
	                else {
	                    schCxt = cxt.subschema({
	                        keyword: "oneOf",
	                        schemaProp: i,
	                        compositeRule: true,
	                    }, schValid);
	                }
	                if (i > 0) {
	                    gen
	                        .if((0, codegen_1._) `${schValid} && ${valid}`)
	                        .assign(valid, false)
	                        .assign(passing, (0, codegen_1._) `[${passing}, ${i}]`)
	                        .else();
	                }
	                gen.if(schValid, () => {
	                    gen.assign(valid, true);
	                    gen.assign(passing, i);
	                    if (schCxt)
	                        cxt.mergeEvaluated(schCxt, codegen_1.Name);
	                });
	            });
	        }
	    },
	};
	oneOf.default = def;
	
	return oneOf;
}

var allOf = {};

var hasRequiredAllOf;

function requireAllOf () {
	if (hasRequiredAllOf) return allOf;
	hasRequiredAllOf = 1;
	Object.defineProperty(allOf, "__esModule", { value: true });
	const util_1 = requireUtil$1();
	const def = {
	    keyword: "allOf",
	    schemaType: "array",
	    code(cxt) {
	        const { gen, schema, it } = cxt;
	        /* istanbul ignore if */
	        if (!Array.isArray(schema))
	            throw new Error("ajv implementation error");
	        const valid = gen.name("valid");
	        schema.forEach((sch, i) => {
	            if ((0, util_1.alwaysValidSchema)(it, sch))
	                return;
	            const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
	            cxt.ok(valid);
	            cxt.mergeEvaluated(schCxt);
	        });
	    },
	};
	allOf.default = def;
	
	return allOf;
}

var _if = {};

var hasRequired_if;

function require_if () {
	if (hasRequired_if) return _if;
	hasRequired_if = 1;
	Object.defineProperty(_if, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$1();
	const error = {
	    message: ({ params }) => (0, codegen_1.str) `must match "${params.ifClause}" schema`,
	    params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`,
	};
	const def = {
	    keyword: "if",
	    schemaType: ["object", "boolean"],
	    trackErrors: true,
	    error,
	    code(cxt) {
	        const { gen, parentSchema, it } = cxt;
	        if (parentSchema.then === undefined && parentSchema.else === undefined) {
	            (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
	        }
	        const hasThen = hasSchema(it, "then");
	        const hasElse = hasSchema(it, "else");
	        if (!hasThen && !hasElse)
	            return;
	        const valid = gen.let("valid", true);
	        const schValid = gen.name("_valid");
	        validateIf();
	        cxt.reset();
	        if (hasThen && hasElse) {
	            const ifClause = gen.let("ifClause");
	            cxt.setParams({ ifClause });
	            gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
	        }
	        else if (hasThen) {
	            gen.if(schValid, validateClause("then"));
	        }
	        else {
	            gen.if((0, codegen_1.not)(schValid), validateClause("else"));
	        }
	        cxt.pass(valid, () => cxt.error(true));
	        function validateIf() {
	            const schCxt = cxt.subschema({
	                keyword: "if",
	                compositeRule: true,
	                createErrors: false,
	                allErrors: false,
	            }, schValid);
	            cxt.mergeEvaluated(schCxt);
	        }
	        function validateClause(keyword, ifClause) {
	            return () => {
	                const schCxt = cxt.subschema({ keyword }, schValid);
	                gen.assign(valid, schValid);
	                cxt.mergeValidEvaluated(schCxt, valid);
	                if (ifClause)
	                    gen.assign(ifClause, (0, codegen_1._) `${keyword}`);
	                else
	                    cxt.setParams({ ifClause: keyword });
	            };
	        }
	    },
	};
	function hasSchema(it, keyword) {
	    const schema = it.schema[keyword];
	    return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema);
	}
	_if.default = def;
	
	return _if;
}

var thenElse = {};

var hasRequiredThenElse;

function requireThenElse () {
	if (hasRequiredThenElse) return thenElse;
	hasRequiredThenElse = 1;
	Object.defineProperty(thenElse, "__esModule", { value: true });
	const util_1 = requireUtil$1();
	const def = {
	    keyword: ["then", "else"],
	    schemaType: ["object", "boolean"],
	    code({ keyword, parentSchema, it }) {
	        if (parentSchema.if === undefined)
	            (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
	    },
	};
	thenElse.default = def;
	
	return thenElse;
}

var hasRequiredApplicator;

function requireApplicator () {
	if (hasRequiredApplicator) return applicator;
	hasRequiredApplicator = 1;
	Object.defineProperty(applicator, "__esModule", { value: true });
	const additionalItems_1 = requireAdditionalItems();
	const prefixItems_1 = requirePrefixItems();
	const items_1 = requireItems();
	const items2020_1 = requireItems2020();
	const contains_1 = requireContains();
	const dependencies_1 = requireDependencies();
	const propertyNames_1 = requirePropertyNames();
	const additionalProperties_1 = requireAdditionalProperties();
	const properties_1 = requireProperties();
	const patternProperties_1 = requirePatternProperties();
	const not_1 = requireNot();
	const anyOf_1 = requireAnyOf();
	const oneOf_1 = requireOneOf();
	const allOf_1 = requireAllOf();
	const if_1 = require_if();
	const thenElse_1 = requireThenElse();
	function getApplicator(draft2020 = false) {
	    const applicator = [
	        // any
	        not_1.default,
	        anyOf_1.default,
	        oneOf_1.default,
	        allOf_1.default,
	        if_1.default,
	        thenElse_1.default,
	        // object
	        propertyNames_1.default,
	        additionalProperties_1.default,
	        dependencies_1.default,
	        properties_1.default,
	        patternProperties_1.default,
	    ];
	    // array
	    if (draft2020)
	        applicator.push(prefixItems_1.default, items2020_1.default);
	    else
	        applicator.push(additionalItems_1.default, items_1.default);
	    applicator.push(contains_1.default);
	    return applicator;
	}
	applicator.default = getApplicator;
	
	return applicator;
}

var format$1 = {};

var format = {};

var hasRequiredFormat$1;

function requireFormat$1 () {
	if (hasRequiredFormat$1) return format;
	hasRequiredFormat$1 = 1;
	Object.defineProperty(format, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const error = {
	    message: ({ schemaCode }) => (0, codegen_1.str) `must match format "${schemaCode}"`,
	    params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`,
	};
	const def = {
	    keyword: "format",
	    type: ["number", "string"],
	    schemaType: "string",
	    $data: true,
	    error,
	    code(cxt, ruleType) {
	        const { gen, data, $data, schema, schemaCode, it } = cxt;
	        const { opts, errSchemaPath, schemaEnv, self } = it;
	        if (!opts.validateFormats)
	            return;
	        if ($data)
	            validate$DataFormat();
	        else
	            validateFormat();
	        function validate$DataFormat() {
	            const fmts = gen.scopeValue("formats", {
	                ref: self.formats,
	                code: opts.code.formats,
	            });
	            const fDef = gen.const("fDef", (0, codegen_1._) `${fmts}[${schemaCode}]`);
	            const fType = gen.let("fType");
	            const format = gen.let("format");
	            // TODO simplify
	            gen.if((0, codegen_1._) `typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._) `${fDef}.type || "string"`).assign(format, (0, codegen_1._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._) `"string"`).assign(format, fDef));
	            cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
	            function unknownFmt() {
	                if (opts.strictSchema === false)
	                    return codegen_1.nil;
	                return (0, codegen_1._) `${schemaCode} && !${format}`;
	            }
	            function invalidFmt() {
	                const callFormat = schemaEnv.$async
	                    ? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`
	                    : (0, codegen_1._) `${format}(${data})`;
	                const validData = (0, codegen_1._) `(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
	                return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
	            }
	        }
	        function validateFormat() {
	            const formatDef = self.formats[schema];
	            if (!formatDef) {
	                unknownFormat();
	                return;
	            }
	            if (formatDef === true)
	                return;
	            const [fmtType, format, fmtRef] = getFormat(formatDef);
	            if (fmtType === ruleType)
	                cxt.pass(validCondition());
	            function unknownFormat() {
	                if (opts.strictSchema === false) {
	                    self.logger.warn(unknownMsg());
	                    return;
	                }
	                throw new Error(unknownMsg());
	                function unknownMsg() {
	                    return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
	                }
	            }
	            function getFormat(fmtDef) {
	                const code = fmtDef instanceof RegExp
	                    ? (0, codegen_1.regexpCode)(fmtDef)
	                    : opts.code.formats
	                        ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}`
	                        : undefined;
	                const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });
	                if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
	                    return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`];
	                }
	                return ["string", fmtDef, fmt];
	            }
	            function validCondition() {
	                if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
	                    if (!schemaEnv.$async)
	                        throw new Error("async format in sync schema");
	                    return (0, codegen_1._) `await ${fmtRef}(${data})`;
	                }
	                return typeof format == "function" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`;
	            }
	        }
	    },
	};
	format.default = def;
	
	return format;
}

var hasRequiredFormat;

function requireFormat () {
	if (hasRequiredFormat) return format$1;
	hasRequiredFormat = 1;
	Object.defineProperty(format$1, "__esModule", { value: true });
	const format_1 = requireFormat$1();
	const format = [format_1.default];
	format$1.default = format;
	
	return format$1;
}

var metadata = {};

var hasRequiredMetadata;

function requireMetadata () {
	if (hasRequiredMetadata) return metadata;
	hasRequiredMetadata = 1;
	Object.defineProperty(metadata, "__esModule", { value: true });
	metadata.contentVocabulary = metadata.metadataVocabulary = void 0;
	metadata.metadataVocabulary = [
	    "title",
	    "description",
	    "default",
	    "deprecated",
	    "readOnly",
	    "writeOnly",
	    "examples",
	];
	metadata.contentVocabulary = [
	    "contentMediaType",
	    "contentEncoding",
	    "contentSchema",
	];
	
	return metadata;
}

var hasRequiredDraft7;

function requireDraft7 () {
	if (hasRequiredDraft7) return draft7;
	hasRequiredDraft7 = 1;
	Object.defineProperty(draft7, "__esModule", { value: true });
	const core_1 = requireCore();
	const validation_1 = requireValidation();
	const applicator_1 = requireApplicator();
	const format_1 = requireFormat();
	const metadata_1 = requireMetadata();
	const draft7Vocabularies = [
	    core_1.default,
	    validation_1.default,
	    (0, applicator_1.default)(),
	    format_1.default,
	    metadata_1.metadataVocabulary,
	    metadata_1.contentVocabulary,
	];
	draft7.default = draft7Vocabularies;
	
	return draft7;
}

var discriminator = {};

var types = {};

var hasRequiredTypes;

function requireTypes () {
	if (hasRequiredTypes) return types;
	hasRequiredTypes = 1;
	Object.defineProperty(types, "__esModule", { value: true });
	types.DiscrError = void 0;
	var DiscrError;
	(function (DiscrError) {
	    DiscrError["Tag"] = "tag";
	    DiscrError["Mapping"] = "mapping";
	})(DiscrError || (types.DiscrError = DiscrError = {}));
	
	return types;
}

var hasRequiredDiscriminator;

function requireDiscriminator () {
	if (hasRequiredDiscriminator) return discriminator;
	hasRequiredDiscriminator = 1;
	Object.defineProperty(discriminator, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const types_1 = requireTypes();
	const compile_1 = requireCompile();
	const ref_error_1 = requireRef_error();
	const util_1 = requireUtil$1();
	const error = {
	    message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag
	        ? `tag "${tagName}" must be string`
	        : `value of tag "${tagName}" must be in oneOf`,
	    params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,
	};
	const def = {
	    keyword: "discriminator",
	    type: "object",
	    schemaType: "object",
	    error,
	    code(cxt) {
	        const { gen, data, schema, parentSchema, it } = cxt;
	        const { oneOf } = parentSchema;
	        if (!it.opts.discriminator) {
	            throw new Error("discriminator: requires discriminator option");
	        }
	        const tagName = schema.propertyName;
	        if (typeof tagName != "string")
	            throw new Error("discriminator: requires propertyName");
	        if (schema.mapping)
	            throw new Error("discriminator: mapping is not supported");
	        if (!oneOf)
	            throw new Error("discriminator: requires oneOf keyword");
	        const valid = gen.let("valid", false);
	        const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`);
	        gen.if((0, codegen_1._) `typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
	        cxt.ok(valid);
	        function validateMapping() {
	            const mapping = getMapping();
	            gen.if(false);
	            for (const tagValue in mapping) {
	                gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
	                gen.assign(valid, applyTagSchema(mapping[tagValue]));
	            }
	            gen.else();
	            cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
	            gen.endIf();
	        }
	        function applyTagSchema(schemaProp) {
	            const _valid = gen.name("valid");
	            const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
	            cxt.mergeEvaluated(schCxt, codegen_1.Name);
	            return _valid;
	        }
	        function getMapping() {
	            var _a;
	            const oneOfMapping = {};
	            const topRequired = hasRequired(parentSchema);
	            let tagRequired = true;
	            for (let i = 0; i < oneOf.length; i++) {
	                let sch = oneOf[i];
	                if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
	                    const ref = sch.$ref;
	                    sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
	                    if (sch instanceof compile_1.SchemaEnv)
	                        sch = sch.schema;
	                    if (sch === undefined)
	                        throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
	                }
	                const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];
	                if (typeof propSch != "object") {
	                    throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
	                }
	                tagRequired = tagRequired && (topRequired || hasRequired(sch));
	                addMappings(propSch, i);
	            }
	            if (!tagRequired)
	                throw new Error(`discriminator: "${tagName}" must be required`);
	            return oneOfMapping;
	            function hasRequired({ required }) {
	                return Array.isArray(required) && required.includes(tagName);
	            }
	            function addMappings(sch, i) {
	                if (sch.const) {
	                    addMapping(sch.const, i);
	                }
	                else if (sch.enum) {
	                    for (const tagValue of sch.enum) {
	                        addMapping(tagValue, i);
	                    }
	                }
	                else {
	                    throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
	                }
	            }
	            function addMapping(tagValue, i) {
	                if (typeof tagValue != "string" || tagValue in oneOfMapping) {
	                    throw new Error(`discriminator: "${tagName}" values must be unique strings`);
	                }
	                oneOfMapping[tagValue] = i;
	            }
	        }
	    },
	};
	discriminator.default = def;
	
	return discriminator;
}

const $schema = "http://json-schema.org/draft-07/schema#";
const $id = "http://json-schema.org/draft-07/schema#";
const title = "Core schema meta-schema";
const definitions = {"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}};
const type = ["object","boolean"];
const properties = {"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}};
const require$$3 = {
  $schema,
  $id,
  title,
  definitions,
  type,
  properties,
  "default": true,
};

var hasRequiredAjv;

function requireAjv () {
	if (hasRequiredAjv) return ajv.exports;
	hasRequiredAjv = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.MissingRefError = exports$1.ValidationError = exports$1.CodeGen = exports$1.Name = exports$1.nil = exports$1.stringify = exports$1.str = exports$1._ = exports$1.KeywordCxt = exports$1.Ajv = void 0;
		const core_1 = requireCore$1();
		const draft7_1 = requireDraft7();
		const discriminator_1 = requireDiscriminator();
		const draft7MetaSchema = require$$3;
		const META_SUPPORT_DATA = ["/properties"];
		const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
		class Ajv extends core_1.default {
		    _addVocabularies() {
		        super._addVocabularies();
		        draft7_1.default.forEach((v) => this.addVocabulary(v));
		        if (this.opts.discriminator)
		            this.addKeyword(discriminator_1.default);
		    }
		    _addDefaultMetaSchema() {
		        super._addDefaultMetaSchema();
		        if (!this.opts.meta)
		            return;
		        const metaSchema = this.opts.$data
		            ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
		            : draft7MetaSchema;
		        this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
		        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
		    }
		    defaultMeta() {
		        return (this.opts.defaultMeta =
		            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
		    }
		}
		exports$1.Ajv = Ajv;
		module.exports = exports$1 = Ajv;
		module.exports.Ajv = Ajv;
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.default = Ajv;
		var validate_1 = requireValidate();
		Object.defineProperty(exports$1, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
		var codegen_1 = requireCodegen();
		Object.defineProperty(exports$1, "_", { enumerable: true, get: function () { return codegen_1._; } });
		Object.defineProperty(exports$1, "str", { enumerable: true, get: function () { return codegen_1.str; } });
		Object.defineProperty(exports$1, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
		Object.defineProperty(exports$1, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
		Object.defineProperty(exports$1, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
		Object.defineProperty(exports$1, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
		var validation_error_1 = requireValidation_error();
		Object.defineProperty(exports$1, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
		var ref_error_1 = requireRef_error();
		Object.defineProperty(exports$1, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
		
	} (ajv, ajv.exports));
	return ajv.exports;
}

var ajvExports = requireAjv();
const Ajv = /*@__PURE__*/getDefaultExportFromCjs(ajvExports);

class ConfigBase {
  name;
  core;
  configPath;
  configData = {};
  ajv;
  validate;
  constructor(name, core, configPath, ConfigSchema) {
    this.name = name;
    this.core = core;
    this.configPath = configPath;
    this.ajv = new Ajv({ useDefaults: true, coerceTypes: true });
    this.validate = this.ajv.compile(ConfigSchema);
    fs$2.mkdirSync(this.configPath, { recursive: true });
    this.read();
  }
  getConfigPath(pathName) {
    const filename = pathName ? `${this.name}_${pathName}.json` : `${this.name}.json`;
    return path$1.join(this.configPath, filename);
  }
  read() {
    const configPath = this.getConfigPath(this.core.selfInfo.uin);
    const defaultConfigPath = this.getConfigPath();
    if (!fs$2.existsSync(configPath)) {
      if (fs$2.existsSync(defaultConfigPath)) {
        this.configData = this.loadConfig(defaultConfigPath);
      }
      this.save();
      return this.configData;
    }
    return this.loadConfig(configPath);
  }
  loadConfig(configPath) {
    try {
      const newConfigData = lib$2.parse(fs$2.readFileSync(configPath, "utf-8"));
      this.validate(newConfigData);
      this.configData = newConfigData;
      this.core.context.logger.logDebug(`[Core] [Config] 配置文件${configPath}加载`, this.configData);
      return this.configData;
    } catch (e) {
      this.handleError(e, "读取配置文件时发生错误");
      return {};
    }
  }
  save(newConfigData = this.configData) {
    const configPath = this.getConfigPath(this.core.selfInfo.uin);
    this.validate(newConfigData);
    this.configData = newConfigData;
    try {
      fs$2.writeFileSync(configPath, JSON.stringify(this.configData, null, 2));
    } catch (e) {
      this.handleError(e, `保存配置文件 ${configPath} 时发生错误:`);
    }
  }
  handleError(e, message) {
    if (e instanceof SyntaxError) {
      this.core.context.logger.logError("[Core] [Config] 操作配置文件格式错误，请检查配置文件:", e.message);
    } else {
      this.core.context.logger.logError(`[Core] [Config] ${message}:`, e.message);
    }
  }
}

// --------------------------------------------------------------------------
// PropertyKey
// --------------------------------------------------------------------------
/** Returns true if this value has this property key */
// --------------------------------------------------------------------------
// Object Instances
// --------------------------------------------------------------------------
/** Returns true if this value is an async iterator */
function IsAsyncIterator$2(value) {
    return IsObject$3(value) && !IsArray$3(value) && !IsUint8Array$2(value) && Symbol.asyncIterator in value;
}
/** Returns true if this value is an array */
function IsArray$3(value) {
    return Array.isArray(value);
}
/** Returns true if this value is bigint */
function IsBigInt$2(value) {
    return typeof value === 'bigint';
}
/** Returns true if this value is a boolean */
function IsBoolean$2(value) {
    return typeof value === 'boolean';
}
/** Returns true if this value is a Date object */
function IsDate$2(value) {
    return value instanceof globalThis.Date;
}
/** Returns true if this value is a function */
function IsFunction$2(value) {
    return typeof value === 'function';
}
/** Returns true if this value is an iterator */
function IsIterator$2(value) {
    return IsObject$3(value) && !IsArray$3(value) && !IsUint8Array$2(value) && Symbol.iterator in value;
}
/** Returns true if this value is null */
function IsNull$2(value) {
    return value === null;
}
/** Returns true if this value is number */
function IsNumber$3(value) {
    return typeof value === 'number';
}
/** Returns true if this value is an object */
function IsObject$3(value) {
    return typeof value === 'object' && value !== null;
}
/** Returns true if this value is RegExp */
function IsRegExp$2(value) {
    return value instanceof globalThis.RegExp;
}
/** Returns true if this value is string */
function IsString$2(value) {
    return typeof value === 'string';
}
/** Returns true if this value is symbol */
function IsSymbol$2(value) {
    return typeof value === 'symbol';
}
/** Returns true if this value is a Uint8Array */
function IsUint8Array$2(value) {
    return value instanceof globalThis.Uint8Array;
}
/** Returns true if this value is undefined */
function IsUndefined$3(value) {
    return value === undefined;
}

function ArrayType(value) {
    return value.map((value) => Visit$2(value));
}
function DateType(value) {
    return new Date(value.getTime());
}
function Uint8ArrayType(value) {
    return new Uint8Array(value);
}
function RegExpType(value) {
    return new RegExp(value.source, value.flags);
}
function ObjectType(value) {
    const result = {};
    for (const key of Object.getOwnPropertyNames(value)) {
        result[key] = Visit$2(value[key]);
    }
    for (const key of Object.getOwnPropertySymbols(value)) {
        result[key] = Visit$2(value[key]);
    }
    return result;
}
// prettier-ignore
function Visit$2(value) {
    return (IsArray$3(value) ? ArrayType(value) :
        IsDate$2(value) ? DateType(value) :
            IsUint8Array$2(value) ? Uint8ArrayType(value) :
                IsRegExp$2(value) ? RegExpType(value) :
                    IsObject$3(value) ? ObjectType(value) :
                        value);
}
/** Clones a value */
function Clone(value) {
    return Visit$2(value);
}

/** Clones a Type */
function CloneType(schema, options) {
    return options === undefined ? Clone(schema) : Clone({ ...options, ...schema });
}

// --------------------------------------------------------------------------
// Iterators
// --------------------------------------------------------------------------
/** Returns true if this value is an async iterator */
// --------------------------------------------------------------------------
// Standard
// --------------------------------------------------------------------------
/** Returns true of this value is an object type */
function IsObject$2(value) {
    return value !== null && typeof value === 'object';
}
/** Returns true if this value is an array, but not a typed array */
function IsArray$2(value) {
    return globalThis.Array.isArray(value) && !globalThis.ArrayBuffer.isView(value);
}
/** Returns true if this value is an undefined */
function IsUndefined$2(value) {
    return value === undefined;
}
/** Returns true if this value is an number */
function IsNumber$2(value) {
    return typeof value === 'number';
}

var TypeSystemPolicy;
(function (TypeSystemPolicy) {
    // ------------------------------------------------------------------
    // TypeSystemPolicy: Instancing
    // ------------------------------------------------------------------
    /**
     * Configures the instantiation behavior of TypeBox types. The `default` option assigns raw JavaScript
     * references for embedded types, which may cause side effects if type properties are explicitly updated
     * outside the TypeBox type builder. The `clone` option creates copies of any shared types upon creation,
     * preventing unintended side effects. The `freeze` option applies `Object.freeze()` to the type, making
     * it fully readonly and immutable. Implementations should use `default` whenever possible, as it is the
     * fastest way to instantiate types. The default setting is `default`.
     */
    TypeSystemPolicy.InstanceMode = 'default';
    // ------------------------------------------------------------------
    // TypeSystemPolicy: Checking
    // ------------------------------------------------------------------
    /** Sets whether TypeBox should assert optional properties using the TypeScript `exactOptionalPropertyTypes` assertion policy. The default is `false` */
    TypeSystemPolicy.ExactOptionalPropertyTypes = false;
    /** Sets whether arrays should be treated as a kind of objects. The default is `false` */
    TypeSystemPolicy.AllowArrayObject = false;
    /** Sets whether `NaN` or `Infinity` should be treated as valid numeric values. The default is `false` */
    TypeSystemPolicy.AllowNaN = false;
    /** Sets whether `null` should validate for void types. The default is `false` */
    TypeSystemPolicy.AllowNullVoid = false;
    /** Checks this value using the ExactOptionalPropertyTypes policy */
    function IsExactOptionalProperty(value, key) {
        return TypeSystemPolicy.ExactOptionalPropertyTypes ? key in value : value[key] !== undefined;
    }
    TypeSystemPolicy.IsExactOptionalProperty = IsExactOptionalProperty;
    /** Checks this value using the AllowArrayObjects policy */
    function IsObjectLike(value) {
        const isObject = IsObject$2(value);
        return TypeSystemPolicy.AllowArrayObject ? isObject : isObject && !IsArray$2(value);
    }
    TypeSystemPolicy.IsObjectLike = IsObjectLike;
    /** Checks this value as a record using the AllowArrayObjects policy */
    function IsRecordLike(value) {
        return IsObjectLike(value) && !(value instanceof Date) && !(value instanceof Uint8Array);
    }
    TypeSystemPolicy.IsRecordLike = IsRecordLike;
    /** Checks this value using the AllowNaN policy */
    function IsNumberLike(value) {
        return TypeSystemPolicy.AllowNaN ? IsNumber$2(value) : Number.isFinite(value);
    }
    TypeSystemPolicy.IsNumberLike = IsNumberLike;
    /** Checks this value using the AllowVoidNull policy */
    function IsVoidLike(value) {
        const isUndefined = IsUndefined$2(value);
        return TypeSystemPolicy.AllowNullVoid ? isUndefined || value === null : isUndefined;
    }
    TypeSystemPolicy.IsVoidLike = IsVoidLike;
})(TypeSystemPolicy || (TypeSystemPolicy = {}));

function ImmutableArray(value) {
    return globalThis.Object.freeze(value).map((value) => Immutable(value));
}
function ImmutableDate(value) {
    return value;
}
function ImmutableUint8Array(value) {
    return value;
}
function ImmutableRegExp(value) {
    return value;
}
function ImmutableObject(value) {
    const result = {};
    for (const key of Object.getOwnPropertyNames(value)) {
        result[key] = Immutable(value[key]);
    }
    for (const key of Object.getOwnPropertySymbols(value)) {
        result[key] = Immutable(value[key]);
    }
    return globalThis.Object.freeze(result);
}
/** Specialized deep immutable value. Applies freeze recursively to the given value */
// prettier-ignore
function Immutable(value) {
    return (IsArray$3(value) ? ImmutableArray(value) :
        IsDate$2(value) ? ImmutableDate(value) :
            IsUint8Array$2(value) ? ImmutableUint8Array(value) :
                IsRegExp$2(value) ? ImmutableRegExp(value) :
                    IsObject$3(value) ? ImmutableObject(value) :
                        value);
}

/** Creates TypeBox schematics using the configured InstanceMode */
function CreateType(schema, options) {
    const result = options !== undefined ? { ...options, ...schema } : schema;
    switch (TypeSystemPolicy.InstanceMode) {
        case 'freeze':
            return Immutable(result);
        case 'clone':
            return Clone(result);
        default:
            return result;
    }
}

/** The base Error type thrown for all TypeBox exceptions  */
class TypeBoxError extends Error {
    constructor(message) {
        super(message);
    }
}

/** Symbol key applied to transform types */
const TransformKind = Symbol.for('TypeBox.Transform');
/** Symbol key applied to readonly types */
const ReadonlyKind = Symbol.for('TypeBox.Readonly');
/** Symbol key applied to optional types */
const OptionalKind = Symbol.for('TypeBox.Optional');
/** Symbol key applied to types */
const Hint = Symbol.for('TypeBox.Hint');
/** Symbol key applied to types */
const Kind = Symbol.for('TypeBox.Kind');

/** `[Kind-Only]` Returns true if this value has a Readonly symbol */
function IsReadonly(value) {
    return IsObject$3(value) && value[ReadonlyKind] === 'Readonly';
}
/** `[Kind-Only]` Returns true if this value has a Optional symbol */
function IsOptional$1(value) {
    return IsObject$3(value) && value[OptionalKind] === 'Optional';
}
/** `[Kind-Only]` Returns true if the given value is TAny */
function IsAny$1(value) {
    return IsKindOf$1(value, 'Any');
}
/** `[Kind-Only]` Returns true if the given value is TArgument */
function IsArgument$1(value) {
    return IsKindOf$1(value, 'Argument');
}
/** `[Kind-Only]` Returns true if the given value is TArray */
function IsArray$1(value) {
    return IsKindOf$1(value, 'Array');
}
/** `[Kind-Only]` Returns true if the given value is TAsyncIterator */
function IsAsyncIterator$1(value) {
    return IsKindOf$1(value, 'AsyncIterator');
}
/** `[Kind-Only]` Returns true if the given value is TBigInt */
function IsBigInt$1(value) {
    return IsKindOf$1(value, 'BigInt');
}
/** `[Kind-Only]` Returns true if the given value is TBoolean */
function IsBoolean$1(value) {
    return IsKindOf$1(value, 'Boolean');
}
/** `[Kind-Only]` Returns true if the given value is TComputed */
function IsComputed$1(value) {
    return IsKindOf$1(value, 'Computed');
}
/** `[Kind-Only]` Returns true if the given value is TConstructor */
function IsConstructor$1(value) {
    return IsKindOf$1(value, 'Constructor');
}
/** `[Kind-Only]` Returns true if the given value is TDate */
function IsDate$1(value) {
    return IsKindOf$1(value, 'Date');
}
/** `[Kind-Only]` Returns true if the given value is TFunction */
function IsFunction$1(value) {
    return IsKindOf$1(value, 'Function');
}
/** `[Kind-Only]` Returns true if the given value is TInteger */
function IsInteger$1(value) {
    return IsKindOf$1(value, 'Integer');
}
/** `[Kind-Only]` Returns true if the given value is TIntersect */
function IsIntersect$1(value) {
    return IsKindOf$1(value, 'Intersect');
}
/** `[Kind-Only]` Returns true if the given value is TIterator */
function IsIterator$1(value) {
    return IsKindOf$1(value, 'Iterator');
}
/** `[Kind-Only]` Returns true if the given value is a TKind with the given name. */
function IsKindOf$1(value, kind) {
    return IsObject$3(value) && Kind in value && value[Kind] === kind;
}
/** `[Kind-Only]` Returns true if the given value is TLiteralValue */
function IsLiteralValue$1(value) {
    return IsBoolean$2(value) || IsNumber$3(value) || IsString$2(value);
}
/** `[Kind-Only]` Returns true if the given value is TLiteral */
function IsLiteral$1(value) {
    return IsKindOf$1(value, 'Literal');
}
/** `[Kind-Only]` Returns true if the given value is a TMappedKey */
function IsMappedKey$1(value) {
    return IsKindOf$1(value, 'MappedKey');
}
/** `[Kind-Only]` Returns true if the given value is TMappedResult */
function IsMappedResult$1(value) {
    return IsKindOf$1(value, 'MappedResult');
}
/** `[Kind-Only]` Returns true if the given value is TNever */
function IsNever$1(value) {
    return IsKindOf$1(value, 'Never');
}
/** `[Kind-Only]` Returns true if the given value is TNot */
function IsNot$1(value) {
    return IsKindOf$1(value, 'Not');
}
/** `[Kind-Only]` Returns true if the given value is TNull */
function IsNull$1(value) {
    return IsKindOf$1(value, 'Null');
}
/** `[Kind-Only]` Returns true if the given value is TNumber */
function IsNumber$1(value) {
    return IsKindOf$1(value, 'Number');
}
/** `[Kind-Only]` Returns true if the given value is TObject */
function IsObject$1(value) {
    return IsKindOf$1(value, 'Object');
}
/** `[Kind-Only]` Returns true if the given value is TPromise */
function IsPromise$1(value) {
    return IsKindOf$1(value, 'Promise');
}
/** `[Kind-Only]` Returns true if the given value is TRecord */
function IsRecord$1(value) {
    return IsKindOf$1(value, 'Record');
}
/** `[Kind-Only]` Returns true if the given value is TRef */
function IsRef$1(value) {
    return IsKindOf$1(value, 'Ref');
}
/** `[Kind-Only]` Returns true if the given value is TRegExp */
function IsRegExp$1(value) {
    return IsKindOf$1(value, 'RegExp');
}
/** `[Kind-Only]` Returns true if the given value is TString */
function IsString$1(value) {
    return IsKindOf$1(value, 'String');
}
/** `[Kind-Only]` Returns true if the given value is TSymbol */
function IsSymbol$1(value) {
    return IsKindOf$1(value, 'Symbol');
}
/** `[Kind-Only]` Returns true if the given value is TTemplateLiteral */
function IsTemplateLiteral$1(value) {
    return IsKindOf$1(value, 'TemplateLiteral');
}
/** `[Kind-Only]` Returns true if the given value is TThis */
function IsThis$1(value) {
    return IsKindOf$1(value, 'This');
}
/** `[Kind-Only]` Returns true of this value is TTransform */
function IsTransform$1(value) {
    return IsObject$3(value) && TransformKind in value;
}
/** `[Kind-Only]` Returns true if the given value is TTuple */
function IsTuple$1(value) {
    return IsKindOf$1(value, 'Tuple');
}
/** `[Kind-Only]` Returns true if the given value is TUndefined */
function IsUndefined$1(value) {
    return IsKindOf$1(value, 'Undefined');
}
/** `[Kind-Only]` Returns true if the given value is TUnion */
function IsUnion$1(value) {
    return IsKindOf$1(value, 'Union');
}
/** `[Kind-Only]` Returns true if the given value is TUint8Array */
function IsUint8Array$1(value) {
    return IsKindOf$1(value, 'Uint8Array');
}
/** `[Kind-Only]` Returns true if the given value is TUnknown */
function IsUnknown$1(value) {
    return IsKindOf$1(value, 'Unknown');
}
/** `[Kind-Only]` Returns true if the given value is a raw TUnsafe */
function IsUnsafe$1(value) {
    return IsKindOf$1(value, 'Unsafe');
}
/** `[Kind-Only]` Returns true if the given value is TVoid */
function IsVoid$1(value) {
    return IsKindOf$1(value, 'Void');
}
/** `[Kind-Only]` Returns true if the given value is TKind */
function IsKind$1(value) {
    return IsObject$3(value) && Kind in value && IsString$2(value[Kind]);
}
/** `[Kind-Only]` Returns true if the given value is TSchema */
function IsSchema$1(value) {
    // prettier-ignore
    return (IsAny$1(value) ||
        IsArgument$1(value) ||
        IsArray$1(value) ||
        IsBoolean$1(value) ||
        IsBigInt$1(value) ||
        IsAsyncIterator$1(value) ||
        IsComputed$1(value) ||
        IsConstructor$1(value) ||
        IsDate$1(value) ||
        IsFunction$1(value) ||
        IsInteger$1(value) ||
        IsIntersect$1(value) ||
        IsIterator$1(value) ||
        IsLiteral$1(value) ||
        IsMappedKey$1(value) ||
        IsMappedResult$1(value) ||
        IsNever$1(value) ||
        IsNot$1(value) ||
        IsNull$1(value) ||
        IsNumber$1(value) ||
        IsObject$1(value) ||
        IsPromise$1(value) ||
        IsRecord$1(value) ||
        IsRef$1(value) ||
        IsRegExp$1(value) ||
        IsString$1(value) ||
        IsSymbol$1(value) ||
        IsTemplateLiteral$1(value) ||
        IsThis$1(value) ||
        IsTuple$1(value) ||
        IsUndefined$1(value) ||
        IsUnion$1(value) ||
        IsUint8Array$1(value) ||
        IsUnknown$1(value) ||
        IsUnsafe$1(value) ||
        IsVoid$1(value) ||
        IsKind$1(value));
}

const KnownTypes = [
    'Argument',
    'Any',
    'Array',
    'AsyncIterator',
    'BigInt',
    'Boolean',
    'Computed',
    'Constructor',
    'Date',
    'Enum',
    'Function',
    'Integer',
    'Intersect',
    'Iterator',
    'Literal',
    'MappedKey',
    'MappedResult',
    'Not',
    'Null',
    'Number',
    'Object',
    'Promise',
    'Record',
    'Ref',
    'RegExp',
    'String',
    'Symbol',
    'TemplateLiteral',
    'This',
    'Tuple',
    'Undefined',
    'Union',
    'Uint8Array',
    'Unknown',
    'Void',
];
function IsPattern(value) {
    try {
        new RegExp(value);
        return true;
    }
    catch {
        return false;
    }
}
function IsControlCharacterFree(value) {
    if (!IsString$2(value))
        return false;
    for (let i = 0; i < value.length; i++) {
        const code = value.charCodeAt(i);
        if ((code >= 7 && code <= 13) || code === 27 || code === 127) {
            return false;
        }
    }
    return true;
}
function IsAdditionalProperties(value) {
    return IsOptionalBoolean(value) || IsSchema(value);
}
function IsOptionalBigInt(value) {
    return IsUndefined$3(value) || IsBigInt$2(value);
}
function IsOptionalNumber(value) {
    return IsUndefined$3(value) || IsNumber$3(value);
}
function IsOptionalBoolean(value) {
    return IsUndefined$3(value) || IsBoolean$2(value);
}
function IsOptionalString(value) {
    return IsUndefined$3(value) || IsString$2(value);
}
function IsOptionalPattern(value) {
    return IsUndefined$3(value) || (IsString$2(value) && IsControlCharacterFree(value) && IsPattern(value));
}
function IsOptionalFormat(value) {
    return IsUndefined$3(value) || (IsString$2(value) && IsControlCharacterFree(value));
}
function IsOptionalSchema(value) {
    return IsUndefined$3(value) || IsSchema(value);
}
/** Returns true if this value has a Optional symbol */
function IsOptional(value) {
    return IsObject$3(value) && value[OptionalKind] === 'Optional';
}
// ------------------------------------------------------------------
// Types
// ------------------------------------------------------------------
/** Returns true if the given value is TAny */
function IsAny(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Any') &&
        IsOptionalString(value.$id));
}
/** Returns true if the given value is TArgument */
function IsArgument(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Argument') &&
        IsNumber$3(value.index));
}
/** Returns true if the given value is TArray */
function IsArray(value) {
    return (IsKindOf(value, 'Array') &&
        value.type === 'array' &&
        IsOptionalString(value.$id) &&
        IsSchema(value.items) &&
        IsOptionalNumber(value.minItems) &&
        IsOptionalNumber(value.maxItems) &&
        IsOptionalBoolean(value.uniqueItems) &&
        IsOptionalSchema(value.contains) &&
        IsOptionalNumber(value.minContains) &&
        IsOptionalNumber(value.maxContains));
}
/** Returns true if the given value is TAsyncIterator */
function IsAsyncIterator(value) {
    // prettier-ignore
    return (IsKindOf(value, 'AsyncIterator') &&
        value.type === 'AsyncIterator' &&
        IsOptionalString(value.$id) &&
        IsSchema(value.items));
}
/** Returns true if the given value is TBigInt */
function IsBigInt(value) {
    // prettier-ignore
    return (IsKindOf(value, 'BigInt') &&
        value.type === 'bigint' &&
        IsOptionalString(value.$id) &&
        IsOptionalBigInt(value.exclusiveMaximum) &&
        IsOptionalBigInt(value.exclusiveMinimum) &&
        IsOptionalBigInt(value.maximum) &&
        IsOptionalBigInt(value.minimum) &&
        IsOptionalBigInt(value.multipleOf));
}
/** Returns true if the given value is TBoolean */
function IsBoolean(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Boolean') &&
        value.type === 'boolean' &&
        IsOptionalString(value.$id));
}
/** Returns true if the given value is TComputed */
function IsComputed(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Computed') &&
        IsString$2(value.target) &&
        IsArray$3(value.parameters) &&
        value.parameters.every((schema) => IsSchema(schema)));
}
/** Returns true if the given value is TConstructor */
function IsConstructor(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Constructor') &&
        value.type === 'Constructor' &&
        IsOptionalString(value.$id) &&
        IsArray$3(value.parameters) &&
        value.parameters.every(schema => IsSchema(schema)) &&
        IsSchema(value.returns));
}
/** Returns true if the given value is TDate */
function IsDate(value) {
    return (IsKindOf(value, 'Date') &&
        value.type === 'Date' &&
        IsOptionalString(value.$id) &&
        IsOptionalNumber(value.exclusiveMaximumTimestamp) &&
        IsOptionalNumber(value.exclusiveMinimumTimestamp) &&
        IsOptionalNumber(value.maximumTimestamp) &&
        IsOptionalNumber(value.minimumTimestamp) &&
        IsOptionalNumber(value.multipleOfTimestamp));
}
/** Returns true if the given value is TFunction */
function IsFunction(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Function') &&
        value.type === 'Function' &&
        IsOptionalString(value.$id) &&
        IsArray$3(value.parameters) &&
        value.parameters.every(schema => IsSchema(schema)) &&
        IsSchema(value.returns));
}
/** Returns true if the given value is TInteger */
function IsInteger(value) {
    return (IsKindOf(value, 'Integer') &&
        value.type === 'integer' &&
        IsOptionalString(value.$id) &&
        IsOptionalNumber(value.exclusiveMaximum) &&
        IsOptionalNumber(value.exclusiveMinimum) &&
        IsOptionalNumber(value.maximum) &&
        IsOptionalNumber(value.minimum) &&
        IsOptionalNumber(value.multipleOf));
}
/** Returns true if the given schema is TProperties */
function IsProperties(value) {
    // prettier-ignore
    return (IsObject$3(value) &&
        Object.entries(value).every(([key, schema]) => IsControlCharacterFree(key) && IsSchema(schema)));
}
/** Returns true if the given value is TIntersect */
function IsIntersect(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Intersect') &&
        (IsString$2(value.type) && value.type !== 'object' ? false : true) &&
        IsArray$3(value.allOf) &&
        value.allOf.every(schema => IsSchema(schema) && !IsTransform(schema)) &&
        IsOptionalString(value.type) &&
        (IsOptionalBoolean(value.unevaluatedProperties) || IsOptionalSchema(value.unevaluatedProperties)) &&
        IsOptionalString(value.$id));
}
/** Returns true if the given value is TIterator */
function IsIterator(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Iterator') &&
        value.type === 'Iterator' &&
        IsOptionalString(value.$id) &&
        IsSchema(value.items));
}
/** Returns true if the given value is a TKind with the given name. */
function IsKindOf(value, kind) {
    return IsObject$3(value) && Kind in value && value[Kind] === kind;
}
/** Returns true if the given value is TLiteral<string> */
function IsLiteralString(value) {
    return IsLiteral(value) && IsString$2(value.const);
}
/** Returns true if the given value is TLiteral<number> */
function IsLiteralNumber(value) {
    return IsLiteral(value) && IsNumber$3(value.const);
}
/** Returns true if the given value is TLiteral<boolean> */
function IsLiteralBoolean(value) {
    return IsLiteral(value) && IsBoolean$2(value.const);
}
/** Returns true if the given value is TLiteral */
function IsLiteral(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Literal') &&
        IsOptionalString(value.$id) && IsLiteralValue(value.const));
}
/** Returns true if the given value is a TLiteralValue */
function IsLiteralValue(value) {
    return IsBoolean$2(value) || IsNumber$3(value) || IsString$2(value);
}
/** Returns true if the given value is a TMappedKey */
function IsMappedKey(value) {
    // prettier-ignore
    return (IsKindOf(value, 'MappedKey') &&
        IsArray$3(value.keys) &&
        value.keys.every(key => IsNumber$3(key) || IsString$2(key)));
}
/** Returns true if the given value is TMappedResult */
function IsMappedResult(value) {
    // prettier-ignore
    return (IsKindOf(value, 'MappedResult') &&
        IsProperties(value.properties));
}
/** Returns true if the given value is TNever */
function IsNever(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Never') &&
        IsObject$3(value.not) &&
        Object.getOwnPropertyNames(value.not).length === 0);
}
/** Returns true if the given value is TNot */
function IsNot(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Not') &&
        IsSchema(value.not));
}
/** Returns true if the given value is TNull */
function IsNull(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Null') &&
        value.type === 'null' &&
        IsOptionalString(value.$id));
}
/** Returns true if the given value is TNumber */
function IsNumber(value) {
    return (IsKindOf(value, 'Number') &&
        value.type === 'number' &&
        IsOptionalString(value.$id) &&
        IsOptionalNumber(value.exclusiveMaximum) &&
        IsOptionalNumber(value.exclusiveMinimum) &&
        IsOptionalNumber(value.maximum) &&
        IsOptionalNumber(value.minimum) &&
        IsOptionalNumber(value.multipleOf));
}
/** Returns true if the given value is TObject */
function IsObject(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Object') &&
        value.type === 'object' &&
        IsOptionalString(value.$id) &&
        IsProperties(value.properties) &&
        IsAdditionalProperties(value.additionalProperties) &&
        IsOptionalNumber(value.minProperties) &&
        IsOptionalNumber(value.maxProperties));
}
/** Returns true if the given value is TPromise */
function IsPromise(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Promise') &&
        value.type === 'Promise' &&
        IsOptionalString(value.$id) &&
        IsSchema(value.item));
}
/** Returns true if the given value is TRecord */
function IsRecord(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Record') &&
        value.type === 'object' &&
        IsOptionalString(value.$id) &&
        IsAdditionalProperties(value.additionalProperties) &&
        IsObject$3(value.patternProperties) &&
        ((schema) => {
            const keys = Object.getOwnPropertyNames(schema.patternProperties);
            return (keys.length === 1 &&
                IsPattern(keys[0]) &&
                IsObject$3(schema.patternProperties) &&
                IsSchema(schema.patternProperties[keys[0]]));
        })(value));
}
/** Returns true if the given value is TRef */
function IsRef(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Ref') &&
        IsOptionalString(value.$id) &&
        IsString$2(value.$ref));
}
/** Returns true if the given value is TRegExp */
function IsRegExp(value) {
    // prettier-ignore
    return (IsKindOf(value, 'RegExp') &&
        IsOptionalString(value.$id) &&
        IsString$2(value.source) &&
        IsString$2(value.flags) &&
        IsOptionalNumber(value.maxLength) &&
        IsOptionalNumber(value.minLength));
}
/** Returns true if the given value is TString */
function IsString(value) {
    // prettier-ignore
    return (IsKindOf(value, 'String') &&
        value.type === 'string' &&
        IsOptionalString(value.$id) &&
        IsOptionalNumber(value.minLength) &&
        IsOptionalNumber(value.maxLength) &&
        IsOptionalPattern(value.pattern) &&
        IsOptionalFormat(value.format));
}
/** Returns true if the given value is TSymbol */
function IsSymbol(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Symbol') &&
        value.type === 'symbol' &&
        IsOptionalString(value.$id));
}
/** Returns true if the given value is TTemplateLiteral */
function IsTemplateLiteral(value) {
    // prettier-ignore
    return (IsKindOf(value, 'TemplateLiteral') &&
        value.type === 'string' &&
        IsString$2(value.pattern) &&
        value.pattern[0] === '^' &&
        value.pattern[value.pattern.length - 1] === '$');
}
/** Returns true if the given value is TThis */
function IsThis(value) {
    // prettier-ignore
    return (IsKindOf(value, 'This') &&
        IsOptionalString(value.$id) &&
        IsString$2(value.$ref));
}
/** Returns true of this value is TTransform */
function IsTransform(value) {
    return IsObject$3(value) && TransformKind in value;
}
/** Returns true if the given value is TTuple */
function IsTuple(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Tuple') &&
        value.type === 'array' &&
        IsOptionalString(value.$id) &&
        IsNumber$3(value.minItems) &&
        IsNumber$3(value.maxItems) &&
        value.minItems === value.maxItems &&
        (( // empty
        IsUndefined$3(value.items) &&
            IsUndefined$3(value.additionalItems) &&
            value.minItems === 0) || (IsArray$3(value.items) &&
            value.items.every(schema => IsSchema(schema)))));
}
/** Returns true if the given value is TUndefined */
function IsUndefined(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Undefined') &&
        value.type === 'undefined' &&
        IsOptionalString(value.$id));
}
/** Returns true if the given value is TUnion */
function IsUnion(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Union') &&
        IsOptionalString(value.$id) &&
        IsObject$3(value) &&
        IsArray$3(value.anyOf) &&
        value.anyOf.every(schema => IsSchema(schema)));
}
/** Returns true if the given value is TUint8Array */
function IsUint8Array(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Uint8Array') &&
        value.type === 'Uint8Array' &&
        IsOptionalString(value.$id) &&
        IsOptionalNumber(value.minByteLength) &&
        IsOptionalNumber(value.maxByteLength));
}
/** Returns true if the given value is TUnknown */
function IsUnknown(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Unknown') &&
        IsOptionalString(value.$id));
}
/** Returns true if the given value is a raw TUnsafe */
function IsUnsafe(value) {
    return IsKindOf(value, 'Unsafe');
}
/** Returns true if the given value is TVoid */
function IsVoid(value) {
    // prettier-ignore
    return (IsKindOf(value, 'Void') &&
        value.type === 'void' &&
        IsOptionalString(value.$id));
}
/** Returns true if the given value is TKind */
function IsKind(value) {
    return IsObject$3(value) && Kind in value && IsString$2(value[Kind]) && !KnownTypes.includes(value[Kind]);
}
/** Returns true if the given value is TSchema */
function IsSchema(value) {
    // prettier-ignore
    return (IsObject$3(value)) && (IsAny(value) ||
        IsArgument(value) ||
        IsArray(value) ||
        IsBoolean(value) ||
        IsBigInt(value) ||
        IsAsyncIterator(value) ||
        IsComputed(value) ||
        IsConstructor(value) ||
        IsDate(value) ||
        IsFunction(value) ||
        IsInteger(value) ||
        IsIntersect(value) ||
        IsIterator(value) ||
        IsLiteral(value) ||
        IsMappedKey(value) ||
        IsMappedResult(value) ||
        IsNever(value) ||
        IsNot(value) ||
        IsNull(value) ||
        IsNumber(value) ||
        IsObject(value) ||
        IsPromise(value) ||
        IsRecord(value) ||
        IsRef(value) ||
        IsRegExp(value) ||
        IsString(value) ||
        IsSymbol(value) ||
        IsTemplateLiteral(value) ||
        IsThis(value) ||
        IsTuple(value) ||
        IsUndefined(value) ||
        IsUnion(value) ||
        IsUint8Array(value) ||
        IsUnknown(value) ||
        IsUnsafe(value) ||
        IsVoid(value) ||
        IsKind(value));
}

const PatternBoolean = '(true|false)';
const PatternNumber = '(0|[1-9][0-9]*)';
const PatternString = '(.*)';
const PatternNever = '(?!.*)';
const PatternNumberExact = `^${PatternNumber}$`;
const PatternStringExact = `^${PatternString}$`;
const PatternNeverExact = `^${PatternNever}$`;

/** Returns true if element right is in the set of left */
// prettier-ignore
function SetIncludes(T, S) {
    return T.includes(S);
}
/** Returns a distinct set of elements */
function SetDistinct(T) {
    return [...new Set(T)];
}
/** Returns the Intersect of the given sets */
function SetIntersect(T, S) {
    return T.filter((L) => S.includes(L));
}
// prettier-ignore
function SetIntersectManyResolve(T, Init) {
    return T.reduce((Acc, L) => {
        return SetIntersect(Acc, L);
    }, Init);
}
// prettier-ignore
function SetIntersectMany(T) {
    return (T.length === 1
        ? T[0]
        // Use left to initialize the accumulator for resolve
        : T.length > 1
            ? SetIntersectManyResolve(T.slice(1), T[0])
            : []);
}
/** Returns the Union of multiple sets */
function SetUnionMany(T) {
    const Acc = [];
    for (const L of T)
        Acc.push(...L);
    return Acc;
}

/** `[Json]` Creates an Any type */
function Any$1(options) {
    return CreateType({ [Kind]: 'Any' }, options);
}

/** `[Json]` Creates an Array type */
function Array$1(items, options) {
    return CreateType({ [Kind]: 'Array', type: 'array', items }, options);
}

/** `[JavaScript]` Creates an Argument Type. */
function Argument(index) {
    return CreateType({ [Kind]: 'Argument', index });
}

/** `[JavaScript]` Creates a AsyncIterator type */
function AsyncIterator$1(items, options) {
    return CreateType({ [Kind]: 'AsyncIterator', type: 'AsyncIterator', items }, options);
}

/** `[Internal]` Creates a deferred computed type. This type is used exclusively in modules to defer resolution of computable types that contain interior references  */
function Computed(target, parameters, options) {
    return CreateType({ [Kind]: 'Computed', target, parameters }, options);
}

function DiscardKey(value, key) {
    const { [key]: _, ...rest } = value;
    return rest;
}
/** Discards property keys from the given value. This function returns a shallow Clone. */
function Discard(value, keys) {
    return keys.reduce((acc, key) => DiscardKey(acc, key), value);
}

/** `[Json]` Creates a Never type */
function Never(options) {
    return CreateType({ [Kind]: 'Never', not: {} }, options);
}

// prettier-ignore
function MappedResult(properties) {
    return CreateType({
        [Kind]: 'MappedResult',
        properties
    });
}

/** `[JavaScript]` Creates a Constructor type */
function Constructor(parameters, returns, options) {
    return CreateType({ [Kind]: 'Constructor', type: 'Constructor', parameters, returns }, options);
}

/** `[JavaScript]` Creates a Function type */
function Function$1(parameters, returns, options) {
    return CreateType({ [Kind]: 'Function', type: 'Function', parameters, returns }, options);
}

function UnionCreate(T, options) {
    return CreateType({ [Kind]: 'Union', anyOf: T }, options);
}

// prettier-ignore
function IsUnionOptional(types) {
    return types.some(type => IsOptional$1(type));
}
// prettier-ignore
function RemoveOptionalFromRest$1(types) {
    return types.map(left => IsOptional$1(left) ? RemoveOptionalFromType$1(left) : left);
}
// prettier-ignore
function RemoveOptionalFromType$1(T) {
    return (Discard(T, [OptionalKind]));
}
// prettier-ignore
function ResolveUnion(types, options) {
    const isOptional = IsUnionOptional(types);
    return (isOptional
        ? Optional(UnionCreate(RemoveOptionalFromRest$1(types), options))
        : UnionCreate(RemoveOptionalFromRest$1(types), options));
}
/** `[Json]` Creates an evaluated Union type */
function UnionEvaluated(T, options) {
    // prettier-ignore
    return (T.length === 1 ? CreateType(T[0], options) :
        T.length === 0 ? Never(options) :
            ResolveUnion(T, options));
}

/** `[Json]` Creates a Union type */
function Union(types, options) {
    // prettier-ignore
    return (types.length === 0 ? Never(options) :
        types.length === 1 ? CreateType(types[0], options) :
            UnionCreate(types, options));
}

// ------------------------------------------------------------------
// TemplateLiteralParserError
// ------------------------------------------------------------------
class TemplateLiteralParserError extends TypeBoxError {
}
// -------------------------------------------------------------------
// Unescape
//
// Unescape for these control characters specifically. Note that this
// function is only called on non union group content, and where we
// still want to allow the user to embed control characters in that
// content. For review.
// -------------------------------------------------------------------
// prettier-ignore
function Unescape(pattern) {
    return pattern
        .replace(/\\\$/g, '$')
        .replace(/\\\*/g, '*')
        .replace(/\\\^/g, '^')
        .replace(/\\\|/g, '|')
        .replace(/\\\(/g, '(')
        .replace(/\\\)/g, ')');
}
// -------------------------------------------------------------------
// Control Characters
// -------------------------------------------------------------------
function IsNonEscaped(pattern, index, char) {
    return pattern[index] === char && pattern.charCodeAt(index - 1) !== 92;
}
function IsOpenParen(pattern, index) {
    return IsNonEscaped(pattern, index, '(');
}
function IsCloseParen(pattern, index) {
    return IsNonEscaped(pattern, index, ')');
}
function IsSeparator(pattern, index) {
    return IsNonEscaped(pattern, index, '|');
}
// -------------------------------------------------------------------
// Control Groups
// -------------------------------------------------------------------
function IsGroup(pattern) {
    if (!(IsOpenParen(pattern, 0) && IsCloseParen(pattern, pattern.length - 1)))
        return false;
    let count = 0;
    for (let index = 0; index < pattern.length; index++) {
        if (IsOpenParen(pattern, index))
            count += 1;
        if (IsCloseParen(pattern, index))
            count -= 1;
        if (count === 0 && index !== pattern.length - 1)
            return false;
    }
    return true;
}
// prettier-ignore
function InGroup(pattern) {
    return pattern.slice(1, pattern.length - 1);
}
// prettier-ignore
function IsPrecedenceOr(pattern) {
    let count = 0;
    for (let index = 0; index < pattern.length; index++) {
        if (IsOpenParen(pattern, index))
            count += 1;
        if (IsCloseParen(pattern, index))
            count -= 1;
        if (IsSeparator(pattern, index) && count === 0)
            return true;
    }
    return false;
}
// prettier-ignore
function IsPrecedenceAnd(pattern) {
    for (let index = 0; index < pattern.length; index++) {
        if (IsOpenParen(pattern, index))
            return true;
    }
    return false;
}
// prettier-ignore
function Or(pattern) {
    let [count, start] = [0, 0];
    const expressions = [];
    for (let index = 0; index < pattern.length; index++) {
        if (IsOpenParen(pattern, index))
            count += 1;
        if (IsCloseParen(pattern, index))
            count -= 1;
        if (IsSeparator(pattern, index) && count === 0) {
            const range = pattern.slice(start, index);
            if (range.length > 0)
                expressions.push(TemplateLiteralParse(range));
            start = index + 1;
        }
    }
    const range = pattern.slice(start);
    if (range.length > 0)
        expressions.push(TemplateLiteralParse(range));
    if (expressions.length === 0)
        return { type: 'const', const: '' };
    if (expressions.length === 1)
        return expressions[0];
    return { type: 'or', expr: expressions };
}
// prettier-ignore
function And(pattern) {
    function Group(value, index) {
        if (!IsOpenParen(value, index))
            throw new TemplateLiteralParserError(`TemplateLiteralParser: Index must point to open parens`);
        let count = 0;
        for (let scan = index; scan < value.length; scan++) {
            if (IsOpenParen(value, scan))
                count += 1;
            if (IsCloseParen(value, scan))
                count -= 1;
            if (count === 0)
                return [index, scan];
        }
        throw new TemplateLiteralParserError(`TemplateLiteralParser: Unclosed group parens in expression`);
    }
    function Range(pattern, index) {
        for (let scan = index; scan < pattern.length; scan++) {
            if (IsOpenParen(pattern, scan))
                return [index, scan];
        }
        return [index, pattern.length];
    }
    const expressions = [];
    for (let index = 0; index < pattern.length; index++) {
        if (IsOpenParen(pattern, index)) {
            const [start, end] = Group(pattern, index);
            const range = pattern.slice(start, end + 1);
            expressions.push(TemplateLiteralParse(range));
            index = end;
        }
        else {
            const [start, end] = Range(pattern, index);
            const range = pattern.slice(start, end);
            if (range.length > 0)
                expressions.push(TemplateLiteralParse(range));
            index = end - 1;
        }
    }
    return ((expressions.length === 0) ? { type: 'const', const: '' } :
        (expressions.length === 1) ? expressions[0] :
            { type: 'and', expr: expressions });
}
// ------------------------------------------------------------------
// TemplateLiteralParse
// ------------------------------------------------------------------
/** Parses a pattern and returns an expression tree */
function TemplateLiteralParse(pattern) {
    // prettier-ignore
    return (IsGroup(pattern) ? TemplateLiteralParse(InGroup(pattern)) :
        IsPrecedenceOr(pattern) ? Or(pattern) :
            IsPrecedenceAnd(pattern) ? And(pattern) :
                { type: 'const', const: Unescape(pattern) });
}
// ------------------------------------------------------------------
// TemplateLiteralParseExact
// ------------------------------------------------------------------
/** Parses a pattern and strips forward and trailing ^ and $ */
function TemplateLiteralParseExact(pattern) {
    return TemplateLiteralParse(pattern.slice(1, pattern.length - 1));
}

// ------------------------------------------------------------------
// TemplateLiteralFiniteError
// ------------------------------------------------------------------
class TemplateLiteralFiniteError extends TypeBoxError {
}
// ------------------------------------------------------------------
// IsTemplateLiteralFiniteCheck
// ------------------------------------------------------------------
// prettier-ignore
function IsNumberExpression(expression) {
    return (expression.type === 'or' &&
        expression.expr.length === 2 &&
        expression.expr[0].type === 'const' &&
        expression.expr[0].const === '0' &&
        expression.expr[1].type === 'const' &&
        expression.expr[1].const === '[1-9][0-9]*');
}
// prettier-ignore
function IsBooleanExpression(expression) {
    return (expression.type === 'or' &&
        expression.expr.length === 2 &&
        expression.expr[0].type === 'const' &&
        expression.expr[0].const === 'true' &&
        expression.expr[1].type === 'const' &&
        expression.expr[1].const === 'false');
}
// prettier-ignore
function IsStringExpression(expression) {
    return expression.type === 'const' && expression.const === '.*';
}
// ------------------------------------------------------------------
// IsTemplateLiteralExpressionFinite
// ------------------------------------------------------------------
// prettier-ignore
function IsTemplateLiteralExpressionFinite(expression) {
    return (IsNumberExpression(expression) || IsStringExpression(expression) ? false :
        IsBooleanExpression(expression) ? true :
            (expression.type === 'and') ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite(expr)) :
                (expression.type === 'or') ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite(expr)) :
                    (expression.type === 'const') ? true :
                        (() => { throw new TemplateLiteralFiniteError(`Unknown expression type`); })());
}
/** Returns true if this TemplateLiteral resolves to a finite set of values */
function IsTemplateLiteralFinite(schema) {
    const expression = TemplateLiteralParseExact(schema.pattern);
    return IsTemplateLiteralExpressionFinite(expression);
}

// ------------------------------------------------------------------
// TemplateLiteralGenerateError
// ------------------------------------------------------------------
class TemplateLiteralGenerateError extends TypeBoxError {
}
// ------------------------------------------------------------------
// TemplateLiteralExpressionGenerate
// ------------------------------------------------------------------
// prettier-ignore
function* GenerateReduce(buffer) {
    if (buffer.length === 1)
        return yield* buffer[0];
    for (const left of buffer[0]) {
        for (const right of GenerateReduce(buffer.slice(1))) {
            yield `${left}${right}`;
        }
    }
}
// prettier-ignore
function* GenerateAnd(expression) {
    return yield* GenerateReduce(expression.expr.map((expr) => [...TemplateLiteralExpressionGenerate(expr)]));
}
// prettier-ignore
function* GenerateOr(expression) {
    for (const expr of expression.expr)
        yield* TemplateLiteralExpressionGenerate(expr);
}
// prettier-ignore
function* GenerateConst(expression) {
    return yield expression.const;
}
function* TemplateLiteralExpressionGenerate(expression) {
    return expression.type === 'and'
        ? yield* GenerateAnd(expression)
        : expression.type === 'or'
            ? yield* GenerateOr(expression)
            : expression.type === 'const'
                ? yield* GenerateConst(expression)
                : (() => {
                    throw new TemplateLiteralGenerateError('Unknown expression');
                })();
}
/** Generates a tuple of strings from the given TemplateLiteral. Returns an empty tuple if infinite. */
function TemplateLiteralGenerate(schema) {
    const expression = TemplateLiteralParseExact(schema.pattern);
    // prettier-ignore
    return (IsTemplateLiteralExpressionFinite(expression)
        ? [...TemplateLiteralExpressionGenerate(expression)]
        : []);
}

/** `[Json]` Creates a Literal type */
function Literal(value, options) {
    return CreateType({
        [Kind]: 'Literal',
        const: value,
        type: typeof value,
    }, options);
}

/** `[Json]` Creates a Boolean type */
function Boolean$2(options) {
    return CreateType({ [Kind]: 'Boolean', type: 'boolean' }, options);
}

/** `[JavaScript]` Creates a BigInt type */
function BigInt$1(options) {
    return CreateType({ [Kind]: 'BigInt', type: 'bigint' }, options);
}

/** `[Json]` Creates a Number type */
function Number$1(options) {
    return CreateType({ [Kind]: 'Number', type: 'number' }, options);
}

/** `[Json]` Creates a String type */
function String$1(options) {
    return CreateType({ [Kind]: 'String', type: 'string' }, options);
}

// ------------------------------------------------------------------
// SyntaxParsers
// ------------------------------------------------------------------
// prettier-ignore
function* FromUnion$9(syntax) {
    const trim = syntax.trim().replace(/"|'/g, '');
    return (trim === 'boolean' ? yield Boolean$2() :
        trim === 'number' ? yield Number$1() :
            trim === 'bigint' ? yield BigInt$1() :
                trim === 'string' ? yield String$1() :
                    yield (() => {
                        const literals = trim.split('|').map((literal) => Literal(literal.trim()));
                        return (literals.length === 0 ? Never() :
                            literals.length === 1 ? literals[0] :
                                UnionEvaluated(literals));
                    })());
}
// prettier-ignore
function* FromTerminal(syntax) {
    if (syntax[1] !== '{') {
        const L = Literal('$');
        const R = FromSyntax(syntax.slice(1));
        return yield* [L, ...R];
    }
    for (let i = 2; i < syntax.length; i++) {
        if (syntax[i] === '}') {
            const L = FromUnion$9(syntax.slice(2, i));
            const R = FromSyntax(syntax.slice(i + 1));
            return yield* [...L, ...R];
        }
    }
    yield Literal(syntax);
}
// prettier-ignore
function* FromSyntax(syntax) {
    for (let i = 0; i < syntax.length; i++) {
        if (syntax[i] === '$') {
            const L = Literal(syntax.slice(0, i));
            const R = FromTerminal(syntax.slice(i));
            return yield* [L, ...R];
        }
    }
    yield Literal(syntax);
}
/** Parses TemplateLiteralSyntax and returns a tuple of TemplateLiteralKinds */
function TemplateLiteralSyntax(syntax) {
    return [...FromSyntax(syntax)];
}

// ------------------------------------------------------------------
// TemplateLiteralPatternError
// ------------------------------------------------------------------
class TemplateLiteralPatternError extends TypeBoxError {
}
// ------------------------------------------------------------------
// TemplateLiteralPattern
// ------------------------------------------------------------------
function Escape(value) {
    return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
// prettier-ignore
function Visit$1(schema, acc) {
    return (IsTemplateLiteral$1(schema) ? schema.pattern.slice(1, schema.pattern.length - 1) :
        IsUnion$1(schema) ? `(${schema.anyOf.map((schema) => Visit$1(schema, acc)).join('|')})` :
            IsNumber$1(schema) ? `${acc}${PatternNumber}` :
                IsInteger$1(schema) ? `${acc}${PatternNumber}` :
                    IsBigInt$1(schema) ? `${acc}${PatternNumber}` :
                        IsString$1(schema) ? `${acc}${PatternString}` :
                            IsLiteral$1(schema) ? `${acc}${Escape(schema.const.toString())}` :
                                IsBoolean$1(schema) ? `${acc}${PatternBoolean}` :
                                    (() => { throw new TemplateLiteralPatternError(`Unexpected Kind '${schema[Kind]}'`); })());
}
function TemplateLiteralPattern(kinds) {
    return `^${kinds.map((schema) => Visit$1(schema, '')).join('')}\$`;
}

/** Returns a Union from the given TemplateLiteral */
function TemplateLiteralToUnion(schema) {
    const R = TemplateLiteralGenerate(schema);
    const L = R.map((S) => Literal(S));
    return UnionEvaluated(L);
}

/** `[Json]` Creates a TemplateLiteral type */
// prettier-ignore
function TemplateLiteral(unresolved, options) {
    const pattern = IsString$2(unresolved)
        ? TemplateLiteralPattern(TemplateLiteralSyntax(unresolved))
        : TemplateLiteralPattern(unresolved);
    return CreateType({ [Kind]: 'TemplateLiteral', type: 'string', pattern }, options);
}

// prettier-ignore
function FromTemplateLiteral$2(templateLiteral) {
    const keys = TemplateLiteralGenerate(templateLiteral);
    return keys.map(key => key.toString());
}
// prettier-ignore
function FromUnion$8(types) {
    const result = [];
    for (const type of types)
        result.push(...IndexPropertyKeys(type));
    return result;
}
// prettier-ignore
function FromLiteral$1(literalValue) {
    return ([literalValue.toString()] // TS 5.4 observes TLiteralValue as not having a toString()
    );
}
/** Returns a tuple of PropertyKeys derived from the given TSchema */
// prettier-ignore
function IndexPropertyKeys(type) {
    return [...new Set((IsTemplateLiteral$1(type) ? FromTemplateLiteral$2(type) :
            IsUnion$1(type) ? FromUnion$8(type.anyOf) :
                IsLiteral$1(type) ? FromLiteral$1(type.const) :
                    IsNumber$1(type) ? ['[number]'] :
                        IsInteger$1(type) ? ['[number]'] :
                            []))];
}

// prettier-ignore
function FromProperties$i(type, properties, options) {
    const result = {};
    for (const K2 of Object.getOwnPropertyNames(properties)) {
        result[K2] = Index(type, IndexPropertyKeys(properties[K2]), options);
    }
    return result;
}
// prettier-ignore
function FromMappedResult$b(type, mappedResult, options) {
    return FromProperties$i(type, mappedResult.properties, options);
}
// prettier-ignore
function IndexFromMappedResult(type, mappedResult, options) {
    const properties = FromMappedResult$b(type, mappedResult, options);
    return MappedResult(properties);
}

// prettier-ignore
function FromRest$6(types, key) {
    return types.map(type => IndexFromPropertyKey(type, key));
}
// prettier-ignore
function FromIntersectRest(types) {
    return types.filter(type => !IsNever$1(type));
}
// prettier-ignore
function FromIntersect$7(types, key) {
    return (IntersectEvaluated(FromIntersectRest(FromRest$6(types, key))));
}
// prettier-ignore
function FromUnionRest(types) {
    return (types.some(L => IsNever$1(L))
        ? []
        : types);
}
// prettier-ignore
function FromUnion$7(types, key) {
    return (UnionEvaluated(FromUnionRest(FromRest$6(types, key))));
}
// prettier-ignore
function FromTuple$4(types, key) {
    return (key in types ? types[key] :
        key === '[number]' ? UnionEvaluated(types) :
            Never());
}
// prettier-ignore
function FromArray$5(type, key) {
    return (key === '[number]'
        ? type
        : Never());
}
// prettier-ignore
function FromProperty$2(properties, propertyKey) {
    return (propertyKey in properties ? properties[propertyKey] : Never());
}
// prettier-ignore
function IndexFromPropertyKey(type, propertyKey) {
    return (IsIntersect$1(type) ? FromIntersect$7(type.allOf, propertyKey) :
        IsUnion$1(type) ? FromUnion$7(type.anyOf, propertyKey) :
            IsTuple$1(type) ? FromTuple$4(type.items ?? [], propertyKey) :
                IsArray$1(type) ? FromArray$5(type.items, propertyKey) :
                    IsObject$1(type) ? FromProperty$2(type.properties, propertyKey) :
                        Never());
}
// prettier-ignore
function IndexFromPropertyKeys(type, propertyKeys) {
    return propertyKeys.map(propertyKey => IndexFromPropertyKey(type, propertyKey));
}
// prettier-ignore
function FromSchema(type, propertyKeys) {
    return (UnionEvaluated(IndexFromPropertyKeys(type, propertyKeys)));
}
/** `[Json]` Returns an Indexed property type for the given keys */
function Index(type, key, options) {
    // computed-type
    if (IsRef$1(type) || IsRef$1(key)) {
        const error = `Index types using Ref parameters require both Type and Key to be of TSchema`;
        if (!IsSchema$1(type) || !IsSchema$1(key))
            throw new TypeBoxError(error);
        return Computed('Index', [type, key]);
    }
    // mapped-types
    if (IsMappedResult$1(key))
        return IndexFromMappedResult(type, key, options);
    if (IsMappedKey$1(key))
        return IndexFromMappedKey(type, key, options);
    // prettier-ignore
    return CreateType(IsSchema$1(key)
        ? FromSchema(type, IndexPropertyKeys(key))
        : FromSchema(type, key), options);
}

// prettier-ignore
function MappedIndexPropertyKey(type, key, options) {
    return { [key]: Index(type, [key], Clone(options)) };
}
// prettier-ignore
function MappedIndexPropertyKeys(type, propertyKeys, options) {
    return propertyKeys.reduce((result, left) => {
        return { ...result, ...MappedIndexPropertyKey(type, left, options) };
    }, {});
}
// prettier-ignore
function MappedIndexProperties(type, mappedKey, options) {
    return MappedIndexPropertyKeys(type, mappedKey.keys, options);
}
// prettier-ignore
function IndexFromMappedKey(type, mappedKey, options) {
    const properties = MappedIndexProperties(type, mappedKey, options);
    return MappedResult(properties);
}

/** `[JavaScript]` Creates an Iterator type */
function Iterator$1(items, options) {
    return CreateType({ [Kind]: 'Iterator', type: 'Iterator', items }, options);
}

function RequiredKeys(properties) {
    const keys = [];
    for (let key in properties) {
        if (!IsOptional$1(properties[key]))
            keys.push(key);
    }
    return keys;
}
/** `[Json]` Creates an Object type */
function _Object(properties, options) {
    const required = RequiredKeys(properties);
    const schematic = required.length > 0 ? { [Kind]: 'Object', type: 'object', properties, required } : { [Kind]: 'Object', type: 'object', properties };
    return CreateType(schematic, options);
}
/** `[Json]` Creates an Object type */
var Object$1 = _Object;

/** `[JavaScript]` Creates a Promise type */
function Promise$1(item, options) {
    return CreateType({ [Kind]: 'Promise', type: 'Promise', item }, options);
}

function RemoveReadonly(schema) {
    return CreateType(Discard(schema, [ReadonlyKind]));
}
function AddReadonly(schema) {
    return CreateType({ ...schema, [ReadonlyKind]: 'Readonly' });
}
// prettier-ignore
function ReadonlyWithFlag(schema, F) {
    return (F === false
        ? RemoveReadonly(schema)
        : AddReadonly(schema));
}
/** `[Json]` Creates a Readonly property */
function Readonly(schema, enable) {
    const F = enable ?? true;
    return IsMappedResult$1(schema) ? ReadonlyFromMappedResult(schema, F) : ReadonlyWithFlag(schema, F);
}

// prettier-ignore
function FromProperties$h(K, F) {
    const Acc = {};
    for (const K2 of globalThis.Object.getOwnPropertyNames(K))
        Acc[K2] = Readonly(K[K2], F);
    return Acc;
}
// prettier-ignore
function FromMappedResult$a(R, F) {
    return FromProperties$h(R.properties, F);
}
// prettier-ignore
function ReadonlyFromMappedResult(R, F) {
    const P = FromMappedResult$a(R, F);
    return MappedResult(P);
}

/** `[Json]` Creates a Tuple type */
function Tuple(types, options) {
    // prettier-ignore
    return CreateType(types.length > 0 ?
        { [Kind]: 'Tuple', type: 'array', items: types, additionalItems: false, minItems: types.length, maxItems: types.length } :
        { [Kind]: 'Tuple', type: 'array', minItems: types.length, maxItems: types.length }, options);
}

// prettier-ignore
function FromMappedResult$9(K, P) {
    return (K in P
        ? FromSchemaType(K, P[K])
        : MappedResult(P));
}
// prettier-ignore
function MappedKeyToKnownMappedResultProperties(K) {
    return { [K]: Literal(K) };
}
// prettier-ignore
function MappedKeyToUnknownMappedResultProperties(P) {
    const Acc = {};
    for (const L of P)
        Acc[L] = Literal(L);
    return Acc;
}
// prettier-ignore
function MappedKeyToMappedResultProperties(K, P) {
    return (SetIncludes(P, K)
        ? MappedKeyToKnownMappedResultProperties(K)
        : MappedKeyToUnknownMappedResultProperties(P));
}
// prettier-ignore
function FromMappedKey$3(K, P) {
    const R = MappedKeyToMappedResultProperties(K, P);
    return FromMappedResult$9(K, R);
}
// prettier-ignore
function FromRest$5(K, T) {
    return T.map(L => FromSchemaType(K, L));
}
// prettier-ignore
function FromProperties$g(K, T) {
    const Acc = {};
    for (const K2 of globalThis.Object.getOwnPropertyNames(T))
        Acc[K2] = FromSchemaType(K, T[K2]);
    return Acc;
}
// prettier-ignore
function FromSchemaType(K, T) {
    // required to retain user defined options for mapped type
    const options = { ...T };
    return (
    // unevaluated modifier types
    IsOptional$1(T) ? Optional(FromSchemaType(K, Discard(T, [OptionalKind]))) :
        IsReadonly(T) ? Readonly(FromSchemaType(K, Discard(T, [ReadonlyKind]))) :
            // unevaluated mapped types
            IsMappedResult$1(T) ? FromMappedResult$9(K, T.properties) :
                IsMappedKey$1(T) ? FromMappedKey$3(K, T.keys) :
                    // unevaluated types
                    IsConstructor$1(T) ? Constructor(FromRest$5(K, T.parameters), FromSchemaType(K, T.returns), options) :
                        IsFunction$1(T) ? Function$1(FromRest$5(K, T.parameters), FromSchemaType(K, T.returns), options) :
                            IsAsyncIterator$1(T) ? AsyncIterator$1(FromSchemaType(K, T.items), options) :
                                IsIterator$1(T) ? Iterator$1(FromSchemaType(K, T.items), options) :
                                    IsIntersect$1(T) ? Intersect(FromRest$5(K, T.allOf), options) :
                                        IsUnion$1(T) ? Union(FromRest$5(K, T.anyOf), options) :
                                            IsTuple$1(T) ? Tuple(FromRest$5(K, T.items ?? []), options) :
                                                IsObject$1(T) ? Object$1(FromProperties$g(K, T.properties), options) :
                                                    IsArray$1(T) ? Array$1(FromSchemaType(K, T.items), options) :
                                                        IsPromise$1(T) ? Promise$1(FromSchemaType(K, T.item), options) :
                                                            T);
}
// prettier-ignore
function MappedFunctionReturnType(K, T) {
    const Acc = {};
    for (const L of K)
        Acc[L] = FromSchemaType(L, T);
    return Acc;
}
/** `[Json]` Creates a Mapped object type */
function Mapped(key, map, options) {
    const K = IsSchema$1(key) ? IndexPropertyKeys(key) : key;
    const RT = map({ [Kind]: 'MappedKey', keys: K });
    const R = MappedFunctionReturnType(K, RT);
    return Object$1(R, options);
}

function RemoveOptional(schema) {
    return CreateType(Discard(schema, [OptionalKind]));
}
function AddOptional(schema) {
    return CreateType({ ...schema, [OptionalKind]: 'Optional' });
}
// prettier-ignore
function OptionalWithFlag(schema, F) {
    return (F === false
        ? RemoveOptional(schema)
        : AddOptional(schema));
}
/** `[Json]` Creates a Optional property */
function Optional(schema, enable) {
    const F = enable ?? true;
    return IsMappedResult$1(schema) ? OptionalFromMappedResult(schema, F) : OptionalWithFlag(schema, F);
}

// prettier-ignore
function FromProperties$f(P, F) {
    const Acc = {};
    for (const K2 of globalThis.Object.getOwnPropertyNames(P))
        Acc[K2] = Optional(P[K2], F);
    return Acc;
}
// prettier-ignore
function FromMappedResult$8(R, F) {
    return FromProperties$f(R.properties, F);
}
// prettier-ignore
function OptionalFromMappedResult(R, F) {
    const P = FromMappedResult$8(R, F);
    return MappedResult(P);
}

// ------------------------------------------------------------------
// IntersectCreate
// ------------------------------------------------------------------
// prettier-ignore
function IntersectCreate(T, options = {}) {
    const allObjects = T.every((schema) => IsObject$1(schema));
    const clonedUnevaluatedProperties = IsSchema$1(options.unevaluatedProperties)
        ? { unevaluatedProperties: options.unevaluatedProperties }
        : {};
    return CreateType((options.unevaluatedProperties === false || IsSchema$1(options.unevaluatedProperties) || allObjects
        ? { ...clonedUnevaluatedProperties, [Kind]: 'Intersect', type: 'object', allOf: T }
        : { ...clonedUnevaluatedProperties, [Kind]: 'Intersect', allOf: T }), options);
}

// prettier-ignore
function IsIntersectOptional(types) {
    return types.every(left => IsOptional$1(left));
}
// prettier-ignore
function RemoveOptionalFromType(type) {
    return (Discard(type, [OptionalKind]));
}
// prettier-ignore
function RemoveOptionalFromRest(types) {
    return types.map(left => IsOptional$1(left) ? RemoveOptionalFromType(left) : left);
}
// prettier-ignore
function ResolveIntersect(types, options) {
    return (IsIntersectOptional(types)
        ? Optional(IntersectCreate(RemoveOptionalFromRest(types), options))
        : IntersectCreate(RemoveOptionalFromRest(types), options));
}
/** `[Json]` Creates an evaluated Intersect type */
function IntersectEvaluated(types, options = {}) {
    if (types.length === 1)
        return CreateType(types[0], options);
    if (types.length === 0)
        return Never(options);
    if (types.some((schema) => IsTransform$1(schema)))
        throw new Error('Cannot intersect transform types');
    return ResolveIntersect(types, options);
}

/** `[Json]` Creates an evaluated Intersect type */
function Intersect(types, options) {
    if (types.length === 1)
        return CreateType(types[0], options);
    if (types.length === 0)
        return Never(options);
    if (types.some((schema) => IsTransform$1(schema)))
        throw new Error('Cannot intersect transform types');
    return IntersectCreate(types, options);
}

/** `[Json]` Creates a Ref type. The referenced type must contain a $id */
function Ref(...args) {
    const [$ref, options] = typeof args[0] === 'string' ? [args[0], args[1]] : [args[0].$id, args[1]];
    if (typeof $ref !== 'string')
        throw new TypeBoxError('Ref: $ref must be a string');
    return CreateType({ [Kind]: 'Ref', $ref }, options);
}

// prettier-ignore
function FromComputed$4(target, parameters) {
    return Computed('Awaited', [Computed(target, parameters)]);
}
// prettier-ignore
function FromRef$3($ref) {
    return Computed('Awaited', [Ref($ref)]);
}
// prettier-ignore
function FromIntersect$6(types) {
    return Intersect(FromRest$4(types));
}
// prettier-ignore
function FromUnion$6(types) {
    return Union(FromRest$4(types));
}
// prettier-ignore
function FromPromise$2(type) {
    return Awaited(type);
}
// prettier-ignore
function FromRest$4(types) {
    return types.map(type => Awaited(type));
}
/** `[JavaScript]` Constructs a type by recursively unwrapping Promise types */
function Awaited(type, options) {
    return CreateType(IsComputed$1(type) ? FromComputed$4(type.target, type.parameters) : IsIntersect$1(type) ? FromIntersect$6(type.allOf) : IsUnion$1(type) ? FromUnion$6(type.anyOf) : IsPromise$1(type) ? FromPromise$2(type.item) : IsRef$1(type) ? FromRef$3(type.$ref) : type, options);
}

// prettier-ignore
function FromRest$3(types) {
    const result = [];
    for (const L of types)
        result.push(KeyOfPropertyKeys(L));
    return result;
}
// prettier-ignore
function FromIntersect$5(types) {
    const propertyKeysArray = FromRest$3(types);
    const propertyKeys = SetUnionMany(propertyKeysArray);
    return propertyKeys;
}
// prettier-ignore
function FromUnion$5(types) {
    const propertyKeysArray = FromRest$3(types);
    const propertyKeys = SetIntersectMany(propertyKeysArray);
    return propertyKeys;
}
// prettier-ignore
function FromTuple$3(types) {
    return types.map((_, indexer) => indexer.toString());
}
// prettier-ignore
function FromArray$4(_) {
    return (['[number]']);
}
// prettier-ignore
function FromProperties$e(T) {
    return (globalThis.Object.getOwnPropertyNames(T));
}
// ------------------------------------------------------------------
// FromPatternProperties
// ------------------------------------------------------------------
// prettier-ignore
function FromPatternProperties(patternProperties) {
    return [];
}
/** Returns a tuple of PropertyKeys derived from the given TSchema. */
// prettier-ignore
function KeyOfPropertyKeys(type) {
    return (IsIntersect$1(type) ? FromIntersect$5(type.allOf) :
        IsUnion$1(type) ? FromUnion$5(type.anyOf) :
            IsTuple$1(type) ? FromTuple$3(type.items ?? []) :
                IsArray$1(type) ? FromArray$4(type.items) :
                    IsObject$1(type) ? FromProperties$e(type.properties) :
                        IsRecord$1(type) ? FromPatternProperties(type.patternProperties) :
                            []);
}

// prettier-ignore
function FromComputed$3(target, parameters) {
    return Computed('KeyOf', [Computed(target, parameters)]);
}
// prettier-ignore
function FromRef$2($ref) {
    return Computed('KeyOf', [Ref($ref)]);
}
// prettier-ignore
function KeyOfFromType(type, options) {
    const propertyKeys = KeyOfPropertyKeys(type);
    const propertyKeyTypes = KeyOfPropertyKeysToRest(propertyKeys);
    const result = UnionEvaluated(propertyKeyTypes);
    return CreateType(result, options);
}
// prettier-ignore
function KeyOfPropertyKeysToRest(propertyKeys) {
    return propertyKeys.map(L => L === '[number]' ? Number$1() : Literal(L));
}
/** `[Json]` Creates a KeyOf type */
function KeyOf(type, options) {
    return (IsComputed$1(type) ? FromComputed$3(type.target, type.parameters) : IsRef$1(type) ? FromRef$2(type.$ref) : IsMappedResult$1(type) ? KeyOfFromMappedResult(type, options) : KeyOfFromType(type, options));
}

// prettier-ignore
function FromProperties$d(properties, options) {
    const result = {};
    for (const K2 of globalThis.Object.getOwnPropertyNames(properties))
        result[K2] = KeyOf(properties[K2], Clone(options));
    return result;
}
// prettier-ignore
function FromMappedResult$7(mappedResult, options) {
    return FromProperties$d(mappedResult.properties, options);
}
// prettier-ignore
function KeyOfFromMappedResult(mappedResult, options) {
    const properties = FromMappedResult$7(mappedResult, options);
    return MappedResult(properties);
}

// prettier-ignore
function CompositeKeys(T) {
    const Acc = [];
    for (const L of T)
        Acc.push(...KeyOfPropertyKeys(L));
    return SetDistinct(Acc);
}
// prettier-ignore
function FilterNever(T) {
    return T.filter(L => !IsNever$1(L));
}
// prettier-ignore
function CompositeProperty(T, K) {
    const Acc = [];
    for (const L of T)
        Acc.push(...IndexFromPropertyKeys(L, [K]));
    return FilterNever(Acc);
}
// prettier-ignore
function CompositeProperties(T, K) {
    const Acc = {};
    for (const L of K) {
        Acc[L] = IntersectEvaluated(CompositeProperty(T, L));
    }
    return Acc;
}
// prettier-ignore
function Composite(T, options) {
    const K = CompositeKeys(T);
    const P = CompositeProperties(T, K);
    const R = Object$1(P, options);
    return R;
}

/** `[JavaScript]` Creates a Date type */
function Date$1(options) {
    return CreateType({ [Kind]: 'Date', type: 'Date' }, options);
}

/** `[Json]` Creates a Null type */
function Null$1(options) {
    return CreateType({ [Kind]: 'Null', type: 'null' }, options);
}

/** `[JavaScript]` Creates a Symbol type */
function Symbol$1(options) {
    return CreateType({ [Kind]: 'Symbol', type: 'symbol' }, options);
}

/** `[JavaScript]` Creates a Undefined type */
function Undefined(options) {
    return CreateType({ [Kind]: 'Undefined', type: 'undefined' }, options);
}

/** `[JavaScript]` Creates a Uint8Array type */
function Uint8Array$1(options) {
    return CreateType({ [Kind]: 'Uint8Array', type: 'Uint8Array' }, options);
}

/** `[Json]` Creates an Unknown type */
function Unknown(options) {
    return CreateType({ [Kind]: 'Unknown' }, options);
}

// prettier-ignore
function FromArray$3(T) {
    return T.map(L => FromValue(L, false));
}
// prettier-ignore
function FromProperties$c(value) {
    const Acc = {};
    for (const K of globalThis.Object.getOwnPropertyNames(value))
        Acc[K] = Readonly(FromValue(value[K], false));
    return Acc;
}
function ConditionalReadonly(T, root) {
    return (root === true ? T : Readonly(T));
}
// prettier-ignore
function FromValue(value, root) {
    return (IsAsyncIterator$2(value) ? ConditionalReadonly(Any$1(), root) :
        IsIterator$2(value) ? ConditionalReadonly(Any$1(), root) :
            IsArray$3(value) ? Readonly(Tuple(FromArray$3(value))) :
                IsUint8Array$2(value) ? Uint8Array$1() :
                    IsDate$2(value) ? Date$1() :
                        IsObject$3(value) ? ConditionalReadonly(Object$1(FromProperties$c(value)), root) :
                            IsFunction$2(value) ? ConditionalReadonly(Function$1([], Unknown()), root) :
                                IsUndefined$3(value) ? Undefined() :
                                    IsNull$2(value) ? Null$1() :
                                        IsSymbol$2(value) ? Symbol$1() :
                                            IsBigInt$2(value) ? BigInt$1() :
                                                IsNumber$3(value) ? Literal(value) :
                                                    IsBoolean$2(value) ? Literal(value) :
                                                        IsString$2(value) ? Literal(value) :
                                                            Object$1({}));
}
/** `[JavaScript]` Creates a readonly const type from the given value. */
function Const(T, options) {
    return CreateType(FromValue(T, true), options);
}

/** `[JavaScript]` Extracts the ConstructorParameters from the given Constructor type */
function ConstructorParameters(schema, options) {
    return (IsConstructor$1(schema) ? Tuple(schema.parameters, options) : Never(options));
}

/** `[Json]` Creates a Enum type */
function Enum(item, options) {
    if (IsUndefined$3(item))
        throw new Error('Enum undefined or empty');
    const values1 = globalThis.Object.getOwnPropertyNames(item)
        .filter((key) => isNaN(key))
        .map((key) => item[key]);
    const values2 = [...new Set(values1)];
    const anyOf = values2.map((value) => Literal(value));
    return Union(anyOf, { ...options, [Hint]: 'Enum' });
}

class ExtendsResolverError extends TypeBoxError {
}
var ExtendsResult;
(function (ExtendsResult) {
    ExtendsResult[ExtendsResult["Union"] = 0] = "Union";
    ExtendsResult[ExtendsResult["True"] = 1] = "True";
    ExtendsResult[ExtendsResult["False"] = 2] = "False";
})(ExtendsResult || (ExtendsResult = {}));
// ------------------------------------------------------------------
// IntoBooleanResult
// ------------------------------------------------------------------
// prettier-ignore
function IntoBooleanResult(result) {
    return result === ExtendsResult.False ? result : ExtendsResult.True;
}
// ------------------------------------------------------------------
// Throw
// ------------------------------------------------------------------
// prettier-ignore
function Throw(message) {
    throw new ExtendsResolverError(message);
}
// ------------------------------------------------------------------
// StructuralRight
// ------------------------------------------------------------------
// prettier-ignore
function IsStructuralRight(right) {
    return (IsNever(right) ||
        IsIntersect(right) ||
        IsUnion(right) ||
        IsUnknown(right) ||
        IsAny(right));
}
// prettier-ignore
function StructuralRight(left, right) {
    return (IsNever(right) ? FromNeverRight() :
        IsIntersect(right) ? FromIntersectRight(left, right) :
            IsUnion(right) ? FromUnionRight(left, right) :
                IsUnknown(right) ? FromUnknownRight() :
                    IsAny(right) ? FromAnyRight() :
                        Throw('StructuralRight'));
}
// ------------------------------------------------------------------
// Any
// ------------------------------------------------------------------
// prettier-ignore
function FromAnyRight(left, right) {
    return ExtendsResult.True;
}
// prettier-ignore
function FromAny(left, right) {
    return (IsIntersect(right) ? FromIntersectRight(left, right) :
        (IsUnion(right) && right.anyOf.some((schema) => IsAny(schema) || IsUnknown(schema))) ? ExtendsResult.True :
            IsUnion(right) ? ExtendsResult.Union :
                IsUnknown(right) ? ExtendsResult.True :
                    IsAny(right) ? ExtendsResult.True :
                        ExtendsResult.Union);
}
// ------------------------------------------------------------------
// Array
// ------------------------------------------------------------------
// prettier-ignore
function FromArrayRight(left, right) {
    return (IsUnknown(left) ? ExtendsResult.False :
        IsAny(left) ? ExtendsResult.Union :
            IsNever(left) ? ExtendsResult.True :
                ExtendsResult.False);
}
// prettier-ignore
function FromArray$2(left, right) {
    return (IsObject(right) && IsObjectArrayLike(right) ? ExtendsResult.True :
        IsStructuralRight(right) ? StructuralRight(left, right) :
            !IsArray(right) ? ExtendsResult.False :
                IntoBooleanResult(Visit(left.items, right.items)));
}
// ------------------------------------------------------------------
// AsyncIterator
// ------------------------------------------------------------------
// prettier-ignore
function FromAsyncIterator$2(left, right) {
    return (IsStructuralRight(right) ? StructuralRight(left, right) :
        !IsAsyncIterator(right) ? ExtendsResult.False :
            IntoBooleanResult(Visit(left.items, right.items)));
}
// ------------------------------------------------------------------
// BigInt
// ------------------------------------------------------------------
// prettier-ignore
function FromBigInt(left, right) {
    return (IsStructuralRight(right) ? StructuralRight(left, right) :
        IsObject(right) ? FromObjectRight(left, right) :
            IsRecord(right) ? FromRecordRight(left, right) :
                IsBigInt(right) ? ExtendsResult.True :
                    ExtendsResult.False);
}
// ------------------------------------------------------------------
// Boolean
// ------------------------------------------------------------------
// prettier-ignore
function FromBooleanRight(left, right) {
    return (IsLiteralBoolean(left) ? ExtendsResult.True :
        IsBoolean(left) ? ExtendsResult.True :
            ExtendsResult.False);
}
// prettier-ignore
function FromBoolean(left, right) {
    return (IsStructuralRight(right) ? StructuralRight(left, right) :
        IsObject(right) ? FromObjectRight(left, right) :
            IsRecord(right) ? FromRecordRight(left, right) :
                IsBoolean(right) ? ExtendsResult.True :
                    ExtendsResult.False);
}
// ------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------
// prettier-ignore
function FromConstructor$2(left, right) {
    return (IsStructuralRight(right) ? StructuralRight(left, right) :
        IsObject(right) ? FromObjectRight(left, right) :
            !IsConstructor(right) ? ExtendsResult.False :
                left.parameters.length > right.parameters.length ? ExtendsResult.False :
                    (!left.parameters.every((schema, index) => IntoBooleanResult(Visit(right.parameters[index], schema)) === ExtendsResult.True)) ? ExtendsResult.False :
                        IntoBooleanResult(Visit(left.returns, right.returns)));
}
// ------------------------------------------------------------------
// Date
// ------------------------------------------------------------------
// prettier-ignore
function FromDate(left, right) {
    return (IsStructuralRight(right) ? StructuralRight(left, right) :
        IsObject(right) ? FromObjectRight(left, right) :
            IsRecord(right) ? FromRecordRight(left, right) :
                IsDate(right) ? ExtendsResult.True :
                    ExtendsResult.False);
}
// ------------------------------------------------------------------
// Function
// ------------------------------------------------------------------
// prettier-ignore
function FromFunction$2(left, right) {
    return (IsStructuralRight(right) ? StructuralRight(left, right) :
        IsObject(right) ? FromObjectRight(left, right) :
            !IsFunction(right) ? ExtendsResult.False :
                left.parameters.length > right.parameters.length ? ExtendsResult.False :
                    (!left.parameters.every((schema, index) => IntoBooleanResult(Visit(right.parameters[index], schema)) === ExtendsResult.True)) ? ExtendsResult.False :
                        IntoBooleanResult(Visit(left.returns, right.returns)));
}
// ------------------------------------------------------------------
// Integer
// ------------------------------------------------------------------
// prettier-ignore
function FromIntegerRight(left, right) {
    return (IsLiteral(left) && IsNumber$3(left.const) ? ExtendsResult.True :
        IsNumber(left) || IsInteger(left) ? ExtendsResult.True :
            ExtendsResult.False);
}
// prettier-ignore
function FromInteger(left, right) {
    return (IsInteger(right) || IsNumber(right) ? ExtendsResult.True :
        IsStructuralRight(right) ? StructuralRight(left, right) :
            IsObject(right) ? FromObjectRight(left, right) :
                IsRecord(right) ? FromRecordRight(left, right) :
                    ExtendsResult.False);
}
// ------------------------------------------------------------------
// Intersect
// ------------------------------------------------------------------
// prettier-ignore
function FromIntersectRight(left, right) {
    return right.allOf.every((schema) => Visit(left, schema) === ExtendsResult.True)
        ? ExtendsResult.True
        : ExtendsResult.False;
}
// prettier-ignore
function FromIntersect$4(left, right) {
    return left.allOf.some((schema) => Visit(schema, right) === ExtendsResult.True)
        ? ExtendsResult.True
        : ExtendsResult.False;
}
// ------------------------------------------------------------------
// Iterator
// ------------------------------------------------------------------
// prettier-ignore
function FromIterator$2(left, right) {
    return (IsStructuralRight(right) ? StructuralRight(left, right) :
        !IsIterator(right) ? ExtendsResult.False :
            IntoBooleanResult(Visit(left.items, right.items)));
}
// ------------------------------------------------------------------
// Literal
// ------------------------------------------------------------------
// prettier-ignore
function FromLiteral(left, right) {
    return (IsLiteral(right) && right.const === left.const ? ExtendsResult.True :
        IsStructuralRight(right) ? StructuralRight(left, right) :
            IsObject(right) ? FromObjectRight(left, right) :
                IsRecord(right) ? FromRecordRight(left, right) :
                    IsString(right) ? FromStringRight(left) :
                        IsNumber(right) ? FromNumberRight(left) :
                            IsInteger(right) ? FromIntegerRight(left) :
                                IsBoolean(right) ? FromBooleanRight(left) :
                                    ExtendsResult.False);
}
// ------------------------------------------------------------------
// Never
// ------------------------------------------------------------------
// prettier-ignore
function FromNeverRight(left, right) {
    return ExtendsResult.False;
}
// prettier-ignore
function FromNever(left, right) {
    return ExtendsResult.True;
}
// ------------------------------------------------------------------
// Not
// ------------------------------------------------------------------
// prettier-ignore
function UnwrapTNot(schema) {
    let [current, depth] = [schema, 0];
    while (true) {
        if (!IsNot(current))
            break;
        current = current.not;
        depth += 1;
    }
    return depth % 2 === 0 ? current : Unknown();
}
// prettier-ignore
function FromNot(left, right) {
    // TypeScript has no concept of negated types, and attempts to correctly check the negated
    // type at runtime would put TypeBox at odds with TypeScripts ability to statically infer
    // the type. Instead we unwrap to either unknown or T and continue evaluating.
    // prettier-ignore
    return (IsNot(left) ? Visit(UnwrapTNot(left), right) :
        IsNot(right) ? Visit(left, UnwrapTNot(right)) :
            Throw('Invalid fallthrough for Not'));
}
// ------------------------------------------------------------------
// Null
// ------------------------------------------------------------------
// prettier-ignore
function FromNull(left, right) {
    return (IsStructuralRight(right) ? StructuralRight(left, right) :
        IsObject(right) ? FromObjectRight(left, right) :
            IsRecord(right) ? FromRecordRight(left, right) :
                IsNull(right) ? ExtendsResult.True :
                    ExtendsResult.False);
}
// ------------------------------------------------------------------
// Number
// ------------------------------------------------------------------
// prettier-ignore
function FromNumberRight(left, right) {
    return (IsLiteralNumber(left) ? ExtendsResult.True :
        IsNumber(left) || IsInteger(left) ? ExtendsResult.True :
            ExtendsResult.False);
}
// prettier-ignore
function FromNumber(left, right) {
    return (IsStructuralRight(right) ? StructuralRight(left, right) :
        IsObject(right) ? FromObjectRight(left, right) :
            IsRecord(right) ? FromRecordRight(left, right) :
                IsInteger(right) || IsNumber(right) ? ExtendsResult.True :
                    ExtendsResult.False);
}
// ------------------------------------------------------------------
// Object
// ------------------------------------------------------------------
// prettier-ignore
function IsObjectPropertyCount(schema, count) {
    return Object.getOwnPropertyNames(schema.properties).length === count;
}
// prettier-ignore
function IsObjectStringLike(schema) {
    return IsObjectArrayLike(schema);
}
// prettier-ignore
function IsObjectSymbolLike(schema) {
    return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'description' in schema.properties && IsUnion(schema.properties.description) && schema.properties.description.anyOf.length === 2 && ((IsString(schema.properties.description.anyOf[0]) &&
        IsUndefined(schema.properties.description.anyOf[1])) || (IsString(schema.properties.description.anyOf[1]) &&
        IsUndefined(schema.properties.description.anyOf[0]))));
}
// prettier-ignore
function IsObjectNumberLike(schema) {
    return IsObjectPropertyCount(schema, 0);
}
// prettier-ignore
function IsObjectBooleanLike(schema) {
    return IsObjectPropertyCount(schema, 0);
}
// prettier-ignore
function IsObjectBigIntLike(schema) {
    return IsObjectPropertyCount(schema, 0);
}
// prettier-ignore
function IsObjectDateLike(schema) {
    return IsObjectPropertyCount(schema, 0);
}
// prettier-ignore
function IsObjectUint8ArrayLike(schema) {
    return IsObjectArrayLike(schema);
}
// prettier-ignore
function IsObjectFunctionLike(schema) {
    const length = Number$1();
    return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'length' in schema.properties && IntoBooleanResult(Visit(schema.properties['length'], length)) === ExtendsResult.True);
}
// prettier-ignore
function IsObjectConstructorLike(schema) {
    return IsObjectPropertyCount(schema, 0);
}
// prettier-ignore
function IsObjectArrayLike(schema) {
    const length = Number$1();
    return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'length' in schema.properties && IntoBooleanResult(Visit(schema.properties['length'], length)) === ExtendsResult.True);
}
// prettier-ignore
function IsObjectPromiseLike(schema) {
    const then = Function$1([Any$1()], Any$1());
    return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'then' in schema.properties && IntoBooleanResult(Visit(schema.properties['then'], then)) === ExtendsResult.True);
}
// ------------------------------------------------------------------
// Property
// ------------------------------------------------------------------
// prettier-ignore
function Property(left, right) {
    return (Visit(left, right) === ExtendsResult.False ? ExtendsResult.False :
        IsOptional(left) && !IsOptional(right) ? ExtendsResult.False :
            ExtendsResult.True);
}
// prettier-ignore
function FromObjectRight(left, right) {
    return (IsUnknown(left) ? ExtendsResult.False :
        IsAny(left) ? ExtendsResult.Union : (IsNever(left) ||
            (IsLiteralString(left) && IsObjectStringLike(right)) ||
            (IsLiteralNumber(left) && IsObjectNumberLike(right)) ||
            (IsLiteralBoolean(left) && IsObjectBooleanLike(right)) ||
            (IsSymbol(left) && IsObjectSymbolLike(right)) ||
            (IsBigInt(left) && IsObjectBigIntLike(right)) ||
            (IsString(left) && IsObjectStringLike(right)) ||
            (IsSymbol(left) && IsObjectSymbolLike(right)) ||
            (IsNumber(left) && IsObjectNumberLike(right)) ||
            (IsInteger(left) && IsObjectNumberLike(right)) ||
            (IsBoolean(left) && IsObjectBooleanLike(right)) ||
            (IsUint8Array(left) && IsObjectUint8ArrayLike(right)) ||
            (IsDate(left) && IsObjectDateLike(right)) ||
            (IsConstructor(left) && IsObjectConstructorLike(right)) ||
            (IsFunction(left) && IsObjectFunctionLike(right))) ? ExtendsResult.True :
            (IsRecord(left) && IsString(RecordKey$1(left))) ? (() => {
                // When expressing a Record with literal key values, the Record is converted into a Object with
                // the Hint assigned as `Record`. This is used to invert the extends logic.
                return right[Hint] === 'Record' ? ExtendsResult.True : ExtendsResult.False;
            })() :
                (IsRecord(left) && IsNumber(RecordKey$1(left))) ? (() => {
                    return IsObjectPropertyCount(right, 0) ? ExtendsResult.True : ExtendsResult.False;
                })() :
                    ExtendsResult.False);
}
// prettier-ignore
function FromObject$6(left, right) {
    return (IsStructuralRight(right) ? StructuralRight(left, right) :
        IsRecord(right) ? FromRecordRight(left, right) :
            !IsObject(right) ? ExtendsResult.False :
                (() => {
                    for (const key of Object.getOwnPropertyNames(right.properties)) {
                        if (!(key in left.properties) && !IsOptional(right.properties[key])) {
                            return ExtendsResult.False;
                        }
                        if (IsOptional(right.properties[key])) {
                            return ExtendsResult.True;
                        }
                        if (Property(left.properties[key], right.properties[key]) === ExtendsResult.False) {
                            return ExtendsResult.False;
                        }
                    }
                    return ExtendsResult.True;
                })());
}
// ------------------------------------------------------------------
// Promise
// ------------------------------------------------------------------
// prettier-ignore
function FromPromise$1(left, right) {
    return (IsStructuralRight(right) ? StructuralRight(left, right) :
        IsObject(right) && IsObjectPromiseLike(right) ? ExtendsResult.True :
            !IsPromise(right) ? ExtendsResult.False :
                IntoBooleanResult(Visit(left.item, right.item)));
}
// ------------------------------------------------------------------
// Record
// ------------------------------------------------------------------
// prettier-ignore
function RecordKey$1(schema) {
    return (PatternNumberExact in schema.patternProperties ? Number$1() :
        PatternStringExact in schema.patternProperties ? String$1() :
            Throw('Unknown record key pattern'));
}
// prettier-ignore
function RecordValue$1(schema) {
    return (PatternNumberExact in schema.patternProperties ? schema.patternProperties[PatternNumberExact] :
        PatternStringExact in schema.patternProperties ? schema.patternProperties[PatternStringExact] :
            Throw('Unable to get record value schema'));
}
// prettier-ignore
function FromRecordRight(left, right) {
    const [Key, Value] = [RecordKey$1(right), RecordValue$1(right)];
    return ((IsLiteralString(left) && IsNumber(Key) && IntoBooleanResult(Visit(left, Value)) === ExtendsResult.True) ? ExtendsResult.True :
        IsUint8Array(left) && IsNumber(Key) ? Visit(left, Value) :
            IsString(left) && IsNumber(Key) ? Visit(left, Value) :
                IsArray(left) && IsNumber(Key) ? Visit(left, Value) :
                    IsObject(left) ? (() => {
                        for (const key of Object.getOwnPropertyNames(left.properties)) {
                            if (Property(Value, left.properties[key]) === ExtendsResult.False) {
                                return ExtendsResult.False;
                            }
                        }
                        return ExtendsResult.True;
                    })() :
                        ExtendsResult.False);
}
// prettier-ignore
function FromRecord$2(left, right) {
    return (IsStructuralRight(right) ? StructuralRight(left, right) :
        IsObject(right) ? FromObjectRight(left, right) :
            !IsRecord(right) ? ExtendsResult.False :
                Visit(RecordValue$1(left), RecordValue$1(right)));
}
// ------------------------------------------------------------------
// RegExp
// ------------------------------------------------------------------
// prettier-ignore
function FromRegExp(left, right) {
    // Note: RegExp types evaluate as strings, not RegExp objects.
    // Here we remap either into string and continue evaluating.
    const L = IsRegExp(left) ? String$1() : left;
    const R = IsRegExp(right) ? String$1() : right;
    return Visit(L, R);
}
// ------------------------------------------------------------------
// String
// ------------------------------------------------------------------
// prettier-ignore
function FromStringRight(left, right) {
    return (IsLiteral(left) && IsString$2(left.const) ? ExtendsResult.True :
        IsString(left) ? ExtendsResult.True :
            ExtendsResult.False);
}
// prettier-ignore
function FromString(left, right) {
    return (IsStructuralRight(right) ? StructuralRight(left, right) :
        IsObject(right) ? FromObjectRight(left, right) :
            IsRecord(right) ? FromRecordRight(left, right) :
                IsString(right) ? ExtendsResult.True :
                    ExtendsResult.False);
}
// ------------------------------------------------------------------
// Symbol
// ------------------------------------------------------------------
// prettier-ignore
function FromSymbol(left, right) {
    return (IsStructuralRight(right) ? StructuralRight(left, right) :
        IsObject(right) ? FromObjectRight(left, right) :
            IsRecord(right) ? FromRecordRight(left, right) :
                IsSymbol(right) ? ExtendsResult.True :
                    ExtendsResult.False);
}
// ------------------------------------------------------------------
// TemplateLiteral
// ------------------------------------------------------------------
// prettier-ignore
function FromTemplateLiteral$1(left, right) {
    // TemplateLiteral types are resolved to either unions for finite expressions or string
    // for infinite expressions. Here we call to TemplateLiteralResolver to resolve for
    // either type and continue evaluating.
    return (IsTemplateLiteral(left) ? Visit(TemplateLiteralToUnion(left), right) :
        IsTemplateLiteral(right) ? Visit(left, TemplateLiteralToUnion(right)) :
            Throw('Invalid fallthrough for TemplateLiteral'));
}
// ------------------------------------------------------------------
// Tuple
// ------------------------------------------------------------------
// prettier-ignore
function IsArrayOfTuple(left, right) {
    return (IsArray(right) &&
        left.items !== undefined &&
        left.items.every((schema) => Visit(schema, right.items) === ExtendsResult.True));
}
// prettier-ignore
function FromTupleRight(left, right) {
    return (IsNever(left) ? ExtendsResult.True :
        IsUnknown(left) ? ExtendsResult.False :
            IsAny(left) ? ExtendsResult.Union :
                ExtendsResult.False);
}
// prettier-ignore
function FromTuple$2(left, right) {
    return (IsStructuralRight(right) ? StructuralRight(left, right) :
        IsObject(right) && IsObjectArrayLike(right) ? ExtendsResult.True :
            IsArray(right) && IsArrayOfTuple(left, right) ? ExtendsResult.True :
                !IsTuple(right) ? ExtendsResult.False :
                    (IsUndefined$3(left.items) && !IsUndefined$3(right.items)) || (!IsUndefined$3(left.items) && IsUndefined$3(right.items)) ? ExtendsResult.False :
                        (IsUndefined$3(left.items) && !IsUndefined$3(right.items)) ? ExtendsResult.True :
                            left.items.every((schema, index) => Visit(schema, right.items[index]) === ExtendsResult.True) ? ExtendsResult.True :
                                ExtendsResult.False);
}
// ------------------------------------------------------------------
// Uint8Array
// ------------------------------------------------------------------
// prettier-ignore
function FromUint8Array(left, right) {
    return (IsStructuralRight(right) ? StructuralRight(left, right) :
        IsObject(right) ? FromObjectRight(left, right) :
            IsRecord(right) ? FromRecordRight(left, right) :
                IsUint8Array(right) ? ExtendsResult.True :
                    ExtendsResult.False);
}
// ------------------------------------------------------------------
// Undefined
// ------------------------------------------------------------------
// prettier-ignore
function FromUndefined(left, right) {
    return (IsStructuralRight(right) ? StructuralRight(left, right) :
        IsObject(right) ? FromObjectRight(left, right) :
            IsRecord(right) ? FromRecordRight(left, right) :
                IsVoid(right) ? FromVoidRight(left) :
                    IsUndefined(right) ? ExtendsResult.True :
                        ExtendsResult.False);
}
// ------------------------------------------------------------------
// Union
// ------------------------------------------------------------------
// prettier-ignore
function FromUnionRight(left, right) {
    return right.anyOf.some((schema) => Visit(left, schema) === ExtendsResult.True)
        ? ExtendsResult.True
        : ExtendsResult.False;
}
// prettier-ignore
function FromUnion$4(left, right) {
    return left.anyOf.every((schema) => Visit(schema, right) === ExtendsResult.True)
        ? ExtendsResult.True
        : ExtendsResult.False;
}
// ------------------------------------------------------------------
// Unknown
// ------------------------------------------------------------------
// prettier-ignore
function FromUnknownRight(left, right) {
    return ExtendsResult.True;
}
// prettier-ignore
function FromUnknown(left, right) {
    return (IsNever(right) ? FromNeverRight() :
        IsIntersect(right) ? FromIntersectRight(left, right) :
            IsUnion(right) ? FromUnionRight(left, right) :
                IsAny(right) ? FromAnyRight() :
                    IsString(right) ? FromStringRight(left) :
                        IsNumber(right) ? FromNumberRight(left) :
                            IsInteger(right) ? FromIntegerRight(left) :
                                IsBoolean(right) ? FromBooleanRight(left) :
                                    IsArray(right) ? FromArrayRight(left) :
                                        IsTuple(right) ? FromTupleRight(left) :
                                            IsObject(right) ? FromObjectRight(left, right) :
                                                IsUnknown(right) ? ExtendsResult.True :
                                                    ExtendsResult.False);
}
// ------------------------------------------------------------------
// Void
// ------------------------------------------------------------------
// prettier-ignore
function FromVoidRight(left, right) {
    return (IsUndefined(left) ? ExtendsResult.True :
        IsUndefined(left) ? ExtendsResult.True :
            ExtendsResult.False);
}
// prettier-ignore
function FromVoid(left, right) {
    return (IsIntersect(right) ? FromIntersectRight(left, right) :
        IsUnion(right) ? FromUnionRight(left, right) :
            IsUnknown(right) ? FromUnknownRight() :
                IsAny(right) ? FromAnyRight() :
                    IsObject(right) ? FromObjectRight(left, right) :
                        IsVoid(right) ? ExtendsResult.True :
                            ExtendsResult.False);
}
// prettier-ignore
function Visit(left, right) {
    return (
    // resolvable
    (IsTemplateLiteral(left) || IsTemplateLiteral(right)) ? FromTemplateLiteral$1(left, right) :
        (IsRegExp(left) || IsRegExp(right)) ? FromRegExp(left, right) :
            (IsNot(left) || IsNot(right)) ? FromNot(left, right) :
                // standard
                IsAny(left) ? FromAny(left, right) :
                    IsArray(left) ? FromArray$2(left, right) :
                        IsBigInt(left) ? FromBigInt(left, right) :
                            IsBoolean(left) ? FromBoolean(left, right) :
                                IsAsyncIterator(left) ? FromAsyncIterator$2(left, right) :
                                    IsConstructor(left) ? FromConstructor$2(left, right) :
                                        IsDate(left) ? FromDate(left, right) :
                                            IsFunction(left) ? FromFunction$2(left, right) :
                                                IsInteger(left) ? FromInteger(left, right) :
                                                    IsIntersect(left) ? FromIntersect$4(left, right) :
                                                        IsIterator(left) ? FromIterator$2(left, right) :
                                                            IsLiteral(left) ? FromLiteral(left, right) :
                                                                IsNever(left) ? FromNever() :
                                                                    IsNull(left) ? FromNull(left, right) :
                                                                        IsNumber(left) ? FromNumber(left, right) :
                                                                            IsObject(left) ? FromObject$6(left, right) :
                                                                                IsRecord(left) ? FromRecord$2(left, right) :
                                                                                    IsString(left) ? FromString(left, right) :
                                                                                        IsSymbol(left) ? FromSymbol(left, right) :
                                                                                            IsTuple(left) ? FromTuple$2(left, right) :
                                                                                                IsPromise(left) ? FromPromise$1(left, right) :
                                                                                                    IsUint8Array(left) ? FromUint8Array(left, right) :
                                                                                                        IsUndefined(left) ? FromUndefined(left, right) :
                                                                                                            IsUnion(left) ? FromUnion$4(left, right) :
                                                                                                                IsUnknown(left) ? FromUnknown(left, right) :
                                                                                                                    IsVoid(left) ? FromVoid(left, right) :
                                                                                                                        Throw(`Unknown left type operand '${left[Kind]}'`));
}
function ExtendsCheck(left, right) {
    return Visit(left, right);
}

// prettier-ignore
function FromProperties$b(P, Right, True, False, options) {
    const Acc = {};
    for (const K2 of globalThis.Object.getOwnPropertyNames(P))
        Acc[K2] = Extends(P[K2], Right, True, False, Clone(options));
    return Acc;
}
// prettier-ignore
function FromMappedResult$6(Left, Right, True, False, options) {
    return FromProperties$b(Left.properties, Right, True, False, options);
}
// prettier-ignore
function ExtendsFromMappedResult(Left, Right, True, False, options) {
    const P = FromMappedResult$6(Left, Right, True, False, options);
    return MappedResult(P);
}

// prettier-ignore
function ExtendsResolve(left, right, trueType, falseType) {
    const R = ExtendsCheck(left, right);
    return (R === ExtendsResult.Union ? Union([trueType, falseType]) :
        R === ExtendsResult.True ? trueType :
            falseType);
}
/** `[Json]` Creates a Conditional type */
function Extends(L, R, T, F, options) {
    // prettier-ignore
    return (IsMappedResult$1(L) ? ExtendsFromMappedResult(L, R, T, F, options) :
        IsMappedKey$1(L) ? CreateType(ExtendsFromMappedKey(L, R, T, F, options)) :
            CreateType(ExtendsResolve(L, R, T, F), options));
}

// prettier-ignore
function FromPropertyKey$2(K, U, L, R, options) {
    return {
        [K]: Extends(Literal(K), U, L, R, Clone(options))
    };
}
// prettier-ignore
function FromPropertyKeys$2(K, U, L, R, options) {
    return K.reduce((Acc, LK) => {
        return { ...Acc, ...FromPropertyKey$2(LK, U, L, R, options) };
    }, {});
}
// prettier-ignore
function FromMappedKey$2(K, U, L, R, options) {
    return FromPropertyKeys$2(K.keys, U, L, R, options);
}
// prettier-ignore
function ExtendsFromMappedKey(T, U, L, R, options) {
    const P = FromMappedKey$2(T, U, L, R, options);
    return MappedResult(P);
}

function ExcludeFromTemplateLiteral(L, R) {
    return Exclude(TemplateLiteralToUnion(L), R);
}

function ExcludeRest(L, R) {
    const excluded = L.filter((inner) => ExtendsCheck(inner, R) === ExtendsResult.False);
    return excluded.length === 1 ? excluded[0] : Union(excluded);
}
/** `[Json]` Constructs a type by excluding from unionType all union members that are assignable to excludedMembers */
function Exclude(L, R, options = {}) {
    // overloads
    if (IsTemplateLiteral$1(L))
        return CreateType(ExcludeFromTemplateLiteral(L, R), options);
    if (IsMappedResult$1(L))
        return CreateType(ExcludeFromMappedResult(L, R), options);
    // prettier-ignore
    return CreateType(IsUnion$1(L) ? ExcludeRest(L.anyOf, R) :
        ExtendsCheck(L, R) !== ExtendsResult.False ? Never() : L, options);
}

// prettier-ignore
function FromProperties$a(P, U) {
    const Acc = {};
    for (const K2 of globalThis.Object.getOwnPropertyNames(P))
        Acc[K2] = Exclude(P[K2], U);
    return Acc;
}
// prettier-ignore
function FromMappedResult$5(R, T) {
    return FromProperties$a(R.properties, T);
}
// prettier-ignore
function ExcludeFromMappedResult(R, T) {
    const P = FromMappedResult$5(R, T);
    return MappedResult(P);
}

function ExtractFromTemplateLiteral(L, R) {
    return Extract(TemplateLiteralToUnion(L), R);
}

function ExtractRest(L, R) {
    const extracted = L.filter((inner) => ExtendsCheck(inner, R) !== ExtendsResult.False);
    return extracted.length === 1 ? extracted[0] : Union(extracted);
}
/** `[Json]` Constructs a type by extracting from type all union members that are assignable to union */
function Extract(L, R, options) {
    // overloads
    if (IsTemplateLiteral$1(L))
        return CreateType(ExtractFromTemplateLiteral(L, R), options);
    if (IsMappedResult$1(L))
        return CreateType(ExtractFromMappedResult(L, R), options);
    // prettier-ignore
    return CreateType(IsUnion$1(L) ? ExtractRest(L.anyOf, R) :
        ExtendsCheck(L, R) !== ExtendsResult.False ? L : Never(), options);
}

// prettier-ignore
function FromProperties$9(P, T) {
    const Acc = {};
    for (const K2 of globalThis.Object.getOwnPropertyNames(P))
        Acc[K2] = Extract(P[K2], T);
    return Acc;
}
// prettier-ignore
function FromMappedResult$4(R, T) {
    return FromProperties$9(R.properties, T);
}
// prettier-ignore
function ExtractFromMappedResult(R, T) {
    const P = FromMappedResult$4(R, T);
    return MappedResult(P);
}

/** `[JavaScript]` Extracts the InstanceType from the given Constructor type */
function InstanceType(schema, options) {
    return (IsConstructor$1(schema) ? CreateType(schema.returns, options) : Never(options));
}

/** `[Json]` Creates a Readonly and Optional property */
function ReadonlyOptional(schema) {
    return Readonly(Optional(schema));
}

// ------------------------------------------------------------------
// RecordCreateFromPattern
// ------------------------------------------------------------------
// prettier-ignore
function RecordCreateFromPattern(pattern, T, options) {
    return CreateType({ [Kind]: 'Record', type: 'object', patternProperties: { [pattern]: T } }, options);
}
// ------------------------------------------------------------------
// RecordCreateFromKeys
// ------------------------------------------------------------------
// prettier-ignore
function RecordCreateFromKeys(K, T, options) {
    const result = {};
    for (const K2 of K)
        result[K2] = T;
    return Object$1(result, { ...options, [Hint]: 'Record' });
}
// prettier-ignore
function FromTemplateLiteralKey(K, T, options) {
    return (IsTemplateLiteralFinite(K)
        ? RecordCreateFromKeys(IndexPropertyKeys(K), T, options)
        : RecordCreateFromPattern(K.pattern, T, options));
}
// prettier-ignore
function FromUnionKey(key, type, options) {
    return RecordCreateFromKeys(IndexPropertyKeys(Union(key)), type, options);
}
// prettier-ignore
function FromLiteralKey(key, type, options) {
    return RecordCreateFromKeys([key.toString()], type, options);
}
// prettier-ignore
function FromRegExpKey(key, type, options) {
    return RecordCreateFromPattern(key.source, type, options);
}
// prettier-ignore
function FromStringKey(key, type, options) {
    const pattern = IsUndefined$3(key.pattern) ? PatternStringExact : key.pattern;
    return RecordCreateFromPattern(pattern, type, options);
}
// prettier-ignore
function FromAnyKey(_, type, options) {
    return RecordCreateFromPattern(PatternStringExact, type, options);
}
// prettier-ignore
function FromNeverKey(_key, type, options) {
    return RecordCreateFromPattern(PatternNeverExact, type, options);
}
// prettier-ignore
function FromBooleanKey(_key, type, options) {
    return Object$1({ true: type, false: type }, options);
}
// prettier-ignore
function FromIntegerKey(_key, type, options) {
    return RecordCreateFromPattern(PatternNumberExact, type, options);
}
// prettier-ignore
function FromNumberKey(_, type, options) {
    return RecordCreateFromPattern(PatternNumberExact, type, options);
}
// ------------------------------------------------------------------
// TRecordOrObject
// ------------------------------------------------------------------
/** `[Json]` Creates a Record type */
function Record(key, type, options = {}) {
    // prettier-ignore
    return (IsUnion$1(key) ? FromUnionKey(key.anyOf, type, options) :
        IsTemplateLiteral$1(key) ? FromTemplateLiteralKey(key, type, options) :
            IsLiteral$1(key) ? FromLiteralKey(key.const, type, options) :
                IsBoolean$1(key) ? FromBooleanKey(key, type, options) :
                    IsInteger$1(key) ? FromIntegerKey(key, type, options) :
                        IsNumber$1(key) ? FromNumberKey(key, type, options) :
                            IsRegExp$1(key) ? FromRegExpKey(key, type, options) :
                                IsString$1(key) ? FromStringKey(key, type, options) :
                                    IsAny$1(key) ? FromAnyKey(key, type, options) :
                                        IsNever$1(key) ? FromNeverKey(key, type, options) :
                                            Never(options));
}
// ------------------------------------------------------------------
// Record Utilities
// ------------------------------------------------------------------
/** Gets the Records Pattern */
function RecordPattern(record) {
    return globalThis.Object.getOwnPropertyNames(record.patternProperties)[0];
}
/** Gets the Records Key Type */
// prettier-ignore
function RecordKey(type) {
    const pattern = RecordPattern(type);
    return (pattern === PatternStringExact ? String$1() :
        pattern === PatternNumberExact ? Number$1() :
            String$1({ pattern }));
}
/** Gets a Record Value Type */
// prettier-ignore
function RecordValue(type) {
    return type.patternProperties[RecordPattern(type)];
}

// prettier-ignore
function FromConstructor$1(args, type) {
    type.parameters = FromTypes$1(args, type.parameters);
    type.returns = FromType$1(args, type.returns);
    return type;
}
// prettier-ignore
function FromFunction$1(args, type) {
    type.parameters = FromTypes$1(args, type.parameters);
    type.returns = FromType$1(args, type.returns);
    return type;
}
// prettier-ignore
function FromIntersect$3(args, type) {
    type.allOf = FromTypes$1(args, type.allOf);
    return type;
}
// prettier-ignore
function FromUnion$3(args, type) {
    type.anyOf = FromTypes$1(args, type.anyOf);
    return type;
}
// prettier-ignore
function FromTuple$1(args, type) {
    if (IsUndefined$3(type.items))
        return type;
    type.items = FromTypes$1(args, type.items);
    return type;
}
// prettier-ignore
function FromArray$1(args, type) {
    type.items = FromType$1(args, type.items);
    return type;
}
// prettier-ignore
function FromAsyncIterator$1(args, type) {
    type.items = FromType$1(args, type.items);
    return type;
}
// prettier-ignore
function FromIterator$1(args, type) {
    type.items = FromType$1(args, type.items);
    return type;
}
// prettier-ignore
function FromPromise(args, type) {
    type.item = FromType$1(args, type.item);
    return type;
}
// prettier-ignore
function FromObject$5(args, type) {
    const mappedProperties = FromProperties$8(args, type.properties);
    return { ...type, ...Object$1(mappedProperties) }; // retain options
}
// prettier-ignore
function FromRecord$1(args, type) {
    const mappedKey = FromType$1(args, RecordKey(type));
    const mappedValue = FromType$1(args, RecordValue(type));
    const result = Record(mappedKey, mappedValue);
    return { ...type, ...result }; // retain options
}
// prettier-ignore
function FromArgument(args, argument) {
    return argument.index in args ? args[argument.index] : Unknown();
}
// prettier-ignore
function FromProperty$1(args, type) {
    const isReadonly = IsReadonly(type);
    const isOptional = IsOptional$1(type);
    const mapped = FromType$1(args, type);
    return (isReadonly && isOptional ? ReadonlyOptional(mapped) :
        isReadonly && !isOptional ? Readonly(mapped) :
            !isReadonly && isOptional ? Optional(mapped) :
                mapped);
}
// prettier-ignore
function FromProperties$8(args, properties) {
    return globalThis.Object.getOwnPropertyNames(properties).reduce((result, key) => {
        return { ...result, [key]: FromProperty$1(args, properties[key]) };
    }, {});
}
// prettier-ignore
function FromTypes$1(args, types) {
    return types.map(type => FromType$1(args, type));
}
// prettier-ignore
function FromType$1(args, type) {
    return (IsConstructor$1(type) ? FromConstructor$1(args, type) :
        IsFunction$1(type) ? FromFunction$1(args, type) :
            IsIntersect$1(type) ? FromIntersect$3(args, type) :
                IsUnion$1(type) ? FromUnion$3(args, type) :
                    IsTuple$1(type) ? FromTuple$1(args, type) :
                        IsArray$1(type) ? FromArray$1(args, type) :
                            IsAsyncIterator$1(type) ? FromAsyncIterator$1(args, type) :
                                IsIterator$1(type) ? FromIterator$1(args, type) :
                                    IsPromise$1(type) ? FromPromise(args, type) :
                                        IsObject$1(type) ? FromObject$5(args, type) :
                                            IsRecord$1(type) ? FromRecord$1(args, type) :
                                                IsArgument$1(type) ? FromArgument(args, type) :
                                                    type);
}
/** `[JavaScript]` Instantiates a type with the given parameters */
// prettier-ignore
function Instantiate(type, args) {
    return FromType$1(args, CloneType(type));
}

/** `[Json]` Creates an Integer type */
function Integer$1(options) {
    return CreateType({ [Kind]: 'Integer', type: 'integer' }, options);
}

// prettier-ignore
function MappedIntrinsicPropertyKey(K, M, options) {
    return {
        [K]: Intrinsic(Literal(K), M, Clone(options))
    };
}
// prettier-ignore
function MappedIntrinsicPropertyKeys(K, M, options) {
    const result = K.reduce((Acc, L) => {
        return { ...Acc, ...MappedIntrinsicPropertyKey(L, M, options) };
    }, {});
    return result;
}
// prettier-ignore
function MappedIntrinsicProperties(T, M, options) {
    return MappedIntrinsicPropertyKeys(T['keys'], M, options);
}
// prettier-ignore
function IntrinsicFromMappedKey(T, M, options) {
    const P = MappedIntrinsicProperties(T, M, options);
    return MappedResult(P);
}

// ------------------------------------------------------------------
// Apply
// ------------------------------------------------------------------
function ApplyUncapitalize(value) {
    const [first, rest] = [value.slice(0, 1), value.slice(1)];
    return [first.toLowerCase(), rest].join('');
}
function ApplyCapitalize(value) {
    const [first, rest] = [value.slice(0, 1), value.slice(1)];
    return [first.toUpperCase(), rest].join('');
}
function ApplyUppercase(value) {
    return value.toUpperCase();
}
function ApplyLowercase(value) {
    return value.toLowerCase();
}
function FromTemplateLiteral(schema, mode, options) {
    // note: template literals require special runtime handling as they are encoded in string patterns.
    // This diverges from the mapped type which would otherwise map on the template literal kind.
    const expression = TemplateLiteralParseExact(schema.pattern);
    const finite = IsTemplateLiteralExpressionFinite(expression);
    if (!finite)
        return { ...schema, pattern: FromLiteralValue(schema.pattern, mode) };
    const strings = [...TemplateLiteralExpressionGenerate(expression)];
    const literals = strings.map((value) => Literal(value));
    const mapped = FromRest$2(literals, mode);
    const union = Union(mapped);
    return TemplateLiteral([union], options);
}
// prettier-ignore
function FromLiteralValue(value, mode) {
    return (typeof value === 'string' ? (mode === 'Uncapitalize' ? ApplyUncapitalize(value) :
        mode === 'Capitalize' ? ApplyCapitalize(value) :
            mode === 'Uppercase' ? ApplyUppercase(value) :
                mode === 'Lowercase' ? ApplyLowercase(value) :
                    value) : value.toString());
}
// prettier-ignore
function FromRest$2(T, M) {
    return T.map(L => Intrinsic(L, M));
}
/** Applies an intrinsic string manipulation to the given type. */
function Intrinsic(schema, mode, options = {}) {
    // prettier-ignore
    return (
    // Intrinsic-Mapped-Inference
    IsMappedKey$1(schema) ? IntrinsicFromMappedKey(schema, mode, options) :
        // Standard-Inference
        IsTemplateLiteral$1(schema) ? FromTemplateLiteral(schema, mode, options) :
            IsUnion$1(schema) ? Union(FromRest$2(schema.anyOf, mode), options) :
                IsLiteral$1(schema) ? Literal(FromLiteralValue(schema.const, mode), options) :
                    // Default Type
                    CreateType(schema, options));
}

/** `[Json]` Intrinsic function to Capitalize LiteralString types */
function Capitalize(T, options = {}) {
    return Intrinsic(T, 'Capitalize', options);
}

/** `[Json]` Intrinsic function to Lowercase LiteralString types */
function Lowercase(T, options = {}) {
    return Intrinsic(T, 'Lowercase', options);
}

/** `[Json]` Intrinsic function to Uncapitalize LiteralString types */
function Uncapitalize(T, options = {}) {
    return Intrinsic(T, 'Uncapitalize', options);
}

/** `[Json]` Intrinsic function to Uppercase LiteralString types */
function Uppercase(T, options = {}) {
    return Intrinsic(T, 'Uppercase', options);
}

// prettier-ignore
function FromProperties$7(properties, propertyKeys, options) {
    const result = {};
    for (const K2 of globalThis.Object.getOwnPropertyNames(properties))
        result[K2] = Omit(properties[K2], propertyKeys, Clone(options));
    return result;
}
// prettier-ignore
function FromMappedResult$3(mappedResult, propertyKeys, options) {
    return FromProperties$7(mappedResult.properties, propertyKeys, options);
}
// prettier-ignore
function OmitFromMappedResult(mappedResult, propertyKeys, options) {
    const properties = FromMappedResult$3(mappedResult, propertyKeys, options);
    return MappedResult(properties);
}

// prettier-ignore
function FromIntersect$2(types, propertyKeys) {
    return types.map((type) => OmitResolve(type, propertyKeys));
}
// prettier-ignore
function FromUnion$2(types, propertyKeys) {
    return types.map((type) => OmitResolve(type, propertyKeys));
}
// ------------------------------------------------------------------
// FromProperty
// ------------------------------------------------------------------
// prettier-ignore
function FromProperty(properties, key) {
    const { [key]: _, ...R } = properties;
    return R;
}
// prettier-ignore
function FromProperties$6(properties, propertyKeys) {
    return propertyKeys.reduce((T, K2) => FromProperty(T, K2), properties);
}
// prettier-ignore
function FromObject$4(properties, propertyKeys) {
    const options = Discard(properties, [TransformKind, '$id', 'required', 'properties']);
    const omittedProperties = FromProperties$6(properties['properties'], propertyKeys);
    return Object$1(omittedProperties, options);
}
// prettier-ignore
function UnionFromPropertyKeys$1(propertyKeys) {
    const result = propertyKeys.reduce((result, key) => IsLiteralValue$1(key) ? [...result, Literal(key)] : result, []);
    return Union(result);
}
// prettier-ignore
function OmitResolve(properties, propertyKeys) {
    return (IsIntersect$1(properties) ? Intersect(FromIntersect$2(properties.allOf, propertyKeys)) :
        IsUnion$1(properties) ? Union(FromUnion$2(properties.anyOf, propertyKeys)) :
            IsObject$1(properties) ? FromObject$4(properties, propertyKeys) :
                Object$1({}));
}
/** `[Json]` Constructs a type whose keys are picked from the given type */
// prettier-ignore
function Omit(type, key, options) {
    const typeKey = IsArray$3(key) ? UnionFromPropertyKeys$1(key) : key;
    const propertyKeys = IsSchema$1(key) ? IndexPropertyKeys(key) : key;
    const isTypeRef = IsRef$1(type);
    const isKeyRef = IsRef$1(key);
    return (IsMappedResult$1(type) ? OmitFromMappedResult(type, propertyKeys, options) :
        IsMappedKey$1(key) ? OmitFromMappedKey(type, key, options) :
            (isTypeRef && isKeyRef) ? Computed('Omit', [type, typeKey], options) :
                (!isTypeRef && isKeyRef) ? Computed('Omit', [type, typeKey], options) :
                    (isTypeRef && !isKeyRef) ? Computed('Omit', [type, typeKey], options) :
                        CreateType({ ...OmitResolve(type, propertyKeys), ...options }));
}

// prettier-ignore
function FromPropertyKey$1(type, key, options) {
    return { [key]: Omit(type, [key], Clone(options)) };
}
// prettier-ignore
function FromPropertyKeys$1(type, propertyKeys, options) {
    return propertyKeys.reduce((Acc, LK) => {
        return { ...Acc, ...FromPropertyKey$1(type, LK, options) };
    }, {});
}
// prettier-ignore
function FromMappedKey$1(type, mappedKey, options) {
    return FromPropertyKeys$1(type, mappedKey.keys, options);
}
// prettier-ignore
function OmitFromMappedKey(type, mappedKey, options) {
    const properties = FromMappedKey$1(type, mappedKey, options);
    return MappedResult(properties);
}

// prettier-ignore
function FromProperties$5(properties, propertyKeys, options) {
    const result = {};
    for (const K2 of globalThis.Object.getOwnPropertyNames(properties))
        result[K2] = Pick(properties[K2], propertyKeys, Clone(options));
    return result;
}
// prettier-ignore
function FromMappedResult$2(mappedResult, propertyKeys, options) {
    return FromProperties$5(mappedResult.properties, propertyKeys, options);
}
// prettier-ignore
function PickFromMappedResult(mappedResult, propertyKeys, options) {
    const properties = FromMappedResult$2(mappedResult, propertyKeys, options);
    return MappedResult(properties);
}

function FromIntersect$1(types, propertyKeys) {
    return types.map((type) => PickResolve(type, propertyKeys));
}
// prettier-ignore
function FromUnion$1(types, propertyKeys) {
    return types.map((type) => PickResolve(type, propertyKeys));
}
// prettier-ignore
function FromProperties$4(properties, propertyKeys) {
    const result = {};
    for (const K2 of propertyKeys)
        if (K2 in properties)
            result[K2] = properties[K2];
    return result;
}
// prettier-ignore
function FromObject$3(T, K) {
    const options = Discard(T, [TransformKind, '$id', 'required', 'properties']);
    const properties = FromProperties$4(T['properties'], K);
    return Object$1(properties, options);
}
// prettier-ignore
function UnionFromPropertyKeys(propertyKeys) {
    const result = propertyKeys.reduce((result, key) => IsLiteralValue$1(key) ? [...result, Literal(key)] : result, []);
    return Union(result);
}
// prettier-ignore
function PickResolve(properties, propertyKeys) {
    return (IsIntersect$1(properties) ? Intersect(FromIntersect$1(properties.allOf, propertyKeys)) :
        IsUnion$1(properties) ? Union(FromUnion$1(properties.anyOf, propertyKeys)) :
            IsObject$1(properties) ? FromObject$3(properties, propertyKeys) :
                Object$1({}));
}
/** `[Json]` Constructs a type whose keys are picked from the given type */
// prettier-ignore
function Pick(type, key, options) {
    const typeKey = IsArray$3(key) ? UnionFromPropertyKeys(key) : key;
    const propertyKeys = IsSchema$1(key) ? IndexPropertyKeys(key) : key;
    const isTypeRef = IsRef$1(type);
    const isKeyRef = IsRef$1(key);
    return (IsMappedResult$1(type) ? PickFromMappedResult(type, propertyKeys, options) :
        IsMappedKey$1(key) ? PickFromMappedKey(type, key, options) :
            (isTypeRef && isKeyRef) ? Computed('Pick', [type, typeKey], options) :
                (!isTypeRef && isKeyRef) ? Computed('Pick', [type, typeKey], options) :
                    (isTypeRef && !isKeyRef) ? Computed('Pick', [type, typeKey], options) :
                        CreateType({ ...PickResolve(type, propertyKeys), ...options }));
}

// prettier-ignore
function FromPropertyKey(type, key, options) {
    return {
        [key]: Pick(type, [key], Clone(options))
    };
}
// prettier-ignore
function FromPropertyKeys(type, propertyKeys, options) {
    return propertyKeys.reduce((result, leftKey) => {
        return { ...result, ...FromPropertyKey(type, leftKey, options) };
    }, {});
}
// prettier-ignore
function FromMappedKey(type, mappedKey, options) {
    return FromPropertyKeys(type, mappedKey.keys, options);
}
// prettier-ignore
function PickFromMappedKey(type, mappedKey, options) {
    const properties = FromMappedKey(type, mappedKey, options);
    return MappedResult(properties);
}

// prettier-ignore
function FromComputed$2(target, parameters) {
    return Computed('Partial', [Computed(target, parameters)]);
}
// prettier-ignore
function FromRef$1($ref) {
    return Computed('Partial', [Ref($ref)]);
}
// prettier-ignore
function FromProperties$3(properties) {
    const partialProperties = {};
    for (const K of globalThis.Object.getOwnPropertyNames(properties))
        partialProperties[K] = Optional(properties[K]);
    return partialProperties;
}
// prettier-ignore
function FromObject$2(type) {
    const options = Discard(type, [TransformKind, '$id', 'required', 'properties']);
    const properties = FromProperties$3(type['properties']);
    return Object$1(properties, options);
}
// prettier-ignore
function FromRest$1(types) {
    return types.map(type => PartialResolve(type));
}
// ------------------------------------------------------------------
// PartialResolve
// ------------------------------------------------------------------
// prettier-ignore
function PartialResolve(type) {
    return (
    // Mappable
    IsComputed$1(type) ? FromComputed$2(type.target, type.parameters) :
        IsRef$1(type) ? FromRef$1(type.$ref) :
            IsIntersect$1(type) ? Intersect(FromRest$1(type.allOf)) :
                IsUnion$1(type) ? Union(FromRest$1(type.anyOf)) :
                    IsObject$1(type) ? FromObject$2(type) :
                        // Intrinsic
                        IsBigInt$1(type) ? type :
                            IsBoolean$1(type) ? type :
                                IsInteger$1(type) ? type :
                                    IsLiteral$1(type) ? type :
                                        IsNull$1(type) ? type :
                                            IsNumber$1(type) ? type :
                                                IsString$1(type) ? type :
                                                    IsSymbol$1(type) ? type :
                                                        IsUndefined$1(type) ? type :
                                                            // Passthrough
                                                            Object$1({}));
}
/** `[Json]` Constructs a type where all properties are optional */
function Partial(type, options) {
    if (IsMappedResult$1(type)) {
        return PartialFromMappedResult(type, options);
    }
    else {
        // special: mapping types require overridable options
        return CreateType({ ...PartialResolve(type), ...options });
    }
}

// prettier-ignore
function FromProperties$2(K, options) {
    const Acc = {};
    for (const K2 of globalThis.Object.getOwnPropertyNames(K))
        Acc[K2] = Partial(K[K2], Clone(options));
    return Acc;
}
// prettier-ignore
function FromMappedResult$1(R, options) {
    return FromProperties$2(R.properties, options);
}
// prettier-ignore
function PartialFromMappedResult(R, options) {
    const P = FromMappedResult$1(R, options);
    return MappedResult(P);
}

// prettier-ignore
function FromComputed$1(target, parameters) {
    return Computed('Required', [Computed(target, parameters)]);
}
// prettier-ignore
function FromRef($ref) {
    return Computed('Required', [Ref($ref)]);
}
// prettier-ignore
function FromProperties$1(properties) {
    const requiredProperties = {};
    for (const K of globalThis.Object.getOwnPropertyNames(properties))
        requiredProperties[K] = Discard(properties[K], [OptionalKind]);
    return requiredProperties;
}
// prettier-ignore
function FromObject$1(type) {
    const options = Discard(type, [TransformKind, '$id', 'required', 'properties']);
    const properties = FromProperties$1(type['properties']);
    return Object$1(properties, options);
}
// prettier-ignore
function FromRest(types) {
    return types.map(type => RequiredResolve(type));
}
// ------------------------------------------------------------------
// RequiredResolve
// ------------------------------------------------------------------
// prettier-ignore
function RequiredResolve(type) {
    return (
    // Mappable
    IsComputed$1(type) ? FromComputed$1(type.target, type.parameters) :
        IsRef$1(type) ? FromRef(type.$ref) :
            IsIntersect$1(type) ? Intersect(FromRest(type.allOf)) :
                IsUnion$1(type) ? Union(FromRest(type.anyOf)) :
                    IsObject$1(type) ? FromObject$1(type) :
                        // Intrinsic
                        IsBigInt$1(type) ? type :
                            IsBoolean$1(type) ? type :
                                IsInteger$1(type) ? type :
                                    IsLiteral$1(type) ? type :
                                        IsNull$1(type) ? type :
                                            IsNumber$1(type) ? type :
                                                IsString$1(type) ? type :
                                                    IsSymbol$1(type) ? type :
                                                        IsUndefined$1(type) ? type :
                                                            // Passthrough
                                                            Object$1({}));
}
/** `[Json]` Constructs a type where all properties are required */
function Required(type, options) {
    if (IsMappedResult$1(type)) {
        return RequiredFromMappedResult(type, options);
    }
    else {
        // special: mapping types require overridable options
        return CreateType({ ...RequiredResolve(type), ...options });
    }
}

// prettier-ignore
function FromProperties(P, options) {
    const Acc = {};
    for (const K2 of globalThis.Object.getOwnPropertyNames(P))
        Acc[K2] = Required(P[K2], options);
    return Acc;
}
// prettier-ignore
function FromMappedResult(R, options) {
    return FromProperties(R.properties, options);
}
// prettier-ignore
function RequiredFromMappedResult(R, options) {
    const P = FromMappedResult(R, options);
    return MappedResult(P);
}

// prettier-ignore
function DereferenceParameters(moduleProperties, types) {
    return types.map((type) => {
        return IsRef$1(type)
            ? Dereference(moduleProperties, type.$ref)
            : FromType(moduleProperties, type);
    });
}
// prettier-ignore
function Dereference(moduleProperties, ref) {
    return (ref in moduleProperties
        ? IsRef$1(moduleProperties[ref])
            ? Dereference(moduleProperties, moduleProperties[ref].$ref)
            : FromType(moduleProperties, moduleProperties[ref])
        : Never());
}
// prettier-ignore
function FromAwaited(parameters) {
    return Awaited(parameters[0]);
}
// prettier-ignore
function FromIndex(parameters) {
    return Index(parameters[0], parameters[1]);
}
// prettier-ignore
function FromKeyOf(parameters) {
    return KeyOf(parameters[0]);
}
// prettier-ignore
function FromPartial(parameters) {
    return Partial(parameters[0]);
}
// prettier-ignore
function FromOmit(parameters) {
    return Omit(parameters[0], parameters[1]);
}
// prettier-ignore
function FromPick(parameters) {
    return Pick(parameters[0], parameters[1]);
}
// prettier-ignore
function FromRequired(parameters) {
    return Required(parameters[0]);
}
// prettier-ignore
function FromComputed(moduleProperties, target, parameters) {
    const dereferenced = DereferenceParameters(moduleProperties, parameters);
    return (target === 'Awaited' ? FromAwaited(dereferenced) :
        target === 'Index' ? FromIndex(dereferenced) :
            target === 'KeyOf' ? FromKeyOf(dereferenced) :
                target === 'Partial' ? FromPartial(dereferenced) :
                    target === 'Omit' ? FromOmit(dereferenced) :
                        target === 'Pick' ? FromPick(dereferenced) :
                            target === 'Required' ? FromRequired(dereferenced) :
                                Never());
}
function FromArray(moduleProperties, type) {
    return Array$1(FromType(moduleProperties, type));
}
function FromAsyncIterator(moduleProperties, type) {
    return AsyncIterator$1(FromType(moduleProperties, type));
}
// prettier-ignore
function FromConstructor(moduleProperties, parameters, instanceType) {
    return Constructor(FromTypes(moduleProperties, parameters), FromType(moduleProperties, instanceType));
}
// prettier-ignore
function FromFunction(moduleProperties, parameters, returnType) {
    return Function$1(FromTypes(moduleProperties, parameters), FromType(moduleProperties, returnType));
}
function FromIntersect(moduleProperties, types) {
    return Intersect(FromTypes(moduleProperties, types));
}
function FromIterator(moduleProperties, type) {
    return Iterator$1(FromType(moduleProperties, type));
}
function FromObject(moduleProperties, properties) {
    return Object$1(globalThis.Object.keys(properties).reduce((result, key) => {
        return { ...result, [key]: FromType(moduleProperties, properties[key]) };
    }, {}));
}
// prettier-ignore
function FromRecord(moduleProperties, type) {
    const [value, pattern] = [FromType(moduleProperties, RecordValue(type)), RecordPattern(type)];
    const result = CloneType(type);
    result.patternProperties[pattern] = value;
    return result;
}
// prettier-ignore
function FromTransform(moduleProperties, transform) {
    return (IsRef$1(transform))
        ? { ...Dereference(moduleProperties, transform.$ref), [TransformKind]: transform[TransformKind] }
        : transform;
}
function FromTuple(moduleProperties, types) {
    return Tuple(FromTypes(moduleProperties, types));
}
function FromUnion(moduleProperties, types) {
    return Union(FromTypes(moduleProperties, types));
}
function FromTypes(moduleProperties, types) {
    return types.map((type) => FromType(moduleProperties, type));
}
// prettier-ignore
function FromType(moduleProperties, type) {
    return (
    // Modifiers
    IsOptional$1(type) ? CreateType(FromType(moduleProperties, Discard(type, [OptionalKind])), type) :
        IsReadonly(type) ? CreateType(FromType(moduleProperties, Discard(type, [ReadonlyKind])), type) :
            // Transform
            IsTransform$1(type) ? CreateType(FromTransform(moduleProperties, type), type) :
                // Types
                IsArray$1(type) ? CreateType(FromArray(moduleProperties, type.items), type) :
                    IsAsyncIterator$1(type) ? CreateType(FromAsyncIterator(moduleProperties, type.items), type) :
                        IsComputed$1(type) ? CreateType(FromComputed(moduleProperties, type.target, type.parameters)) :
                            IsConstructor$1(type) ? CreateType(FromConstructor(moduleProperties, type.parameters, type.returns), type) :
                                IsFunction$1(type) ? CreateType(FromFunction(moduleProperties, type.parameters, type.returns), type) :
                                    IsIntersect$1(type) ? CreateType(FromIntersect(moduleProperties, type.allOf), type) :
                                        IsIterator$1(type) ? CreateType(FromIterator(moduleProperties, type.items), type) :
                                            IsObject$1(type) ? CreateType(FromObject(moduleProperties, type.properties), type) :
                                                IsRecord$1(type) ? CreateType(FromRecord(moduleProperties, type)) :
                                                    IsTuple$1(type) ? CreateType(FromTuple(moduleProperties, type.items || []), type) :
                                                        IsUnion$1(type) ? CreateType(FromUnion(moduleProperties, type.anyOf), type) :
                                                            type);
}
// prettier-ignore
function ComputeType(moduleProperties, key) {
    return (key in moduleProperties
        ? FromType(moduleProperties, moduleProperties[key])
        : Never());
}
// prettier-ignore
function ComputeModuleProperties(moduleProperties) {
    return globalThis.Object.getOwnPropertyNames(moduleProperties).reduce((result, key) => {
        return { ...result, [key]: ComputeType(moduleProperties, key) };
    }, {});
}

// ------------------------------------------------------------------
// Module
// ------------------------------------------------------------------
// prettier-ignore
class TModule {
    constructor($defs) {
        const computed = ComputeModuleProperties($defs);
        const identified = this.WithIdentifiers(computed);
        this.$defs = identified;
    }
    /** `[Json]` Imports a Type by Key. */
    Import(key, options) {
        const $defs = { ...this.$defs, [key]: CreateType(this.$defs[key], options) };
        return CreateType({ [Kind]: 'Import', $defs, $ref: key });
    }
    // prettier-ignore
    WithIdentifiers($defs) {
        return globalThis.Object.getOwnPropertyNames($defs).reduce((result, key) => {
            return { ...result, [key]: { ...$defs[key], $id: key } };
        }, {});
    }
}
/** `[Json]` Creates a Type Definition Module. */
function Module(properties) {
    return new TModule(properties);
}

/** `[Json]` Creates a Not type */
function Not(type, options) {
    return CreateType({ [Kind]: 'Not', not: type }, options);
}

/** `[JavaScript]` Extracts the Parameters from the given Function type */
function Parameters(schema, options) {
    return (IsFunction$1(schema) ? Tuple(schema.parameters, options) : Never());
}

// Auto Tracked For Recursive Types without ID's
let Ordinal = 0;
/** `[Json]` Creates a Recursive type */
function Recursive(callback, options = {}) {
    if (IsUndefined$3(options.$id))
        options.$id = `T${Ordinal++}`;
    const thisType = CloneType(callback({ [Kind]: 'This', $ref: `${options.$id}` }));
    thisType.$id = options.$id;
    // prettier-ignore
    return CreateType({ [Hint]: 'Recursive', ...thisType }, options);
}

/** `[JavaScript]` Creates a RegExp type */
function RegExp$1(unresolved, options) {
    const expr = IsString$2(unresolved) ? new globalThis.RegExp(unresolved) : unresolved;
    return CreateType({ [Kind]: 'RegExp', type: 'RegExp', source: expr.source, flags: expr.flags }, options);
}

// ------------------------------------------------------------------
// TypeGuard
// ------------------------------------------------------------------
// prettier-ignore
function RestResolve(T) {
    return (IsIntersect$1(T) ? T.allOf :
        IsUnion$1(T) ? T.anyOf :
            IsTuple$1(T) ? T.items ?? [] :
                []);
}
/** `[Json]` Extracts interior Rest elements from Tuple, Intersect and Union types */
function Rest(T) {
    return RestResolve(T);
}

/** `[JavaScript]` Extracts the ReturnType from the given Function type */
function ReturnType(schema, options) {
    return (IsFunction$1(schema) ? CreateType(schema.returns, options) : Never(options));
}

// ------------------------------------------------------------------
// TransformBuilders
// ------------------------------------------------------------------
class TransformDecodeBuilder {
    constructor(schema) {
        this.schema = schema;
    }
    Decode(decode) {
        return new TransformEncodeBuilder(this.schema, decode);
    }
}
// prettier-ignore
class TransformEncodeBuilder {
    constructor(schema, decode) {
        this.schema = schema;
        this.decode = decode;
    }
    EncodeTransform(encode, schema) {
        const Encode = (value) => schema[TransformKind].Encode(encode(value));
        const Decode = (value) => this.decode(schema[TransformKind].Decode(value));
        const Codec = { Encode: Encode, Decode: Decode };
        return { ...schema, [TransformKind]: Codec };
    }
    EncodeSchema(encode, schema) {
        const Codec = { Decode: this.decode, Encode: encode };
        return { ...schema, [TransformKind]: Codec };
    }
    Encode(encode) {
        return (IsTransform$1(this.schema) ? this.EncodeTransform(encode, this.schema) : this.EncodeSchema(encode, this.schema));
    }
}
/** `[Json]` Creates a Transform type */
function Transform(schema) {
    return new TransformDecodeBuilder(schema);
}

/** `[Json]` Creates a Unsafe type that will infers as the generic argument T */
function Unsafe(options = {}) {
    return CreateType({ [Kind]: options[Kind] ?? 'Unsafe' }, options);
}

/** `[JavaScript]` Creates a Void type */
function Void(options) {
    return CreateType({ [Kind]: 'Void', type: 'void' }, options);
}

// ------------------------------------------------------------------
// Type: Module
// ------------------------------------------------------------------

const TypeBuilder = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
    __proto__: null,
    Any: Any$1,
    Argument,
    Array: Array$1,
    AsyncIterator: AsyncIterator$1,
    Awaited,
    BigInt: BigInt$1,
    Boolean: Boolean$2,
    Capitalize,
    Composite,
    Const,
    Constructor,
    ConstructorParameters,
    Date: Date$1,
    Enum,
    Exclude,
    Extends,
    Extract,
    Function: Function$1,
    Index,
    InstanceType,
    Instantiate,
    Integer: Integer$1,
    Intersect,
    Iterator: Iterator$1,
    KeyOf,
    Literal,
    Lowercase,
    Mapped,
    Module,
    Never,
    Not,
    Null: Null$1,
    Number: Number$1,
    Object: Object$1,
    Omit,
    Optional,
    Parameters,
    Partial,
    Pick,
    Promise: Promise$1,
    Readonly,
    ReadonlyOptional,
    Record,
    Recursive,
    Ref,
    RegExp: RegExp$1,
    Required,
    Rest,
    ReturnType,
    String: String$1,
    Symbol: Symbol$1,
    TemplateLiteral,
    Transform,
    Tuple,
    Uint8Array: Uint8Array$1,
    Uncapitalize,
    Undefined,
    Union,
    Unknown,
    Unsafe,
    Uppercase,
    Void
}, Symbol.toStringTag, { value: 'Module' }));

// ------------------------------------------------------------------
// JsonTypeBuilder
// ------------------------------------------------------------------
/** JavaScript Type Builder with Static Resolution for TypeScript */
const Type = TypeBuilder;

const NapcatConfigSchema = Type.Object({
  fileLog: Type.Boolean({ default: false }),
  consoleLog: Type.Boolean({ default: true }),
  fileLogLevel: Type.String({ default: "debug" }),
  consoleLogLevel: Type.String({ default: "info" }),
  packetBackend: Type.String({ default: "auto" }),
  packetServer: Type.String({ default: "" }),
  o3HookMode: Type.Number({ default: 0 })
});
class NapCatConfigLoader extends ConfigBase {
  constructor(core, configPath, schema) {
    super("napcat", core, configPath, schema);
  }
}

class NodeIKernelSessionListener {
  onNTSessionCreate(_args) {
  }
  onGProSessionCreate(_args) {
  }
  onSessionInitComplete(_args) {
  }
  onOpentelemetryInit(_info) {
  }
  onUserOnlineResult(_args) {
  }
  onGetSelfTinyId(_args) {
  }
}

class NodeIKernelLoginListener {
  onLoginConnected() {
  }
  onLoginDisConnected(..._args) {
  }
  onLoginConnecting(..._args) {
  }
  onQRCodeGetPicture(_arg) {
  }
  onQRCodeLoginPollingStarted(..._args) {
  }
  onQRCodeSessionUserScaned(..._args) {
  }
  onQRCodeLoginSucceed(_arg) {
  }
  onQRCodeSessionFailed(..._args) {
  }
  onLoginFailed(..._args) {
  }
  onLogoutSucceed(..._args) {
  }
  onLogoutFailed(..._args) {
  }
  onUserLoggedIn(..._args) {
  }
  onQRCodeSessionQuickLoginFailed(..._args) {
  }
  onPasswordLoginFailed(..._args) {
  }
  OnConfirmUnusualDeviceFailed(..._args) {
  }
  onQQLoginNumLimited(..._args) {
  }
  onLoginState(..._args) {
  }
}

class NodeIKernelMsgListener {
  onAddSendMsg(_msgRecord) {
  }
  onBroadcastHelperDownloadComplete(_broadcastHelperTransNotifyInfo) {
  }
  onBroadcastHelperProgressUpdate(_broadcastHelperTransNotifyInfo) {
  }
  onChannelFreqLimitInfoUpdate(_contact, _z, _freqLimitInfo) {
  }
  onContactUnreadCntUpdate(_hashMap) {
  }
  onCustomWithdrawConfigUpdate(_customWithdrawConfig) {
  }
  onDraftUpdate(_contact, _arrayList, _j2) {
  }
  onEmojiDownloadComplete(_emojiNotifyInfo) {
  }
  onEmojiResourceUpdate(_emojiResourceInfo) {
  }
  onFeedEventUpdate(_firstViewDirectMsgNotifyInfo) {
  }
  onFileMsgCome(_arrayList) {
  }
  onFirstViewDirectMsgUpdate(_firstViewDirectMsgNotifyInfo) {
  }
  onFirstViewGroupGuildMapping(_arrayList) {
  }
  onGrabPasswordRedBag(_i2, _str, _i3, _recvdOrder, _msgRecord) {
  }
  onGroupFileInfoAdd(_groupItem) {
  }
  onGroupFileInfoUpdate(_groupFileListResult) {
  }
  onGroupGuildUpdate(_groupGuildNotifyInfo) {
  }
  onGroupTransferInfoAdd(_groupItem) {
  }
  onGroupTransferInfoUpdate(_groupFileListResult) {
  }
  onGuildInteractiveUpdate(_guildInteractiveNotificationItem) {
  }
  onGuildMsgAbFlagChanged(_guildMsgAbFlag) {
  }
  onGuildNotificationAbstractUpdate(_guildNotificationAbstractInfo) {
  }
  onHitCsRelatedEmojiResult(_downloadRelateEmojiResultInfo) {
  }
  onHitEmojiKeywordResult(_hitRelatedEmojiWordsResult) {
  }
  onHitRelatedEmojiResult(_relatedWordEmojiInfo) {
  }
  onImportOldDbProgressUpdate(_importOldDbMsgNotifyInfo) {
  }
  onInputStatusPush(_inputStatusInfo) {
  }
  onKickedOffLine(_kickedInfo) {
  }
  onLineDev(_arrayList) {
  }
  onLogLevelChanged(_j2) {
  }
  onMsgAbstractUpdate(_arrayList) {
  }
  onMsgBoxChanged(_arrayList) {
  }
  onMsgDelete(_contact, _arrayList) {
  }
  onMsgEventListUpdate(_hashMap) {
  }
  onMsgInfoListAdd(_arrayList) {
  }
  onMsgInfoListUpdate(_msgList) {
  }
  onMsgQRCodeStatusChanged(_i2) {
  }
  onMsgRecall(_chatType, _uid, _msgSeq) {
  }
  onMsgSecurityNotify(_msgRecord) {
  }
  onMsgSettingUpdate(_msgSetting) {
  }
  onNtFirstViewMsgSyncEnd() {
  }
  onNtMsgSyncEnd() {
  }
  onNtMsgSyncStart() {
  }
  onReadFeedEventUpdate(_firstViewDirectMsgNotifyInfo) {
  }
  onRecvGroupGuildFlag(_i2) {
  }
  onRecvMsg(_arrayList) {
  }
  onRecvMsgSvrRspTransInfo(_j2, _contact, _i2, _i3, _str, _bArr) {
  }
  onRecvOnlineFileMsg(_arrayList) {
  }
  onRecvS2CMsg(_arrayList) {
  }
  onRecvSysMsg(_arrayList) {
  }
  onRecvUDCFlag(_i2) {
  }
  onRichMediaDownloadComplete(_fileTransNotifyInfo) {
  }
  onRichMediaProgerssUpdate(_fileTransNotifyInfo) {
  }
  onRichMediaUploadComplete(_fileTransNotifyInfo) {
  }
  onSearchGroupFileInfoUpdate(_searchGroupFileResult) {
  }
  onSendMsgError(_j2, _contact, _i2, _str) {
  }
  onSysMsgNotification(_i2, _j2, _j3, _arrayList) {
  }
  onTempChatInfoUpdate(_tempChatInfo) {
  }
  onUnreadCntAfterFirstView(_hashMap) {
  }
  onUnreadCntUpdate(_hashMap) {
  }
  onUserChannelTabStatusChanged(_z) {
  }
  onUserOnlineStatusChanged(_z) {
  }
  onUserTabStatusChanged(_arrayList) {
  }
  onlineStatusBigIconDownloadPush(_i2, _j2, _str) {
  }
  onlineStatusSmallIconDownloadPush(_i2, _j2, _str) {
  }
  // 第一次发现于Linux
  onUserSecQualityChanged(..._args) {
  }
  onMsgWithRichLinkInfoUpdate(..._args) {
  }
  onRedTouchChanged(..._args) {
  }
  // 第一次发现于Win 9.9.9-23159
  onBroadcastHelperProgerssUpdate(..._args) {
  }
}

class NodeIKernelGroupListener {
  onGroupListInited(_listEmpty) {
  }
  // 发现于Win 9.9.9 23159
  onGroupMemberLevelInfoChange(..._args) {
  }
  onGetGroupBulletinListResult(..._args) {
  }
  onGroupAllInfoChange(..._args) {
  }
  onGroupBulletinChange(..._args) {
  }
  onGroupBulletinRemindNotify(..._args) {
  }
  onGroupArkInviteStateResult(..._args) {
  }
  onGroupBulletinRichMediaDownloadComplete(..._args) {
  }
  onGroupConfMemberChange(..._args) {
  }
  onGroupDetailInfoChange(_detailInfo) {
  }
  onGroupExtListUpdate(..._args) {
  }
  onGroupFirstBulletinNotify(..._args) {
  }
  onGroupListUpdate(_updateType, _groupList) {
  }
  onGroupNotifiesUpdated(_dboubt, _notifies) {
  }
  onGroupBulletinRichMediaProgressUpdate(..._args) {
  }
  onGroupNotifiesUnreadCountUpdated(..._args) {
  }
  onGroupSingleScreenNotifies(_doubt, _seq, _notifies) {
  }
  onGroupsMsgMaskResult(..._args) {
  }
  onGroupStatisticInfoChange(..._args) {
  }
  onJoinGroupNotify(..._args) {
  }
  onJoinGroupNoVerifyFlag(..._args) {
  }
  onMemberInfoChange(_groupCode, _dateSource, _members) {
  }
  onMemberListChange(_arg) {
  }
  onSearchMemberChange(..._args) {
  }
  onShutUpMemberListChanged(_groupCode, _members) {
  }
}

class NodeIKernelBuddyListener {
  onBuddyListChangedV2(_arg) {
  }
  onAddBuddyNeedVerify(_arg) {
  }
  onAddMeSettingChanged(_arg) {
  }
  onAvatarUrlUpdated(_arg) {
  }
  onBlockChanged(_arg) {
  }
  onBuddyDetailInfoChange(_arg) {
  }
  onBuddyInfoChange(_arg) {
  }
  onBuddyListChange(_arg) {
  }
  onBuddyRemarkUpdated(_arg) {
  }
  onBuddyReqChange(_arg) {
  }
  onBuddyReqUnreadCntChange(_arg) {
  }
  onCheckBuddySettingResult(_arg) {
  }
  onDelBatchBuddyInfos(_arg) {
  }
  onDoubtBuddyReqChange(_arg) {
  }
  onDoubtBuddyReqUnreadNumChange(_num) {
  }
  onNickUpdated(_arg) {
  }
  onSmartInfos(_arg) {
  }
  onSpacePermissionInfos(_arg) {
  }
}

class NodeIKernelProfileListener {
  onUserDetailInfoChanged(_arg) {
  }
  onProfileSimpleChanged(..._args) {
  }
  onProfileDetailInfoChanged(_profile) {
  }
  onStatusUpdate(..._args) {
  }
  onSelfStatusChanged(..._args) {
  }
  onStrangerRemarkChanged(..._args) {
  }
  onMemberListChange(..._args) {
  }
  onMemberInfoChange(..._args) {
  }
  onGroupListUpdate(..._args) {
  }
  onGroupAllInfoChange(..._args) {
  }
  onGroupDetailInfoChange(..._args) {
  }
  onGroupConfMemberChange(..._args) {
  }
  onGroupExtListUpdate(..._args) {
  }
  onGroupNotifiesUpdated(..._args) {
  }
  onGroupNotifiesUnreadCountUpdated(..._args) {
  }
  onGroupMemberLevelInfoChange(..._args) {
  }
  onGroupBulletinChange(..._args) {
  }
}

function proxyHandlerOf(logger) {
  return {
    get(target, prop, receiver) {
      if (typeof target[prop] === "undefined") {
        return (..._args) => {
          logger.logDebug(`${target.constructor.name} has no method ${prop}`);
        };
      }
      return Reflect.get(target, prop, receiver);
    }
  };
}
function proxiedListenerOf(listener, logger) {
  return new Proxy(listener, proxyHandlerOf(logger));
}

class TypedEventEmitter {
  emitter = new EventEmitter$1();
  on(event, listener) {
    this.emitter.on(event, listener);
    return () => this.off(event, listener);
  }
  once(event, listener) {
    this.emitter.once(event, listener);
  }
  off(event, listener) {
    this.emitter.off(event, listener);
  }
  emit(event, payload) {
    this.emitter.emit(event, payload);
  }
}

const appEvent = new TypedEventEmitter();

var NapCatCoreWorkingEnv$1 = /* @__PURE__ */ ((NapCatCoreWorkingEnv2) => {
  NapCatCoreWorkingEnv2[NapCatCoreWorkingEnv2["Unknown"] = 0] = "Unknown";
  NapCatCoreWorkingEnv2[NapCatCoreWorkingEnv2["Shell"] = 1] = "Shell";
  NapCatCoreWorkingEnv2[NapCatCoreWorkingEnv2["Framework"] = 2] = "Framework";
  return NapCatCoreWorkingEnv2;
})(NapCatCoreWorkingEnv$1 || {});
function loadQQWrapper(QQVersion) {
  if (process.env["NAPCAT_WRAPPER_PATH"]) {
    const wrapperPath = process.env["NAPCAT_WRAPPER_PATH"];
    const nativemodule2 = { exports: {} };
    process.dlopen(nativemodule2, wrapperPath);
    return nativemodule2.exports;
  }
  let appPath;
  if (os$1.platform() === "darwin") {
    appPath = path$1.resolve(path$1.dirname(process.execPath), "../Resources/app");
  } else if (os$1.platform() === "linux") {
    appPath = path$1.resolve(path$1.dirname(process.execPath), "./resources/app");
  } else {
    appPath = path$1.resolve(path$1.dirname(process.execPath), `./versions/${QQVersion}/`);
  }
  let wrapperNodePath = path$1.resolve(appPath, "wrapper.node");
  if (!fs$2.existsSync(wrapperNodePath)) {
    wrapperNodePath = path$1.join(appPath, "./resources/app/wrapper.node");
  }
  if (!fs$2.existsSync(wrapperNodePath)) {
    wrapperNodePath = path$1.join(path$1.dirname(process.execPath), `./resources/app/versions/${QQVersion}/wrapper.node`);
  }
  const nativemodule = { exports: {} };
  process.dlopen(nativemodule, wrapperNodePath);
  return nativemodule.exports;
}
function getMajorPath(QQVersion) {
  let appPath;
  if (os$1.platform() === "darwin") {
    appPath = path$1.resolve(path$1.dirname(process.execPath), "../Resources/app");
  } else if (os$1.platform() === "linux") {
    appPath = path$1.resolve(path$1.dirname(process.execPath), "./resources/app");
  } else {
    appPath = path$1.resolve(path$1.dirname(process.execPath), `./versions/${QQVersion}/`);
  }
  let majorPath = path$1.resolve(appPath, "major.node");
  if (!fs$2.existsSync(majorPath)) {
    majorPath = path$1.join(appPath, "./resources/app/major.node");
  }
  if (!fs$2.existsSync(majorPath)) {
    majorPath = path$1.join(path$1.dirname(process.execPath), `./resources/app/versions/${QQVersion}/major.node`);
  }
  return majorPath;
}
class NapCatCore {
  context;
  eventWrapper;
  event = appEvent;
  NapCatDataPath = "";
  NapCatTempPath = "";
  apis;
  // runtime info, not readonly
  selfInfo;
  util;
  configLoader;
  // 通过构造器递过去的 runtime info 应该尽量少
  constructor(context, selfInfo) {
    this.selfInfo = selfInfo;
    this.context = context;
    this.util = this.context.wrapper.NodeQQNTWrapperUtil;
    this.eventWrapper = new NTEventWrapper(context.session);
    this.configLoader = new NapCatConfigLoader(this, this.context.pathWrapper.configPath, NapcatConfigSchema);
    this.apis = {
      FileApi: new NTQQFileApi(this.context, this),
      SystemApi: new NTQQSystemApi(this.context, this),
      CollectionApi: new NTQQCollectionApi(this.context, this),
      PacketApi: new NTQQPacketApi(this.context, this),
      WebApi: new NTQQWebApi(this.context, this),
      FriendApi: new NTQQFriendApi(this.context, this),
      MsgApi: new NTQQMsgApi(this.context, this),
      UserApi: new NTQQUserApi(this.context, this),
      GroupApi: new NTQQGroupApi(this.context, this)
    };
    container.bind(NapCatCore).toConstantValue(this);
    container.bind(TypedEventEmitter).toConstantValue(this.event);
    ReceiverServiceRegistry.forEach((ServiceClass, serviceName) => {
      container.bind(ServiceClass).toSelf();
      this.context.packetHandler.onCmd(serviceName, ({ seq, hex_data }) => {
        const serviceInstance = container.get(ServiceClass);
        return serviceInstance.handler(seq, hex_data);
      });
    });
  }
  async initCore() {
    this.NapCatDataPath = path$1.join(this.dataPath, "NapCat");
    fs$2.mkdirSync(this.NapCatDataPath, { recursive: true });
    this.NapCatTempPath = path$1.join(this.NapCatDataPath, "temp");
    if (!fs$2.existsSync(this.NapCatTempPath)) {
      fs$2.mkdirSync(this.NapCatTempPath, { recursive: true });
    }
    for (const apiKey in this.apis) {
      const api = this.apis[apiKey];
      if ("initApi" in api && typeof api.initApi === "function") {
        await api.initApi();
      }
    }
    this.initNapCatCoreListeners().then().catch((e) => this.context.logger.logError(e));
    this.context.logger.setFileLogEnabled(
      this.configLoader.configData.fileLog
    );
    this.context.logger.setConsoleLogEnabled(
      this.configLoader.configData.consoleLog
    );
    this.context.logger.setFileAndConsoleLogLevel(
      this.configLoader.configData.fileLogLevel,
      this.configLoader.configData.consoleLogLevel
    );
  }
  get dataPath() {
    let result = this.context.wrapper.NodeQQNTWrapperUtil.getNTUserDataInfoConfig();
    if (!result) {
      result = path$1.resolve(os$1.homedir(), "./.config/QQ");
      fs$2.mkdirSync(result, { recursive: true });
    }
    return result;
  }
  // Renamed from 'InitDataListener'
  async initNapCatCoreListeners() {
    const msgListener = new NodeIKernelMsgListener();
    msgListener.onKickedOffLine = (Info) => {
      this.context.logger.logError("[KickedOffLine] [" + Info.tipsTitle + "] " + Info.tipsDesc);
      this.selfInfo.online = false;
    };
    msgListener.onRecvMsg = (msgs) => {
      msgs.forEach((msg) => this.context.logger.logMessage(msg, this.selfInfo));
    };
    msgListener.onAddSendMsg = (msg) => {
      this.context.logger.logMessage(msg, this.selfInfo);
    };
    this.context.session.getMsgService().addKernelMsgListener(
      proxiedListenerOf(msgListener, this.context.logger)
    );
    const profileListener = new NodeIKernelProfileListener();
    profileListener.onProfileDetailInfoChanged = (profile) => {
      if (profile.uid === this.selfInfo.uid) {
        Object.assign(this.selfInfo, profile);
      }
    };
    profileListener.onSelfStatusChanged = (Info) => {
      if (Info.status === 20) {
        this.selfInfo.online = false;
        this.context.logger.log("账号状态变更为离线");
      } else {
        this.selfInfo.online = true;
      }
    };
    this.context.session.getProfileService().addKernelProfileListener(
      proxiedListenerOf(profileListener, this.context.logger)
    );
  }
}
async function genSessionConfig(guid, QQVersionAppid, QQVersion, selfUin, selfUid, account_path) {
  const downloadPath = path$1.join(account_path, "NapCat", "temp");
  fs$2.mkdirSync(downloadPath, { recursive: true });
  const platformMapping = {
    win32: PlatformType.KWINDOWS,
    darwin: PlatformType.KMAC,
    linux: PlatformType.KLINUX
  };
  const systemPlatform = platformMapping[os$1.platform()] ?? PlatformType.KWINDOWS;
  return {
    selfUin,
    selfUid,
    desktopPathConfig: {
      account_path
      // 可以通过NodeQQNTWrapperUtil().getNTUserDataInfoConfig()获取
    },
    clientVer: QQVersion,
    a2: "",
    d2: "",
    d2Key: "",
    machineId: "",
    platform: systemPlatform,
    // 3是Windows?
    platVer: systemVersion,
    // 系统版本号, 应该可以固定
    appid: QQVersionAppid,
    rdeliveryConfig: {
      appKey: "",
      systemId: 0,
      appId: "",
      logicEnvironment: "",
      platform: systemPlatform,
      language: "",
      sdkVersion: "",
      userId: "",
      appVersion: "",
      osVersion: "",
      bundleId: "",
      serverUrl: "",
      fixedAfterHitKeys: [""]
    },
    defaultFileDownloadPath: downloadPath,
    deviceInfo: {
      guid,
      buildVer: QQVersion,
      localId: 2052,
      devName: hostname,
      devType: systemName,
      vendorName: "",
      osVer: systemVersion,
      vendorOsName: systemName,
      setMute: false,
      vendorType: VendorType.KNOSETONIOS
    },
    deviceConfig: '{"appearance":{"isSplitViewMode":true},"msg":{}}'
  };
}

const container = new ne();
const ReceiverServiceRegistry = /* @__PURE__ */ new Map();
class ServiceBase {
  get core() {
    return container.get(NapCatCore);
  }
  get event() {
    return container.get(TypedEventEmitter);
  }
}
function ReceiveService(serviceName) {
  return function(constructor) {
    W$2()(constructor);
    ReceiverServiceRegistry.set(serviceName, constructor);
    return constructor;
  };
}

var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
var __decorateClass$2 = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (decorator(result)) || result;
  return result;
};
let OlPushService = class extends ServiceBase {
  async handler(_seq, hex_data) {
    const data = new NapProtoMsg(PushMsg).decode(Buffer.from(hex_data, "hex"));
    if (data.message.contentHead.type === 732 && data.message.contentHead.subType === 16) {
      const pbNotify = data.message.body?.msgContent?.slice(7);
      if (!pbNotify) {
        return;
      }
      const notify = new NapProtoMsg(GroupReactNotify).decode(pbNotify);
      if ((notify.field13 ?? 0) === 35) {
        const groupCode = notify.groupUin?.toString() ?? "";
        const operatorUid = notify.groupReactionData?.data?.data?.groupReactionDataContent?.operatorUid ?? "";
        const type = notify.groupReactionData?.data?.data?.groupReactionDataContent?.type ?? 0;
        const seq = notify.groupReactionData?.data?.data?.groupReactionTarget?.seq?.toString() ?? "";
        const code = notify.groupReactionData?.data?.data?.groupReactionDataContent?.code ?? "";
        const count = notify.groupReactionData?.data?.data?.groupReactionDataContent?.count ?? 0;
        const senderUin = await this.core.apis.UserApi.getUinByUidV2(operatorUid);
        this.event.emit("event:emoji_like", {
          groupId: groupCode,
          senderUin,
          emojiId: code,
          msgSeq: seq,
          isAdd: type === 1,
          count
        });
      }
    }
  }
};
OlPushService = __decorateClass$2([
  ReceiveService("trpc.msg.olpush.OlPushService.MsgPush")
], OlPushService);

const ActionName = {
  TestAutoRegister01: "test_auto_register_01",
  TestAutoRegister02: "test_auto_register_02",
  // 所有 Normal Stream Api 表示并未流传输 表示与流传输有关
  CleanStreamTempFile: "clean_stream_temp_file",
  // 所有 Upload/Download Stream Api 应当 _stream 结尾
  TestDownloadStream: "test_download_stream",
  UploadFileStream: "upload_file_stream",
  DownloadFileStream: "download_file_stream",
  DownloadFileRecordStream: "download_file_record_stream",
  DownloadFileImageStream: "download_file_image_stream",
  DelGroupAlbumMedia: "del_group_album_media",
  SetGroupAlbumMediaLike: "set_group_album_media_like",
  DoGroupAlbumComment: "do_group_album_comment",
  GetGroupAlbumMediaList: "get_group_album_media_list",
  UploadImageToQunAlbum: "upload_image_to_qun_album",
  GetQunAlbumList: "get_qun_album_list",
  SetGroupTodo: "set_group_todo",
  SetGroupKickMembers: "set_group_kick_members",
  SetGroupRobotAddOption: "set_group_robot_add_option",
  SetGroupAddOption: "set_group_add_option",
  SetGroupSearch: "set_group_search",
  // new extends 完全差异OneBot类别
  GetDoubtFriendsAddRequest: "get_doubt_friends_add_request",
  SetDoubtFriendsAddRequest: "set_doubt_friends_add_request",
  // napcat
  GetRkeyEx: "get_rkey",
  GetRkeyServer: "get_rkey_server",
  SetGroupRemark: "set_group_remark",
  NapCat_GetPrivateFileUrl: "get_private_file_url",
  ClickInlineKeyboardButton: "click_inline_keyboard_button",
  GetUnidirectionalFriendList: "get_unidirectional_friend_list",
  // onebot 11
  SendPrivateMsg: "send_private_msg",
  SendGroupMsg: "send_group_msg",
  SendMsg: "send_msg",
  DeleteMsg: "delete_msg",
  GetMsg: "get_msg",
  GoCQHTTP_GetForwardMsg: "get_forward_msg",
  SendLike: "send_like",
  SetGroupKick: "set_group_kick",
  SetGroupBan: "set_group_ban",
  // SetGroupAnoymousBan : 'set_group_anonymous_ban',
  SetGroupWholeBan: "set_group_whole_ban",
  SetGroupAdmin: "set_group_admin",
  // SetGroupAnoymous : 'set_group_anonymous',
  SetGroupCard: "set_group_card",
  SetGroupName: "set_group_name",
  SetGroupLeave: "set_group_leave",
  SetSpecialTitle: "set_group_special_title",
  SetFriendAddRequest: "set_friend_add_request",
  SetFriendRemark: "set_friend_remark",
  SetGroupAddRequest: "set_group_add_request",
  GetLoginInfo: "get_login_info",
  GoCQHTTP_GetStrangerInfo: "get_stranger_info",
  GetFriendList: "get_friend_list",
  GetGroupInfo: "get_group_info",
  GetGroupList: "get_group_list",
  GetGroupMemberInfo: "get_group_member_info",
  GetGroupMemberList: "get_group_member_list",
  GetGroupHonorInfo: "get_group_honor_info",
  GetCookies: "get_cookies",
  GetCSRF: "get_csrf_token",
  GetCredentials: "get_credentials",
  GetRecord: "get_record",
  GetImage: "get_image",
  CanSendImage: "can_send_image",
  CanSendRecord: "can_send_record",
  GetStatus: "get_status",
  GetVersionInfo: "get_version_info",
  // Reboot : 'set_restart',
  CleanCache: "clean_cache",
  Exit: "bot_exit",
  // go-cqhttp
  SetQQProfile: "set_qq_profile",
  // QidianGetAccountInfo : 'qidian_get_account_info',
  GoCQHTTP_GetModelShow: "_get_model_show",
  GoCQHTTP_SetModelShow: "_set_model_show",
  GetOnlineClient: "get_online_clients",
  // GetUnidirectionalFriendList : 'get_unidirectional_friend_list',
  GoCQHTTP_DeleteFriend: "delete_friend",
  // DeleteUnidirectionalFriendList : 'delete_unidirectional_friend',
  GoCQHTTP_MarkMsgAsRead: "mark_msg_as_read",
  GoCQHTTP_SendGroupForwardMsg: "send_group_forward_msg",
  GoCQHTTP_SendPrivateForwardMsg: "send_private_forward_msg",
  GoCQHTTP_GetGroupMsgHistory: "get_group_msg_history",
  OCRImage: "ocr_image",
  IOCRImage: ".ocr_image",
  GetGroupSystemMsg: "get_group_system_msg",
  GoCQHTTP_GetEssenceMsg: "get_essence_msg_list",
  GoCQHTTP_GetGroupAtAllRemain: "get_group_at_all_remain",
  SetGroupPortrait: "set_group_portrait",
  SetEssenceMsg: "set_essence_msg",
  DelEssenceMsg: "delete_essence_msg",
  GoCQHTTP_SendGroupNotice: "_send_group_notice",
  GoCQHTTP_GetGroupNotice: "_get_group_notice",
  GoCQHTTP_UploadGroupFile: "upload_group_file",
  GOCQHTTP_DeleteGroupFile: "delete_group_file",
  GoCQHTTP_CreateGroupFileFolder: "create_group_file_folder",
  GoCQHTTP_DeleteGroupFileFolder: "delete_group_folder",
  GoCQHTTP_GetGroupFileSystemInfo: "get_group_file_system_info",
  GoCQHTTP_GetGroupRootFiles: "get_group_root_files",
  GoCQHTTP_GetGroupFilesByFolder: "get_group_files_by_folder",
  GOCQHTTP_GetGroupFileUrl: "get_group_file_url",
  GOCQHTTP_UploadPrivateFile: "upload_private_file",
  // GOCQHTTP_ReloadEventFilter : 'reload_event_filter',
  GoCQHTTP_DownloadFile: "download_file",
  GoCQHTTP_CheckUrlSafely: "check_url_safely",
  GoCQHTTP_HandleQuickAction: ".handle_quick_operation",
  // 以下为扩展napcat扩展
  Unknown: "unknown",
  SetDiyOnlineStatus: "set_diy_online_status",
  SharePeer: "ArkSharePeer",
  // @deprecated
  ShareGroupEx: "ArkShareGroup",
  // @deprecated
  // 标准化接口
  SendGroupArkShare: "send_group_ark_share",
  SendArkShare: "send_ark_share",
  // RebootNormal : 'reboot_normal', //无快速登录重新启动
  GetRobotUinRange: "get_robot_uin_range",
  SetOnlineStatus: "set_online_status",
  GetFriendsWithCategory: "get_friends_with_category",
  SetQQAvatar: "set_qq_avatar",
  GetFile: "get_file",
  ForwardFriendSingleMsg: "forward_friend_single_msg",
  ForwardGroupSingleMsg: "forward_group_single_msg",
  TranslateEnWordToZn: "translate_en2zh",
  SetMsgEmojiLike: "set_msg_emoji_like",
  GoCQHTTP_SendForwardMsg: "send_forward_msg",
  MarkPrivateMsgAsRead: "mark_private_msg_as_read",
  MarkGroupMsgAsRead: "mark_group_msg_as_read",
  GetFriendMsgHistory: "get_friend_msg_history",
  CreateCollection: "create_collection",
  GetCollectionList: "get_collection_list",
  SetLongNick: "set_self_longnick",
  GetRecentContact: "get_recent_contact",
  _MarkAllMsgAsRead: "_mark_all_as_read",
  GetProfileLike: "get_profile_like",
  FetchCustomFace: "fetch_custom_face",
  FetchEmojiLike: "fetch_emoji_like",
  SetInputStatus: "set_input_status",
  GetGroupInfoEx: "get_group_info_ex",
  GetGroupDetailInfo: "get_group_detail_info",
  GetGroupIgnoreAddRequest: "get_group_ignore_add_request",
  DelGroupNotice: "_del_group_notice",
  FriendPoke: "friend_poke",
  GroupPoke: "group_poke",
  GetPacketStatus: "nc_get_packet_status",
  GetUserStatus: "nc_get_user_status",
  GetRkey: "nc_get_rkey",
  GetGroupShutList: "get_group_shut_list",
  MoveGroupFile: "move_group_file",
  TransGroupFile: "trans_group_file",
  RenameGroupFile: "rename_group_file",
  GetGuildList: "get_guild_list",
  GetGuildProfile: "get_guild_service_profile",
  GetGroupIgnoredNotifies: "get_group_ignored_notifies",
  SetGroupSign: "set_group_sign",
  SendGroupSign: "send_group_sign",
  SendPacket: "send_packet",
  GetMiniAppArk: "get_mini_app_ark",
  // UploadForwardMsg : "upload_forward_msg",
  GetAiRecord: "get_ai_record",
  GetAiCharacters: "get_ai_characters",
  SendGroupAiRecord: "send_group_ai_record",
  GetClientkey: "get_clientkey",
  SendPoke: "send_poke"
};

var StreamStatus = /* @__PURE__ */ ((StreamStatus2) => {
  StreamStatus2["Stream"] = "stream";
  StreamStatus2["Response"] = "response";
  StreamStatus2["Reset"] = "reset";
  StreamStatus2["Error"] = "error";
  return StreamStatus2;
})(StreamStatus || {});

class OB11Response {
  static createResponse(data, status, retcode, message = "", echo = null, useStream = false) {
    return {
      status,
      retcode,
      data,
      message,
      wording: message,
      echo,
      stream: useStream ? "stream-action" : "normal-action"
    };
  }
  static res(data, status, retcode, message = "", echo = null, useStream = false) {
    return this.createResponse(data, status, retcode, message, echo, useStream);
  }
  static ok(data, echo = null, useStream = false) {
    return this.createResponse(data, "ok", 0, "", echo, useStream);
  }
  static error(err, retcode, echo = null, useStream = false) {
    return this.createResponse(useStream ? { type: StreamStatus.Error, data_type: "error" } : null, "failed", retcode, err, echo, useStream);
  }
}
class OneBotAction {
  actionName = ActionName.Unknown;
  core;
  validate = void 0;
  payloadSchema = void 0;
  obContext;
  useStream = false;
  constructor(obContext, core) {
    this.obContext = obContext;
    this.core = core;
  }
  async check(payload) {
    if (this.payloadSchema) {
      this.validate = new Ajv({ allowUnionTypes: true, useDefaults: true, coerceTypes: true }).compile(this.payloadSchema);
    }
    if (this.validate && !this.validate(payload)) {
      const errors = this.validate.errors;
      const errorMessages = errors.map((e) => `Key: ${e.instancePath.split("/").slice(1).join(".")}, Message: ${e.message}`);
      return {
        valid: false,
        message: errorMessages.join("\n") ?? "未知错误"
      };
    }
    return { valid: true };
  }
  async handle(payload, adaptername, config, req = { send: async () => {
  } }, echo) {
    const result = await this.check(payload);
    if (!result.valid) {
      return OB11Response.error(result.message, 400);
    }
    try {
      const resData = await this._handle(payload, adaptername, config, req);
      return OB11Response.ok(resData, echo, this.useStream);
    } catch (e) {
      this.core.context.logger.logError("发生错误", e);
      return OB11Response.error(e.message.toString() || e?.stack?.toString() || "未知错误，可能操作超时", 200, echo, this.useStream);
    }
  }
  async websocketHandle(payload, echo, adaptername, config, req = { send: async () => {
  } }) {
    const result = await this.check(payload);
    if (!result.valid) {
      return OB11Response.error(result.message, 1400, echo, this.useStream);
    }
    try {
      const resData = await this._handle(payload, adaptername, config, req);
      return OB11Response.ok(resData, echo, this.useStream);
    } catch (e) {
      this.core.context.logger.logError("发生错误", e);
      return OB11Response.error((e.message.toString() || e.stack?.toString()) ?? "Error", 1200, echo, this.useStream);
    }
  }
}

const AutoRegisterRouter = [];
function ActionHandler(target) {
  AutoRegisterRouter.push(target);
}

var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
var __decorateClass$1 = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (decorator(result)) || result;
  return result;
};
let TestAutoRegister01 = class extends OneBotAction {
  actionName = ActionName.TestAutoRegister01;
  async _handle(_payload) {
    return "AutoRegister Router Test";
  }
};
TestAutoRegister01 = __decorateClass$1([
  ActionHandler
], TestAutoRegister01);

var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (decorator(result)) || result;
  return result;
};
let TestAutoRegister02 = class extends OneBotAction {
  actionName = ActionName.TestAutoRegister02;
  async _handle(_payload) {
    return "AutoRegister Router Test";
  }
};
TestAutoRegister02 = __decorateClass([
  ActionHandler
], TestAutoRegister02);

class NodeIDependsAdapter {
  onMSFStatusChange(_statusType, _changeReasonType) {
  }
  onMSFSsoError(_code, _desc) {
  }
  getGroupCode(_args) {
  }
  // onSendMsfReply (_seq: string, _cmd: string, _uk1: number, _uk2: string, _rsp: {
  //   ssoRetCode: 0,
  //   trpcRetCode: 0,
  //   trpcFuncCode: 0,
  //   errorMsg: '',
  //   pbBuffer: Uint8Array,
  //   transInfoMap: Map<unknown, unknown>;
  // }) {
  //   console.log('[NodeIDependsAdapter] onSendMsfReply', _seq, _cmd, _uk1, _uk2, Buffer.from(_rsp.pbBuffer).toString('hex'));
  // }
}

class NodeIDispatcherAdapter {
  dispatchRequest(_arg) {
  }
  dispatchCall(_arg) {
  }
  dispatchCallWithJson(_arg) {
  }
}

class NodeIGlobalAdapter {
  onLog(..._args) {
  }
  onGetSrvCalTime(..._args) {
  }
  onShowErrUITips(..._args) {
  }
  fixPicImgType(..._args) {
  }
  getAppSetting(..._args) {
  }
  onInstallFinished(..._args) {
  }
  onUpdateGeneralFlag(..._args) {
  }
  onGetOfflineMsg(..._args) {
  }
}

class NapCatPathWrapper {
  binaryPath;
  logsPath;
  configPath;
  cachePath;
  staticPath;
  pluginPath;
  constructor(mainPath = dirname(fileURLToPath(import.meta.url))) {
    this.binaryPath = mainPath;
    let writePath;
    if (process.env["NAPCAT_WORKDIR"]) {
      writePath = process.env["NAPCAT_WORKDIR"];
    } else if (os__default.platform() === "darwin") {
      writePath = path__default.join(os__default.homedir(), "Library", "Application Support", "QQ", "NapCat");
    } else {
      writePath = this.binaryPath;
    }
    this.logsPath = path__default.join(writePath, "logs");
    this.configPath = path__default.join(writePath, "config");
    this.pluginPath = path__default.join(writePath, "plugins");
    this.cachePath = path__default.join(writePath, "cache");
    this.staticPath = path__default.join(this.binaryPath, "static");
    if (!fs__default.existsSync(this.logsPath)) {
      fs__default.mkdirSync(this.logsPath, { recursive: true });
    }
    if (!fs__default.existsSync(this.configPath)) {
      fs__default.mkdirSync(this.configPath, { recursive: true });
    }
    if (!fs__default.existsSync(this.cachePath)) {
      fs__default.mkdirSync(this.cachePath, { recursive: true });
    }
  }
}

const MODE_NUMBER = 1 << 0;
const MODE_ALPHA_NUM = 1 << 1;
const MODE_8BIT_BYTE = 1 << 2;
const MODE_KANJI = 1 << 3;
const QRMode = {
  MODE_NUMBER,
  MODE_ALPHA_NUM,
  MODE_8BIT_BYTE,
  MODE_KANJI
};

class QR8bitByte {
  mode;
  data;
  constructor(data) {
    this.mode = MODE_8BIT_BYTE;
    this.data = data;
  }
  getLength() {
    return this.data.length;
  }
  write(buffer) {
    for (let i = 0; i < this.data.length; i++) {
      buffer.put(this.data.charCodeAt(i), 8);
    }
  }
}

const QRMath = {
  glog(n) {
    if (n < 1) {
      throw new Error("glog(" + n + ")");
    }
    return QRMath.LOG_TABLE[n];
  },
  gexp(n) {
    while (n < 0) {
      n += 255;
    }
    while (n >= 256) {
      n -= 255;
    }
    return QRMath.EXP_TABLE[n];
  },
  EXP_TABLE: new Array(256).fill(0),
  LOG_TABLE: new Array(256).fill(0)
};
for (let i = 0; i < 8; i++) {
  QRMath.EXP_TABLE[i] = 1 << i;
}
for (let i = 8; i < 256; i++) {
  QRMath.EXP_TABLE[i] = QRMath.EXP_TABLE[i - 4] ^ QRMath.EXP_TABLE[i - 5] ^ QRMath.EXP_TABLE[i - 6] ^ QRMath.EXP_TABLE[i - 8];
}
for (let i = 0; i < 255; i++) {
  QRMath.LOG_TABLE[QRMath.EXP_TABLE[i]] = i;
}

class QRPolynomial {
  num;
  constructor(num, shift) {
    if (num.length === void 0) {
      throw new Error(num.length + "/" + shift);
    }
    let offset = 0;
    while (offset < num.length && num[offset] === 0) {
      offset++;
    }
    this.num = new Array(num.length - offset + shift);
    for (let i = 0; i < num.length - offset; i++) {
      this.num[i] = num[i + offset];
    }
  }
  get(index) {
    return this.num[index];
  }
  getLength() {
    return this.num.length;
  }
  multiply(e) {
    const num = new Array(this.getLength() + e.getLength() - 1);
    for (let i = 0; i < this.getLength(); i++) {
      for (let j = 0; j < e.getLength(); j++) {
        num[i + j] ^= QRMath.gexp(QRMath.glog(this.get(i)) + QRMath.glog(e.get(j)));
      }
    }
    return new QRPolynomial(num, 0);
  }
  mod(e) {
    if (this.getLength() - e.getLength() < 0) {
      return this;
    }
    const ratio = QRMath.glog(this.get(0)) - QRMath.glog(e.get(0));
    const num = new Array(this.getLength());
    for (let i = 0; i < this.getLength(); i++) {
      num[i] = this.get(i);
    }
    for (let x = 0; x < e.getLength(); x++) {
      num[x] ^= QRMath.gexp(QRMath.glog(e.get(x)) + ratio);
    }
    return new QRPolynomial(num, 0).mod(e);
  }
}

const QRMaskPattern = {
  PATTERN000: 0,
  PATTERN001: 1,
  PATTERN010: 2,
  PATTERN011: 3,
  PATTERN100: 4,
  PATTERN101: 5,
  PATTERN110: 6,
  PATTERN111: 7
};

const PATTERN_POSITION_TABLE = [
  [],
  [6, 18],
  [6, 22],
  [6, 26],
  [6, 30],
  [6, 34],
  [6, 22, 38],
  [6, 24, 42],
  [6, 26, 46],
  [6, 28, 50],
  [6, 30, 54],
  [6, 32, 58],
  [6, 34, 62],
  [6, 26, 46, 66],
  [6, 26, 48, 70],
  [6, 26, 50, 74],
  [6, 30, 54, 78],
  [6, 30, 56, 82],
  [6, 30, 58, 86],
  [6, 34, 62, 90],
  [6, 28, 50, 72, 94],
  [6, 26, 50, 74, 98],
  [6, 30, 54, 78, 102],
  [6, 28, 54, 80, 106],
  [6, 32, 58, 84, 110],
  [6, 30, 58, 86, 114],
  [6, 34, 62, 90, 118],
  [6, 26, 50, 74, 98, 122],
  [6, 30, 54, 78, 102, 126],
  [6, 26, 52, 78, 104, 130],
  [6, 30, 56, 82, 108, 134],
  [6, 34, 60, 86, 112, 138],
  [6, 30, 58, 86, 114, 142],
  [6, 34, 62, 90, 118, 146],
  [6, 30, 54, 78, 102, 126, 150],
  [6, 24, 50, 76, 102, 128, 154],
  [6, 28, 54, 80, 106, 132, 158],
  [6, 32, 58, 84, 110, 136, 162],
  [6, 26, 54, 82, 110, 138, 166],
  [6, 30, 58, 86, 114, 142, 170]
];
const G15 = 1 << 10 | 1 << 8 | 1 << 5 | 1 << 4 | 1 << 2 | 1 << 1 | 1 << 0;
const G18 = 1 << 12 | 1 << 11 | 1 << 10 | 1 << 9 | 1 << 8 | 1 << 5 | 1 << 2 | 1 << 0;
const G15_MASK = 1 << 14 | 1 << 12 | 1 << 10 | 1 << 4 | 1 << 1;
function getBCHTypeInfo(data) {
  let d = data << 10;
  while (getBCHDigit(d) - getBCHDigit(G15) >= 0) {
    d ^= G15 << getBCHDigit(d) - getBCHDigit(G15);
  }
  return (data << 10 | d) ^ G15_MASK;
}
function getBCHTypeNumber(data) {
  let d = data << 12;
  while (getBCHDigit(d) - getBCHDigit(G18) >= 0) {
    d ^= G18 << getBCHDigit(d) - getBCHDigit(G18);
  }
  return data << 12 | d;
}
function getBCHDigit(data) {
  let digit = 0;
  while (data !== 0) {
    digit++;
    data >>>= 1;
  }
  return digit;
}
function getPatternPosition(typeNumber) {
  return PATTERN_POSITION_TABLE[typeNumber - 1];
}
function getMask(maskPattern, i, j) {
  switch (maskPattern) {
    case QRMaskPattern.PATTERN000:
      return (i + j) % 2 === 0;
    case QRMaskPattern.PATTERN001:
      return i % 2 === 0;
    case QRMaskPattern.PATTERN010:
      return j % 3 === 0;
    case QRMaskPattern.PATTERN011:
      return (i + j) % 3 === 0;
    case QRMaskPattern.PATTERN100:
      return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0;
    case QRMaskPattern.PATTERN101:
      return i * j % 2 + i * j % 3 === 0;
    case QRMaskPattern.PATTERN110:
      return (i * j % 2 + i * j % 3) % 2 === 0;
    case QRMaskPattern.PATTERN111:
      return (i * j % 3 + (i + j) % 2) % 2 === 0;
    default:
      throw new Error("bad maskPattern:" + maskPattern);
  }
}
function getErrorCorrectPolynomial(errorCorrectLength) {
  let a = new QRPolynomial([1], 0);
  for (let i = 0; i < errorCorrectLength; i++) {
    a = a.multiply(new QRPolynomial([1, QRMath.gexp(i)], 0));
  }
  return a;
}
function getLengthInBits(mode, type) {
  if (type >= 1 && type < 10) {
    switch (mode) {
      case QRMode.MODE_NUMBER:
        return 10;
      case QRMode.MODE_ALPHA_NUM:
        return 9;
      case QRMode.MODE_8BIT_BYTE:
        return 8;
      case QRMode.MODE_KANJI:
        return 8;
      default:
        throw new Error("mode:" + mode);
    }
  } else if (type < 27) {
    switch (mode) {
      case QRMode.MODE_NUMBER:
        return 12;
      case QRMode.MODE_ALPHA_NUM:
        return 11;
      case QRMode.MODE_8BIT_BYTE:
        return 16;
      case QRMode.MODE_KANJI:
        return 10;
      default:
        throw new Error("mode:" + mode);
    }
  } else if (type < 41) {
    switch (mode) {
      case QRMode.MODE_NUMBER:
        return 14;
      case QRMode.MODE_ALPHA_NUM:
        return 13;
      case QRMode.MODE_8BIT_BYTE:
        return 16;
      case QRMode.MODE_KANJI:
        return 12;
      default:
        throw new Error("mode:" + mode);
    }
  } else {
    throw new Error("type:" + type);
  }
}
function getLostPoint(qrCode) {
  const moduleCount = qrCode.getModuleCount();
  let lostPoint = 0;
  for (let row = 0; row < moduleCount; row++) {
    for (let col = 0; col < moduleCount; col++) {
      let sameCount = 0;
      const dark = qrCode.isDark(row, col);
      for (let r = -1; r <= 1; r++) {
        if (row + r < 0 || moduleCount <= row + r) continue;
        for (let c = -1; c <= 1; c++) {
          if (col + c < 0 || moduleCount <= col + c) continue;
          if (r === 0 && c === 0) continue;
          if (dark === qrCode.isDark(row + r, col + c)) sameCount++;
        }
      }
      if (sameCount > 5) lostPoint += 3 + sameCount - 5;
    }
  }
  for (let row = 0; row < moduleCount - 1; row++) {
    for (let col = 0; col < moduleCount - 1; col++) {
      let count = 0;
      if (qrCode.isDark(row, col)) count++;
      if (qrCode.isDark(row + 1, col)) count++;
      if (qrCode.isDark(row, col + 1)) count++;
      if (qrCode.isDark(row + 1, col + 1)) count++;
      if (count === 0 || count === 4) lostPoint += 3;
    }
  }
  for (let row = 0; row < moduleCount; row++) {
    for (let col = 0; col < moduleCount - 6; col++) {
      if (qrCode.isDark(row, col) && !qrCode.isDark(row, col + 1) && qrCode.isDark(row, col + 2) && qrCode.isDark(row, col + 3) && qrCode.isDark(row, col + 4) && !qrCode.isDark(row, col + 5) && qrCode.isDark(row, col + 6)) {
        lostPoint += 40;
      }
    }
  }
  for (let col = 0; col < moduleCount; col++) {
    for (let row = 0; row < moduleCount - 6; row++) {
      if (qrCode.isDark(row, col) && !qrCode.isDark(row + 1, col) && qrCode.isDark(row + 2, col) && qrCode.isDark(row + 3, col) && qrCode.isDark(row + 4, col) && !qrCode.isDark(row + 5, col) && qrCode.isDark(row + 6, col)) {
        lostPoint += 40;
      }
    }
  }
  let darkCount = 0;
  for (let col = 0; col < moduleCount; col++) {
    for (let row = 0; row < moduleCount; row++) {
      if (qrCode.isDark(row, col)) darkCount++;
    }
  }
  const ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5;
  lostPoint += ratio * 10;
  return lostPoint;
}

const QRErrorCorrectLevel = {
  L: 1,
  M: 0,
  Q: 3,
  H: 2
};

class QRRSBlock {
  totalCount;
  dataCount;
  constructor(totalCount, dataCount) {
    this.totalCount = totalCount;
    this.dataCount = dataCount;
  }
  static RS_BLOCK_TABLE = [
    // L
    // M
    // Q
    // H
    // 1
    [1, 26, 19],
    [1, 26, 16],
    [1, 26, 13],
    [1, 26, 9],
    // 2
    [1, 44, 34],
    [1, 44, 28],
    [1, 44, 22],
    [1, 44, 16],
    // 3
    [1, 70, 55],
    [1, 70, 44],
    [2, 35, 17],
    [2, 35, 13],
    // 4
    [1, 100, 80],
    [2, 50, 32],
    [2, 50, 24],
    [4, 25, 9],
    // 5
    [1, 134, 108],
    [2, 67, 43],
    [2, 33, 15, 2, 34, 16],
    [2, 33, 11, 2, 34, 12],
    // 6
    [2, 86, 68],
    [4, 43, 27],
    [4, 43, 19],
    [4, 43, 15],
    // 7
    [2, 98, 78],
    [4, 49, 31],
    [2, 32, 14, 4, 33, 15],
    [4, 39, 13, 1, 40, 14],
    // 8
    [2, 121, 97],
    [2, 60, 38, 2, 61, 39],
    [4, 40, 18, 2, 41, 19],
    [4, 40, 14, 2, 41, 15],
    // 9
    [2, 146, 116],
    [3, 58, 36, 2, 59, 37],
    [4, 36, 16, 4, 37, 17],
    [4, 36, 12, 4, 37, 13],
    // 10
    [2, 86, 68, 2, 87, 69],
    [4, 69, 43, 1, 70, 44],
    [6, 43, 19, 2, 44, 20],
    [6, 43, 15, 2, 44, 16],
    // 11
    [4, 101, 81],
    [1, 80, 50, 4, 81, 51],
    [4, 50, 22, 4, 51, 23],
    [3, 36, 12, 8, 37, 13],
    // 12
    [2, 116, 92, 2, 117, 93],
    [6, 58, 36, 2, 59, 37],
    [4, 46, 20, 6, 47, 21],
    [7, 42, 14, 4, 43, 15],
    // 13
    [4, 133, 107],
    [8, 59, 37, 1, 60, 38],
    [8, 44, 20, 4, 45, 21],
    [12, 33, 11, 4, 34, 12],
    // 14
    [3, 145, 115, 1, 146, 116],
    [4, 64, 40, 5, 65, 41],
    [11, 36, 16, 5, 37, 17],
    [11, 36, 12, 5, 37, 13],
    // 15
    [5, 109, 87, 1, 110, 88],
    [5, 65, 41, 5, 66, 42],
    [5, 54, 24, 7, 55, 25],
    [11, 36, 12],
    // 16
    [5, 122, 98, 1, 123, 99],
    [7, 73, 45, 3, 74, 46],
    [15, 43, 19, 2, 44, 20],
    [3, 45, 15, 13, 46, 16],
    // 17
    [1, 135, 107, 5, 136, 108],
    [10, 74, 46, 1, 75, 47],
    [1, 50, 22, 15, 51, 23],
    [2, 42, 14, 17, 43, 15],
    // 18
    [5, 150, 120, 1, 151, 121],
    [9, 69, 43, 4, 70, 44],
    [17, 50, 22, 1, 51, 23],
    [2, 42, 14, 19, 43, 15],
    // 19
    [3, 141, 113, 4, 142, 114],
    [3, 70, 44, 11, 71, 45],
    [17, 47, 21, 4, 48, 22],
    [9, 39, 13, 16, 40, 14],
    // 20
    [3, 135, 107, 5, 136, 108],
    [3, 67, 41, 13, 68, 42],
    [15, 54, 24, 5, 55, 25],
    [15, 43, 15, 10, 44, 16],
    // 21
    [4, 144, 116, 4, 145, 117],
    [17, 68, 42],
    [17, 50, 22, 6, 51, 23],
    [19, 46, 16, 6, 47, 17],
    // 22
    [2, 139, 111, 7, 140, 112],
    [17, 74, 46],
    [7, 54, 24, 16, 55, 25],
    [34, 37, 13],
    // 23
    [4, 151, 121, 5, 152, 122],
    [4, 75, 47, 14, 76, 48],
    [11, 54, 24, 14, 55, 25],
    [16, 45, 15, 14, 46, 16],
    // 24
    [6, 147, 117, 4, 148, 118],
    [6, 73, 45, 14, 74, 46],
    [11, 54, 24, 16, 55, 25],
    [30, 46, 16, 2, 47, 17],
    // 25
    [8, 132, 106, 4, 133, 107],
    [8, 75, 47, 13, 76, 48],
    [7, 54, 24, 22, 55, 25],
    [22, 45, 15, 13, 46, 16],
    // 26
    [10, 142, 114, 2, 143, 115],
    [19, 74, 46, 4, 75, 47],
    [28, 50, 22, 6, 51, 23],
    [33, 46, 16, 4, 47, 17],
    // 27
    [8, 152, 122, 4, 153, 123],
    [22, 73, 45, 3, 74, 46],
    [8, 53, 23, 26, 54, 24],
    [12, 45, 15, 28, 46, 16],
    // 28
    [3, 147, 117, 10, 148, 118],
    [3, 73, 45, 23, 74, 46],
    [4, 54, 24, 31, 55, 25],
    [11, 45, 15, 31, 46, 16],
    // 29
    [7, 146, 116, 7, 147, 117],
    [21, 73, 45, 7, 74, 46],
    [1, 53, 23, 37, 54, 24],
    [19, 45, 15, 26, 46, 16],
    // 30
    [5, 145, 115, 10, 146, 116],
    [19, 75, 47, 10, 76, 48],
    [15, 54, 24, 25, 55, 25],
    [23, 45, 15, 25, 46, 16],
    // 31
    [13, 145, 115, 3, 146, 116],
    [2, 74, 46, 29, 75, 47],
    [42, 54, 24, 1, 55, 25],
    [23, 45, 15, 28, 46, 16],
    // 32
    [17, 145, 115],
    [10, 74, 46, 23, 75, 47],
    [10, 54, 24, 35, 55, 25],
    [19, 45, 15, 35, 46, 16],
    // 33
    [17, 145, 115, 1, 146, 116],
    [14, 74, 46, 21, 75, 47],
    [29, 54, 24, 19, 55, 25],
    [11, 45, 15, 46, 46, 16],
    // 34
    [13, 145, 115, 6, 146, 116],
    [14, 74, 46, 23, 75, 47],
    [44, 54, 24, 7, 55, 25],
    [59, 46, 16, 1, 47, 17],
    // 35
    [12, 151, 121, 7, 152, 122],
    [12, 75, 47, 26, 76, 48],
    [39, 54, 24, 14, 55, 25],
    [22, 45, 15, 41, 46, 16],
    // 36
    [6, 151, 121, 14, 152, 122],
    [6, 75, 47, 34, 76, 48],
    [46, 54, 24, 10, 55, 25],
    [2, 45, 15, 64, 46, 16],
    // 37
    [17, 152, 122, 4, 153, 123],
    [29, 74, 46, 14, 75, 47],
    [49, 54, 24, 10, 55, 25],
    [24, 45, 15, 46, 46, 16],
    // 38
    [4, 152, 122, 18, 153, 123],
    [13, 74, 46, 32, 75, 47],
    [48, 54, 24, 14, 55, 25],
    [42, 45, 15, 32, 46, 16],
    // 39
    [20, 147, 117, 4, 148, 118],
    [40, 75, 47, 7, 76, 48],
    [43, 54, 24, 22, 55, 25],
    [10, 45, 15, 67, 46, 16],
    // 40
    [19, 148, 118, 6, 149, 119],
    [18, 75, 47, 31, 76, 48],
    [34, 54, 24, 34, 55, 25],
    [20, 45, 15, 61, 46, 16]
  ];
}
function getRSBlocks(typeNumber, errorCorrectLevel) {
  const rsBlock = getRsBlockTable(typeNumber, errorCorrectLevel);
  if (rsBlock === void 0) {
    throw new Error(`bad rs block @ typeNumber: ${typeNumber} / errorCorrectLevel: ${errorCorrectLevel}`);
  }
  const length = rsBlock.length / 3;
  const list = [];
  for (let i = 0; i < length; i++) {
    const count = rsBlock[i * 3 + 0];
    const totalCount = rsBlock[i * 3 + 1];
    const dataCount = rsBlock[i * 3 + 2];
    if (count === void 0) {
      throw new Error(`count is undefined for typeNumber: ${typeNumber} / errorCorrectLevel: ${errorCorrectLevel}`);
    }
    for (let j = 0; j < count; j++) {
      list.push(new QRRSBlock(totalCount, dataCount));
    }
  }
  return list;
}
function getRsBlockTable(typeNumber, errorCorrectLevel) {
  switch (errorCorrectLevel) {
    case QRErrorCorrectLevel.L:
      return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0];
    case QRErrorCorrectLevel.M:
      return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1];
    case QRErrorCorrectLevel.Q:
      return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2];
    case QRErrorCorrectLevel.H:
      return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3];
    default:
      return void 0;
  }
}

class QRBitBuffer {
  buffer;
  length;
  constructor() {
    this.buffer = [];
    this.length = 0;
  }
  get(index) {
    const bufIndex = Math.floor(index / 8);
    return (this.buffer[bufIndex] >>> 7 - index % 8 & 1) === 1;
  }
  put(num, length) {
    for (let i = 0; i < length; i++) {
      this.putBit((num >>> length - i - 1 & 1) === 1);
    }
  }
  getLengthInBits() {
    return this.length;
  }
  putBit(bit) {
    const bufIndex = Math.floor(this.length / 8);
    if (this.buffer.length <= bufIndex) {
      this.buffer.push(0);
    }
    if (bit) {
      this.buffer[bufIndex] |= 128 >>> this.length % 8;
    }
    this.length++;
  }
}

class QRCode {
  typeNumber;
  errorCorrectLevel;
  modules;
  moduleCount;
  dataCache;
  dataList;
  static PAD0 = 236;
  static PAD1 = 17;
  constructor(typeNumber, errorCorrectLevel) {
    this.typeNumber = typeNumber;
    this.errorCorrectLevel = errorCorrectLevel;
    this.modules = null;
    this.moduleCount = 0;
    this.dataCache = null;
    this.dataList = [];
  }
  addData(data) {
    const newData = new QR8bitByte(data);
    this.dataList.push(newData);
    this.dataCache = null;
  }
  isDark(row, col) {
    if (row < 0 || this.moduleCount <= row || col < 0 || this.moduleCount <= col) {
      throw new Error(`${row},${col}`);
    }
    if (this.modules === null || this.modules[row] === null || this.modules[row][col] === null) {
      throw new Error(`Module at (${row},${col}) is null`);
    }
    return this.modules[row][col];
  }
  getModuleCount() {
    return this.moduleCount;
  }
  make() {
    if (this.typeNumber < 1) {
      let typeNumber = 1;
      for (typeNumber = 1; typeNumber < 40; typeNumber++) {
        const rsBlocks = getRSBlocks(typeNumber, this.errorCorrectLevel);
        const buffer = new QRBitBuffer();
        let totalDataCount = 0;
        for (let i = 0; i < rsBlocks.length; i++) {
          totalDataCount += rsBlocks[i].dataCount;
        }
        for (let x = 0; x < this.dataList.length; x++) {
          const data = this.dataList[x];
          buffer.put(data.mode, 4);
          buffer.put(data.getLength(), getLengthInBits(data.mode, typeNumber));
          data.write(buffer);
        }
        if (buffer.getLengthInBits() <= totalDataCount * 8) {
          break;
        }
      }
      this.typeNumber = typeNumber;
    }
    this.makeImpl(false, this.getBestMaskPattern());
  }
  makeImpl(test, maskPattern) {
    this.moduleCount = this.typeNumber * 4 + 17;
    this.modules = new Array(this.moduleCount);
    for (let row = 0; row < this.moduleCount; row++) {
      this.modules[row] = new Array(this.moduleCount);
      for (let col = 0; col < this.moduleCount; col++) {
        this.modules[row][col] = null;
      }
    }
    this.setupPositionProbePattern(0, 0);
    this.setupPositionProbePattern(this.moduleCount - 7, 0);
    this.setupPositionProbePattern(0, this.moduleCount - 7);
    this.setupPositionAdjustPattern();
    this.setupTimingPattern();
    this.setupTypeInfo(test, maskPattern);
    if (this.typeNumber >= 7) {
      this.setupTypeNumber(test);
    }
    if (this.dataCache === null) {
      this.dataCache = QRCode.createData(this.typeNumber, this.errorCorrectLevel, this.dataList);
    }
    this.mapData(this.dataCache, maskPattern);
  }
  setupPositionProbePattern(row, col) {
    for (let r = -1; r <= 7; r++) {
      if (row + r <= -1 || this.moduleCount <= row + r) continue;
      for (let c = -1; c <= 7; c++) {
        if (col + c <= -1 || this.moduleCount <= col + c) continue;
        if (r >= 0 && r <= 6 && (c === 0 || c === 6) || c >= 0 && c <= 6 && (r === 0 || r === 6) || r >= 2 && r <= 4 && c >= 2 && c <= 4) {
          this.modules[row + r][col + c] = true;
        } else {
          this.modules[row + r][col + c] = false;
        }
      }
    }
  }
  getBestMaskPattern() {
    let minLostPoint = 0;
    let pattern = 0;
    for (let i = 0; i < 8; i++) {
      this.makeImpl(true, i);
      const lostPoint = getLostPoint(this);
      if (i === 0 || minLostPoint > lostPoint) {
        minLostPoint = lostPoint;
        pattern = i;
      }
    }
    return pattern;
  }
  createMovieClip(target_mc, instance_name, depth) {
    const qr_mc = target_mc.createEmptyMovieClip(instance_name, depth);
    const cs = 1;
    this.make();
    for (let row = 0; row < this.modules.length; row++) {
      const y = row * cs;
      for (let col = 0; col < this.modules[row].length; col++) {
        const x = col * cs;
        const dark = this.modules[row][col];
        if (dark) {
          qr_mc.beginFill(0, 100);
          qr_mc.moveTo(x, y);
          qr_mc.lineTo(x + cs, y);
          qr_mc.lineTo(x + cs, y + cs);
          qr_mc.lineTo(x, y + cs);
          qr_mc.endFill();
        }
      }
    }
    return qr_mc;
  }
  setupTimingPattern() {
    for (let r = 8; r < this.moduleCount - 8; r++) {
      if (this.modules[r][6] !== null) {
        continue;
      }
      this.modules[r][6] = r % 2 === 0;
    }
    for (let c = 8; c < this.moduleCount - 8; c++) {
      if (this.modules[6][c] !== null) {
        continue;
      }
      this.modules[6][c] = c % 2 === 0;
    }
  }
  setupPositionAdjustPattern() {
    const pos = getPatternPosition(this.typeNumber);
    for (let i = 0; i < pos.length; i++) {
      for (let j = 0; j < pos.length; j++) {
        const row = pos[i];
        const col = pos[j];
        if (this.modules[row][col] !== null) {
          continue;
        }
        for (let r = -2; r <= 2; r++) {
          for (let c = -2; c <= 2; c++) {
            if (Math.abs(r) === 2 || Math.abs(c) === 2 || r === 0 && c === 0) {
              this.modules[row + r][col + c] = true;
            } else {
              this.modules[row + r][col + c] = false;
            }
          }
        }
      }
    }
  }
  setupTypeNumber(test) {
    const bits = getBCHTypeNumber(this.typeNumber);
    let mod;
    for (let i = 0; i < 18; i++) {
      mod = !test && (bits >> i & 1) === 1;
      this.modules[Math.floor(i / 3)][i % 3 + this.moduleCount - 8 - 3] = mod;
    }
    for (let x = 0; x < 18; x++) {
      mod = !test && (bits >> x & 1) === 1;
      this.modules[x % 3 + this.moduleCount - 8 - 3][Math.floor(x / 3)] = mod;
    }
  }
  setupTypeInfo(test, maskPattern) {
    const data = this.errorCorrectLevel << 3 | maskPattern;
    const bits = getBCHTypeInfo(data);
    let mod;
    for (let v = 0; v < 15; v++) {
      mod = !test && (bits >> v & 1) === 1;
      if (v < 6) {
        this.modules[v][8] = mod;
      } else if (v < 8) {
        this.modules[v + 1][8] = mod;
      } else {
        this.modules[this.moduleCount - 15 + v][8] = mod;
      }
    }
    for (let h = 0; h < 15; h++) {
      mod = !test && (bits >> h & 1) === 1;
      if (h < 8) {
        this.modules[8][this.moduleCount - h - 1] = mod;
      } else if (h < 9) {
        this.modules[8][15 - h - 1 + 1] = mod;
      } else {
        this.modules[8][15 - h - 1] = mod;
      }
    }
    this.modules[this.moduleCount - 8][8] = !test;
  }
  mapData(data, maskPattern) {
    let inc = -1;
    let row = this.moduleCount - 1;
    let bitIndex = 7;
    let byteIndex = 0;
    for (let col = this.moduleCount - 1; col > 0; col -= 2) {
      if (col === 6) col--;
      while (true) {
        for (let c = 0; c < 2; c++) {
          if (this.modules[row][col - c] === null) {
            let dark = false;
            if (byteIndex < data.length) {
              dark = ((data[byteIndex] ?? 0) >>> bitIndex & 1) === 1;
            }
            const mask = getMask(maskPattern, row, col - c);
            if (mask) {
              dark = !dark;
            }
            this.modules[row][col - c] = dark;
            bitIndex--;
            if (bitIndex === -1) {
              byteIndex++;
              bitIndex = 7;
            }
          }
        }
        row += inc;
        if (row < 0 || this.moduleCount <= row) {
          row -= inc;
          inc = -inc;
          break;
        }
      }
    }
  }
  static createData(typeNumber, errorCorrectLevel, dataList) {
    const rsBlocks = getRSBlocks(typeNumber, errorCorrectLevel);
    const buffer = new QRBitBuffer();
    for (let i = 0; i < dataList.length; i++) {
      const data = dataList[i];
      buffer.put(data.mode, 4);
      buffer.put(data.getLength(), getLengthInBits(data.mode, typeNumber));
      data.write(buffer);
    }
    let totalDataCount = 0;
    for (let x = 0; x < rsBlocks.length; x++) {
      totalDataCount += rsBlocks[x].dataCount;
    }
    if (buffer.getLengthInBits() > totalDataCount * 8) {
      throw new Error(`code length overflow. (${buffer.getLengthInBits()} > ${totalDataCount * 8})`);
    }
    if (buffer.getLengthInBits() + 4 <= totalDataCount * 8) {
      buffer.put(0, 4);
    }
    while (buffer.getLengthInBits() % 8 !== 0) {
      buffer.putBit(false);
    }
    while (true) {
      if (buffer.getLengthInBits() >= totalDataCount * 8) {
        break;
      }
      buffer.put(QRCode.PAD0, 8);
      if (buffer.getLengthInBits() >= totalDataCount * 8) {
        break;
      }
      buffer.put(QRCode.PAD1, 8);
    }
    return QRCode.createBytes(buffer, rsBlocks);
  }
  static createBytes(buffer, rsBlocks) {
    let offset = 0;
    let maxDcCount = 0;
    let maxEcCount = 0;
    const dcdata = new Array(rsBlocks.length);
    const ecdata = new Array(rsBlocks.length);
    for (let r = 0; r < rsBlocks.length; r++) {
      const dcCount = rsBlocks[r].dataCount;
      const ecCount = rsBlocks[r].totalCount - dcCount;
      maxDcCount = Math.max(maxDcCount, dcCount);
      maxEcCount = Math.max(maxEcCount, ecCount);
      dcdata[r] = new Array(dcCount);
      for (let i = 0; i < dcdata[r].length; i++) {
        dcdata[r][i] = 255 & buffer.buffer[i + offset];
      }
      offset += dcCount;
      const rsPoly = getErrorCorrectPolynomial(ecCount);
      const rawPoly = new QRPolynomial(dcdata[r], rsPoly.getLength() - 1);
      const modPoly = rawPoly.mod(rsPoly);
      ecdata[r] = new Array(rsPoly.getLength() - 1);
      for (let x = 0; x < ecdata[r].length; x++) {
        const modIndex = x + modPoly.getLength() - ecdata[r].length;
        ecdata[r][x] = modIndex >= 0 ? modPoly.get(modIndex) : 0;
      }
    }
    let totalCodeCount = 0;
    for (let y = 0; y < rsBlocks.length; y++) {
      totalCodeCount += rsBlocks[y].totalCount;
    }
    const data = new Array(totalCodeCount);
    let index = 0;
    for (let z = 0; z < maxDcCount; z++) {
      for (let s = 0; s < rsBlocks.length; s++) {
        if (z < dcdata[s].length) {
          data[index++] = dcdata[s][z];
        }
      }
    }
    for (let xx = 0; xx < maxEcCount; xx++) {
      for (let t = 0; t < rsBlocks.length; t++) {
        if (xx < ecdata[t].length) {
          data[index++] = ecdata[t][xx];
        }
      }
    }
    return data;
  }
}

const black = "\x1B[40m  \x1B[0m";
const white = "\x1B[47m  \x1B[0m";
const toCell = (value) => {
  return value ? black : white;
};
const repeat = (color) => {
  return {
    times: (count) => {
      return new Array(count + 1).join(color);
    }
  };
};
const fill = (length, value) => {
  const arr = new Array(length);
  for (let i = 0; i < length; i++) {
    arr[i] = value;
  }
  return arr;
};
const qrcode = {
  error: QRErrorCorrectLevel.L,
  generate(input, opts, cb) {
    if (typeof opts === "function") {
      cb = opts;
      opts = {};
    }
    const qrcode = new QRCode(-1, this.error);
    qrcode.addData(input);
    qrcode.make();
    let output = "";
    if (opts && opts.small) {
      const BLACK = true;
      const WHITE = false;
      const moduleCount = qrcode.getModuleCount();
      const moduleData = qrcode.modules ? qrcode.modules.slice() : [];
      const oddRow = moduleCount % 2 === 1;
      if (oddRow) {
        moduleData.push(fill(moduleCount, WHITE));
      }
      const platte = {
        WHITE_ALL: "█",
        WHITE_BLACK: "▀",
        BLACK_WHITE: "▄",
        BLACK_ALL: " "
      };
      const borderTop = repeat(platte.BLACK_WHITE).times(moduleCount + 2);
      const borderBottom = repeat(platte.WHITE_BLACK).times(moduleCount + 2);
      output += borderTop + "\n";
      for (let row = 0; row < moduleCount; row += 2) {
        output += platte.WHITE_ALL;
        for (let col = 0; col < moduleCount; col++) {
          if (moduleData[row]?.[col] === WHITE && moduleData[row + 1]?.[col] === WHITE) {
            output += platte.WHITE_ALL;
          } else if (moduleData[row]?.[col] === WHITE && moduleData[row + 1]?.[col] === BLACK) {
            output += platte.WHITE_BLACK;
          } else if (moduleData[row]?.[col] === BLACK && moduleData[row + 1]?.[col] === WHITE) {
            output += platte.BLACK_WHITE;
          } else {
            output += platte.BLACK_ALL;
          }
        }
        output += platte.WHITE_ALL + "\n";
      }
      if (!oddRow) {
        output += borderBottom;
      }
    } else {
      const border = repeat(white).times(qrcode.getModuleCount() + 2);
      output += border + "\n";
      if (qrcode.modules) {
        qrcode.modules.forEach((row) => {
          output += white;
          output += row.map(toCell).join("");
          output += white + "\n";
        });
      }
      output += border;
    }
    if (cb) cb(output);
    else console.log(output);
  },
  setErrorLevel(error) {
    this.error = QRErrorCorrectLevel[error] || this.error;
  }
};

class OB11ConfigLoader extends ConfigBase {
  constructor(core, configPath, schema) {
    super("onebot11", core, configPath, schema);
  }
}

function deepMerge(target, source) {
  for (const key in source) {
    if (Object.prototype.hasOwnProperty.call(source, key)) {
      if (source[key] === void 0) {
        continue;
      }
      if (target[key] !== void 0 && typeof target[key] === "object" && !Array.isArray(target[key]) && typeof source[key] === "object" && !Array.isArray(source[key])) {
        target[key] = deepMerge({ ...target[key] }, source[key]);
      } else {
        target[key] = source[key];
      }
    }
  }
  return target;
}

const themeType = Type.Object(
  {
    dark: Type.Record(Type.String(), Type.String()),
    light: Type.Record(Type.String(), Type.String()),
    fontMode: Type.String({ default: "system" })
  },
  {
    default: {
      fontMode: "system",
      dark: {
        "--heroui-background": "0 0% 0%",
        "--heroui-foreground-50": "240 5.88% 10%",
        "--heroui-foreground-100": "240 3.7% 15.88%",
        "--heroui-foreground-200": "240 5.26% 26.08%",
        "--heroui-foreground-300": "240 5.2% 33.92%",
        "--heroui-foreground-400": "240 3.83% 46.08%",
        "--heroui-foreground-500": "240 5.03% 64.9%",
        "--heroui-foreground-600": "240 4.88% 83.92%",
        "--heroui-foreground-700": "240 5.88% 90%",
        "--heroui-foreground-800": "240 4.76% 95.88%",
        "--heroui-foreground-900": "0 0% 98.04%",
        "--heroui-foreground": "210 5.56% 92.94%",
        "--heroui-focus": "212.01999999999998 100% 46.67%",
        "--heroui-overlay": "0 0% 0%",
        "--heroui-divider": "0 0% 100%",
        "--heroui-divider-opacity": "0.15",
        "--heroui-content1": "240 5.88% 10%",
        "--heroui-content1-foreground": "0 0% 98.04%",
        "--heroui-content2": "240 3.7% 15.88%",
        "--heroui-content2-foreground": "240 4.76% 95.88%",
        "--heroui-content3": "240 5.26% 26.08%",
        "--heroui-content3-foreground": "240 5.88% 90%",
        "--heroui-content4": "240 5.2% 33.92%",
        "--heroui-content4-foreground": "240 4.88% 83.92%",
        "--heroui-default-50": "240 5.88% 10%",
        "--heroui-default-100": "240 3.7% 15.88%",
        "--heroui-default-200": "240 5.26% 26.08%",
        "--heroui-default-300": "240 5.2% 33.92%",
        "--heroui-default-400": "240 3.83% 46.08%",
        "--heroui-default-500": "240 5.03% 64.9%",
        "--heroui-default-600": "240 4.88% 83.92%",
        "--heroui-default-700": "240 5.88% 90%",
        "--heroui-default-800": "240 4.76% 95.88%",
        "--heroui-default-900": "0 0% 98.04%",
        "--heroui-default-foreground": "0 0% 100%",
        "--heroui-default": "240 5.26% 26.08%",
        "--heroui-danger-50": "301.89 82.61% 22.55%",
        "--heroui-danger-100": "308.18 76.39% 28.24%",
        "--heroui-danger-200": "313.85 70.65% 36.08%",
        "--heroui-danger-300": "319.73 65.64% 44.51%",
        "--heroui-danger-400": "325.82 69.62% 53.53%",
        "--heroui-danger-500": "331.82 75% 65.49%",
        "--heroui-danger-600": "337.84 83.46% 73.92%",
        "--heroui-danger-700": "343.42 90.48% 83.53%",
        "--heroui-danger-800": "350.53 90.48% 91.76%",
        "--heroui-danger-900": "324 90.91% 95.69%",
        "--heroui-danger-foreground": "0 0% 100%",
        "--heroui-danger": "325.82 69.62% 53.53%",
        "--heroui-primary-50": "340 84.91% 10.39%",
        "--heroui-primary-100": "339.33 86.54% 20.39%",
        "--heroui-primary-200": "339.11 85.99% 30.78%",
        "--heroui-primary-300": "339 86.54% 40.78%",
        "--heroui-primary-400": "339.2 90.36% 51.18%",
        "--heroui-primary-500": "339 90% 60.78%",
        "--heroui-primary-600": "339.11 90.6% 70.78%",
        "--heroui-primary-700": "339.33 90% 80.39%",
        "--heroui-primary-800": "340 91.84% 90.39%",
        "--heroui-primary-900": "339.13 92% 95.1%",
        "--heroui-primary-foreground": "0 0% 100%",
        "--heroui-primary": "339.2 90.36% 51.18%",
        "--heroui-secondary-50": "270 66.67% 9.41%",
        "--heroui-secondary-100": "270 66.67% 18.82%",
        "--heroui-secondary-200": "270 66.67% 28.24%",
        "--heroui-secondary-300": "270 66.67% 37.65%",
        "--heroui-secondary-400": "270 66.67% 47.06%",
        "--heroui-secondary-500": "270 59.26% 57.65%",
        "--heroui-secondary-600": "270 59.26% 68.24%",
        "--heroui-secondary-700": "270 59.26% 78.82%",
        "--heroui-secondary-800": "270 59.26% 89.41%",
        "--heroui-secondary-900": "270 61.54% 94.9%",
        "--heroui-secondary-foreground": "0 0% 100%",
        "--heroui-secondary": "270 59.26% 57.65%",
        "--heroui-success-50": "145.71 77.78% 8.82%",
        "--heroui-success-100": "146.2 79.78% 17.45%",
        "--heroui-success-200": "145.79 79.26% 26.47%",
        "--heroui-success-300": "146.01 79.89% 35.1%",
        "--heroui-success-400": "145.96 79.46% 43.92%",
        "--heroui-success-500": "146.01 62.45% 55.1%",
        "--heroui-success-600": "145.79 62.57% 66.47%",
        "--heroui-success-700": "146.2 61.74% 77.45%",
        "--heroui-success-800": "145.71 61.4% 88.82%",
        "--heroui-success-900": "146.67 64.29% 94.51%",
        "--heroui-success-foreground": "0 0% 0%",
        "--heroui-success": "145.96 79.46% 43.92%",
        "--heroui-warning-50": "37.14 75% 10.98%",
        "--heroui-warning-100": "37.14 75% 21.96%",
        "--heroui-warning-200": "36.96 73.96% 33.14%",
        "--heroui-warning-300": "37.01 74.22% 44.12%",
        "--heroui-warning-400": "37.03 91.27% 55.1%",
        "--heroui-warning-500": "37.01 91.26% 64.12%",
        "--heroui-warning-600": "36.96 91.24% 73.14%",
        "--heroui-warning-700": "37.14 91.3% 81.96%",
        "--heroui-warning-800": "37.14 91.3% 90.98%",
        "--heroui-warning-900": "54.55 91.67% 95.29%",
        "--heroui-warning-foreground": "0 0% 0%",
        "--heroui-warning": "37.03 91.27% 55.1%",
        "--heroui-code-background": "240 5.56% 7.06%",
        "--heroui-strong": "190.14 94.67% 44.12%",
        "--heroui-code-mdx": "190.14 94.67% 44.12%",
        "--heroui-divider-weight": "1px",
        "--heroui-disabled-opacity": ".5",
        "--heroui-font-size-tiny": "0.75rem",
        "--heroui-font-size-small": "0.875rem",
        "--heroui-font-size-medium": "1rem",
        "--heroui-font-size-large": "1.125rem",
        "--heroui-line-height-tiny": "1rem",
        "--heroui-line-height-small": "1.25rem",
        "--heroui-line-height-medium": "1.5rem",
        "--heroui-line-height-large": "1.75rem",
        "--heroui-radius-small": "8px",
        "--heroui-radius-medium": "12px",
        "--heroui-radius-large": "14px",
        "--heroui-border-width-small": "1px",
        "--heroui-border-width-medium": "2px",
        "--heroui-border-width-large": "3px",
        "--heroui-box-shadow-small": "0px 0px 5px 0px rgba(0, 0, 0, .05), 0px 2px 10px 0px rgba(0, 0, 0, .2), inset 0px 0px 1px 0px hsla(0, 0%, 100%, .15)",
        "--heroui-box-shadow-medium": "0px 0px 15px 0px rgba(0, 0, 0, .06), 0px 2px 30px 0px rgba(0, 0, 0, .22), inset 0px 0px 1px 0px hsla(0, 0%, 100%, .15)",
        "--heroui-box-shadow-large": "0px 0px 30px 0px rgba(0, 0, 0, .07), 0px 30px 60px 0px rgba(0, 0, 0, .26), inset 0px 0px 1px 0px hsla(0, 0%, 100%, .15)",
        "--heroui-hover-opacity": ".9"
      },
      light: {
        "--heroui-background": "0 0% 100%",
        "--heroui-foreground-50": "240 5.88% 95%",
        "--heroui-foreground-100": "240 3.7% 90%",
        "--heroui-foreground-200": "240 5.26% 80%",
        "--heroui-foreground-300": "240 5.2% 70%",
        "--heroui-foreground-400": "240 3.83% 60%",
        "--heroui-foreground-500": "240 5.03% 50%",
        "--heroui-foreground-600": "240 4.88% 40%",
        "--heroui-foreground-700": "240 5.88% 30%",
        "--heroui-foreground-800": "240 4.76% 20%",
        "--heroui-foreground-900": "0 0% 10%",
        "--heroui-foreground": "210 5.56% 7.06%",
        "--heroui-focus": "212.01999999999998 100% 53.33%",
        "--heroui-overlay": "0 0% 100%",
        "--heroui-divider": "0 0% 0%",
        "--heroui-divider-opacity": "0.85",
        "--heroui-content1": "240 5.88% 95%",
        "--heroui-content1-foreground": "0 0% 10%",
        "--heroui-content2": "240 3.7% 90%",
        "--heroui-content2-foreground": "240 4.76% 20%",
        "--heroui-content3": "240 5.26% 80%",
        "--heroui-content3-foreground": "240 5.88% 30%",
        "--heroui-content4": "240 5.2% 70%",
        "--heroui-content4-foreground": "240 4.88% 40%",
        "--heroui-default-50": "240 5.88% 95%",
        "--heroui-default-100": "240 3.7% 90%",
        "--heroui-default-200": "240 5.26% 80%",
        "--heroui-default-300": "240 5.2% 70%",
        "--heroui-default-400": "240 3.83% 60%",
        "--heroui-default-500": "240 5.03% 50%",
        "--heroui-default-600": "240 4.88% 40%",
        "--heroui-default-700": "240 5.88% 30%",
        "--heroui-default-800": "240 4.76% 20%",
        "--heroui-default-900": "0 0% 10%",
        "--heroui-default-foreground": "0 0% 0%",
        "--heroui-default": "240 5.26% 80%",
        "--heroui-danger-50": "324 90.91% 95.69%",
        "--heroui-danger-100": "350.53 90.48% 91.76%",
        "--heroui-danger-200": "343.42 90.48% 83.53%",
        "--heroui-danger-300": "337.84 83.46% 73.92%",
        "--heroui-danger-400": "331.82 75% 65.49%",
        "--heroui-danger-500": "325.82 69.62% 53.53%",
        "--heroui-danger-600": "319.73 65.64% 44.51%",
        "--heroui-danger-700": "313.85 70.65% 36.08%",
        "--heroui-danger-800": "308.18 76.39% 28.24%",
        "--heroui-danger-900": "301.89 82.61% 22.55%",
        "--heroui-danger-foreground": "0 0% 100%",
        "--heroui-danger": "325.82 69.62% 53.53%",
        "--heroui-primary-50": "339.13 92% 95.1%",
        "--heroui-primary-100": "340 91.84% 90.39%",
        "--heroui-primary-200": "339.33 90% 80.39%",
        "--heroui-primary-300": "339.11 90.6% 70.78%",
        "--heroui-primary-400": "339 90% 60.78%",
        "--heroui-primary-500": "339.2 90.36% 51.18%",
        "--heroui-primary-600": "339 86.54% 40.78%",
        "--heroui-primary-700": "339.11 85.99% 30.78%",
        "--heroui-primary-800": "339.33 86.54% 20.39%",
        "--heroui-primary-900": "340 84.91% 10.39%",
        "--heroui-primary-foreground": "0 0% 100%",
        "--heroui-primary": "339.2 90.36% 51.18%",
        "--heroui-secondary-50": "270 61.54% 94.9%",
        "--heroui-secondary-100": "270 59.26% 89.41%",
        "--heroui-secondary-200": "270 59.26% 78.82%",
        "--heroui-secondary-300": "270 59.26% 68.24%",
        "--heroui-secondary-400": "270 59.26% 57.65%",
        "--heroui-secondary-500": "270 66.67% 47.06%",
        "--heroui-secondary-600": "270 66.67% 37.65%",
        "--heroui-secondary-700": "270 66.67% 28.24%",
        "--heroui-secondary-800": "270 66.67% 18.82%",
        "--heroui-secondary-900": "270 66.67% 9.41%",
        "--heroui-secondary-foreground": "0 0% 100%",
        "--heroui-secondary": "270 66.67% 47.06%",
        "--heroui-success-50": "146.67 64.29% 94.51%",
        "--heroui-success-100": "145.71 61.4% 88.82%",
        "--heroui-success-200": "146.2 61.74% 77.45%",
        "--heroui-success-300": "145.79 62.57% 66.47%",
        "--heroui-success-400": "146.01 62.45% 55.1%",
        "--heroui-success-500": "145.96 79.46% 43.92%",
        "--heroui-success-600": "146.01 79.89% 35.1%",
        "--heroui-success-700": "145.79 79.26% 26.47%",
        "--heroui-success-800": "146.2 79.78% 17.45%",
        "--heroui-success-900": "145.71 77.78% 8.82%",
        "--heroui-success-foreground": "0 0% 0%",
        "--heroui-success": "145.96 79.46% 43.92%",
        "--heroui-warning-50": "54.55 91.67% 95.29%",
        "--heroui-warning-100": "37.14 91.3% 90.98%",
        "--heroui-warning-200": "37.14 91.3% 81.96%",
        "--heroui-warning-300": "36.96 91.24% 73.14%",
        "--heroui-warning-400": "37.01 91.26% 64.12%",
        "--heroui-warning-500": "37.03 91.27% 55.1%",
        "--heroui-warning-600": "37.01 74.22% 44.12%",
        "--heroui-warning-700": "36.96 73.96% 33.14%",
        "--heroui-warning-800": "37.14 75% 21.96%",
        "--heroui-warning-900": "37.14 75% 10.98%",
        "--heroui-warning-foreground": "0 0% 0%",
        "--heroui-warning": "37.03 91.27% 55.1%",
        "--heroui-code-background": "221.25 17.39% 18.04%",
        "--heroui-strong": "316.95 100% 65.29%",
        "--heroui-code-mdx": "316.95 100% 65.29%",
        "--heroui-divider-weight": "1px",
        "--heroui-disabled-opacity": ".5",
        "--heroui-font-size-tiny": "0.75rem",
        "--heroui-font-size-small": "0.875rem",
        "--heroui-font-size-medium": "1rem",
        "--heroui-font-size-large": "1.125rem",
        "--heroui-line-height-tiny": "1rem",
        "--heroui-line-height-small": "1.25rem",
        "--heroui-line-height-medium": "1.5rem",
        "--heroui-line-height-large": "1.75rem",
        "--heroui-radius-small": "8px",
        "--heroui-radius-medium": "12px",
        "--heroui-radius-large": "14px",
        "--heroui-border-width-small": "1px",
        "--heroui-border-width-medium": "2px",
        "--heroui-border-width-large": "3px",
        "--heroui-box-shadow-small": "0px 0px 5px 0px rgba(0, 0, 0, .02), 0px 2px 10px 0px rgba(0, 0, 0, .06), 0px 0px 1px 0px rgba(0, 0, 0, .3)",
        "--heroui-box-shadow-medium": "0px 0px 15px 0px rgba(0, 0, 0, .03), 0px 2px 30px 0px rgba(0, 0, 0, .08), 0px 0px 1px 0px rgba(0, 0, 0, .3)",
        "--heroui-box-shadow-large": "0px 0px 30px 0px rgba(0, 0, 0, .04), 0px 30px 60px 0px rgba(0, 0, 0, .12), 0px 0px 1px 0px rgba(0, 0, 0, .3)",
        "--heroui-hover-opacity": ".8"
      }
    }
  }
);

const normalizeHost = (host) => {
  if (isIP(host) === 6) return `[${host}]`;
  return host;
};
const createUrl = (host, port, path = "/", search, protocol = "http") => {
  const url = new URL(`${protocol}://${normalizeHost(host)}`);
  url.port = port;
  url.pathname = path;
  if (search) {
    for (const key in search) {
      url.searchParams.set(key, search[key]);
    }
  }
  return decodeURIComponent(url.toString());
};
const getRandomToken = (length = 8) => {
  return randomBytes(36).toString("hex").slice(0, length);
};

const WebUiConfigSchema = Type.Object({
  host: Type.String({ default: "0.0.0.0" }),
  port: Type.Number({ default: 6099 }),
  token: Type.String({ default: getRandomToken(12) }),
  loginRate: Type.Number({ default: 10 }),
  autoLoginAccount: Type.String({ default: "" }),
  theme: themeType,
  // 是否关闭WebUI
  disableWebUI: Type.Boolean({ default: false }),
  // 是否关闭非局域网访问
  disableNonLANAccess: Type.Boolean({ default: false })
});
class WebUiConfigWrapper {
  WebUiConfigData = void 0;
  validateAndApplyDefaults(config) {
    new Ajv({ coerceTypes: true, useDefaults: true }).compile(WebUiConfigSchema)(config);
    return config;
  }
  async ensureConfigFileExists(configPath) {
    const configExists = await fs$1.access(configPath, constants$1.F_OK).then(() => true).catch(() => false);
    if (!configExists) {
      await fs$1.writeFile(configPath, JSON.stringify(this.validateAndApplyDefaults({}), null, 4));
    }
  }
  async readAndValidateConfig(configPath) {
    const fileContent = await fs$1.readFile(configPath, "utf-8");
    return this.validateAndApplyDefaults(JSON.parse(fileContent));
  }
  async writeConfig(configPath, config) {
    const hasWritePermission = await fs$1.access(configPath, constants$1.W_OK).then(() => true).catch(() => false);
    if (hasWritePermission) {
      await fs$1.writeFile(configPath, JSON.stringify(config, null, 4));
    } else {
      console.warn(`文件: ${configPath} 没有写入权限, 配置的更改部分可能会在重启后还原.`);
    }
  }
  async GetWebUIConfig() {
    if (this.WebUiConfigData) {
      return this.WebUiConfigData;
    }
    try {
      const configPath = resolve$1(webUiPathWrapper.configPath, "./webui.json");
      await this.ensureConfigFileExists(configPath);
      const parsedConfig = await this.readAndValidateConfig(configPath);
      this.WebUiConfigData = {
        ...parsedConfig,
        // 首次读取内存中是没有token的，需要进行一层兜底
        token: getInitialWebUiToken() || parsedConfig.token
      };
      return this.WebUiConfigData;
    } catch (e) {
      console.log("读取配置文件失败", e);
      const defaultConfig = this.validateAndApplyDefaults({});
      this.WebUiConfigData = {
        ...defaultConfig,
        token: getInitialWebUiToken() || defaultConfig.token
      };
      return this.WebUiConfigData;
    }
  }
  async UpdateWebUIConfig(newConfig) {
    const configPath = resolve$1(webUiPathWrapper.configPath, "./webui.json");
    const currentConfig = await this.GetRawWebUIConfig();
    const mergedConfig = deepMerge({ ...currentConfig }, newConfig);
    const updatedConfig = this.validateAndApplyDefaults(mergedConfig);
    await this.writeConfig(configPath, updatedConfig);
    this.WebUiConfigData = updatedConfig;
  }
  /**
     * 获取配置文件中实际存储的配置（不被内存token覆盖）
     * 主要用于配置更新和特殊场景
     */
  async GetRawWebUIConfig() {
    if (this.WebUiConfigData) {
      return this.WebUiConfigData;
    }
    try {
      const configPath = resolve$1(webUiPathWrapper.configPath, "./webui.json");
      await this.ensureConfigFileExists(configPath);
      const parsedConfig = await this.readAndValidateConfig(configPath);
      this.WebUiConfigData = parsedConfig;
      return this.WebUiConfigData;
    } catch (e) {
      console.log("读取配置文件失败", e);
      return this.validateAndApplyDefaults({});
    }
  }
  async UpdateToken(oldToken, newToken) {
    const cachedToken = getInitialWebUiToken();
    const tokenToCheck = cachedToken || (await this.GetWebUIConfig()).token;
    if (tokenToCheck !== oldToken) {
      throw new Error("旧 token 不匹配");
    }
    await this.UpdateWebUIConfig({ token: newToken });
  }
  // 获取日志文件夹路径
  async GetLogsPath() {
    return resolve$1(webUiPathWrapper.logsPath);
  }
  // 获取日志列表
  async GetLogsList() {
    const logsPath = resolve$1(webUiPathWrapper.logsPath);
    const logsExist = await fs$1.access(logsPath, constants$1.F_OK).then(() => true).catch(() => false);
    if (logsExist) {
      return (await fs$1.readdir(logsPath)).filter((file) => file.endsWith(".log")).map((file) => file.replace(".log", ""));
    }
    return [];
  }
  // 获取指定日志文件内容
  async GetLogContent(filename) {
    const logPath = resolve$1(webUiPathWrapper.logsPath, `${filename}.log`);
    const logExists = await fs$1.access(logPath, constants$1.R_OK).then(() => true).catch(() => false);
    if (logExists) {
      return await fs$1.readFile(logPath, "utf-8");
    }
    return "";
  }
  // 获取字体文件夹内的字体列表
  async GetFontList() {
    const fontsPath = resolve$1(webUiPathWrapper.configPath, "./fonts");
    const fontsExist = await fs$1.access(fontsPath, constants$1.F_OK).then(() => true).catch(() => false);
    if (fontsExist) {
      return (await fs$1.readdir(fontsPath)).filter((file) => file.endsWith(".ttf"));
    }
    return [];
  }
  // 判断字体是否存在（支持多种格式）
  async CheckWebUIFontExist() {
    const fontPath = await this.GetWebUIFontPath();
    if (!fontPath) return false;
    return await fs$1.access(fontPath, constants$1.F_OK).then(() => true).catch(() => false);
  }
  // 获取webui字体文件路径（支持多种格式）
  async GetWebUIFontPath() {
    const fontsPath = resolve$1(webUiPathWrapper.configPath, "./fonts");
    const extensions = [".woff", ".woff2", ".ttf", ".otf"];
    for (const ext of extensions) {
      const fontPath = resolve$1(fontsPath, `webui${ext}`);
      const exists = await fs$1.access(fontPath, constants$1.F_OK).then(() => true).catch(() => false);
      if (exists) {
        return fontPath;
      }
    }
    return null;
  }
  // 同步版本，用于 multer 配置
  GetWebUIFontPathSync() {
    return resolve$1(webUiPathWrapper.configPath, "./fonts/webui.woff");
  }
  getAutoLoginAccount() {
    return this.WebUiConfigData?.autoLoginAccount;
  }
  // 获取自动登录账号
  async GetAutoLoginAccount() {
    return (await this.GetWebUIConfig()).autoLoginAccount;
  }
  // 更新自动登录账号
  async UpdateAutoLoginAccount(uin) {
    await this.UpdateWebUIConfig({ autoLoginAccount: uin });
  }
  // 获取主题内容
  async GetTheme() {
    const config = await this.GetWebUIConfig();
    return config.theme;
  }
  // 更新主题内容
  async UpdateTheme(theme) {
    await this.UpdateWebUIConfig({ theme });
  }
  // 获取是否禁用WebUI
  async GetDisableWebUI() {
    const config = await this.GetWebUIConfig();
    return config.disableWebUI;
  }
  // 更新是否禁用WebUI
  async UpdateDisableWebUI(disable) {
    await this.UpdateWebUIConfig({ disableWebUI: disable });
  }
  // 获取是否禁用非局域网访问
  async GetDisableNonLANAccess() {
    const config = await this.GetWebUIConfig();
    return config.disableNonLANAccess;
  }
  // 更新是否禁用非局域网访问
  async UpdateDisableNonLANAccess(disable) {
    await this.UpdateWebUIConfig({ disableNonLANAccess: disable });
  }
}

const HttpServerConfigSchema$1 = Type.Object({
  name: Type.String({ default: "http-server" }),
  enable: Type.Boolean({ default: false }),
  port: Type.Number({ default: 3e3 }),
  host: Type.String({ default: "127.0.0.1" }),
  enableCors: Type.Boolean({ default: true }),
  enableWebsocket: Type.Boolean({ default: true }),
  messagePostFormat: Type.String({ default: "array" }),
  token: Type.String({ default: "" }),
  debug: Type.Boolean({ default: false })
});
const HttpSseServerConfigSchema$1 = Type.Object({
  name: Type.String({ default: "http-sse-server" }),
  enable: Type.Boolean({ default: false }),
  port: Type.Number({ default: 3e3 }),
  host: Type.String({ default: "127.0.0.1" }),
  enableCors: Type.Boolean({ default: true }),
  enableWebsocket: Type.Boolean({ default: true }),
  messagePostFormat: Type.String({ default: "array" }),
  token: Type.String({ default: "" }),
  debug: Type.Boolean({ default: false }),
  reportSelfMessage: Type.Boolean({ default: false })
});
const HttpClientConfigSchema$1 = Type.Object({
  name: Type.String({ default: "http-client" }),
  enable: Type.Boolean({ default: false }),
  url: Type.String({ default: "http://localhost:8080" }),
  messagePostFormat: Type.String({ default: "array" }),
  reportSelfMessage: Type.Boolean({ default: false }),
  token: Type.String({ default: "" }),
  debug: Type.Boolean({ default: false })
});
const WebsocketServerConfigSchema$1 = Type.Object({
  name: Type.String({ default: "websocket-server" }),
  enable: Type.Boolean({ default: false }),
  host: Type.String({ default: "127.0.0.1" }),
  port: Type.Number({ default: 3001 }),
  messagePostFormat: Type.String({ default: "array" }),
  reportSelfMessage: Type.Boolean({ default: false }),
  token: Type.String({ default: "" }),
  enableForcePushEvent: Type.Boolean({ default: true }),
  debug: Type.Boolean({ default: false }),
  heartInterval: Type.Number({ default: 3e4 })
});
const WebsocketClientConfigSchema$1 = Type.Object({
  name: Type.String({ default: "websocket-client" }),
  enable: Type.Boolean({ default: false }),
  url: Type.String({ default: "ws://localhost:8082" }),
  messagePostFormat: Type.String({ default: "array" }),
  reportSelfMessage: Type.Boolean({ default: false }),
  reconnectInterval: Type.Number({ default: 5e3 }),
  token: Type.String({ default: "" }),
  debug: Type.Boolean({ default: false }),
  heartInterval: Type.Number({ default: 3e4 })
});
const PluginConfigSchema$1 = Type.Object({
  name: Type.String({ default: "plugin" }),
  enable: Type.Boolean({ default: false }),
  messagePostFormat: Type.String({ default: "array" }),
  reportSelfMessage: Type.Boolean({ default: false }),
  debug: Type.Boolean({ default: false })
});
const NetworkConfigSchema$1 = Type.Object({
  httpServers: Type.Array(HttpServerConfigSchema$1, { default: [] }),
  httpSseServers: Type.Array(HttpSseServerConfigSchema$1, { default: [] }),
  httpClients: Type.Array(HttpClientConfigSchema$1, { default: [] }),
  websocketServers: Type.Array(WebsocketServerConfigSchema$1, { default: [] }),
  websocketClients: Type.Array(WebsocketClientConfigSchema$1, { default: [] }),
  plugins: Type.Array(PluginConfigSchema$1, { default: [] })
}, { default: {} });
const OneBotConfigSchema$1 = Type.Object({
  network: NetworkConfigSchema$1,
  musicSignUrl: Type.String({ default: "" }),
  enableLocalFile2Url: Type.Boolean({ default: false }),
  parseMultMsg: Type.Boolean({ default: false })
});
function loadConfig(config) {
  const ajv = new Ajv({ useDefaults: true, coerceTypes: true });
  const validate = ajv.compile(OneBotConfigSchema$1);
  const valid = validate(config);
  if (!valid) {
    throw new Error(ajv.errorsText(validate.errors));
  }
  return config;
}

class Store {
  store = /* @__PURE__ */ new Map();
  set(key, value, ttl) {
    this.store.set(key, value);
    if (ttl) {
      setTimeout(() => this.store.delete(key), ttl * 1e3);
    }
  }
  get(key) {
    return this.store.get(key) ?? null;
  }
  exists(...keys) {
    return keys.filter((key) => this.store.has(key)).length;
  }
}
const store = new Store();

var NapCatCoreWorkingEnv = /* @__PURE__ */ ((NapCatCoreWorkingEnv2) => {
  NapCatCoreWorkingEnv2[NapCatCoreWorkingEnv2["Unknown"] = 0] = "Unknown";
  NapCatCoreWorkingEnv2[NapCatCoreWorkingEnv2["Shell"] = 1] = "Shell";
  NapCatCoreWorkingEnv2[NapCatCoreWorkingEnv2["Framework"] = 2] = "Framework";
  return NapCatCoreWorkingEnv2;
})(NapCatCoreWorkingEnv || {});

const LoginRuntime = {
  workingEnv: NapCatCoreWorkingEnv.Unknown,
  LoginCurrentTime: Date.now(),
  LoginCurrentRate: 0,
  QQLoginStatus: false,
  // 已实现 但太傻了 得去那边注册个回调刷新
  QQQRCodeURL: "",
  QQLoginUin: "",
  QQLoginInfo: {
    uid: "",
    uin: "",
    nick: ""
  },
  QQVersion: "unknown",
  OneBotContext: null,
  onQQLoginStatusChange: async (status) => {
    LoginRuntime.QQLoginStatus = status;
  },
  onWebUiTokenChange: async (_token) => {
  },
  NapCatHelper: {
    onOB11ConfigChanged: async () => {
    },
    onQuickLoginRequested: async () => {
      return { result: false, message: "" };
    },
    QQLoginList: [],
    NewQQLoginList: []
  },
  NapCatVersion: napCatVersion,
  WebUiConfigQuickFunction: async () => {
  }
};
const WebUiDataRuntime = {
  setWorkingEnv(env) {
    LoginRuntime.workingEnv = env;
  },
  getWorkingEnv() {
    return LoginRuntime.workingEnv;
  },
  setWebUiTokenChangeCallback(func) {
    LoginRuntime.onWebUiTokenChange = func;
  },
  getWebUiTokenChangeCallback() {
    return LoginRuntime.onWebUiTokenChange;
  },
  checkLoginRate(ip, RateLimit) {
    const key = `login_rate:${ip}`;
    const count = store.get(key) || 0;
    if (count === 0) {
      store.set(key, 1, 60);
      return true;
    }
    if (count >= RateLimit) {
      return false;
    }
    store.set(key, count + 1);
    return true;
  },
  getQQLoginStatus() {
    return LoginRuntime.QQLoginStatus;
  },
  setQQLoginCallback(func) {
    LoginRuntime.onQQLoginStatusChange = func;
  },
  getQQLoginCallback() {
    return LoginRuntime.onQQLoginStatusChange;
  },
  setQQLoginStatus(status) {
    LoginRuntime.QQLoginStatus = status;
  },
  setQQLoginQrcodeURL(url) {
    LoginRuntime.QQQRCodeURL = url;
  },
  getQQLoginQrcodeURL() {
    return LoginRuntime.QQQRCodeURL;
  },
  setQQLoginInfo(info) {
    LoginRuntime.QQLoginInfo = info;
    LoginRuntime.QQLoginUin = info.uin.toString();
  },
  getQQLoginInfo() {
    return LoginRuntime.QQLoginInfo;
  },
  getQQLoginUin() {
    return LoginRuntime.QQLoginUin;
  },
  getQQQuickLoginList() {
    return LoginRuntime.NapCatHelper.QQLoginList;
  },
  setQQQuickLoginList(list) {
    LoginRuntime.NapCatHelper.QQLoginList = list;
  },
  getQQNewLoginList() {
    return LoginRuntime.NapCatHelper.NewQQLoginList;
  },
  setQQNewLoginList(list) {
    LoginRuntime.NapCatHelper.NewQQLoginList = list;
  },
  setQuickLoginCall(func) {
    LoginRuntime.NapCatHelper.onQuickLoginRequested = func;
  },
  requestQuickLogin: function(uin) {
    return LoginRuntime.NapCatHelper.onQuickLoginRequested(uin);
  },
  setOnOB11ConfigChanged(func) {
    LoginRuntime.NapCatHelper.onOB11ConfigChanged = func;
  },
  setOB11Config: function(ob11) {
    return LoginRuntime.NapCatHelper.onOB11ConfigChanged(ob11);
  },
  GetNapCatVersion() {
    return LoginRuntime.NapCatVersion;
  },
  setQQVersion(version) {
    LoginRuntime.QQVersion = version;
  },
  getQQVersion() {
    return LoginRuntime.QQVersion;
  },
  setWebUiConfigQuickFunction(func) {
    LoginRuntime.WebUiConfigQuickFunction = func;
  },
  runWebUiConfigQuickFunction: async function() {
    await LoginRuntime.WebUiConfigQuickFunction();
  },
  setOneBotContext(context) {
    LoginRuntime.OneBotContext = context;
  },
  getOneBotContext() {
    return LoginRuntime.OneBotContext;
  }
};

var HttpStatusCode = /* @__PURE__ */ ((HttpStatusCode2) => {
  HttpStatusCode2[HttpStatusCode2["OK"] = 200] = "OK";
  HttpStatusCode2[HttpStatusCode2["BadRequest"] = 400] = "BadRequest";
  HttpStatusCode2[HttpStatusCode2["Unauthorized"] = 401] = "Unauthorized";
  HttpStatusCode2[HttpStatusCode2["Forbidden"] = 403] = "Forbidden";
  HttpStatusCode2[HttpStatusCode2["NotFound"] = 404] = "NotFound";
  HttpStatusCode2[HttpStatusCode2["InternalServerError"] = 500] = "InternalServerError";
  return HttpStatusCode2;
})(HttpStatusCode || {});
var ResponseCode = /* @__PURE__ */ ((ResponseCode2) => {
  ResponseCode2[ResponseCode2["Success"] = 0] = "Success";
  ResponseCode2[ResponseCode2["Error"] = -1] = "Error";
  return ResponseCode2;
})(ResponseCode || {});

const sendError = (res, message = "error", useSend = false) => {
  const result = {
    code: ResponseCode.Error,
    message
  };
  if (useSend) {
    res.status(HttpStatusCode.OK).send(JSON.stringify(result));
    return;
  }
  res.status(HttpStatusCode.OK).json(result);
};
const sendSuccess = (res, data, message = "success", useSend = false) => {
  const result = {
    code: ResponseCode.Success,
    data,
    message
  };
  if (useSend) {
    res.status(HttpStatusCode.OK).send(JSON.stringify(result));
    return;
  }
  res.status(HttpStatusCode.OK).json(result);
};

const isEmpty = (data) => data === void 0 || data === null || data === "";

const OB11GetConfigHandler = (_, res) => {
  const isLogin = WebUiDataRuntime.getQQLoginStatus();
  if (!isLogin) {
    return sendError(res, "Not Login");
  }
  const uin = WebUiDataRuntime.getQQLoginUin();
  const configFilePath = resolve$1(webUiPathWrapper.configPath, `./onebot11_${uin}.json`);
  try {
    const configFileContent = existsSync(configFilePath) ? readFileSync(configFilePath).toString() : readFileSync(resolve$1(webUiPathWrapper.configPath, "./onebot11.json")).toString();
    const data = loadConfig(lib$2.parse(configFileContent));
    return sendSuccess(res, data);
  } catch (_e) {
    return sendError(res, "Config Get Error");
  }
};
const OB11SetConfigHandler = async (req, res) => {
  const isLogin = WebUiDataRuntime.getQQLoginStatus();
  if (!isLogin) {
    return sendError(res, "Not Login");
  }
  if (isEmpty(req.body.config)) {
    return sendError(res, "config is empty");
  }
  try {
    const config = loadConfig(lib$2.parse(req.body.config));
    await WebUiDataRuntime.setOB11Config(config);
    return sendSuccess(res, null);
  } catch (e) {
    return sendError(res, "Error: " + e);
  }
};

const router$9 = Router();
router$9.post("/GetConfig", OB11GetConfigHandler);
router$9.post("/SetConfig", OB11SetConfigHandler);

class AuthHelper {
  static secretKey = process.env["NAPCAT_WEBUI_JWT_SECRET_KEY"] || Math.random().toString(36).slice(2);
  /**
     * 签名凭证方法。
     * @param hash 待签名的凭证字符串。
     * @returns 签名后的凭证对象。
     */
  static signCredential(hash) {
    const innerJson = {
      CreatedTime: Date.now(),
      HashEncoded: hash
    };
    const jsonString = JSON.stringify(innerJson);
    const hmac = crypto__default.createHmac("sha256", AuthHelper.secretKey).update(jsonString, "utf8").digest("hex");
    return { Data: innerJson, Hmac: hmac };
  }
  /**
     * 检查凭证是否被篡改的方法。
     * @param credentialJson 凭证的JSON对象。
     * @returns 布尔值，表示凭证是否有效。
     */
  static checkCredential(credentialJson) {
    try {
      const jsonString = JSON.stringify(credentialJson.Data);
      const calculatedHmac = crypto__default.createHmac("sha256", AuthHelper.secretKey).update(jsonString, "utf8").digest("hex");
      return calculatedHmac === credentialJson.Hmac;
    } catch (_error) {
      return false;
    }
  }
  /**
     * 验证凭证在1小时内有效且token与原始token相同。
     * @param token 待验证的原始token。
     * @param credentialJson 已签名的凭证JSON对象。
     * @returns 布尔值，表示凭证是否有效且token匹配。
     */
  static validateCredentialWithinOneHour(token, credentialJson) {
    const isValid = AuthHelper.checkCredential(credentialJson);
    if (!isValid) {
      return false;
    }
    if (AuthHelper.isCredentialRevoked(credentialJson)) {
      return false;
    }
    const currentTime = Date.now() / 1e3;
    const createdTime = credentialJson.Data.CreatedTime;
    const timeDifference = currentTime - createdTime;
    return timeDifference <= 3600 && credentialJson.Data.HashEncoded === AuthHelper.generatePasswordHash(token);
  }
  /**
     * 注销指定的Token凭证
     * @param credentialJson 凭证JSON对象
     * @returns void
     */
  static revokeCredential(credentialJson) {
    const jsonString = JSON.stringify(credentialJson.Data);
    const hmac = crypto__default.createHmac("sha256", AuthHelper.secretKey).update(jsonString, "utf8").digest("hex");
    store.set(`revoked:${hmac}`, true, 3600);
  }
  /**
     * 检查凭证是否已被注销
     * @param credentialJson 凭证JSON对象
     * @returns 布尔值，表示凭证是否已被注销
     */
  static isCredentialRevoked(credentialJson) {
    const jsonString = JSON.stringify(credentialJson.Data);
    const hmac = crypto__default.createHmac("sha256", AuthHelper.secretKey).update(jsonString, "utf8").digest("hex");
    return store.exists(`revoked:${hmac}`) > 0;
  }
  /**
     * 生成密码Hash
     * @param password 密码
     * @returns 生成的Hash值
     */
  static generatePasswordHash(password) {
    return crypto__default.createHash("sha256").update(password + ".napcat").digest().toString("hex");
  }
  /**
     * 对比密码和Hash值
     * @param password 密码
     * @param hash Hash值
     * @returns 布尔值，表示密码是否匹配Hash值
     */
  static comparePasswordHash(password, hash) {
    return this.generatePasswordHash(password) === hash;
  }
}

async function auth(req, res, next) {
  if (req.url === "/auth/login") {
    return next();
  }
  if (req.url === "/auth/passkey/generate-authentication-options" || req.url === "/auth/passkey/verify-authentication") {
    return next();
  }
  if (req.headers?.authorization) {
    const authorization = req.headers.authorization.split(" ");
    if (authorization.length < 2) {
      return sendError(res, "Unauthorized");
    }
    const hash = authorization[1];
    if (!hash) return sendError(res, "Unauthorized");
    let Credential;
    try {
      Credential = JSON.parse(Buffer.from(hash, "base64").toString("utf-8"));
    } catch (_e) {
      return sendError(res, "Unauthorized");
    }
    const initialToken = getInitialWebUiToken();
    if (!initialToken) {
      return sendError(res, "Server token not initialized");
    }
    const credentialJson = AuthHelper.validateCredentialWithinOneHour(initialToken, Credential);
    if (credentialJson) {
      return next();
    }
    return sendError(res, "Unauthorized");
  }
  return sendError(res, "Unauthorized");
}

const QQGetQRcodeHandler = async (_, res) => {
  if (WebUiDataRuntime.getQQLoginStatus()) {
    return sendError(res, "QQ Is Logined");
  }
  const qrcodeUrl = WebUiDataRuntime.getQQLoginQrcodeURL();
  if (isEmpty(qrcodeUrl)) {
    return sendError(res, "QRCode Get Error");
  }
  const data = {
    qrcode: qrcodeUrl
  };
  return sendSuccess(res, data);
};
const QQCheckLoginStatusHandler = async (_, res) => {
  const data = {
    isLogin: WebUiDataRuntime.getQQLoginStatus(),
    qrcodeurl: WebUiDataRuntime.getQQLoginQrcodeURL()
  };
  return sendSuccess(res, data);
};
const QQSetQuickLoginHandler = async (req, res) => {
  const { uin } = req.body;
  const isLogin = WebUiDataRuntime.getQQLoginStatus();
  if (isLogin) {
    return sendError(res, "QQ Is Logined");
  }
  if (isEmpty(uin)) {
    return sendError(res, "uin is empty");
  }
  const { result, message } = await WebUiDataRuntime.requestQuickLogin(uin);
  if (!result) {
    return sendError(res, message);
  }
  return sendSuccess(res, null);
};
const QQGetQuickLoginListHandler = async (_, res) => {
  const quickLoginList = WebUiDataRuntime.getQQQuickLoginList();
  return sendSuccess(res, quickLoginList);
};
const QQGetLoginListNewHandler = async (_, res) => {
  const newLoginList = WebUiDataRuntime.getQQNewLoginList();
  return sendSuccess(res, newLoginList);
};
const getQQLoginInfoHandler = async (_, res) => {
  const data = WebUiDataRuntime.getQQLoginInfo();
  return sendSuccess(res, data);
};
const getAutoLoginAccountHandler = async (_, res) => {
  const data = WebUiConfig.getAutoLoginAccount();
  return sendSuccess(res, data);
};
const setAutoLoginAccountHandler = async (req, res) => {
  const { uin } = req.body;
  await WebUiConfig.UpdateAutoLoginAccount(uin);
  return sendSuccess(res, null);
};

const router$8 = Router();
router$8.all("/GetQuickLoginList", QQGetQuickLoginListHandler);
router$8.all("/GetQuickLoginListNew", QQGetLoginListNewHandler);
router$8.post("/CheckLoginStatus", QQCheckLoginStatusHandler);
router$8.post("/GetQQLoginQrcode", QQGetQRcodeHandler);
router$8.post("/SetQuickLogin", QQSetQuickLoginHandler);
router$8.post("/GetQQLoginInfo", getQQLoginInfoHandler);
router$8.post("/GetQuickLoginQQ", getAutoLoginAccountHandler);
router$8.post("/SetQuickLoginQQ", setAutoLoginAccountHandler);

/* ------------------------------------------------------------------------------------

  base64 - MIT License - Hexagon <hexagon@56k.guru>

  ------------------------------------------------------------------------------------

  License:

	Copyright (c) 2021 Hexagon <hexagon@56k.guru>

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:
	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.
	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.

  ------------------------------------------------------------------------------------  */

const 
	// Regular base64 characters
	chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",

	// Base64url characters
	charsUrl = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",

	genLookup = (target) => {
		const lookupTemp = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
		const len = chars.length;
		for (let i = 0; i < len; i++) {
			lookupTemp[target.charCodeAt(i)] = i;
		}
		return lookupTemp;
	},
  
	// Use a lookup table to find the index.
	lookup = genLookup(chars),
	lookupUrl = genLookup(charsUrl); 

/**
 * Pre-calculated regexes for validating base64 and base64url
 */
const base64UrlPattern = /^[-A-Za-z0-9\-_]*$/;
const base64Pattern = /^[-A-Za-z0-9+/]*={0,3}$/;

/**
 * @namespace base64
 */
const base64 = {};

/**
 * Convenience function for converting a base64 encoded string to an ArrayBuffer instance
 * @public
 * 
 * @param {string} data - Base64 representation of data
 * @param {boolean} [urlMode] - If set to true, URL mode string will be expected
 * @returns {ArrayBuffer} - Decoded data
 */
base64.toArrayBuffer = (data, urlMode) => {
	const 
		len = data.length;
	let bufferLength = data.length * 0.75,
		i,
		p = 0,
		encoded1,
		encoded2,
		encoded3,
		encoded4;

	if (data[data.length - 1] === "=") {
		bufferLength--;
		if (data[data.length - 2] === "=") {
			bufferLength--;
		}
	}

	const 
		arraybuffer = new ArrayBuffer(bufferLength),
		bytes = new Uint8Array(arraybuffer),
		target = urlMode ? lookupUrl : lookup;

	for (i = 0; i < len; i += 4) {
		encoded1 = target[data.charCodeAt(i)];
		encoded2 = target[data.charCodeAt(i + 1)];
		encoded3 = target[data.charCodeAt(i + 2)];
		encoded4 = target[data.charCodeAt(i + 3)];

		bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
		bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
		bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
	}

	return arraybuffer;

};

/**
 * Convenience function for creating a base64 encoded string from an ArrayBuffer instance
 * @public
 * 
 * @param {ArrayBuffer} arrBuf - ArrayBuffer to be encoded
 * @param {boolean} [urlMode] - If set to true, URL mode string will be returned
 * @returns {string} - Base64 representation of data
 */
base64.fromArrayBuffer = (arrBuf, urlMode) => {
	const bytes = new Uint8Array(arrBuf);
	let
		i,
		result = "";

	const
		len = bytes.length,
		target = urlMode ? charsUrl : chars;

	for (i = 0; i < len; i += 3) {
		result += target[bytes[i] >> 2];
		result += target[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
		result += target[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
		result += target[bytes[i + 2] & 63];
	}

	const remainder = len % 3;
	if (remainder === 2) {
		result = result.substring(0, result.length - 1) + (urlMode ? "" : "=");
	} else if (remainder === 1) {
		result = result.substring(0, result.length - 2) + (urlMode ? "" : "==");
	}

	return result;

};

/**
 * Convenience function for converting base64 to string
 * @public
 * 
 * @param {string} str - Base64 encoded string to be decoded
 * @param {boolean} [urlMode] - If set to true, URL mode string will be expected
 * @returns {string} - Decoded string
 */
base64.toString = (str, urlMode) => {
	return new TextDecoder().decode(base64.toArrayBuffer(str, urlMode));
};

/**
 * Convenience function for converting a javascript string to base64
 * @public
 * 
 * @param {string} str - String to be converted to base64
 * @param {boolean} [urlMode] - If set to true, URL mode string will be returned
 * @returns {string} - Base64 encoded string
 */
base64.fromString = (str, urlMode) => {
	return base64.fromArrayBuffer(new TextEncoder().encode(str), urlMode);
};

/**
 * Function to validate base64
 * @public
 * @param {string} encoded - Base64 or Base64url encoded data
 * @param {boolean} [urlMode] - If set to true, base64url will be expected
 * @returns {boolean} - Valid base64/base64url?
 */
base64.validate = (encoded, urlMode) => {

	// Bail out if not string
	if (!(typeof encoded === "string" || encoded instanceof String)) {
		return false;
	}

	// Go on validate
	try {
		return urlMode ? base64UrlPattern.test(encoded) : base64Pattern.test(encoded);
	} catch (_e) {
		return false;
	}
};

base64.base64 = base64;

/**
 * A runtime-agnostic collection of methods for working with Base64URL encoding
 * @module
 */
/**
 * Decode from a Base64URL-encoded string to an ArrayBuffer. Best used when converting a
 * credential ID from a JSON string to an ArrayBuffer, like in allowCredentials or
 * excludeCredentials.
 *
 * @param buffer Value to decode from base64
 * @param to (optional) The decoding to use, in case it's desirable to decode from base64 instead
 */
function toBuffer(base64urlString, from = 'base64url') {
    const _buffer = base64.toArrayBuffer(base64urlString, from === 'base64url');
    return new Uint8Array(_buffer);
}
/**
 * Encode the given array buffer into a Base64URL-encoded string. Ideal for converting various
 * credential response ArrayBuffers to string for sending back to the server as JSON.
 *
 * @param buffer Value to encode to base64
 * @param to (optional) The encoding to use, in case it's desirable to encode to base64 instead
 */
function fromBuffer(buffer, to = 'base64url') {
    /**
     * Gracefully handle Uint8Array subclass types, like Node's Buffer, that can have a large
     * ArrayBuffer backing it.
     */
    const _normalized = new Uint8Array(buffer);
    return base64.fromArrayBuffer(_normalized.buffer, to === 'base64url');
}
/**
 * Convert a base64url string into base64
 */
function toBase64(base64urlString) {
    const fromBase64Url = base64.toArrayBuffer(base64urlString, true);
    const toBase64 = base64.fromArrayBuffer(fromBase64Url);
    return toBase64;
}
/**
 * Decode a base64url string into its original UTF-8 string
 */
function toUTF8String$1(base64urlString) {
    return base64.toString(base64urlString, true);
}
/**
 * Confirm that the string is encoded into base64
 */
function isBase64(input) {
    return base64.validate(input, false);
}
/**
 * Confirm that the string is encoded into base64url, with support for optional padding
 */
function isBase64URL(input) {
    // Trim padding characters from the string if present
    input = trimPadding(input);
    return base64.validate(input, true);
}
/**
 * Remove optional padding from a base64url-encoded string
 */
function trimPadding(input) {
    return input.replace(/=/g, '');
}

function decodeLength(data, argument, index) {
    if (argument < 24) {
        return [argument, 1];
    }
    const remainingDataLength = data.byteLength - index - 1;
    const view = new DataView(data.buffer, index + 1);
    let output;
    let bytes = 0;
    switch (argument) {
        case 24: {
            if (remainingDataLength > 0) {
                output = view.getUint8(0);
                bytes = 2;
            }
            break;
        }
        case 25: {
            if (remainingDataLength > 1) {
                output = view.getUint16(0, false);
                bytes = 3;
            }
            break;
        }
        case 26: {
            if (remainingDataLength > 3) {
                output = view.getUint32(0, false);
                bytes = 5;
            }
            break;
        }
        case 27: {
            if (remainingDataLength > 7) {
                const bigOutput = view.getBigUint64(0, false);
                // Bound it to [24, MAX_SAFE_INTEGER], where it is safe
                // to encode as a javascript number
                if (bigOutput >= 24n && bigOutput <= Number.MAX_SAFE_INTEGER) {
                    return [Number(bigOutput), 9];
                }
            }
            break;
        }
    }
    if (output && output >= 24) {
        return [output, bytes];
    }
    throw new Error("Length not supported or not well formed");
}
const MAJOR_TYPE_UNSIGNED_INTEGER = 0;
const MAJOR_TYPE_NEGATIVE_INTEGER = 1;
const MAJOR_TYPE_BYTE_STRING = 2;
const MAJOR_TYPE_TEXT_STRING = 3;
const MAJOR_TYPE_ARRAY = 4;
const MAJOR_TYPE_MAP = 5;
const MAJOR_TYPE_TAG = 6;
const MAJOR_TYPE_SIMPLE_OR_FLOAT = 7;
function encodeLength(major, argument) {
    const majorEncoded = major << 5;
    if (argument < 0) {
        throw new Error("CBOR Data Item argument must not be negative");
    }
    // Convert to bigint first.
    // Encode integers around and above 32 bits in big endian / network byte order
    // is unreliable in javascript.
    // https://tc39.es/ecma262/#sec-bitwise-shift-operators
    // Bit shifting operations result in 32 bit signed numbers
    let bigintArgument;
    if (typeof argument == "number") {
        if (!Number.isInteger(argument)) {
            throw new Error("CBOR Data Item argument must be an integer");
        }
        bigintArgument = BigInt(argument);
    }
    else {
        bigintArgument = argument;
    }
    // Negative 0 is not a thing
    if (major == MAJOR_TYPE_NEGATIVE_INTEGER) {
        if (bigintArgument == 0n) {
            throw new Error("CBOR Data Item argument cannot be zero when negative");
        }
        bigintArgument = bigintArgument - 1n;
    }
    if (bigintArgument > 18446744073709551615n) {
        throw new Error("CBOR number out of range");
    }
    // Encode into 64 bits and extract the tail
    const buffer = new Uint8Array(8);
    const view = new DataView(buffer.buffer);
    view.setBigUint64(0, bigintArgument, false);
    if (bigintArgument <= 23) {
        return [majorEncoded | buffer[7]];
    }
    else if (bigintArgument <= 255) {
        return [majorEncoded | 24, buffer[7]];
    }
    else if (bigintArgument <= 65535) {
        return [majorEncoded | 25, ...buffer.slice(6)];
    }
    else if (bigintArgument <= 4294967295) {
        return [
            majorEncoded | 26,
            ...buffer.slice(4),
        ];
    }
    else {
        return [
            majorEncoded | 27,
            ...buffer,
        ];
    }
}

/**
 * A value which is wrapped with a CBOR Tag.
 * Several tags are registered with defined meanings like 0 for a date string.
 * These meanings are **not interpreted** when decoded or encoded.
 *
 * This class is an immutable record.
 * If the tag number or value needs to change, then construct a new tag
 */
class CBORTag {
    /**
     * Wrap a value with a tag number.
     * When encoded, this tag will be attached to the value.
     *
     * @param tag Tag number
     * @param value Wrapped value
     */
    constructor(tag, value) {
        Object.defineProperty(this, "tagId", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
        Object.defineProperty(this, "tagValue", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
        this.tagId = tag;
        this.tagValue = value;
    }
    /**
     * Read the tag number
     */
    get tag() {
        return this.tagId;
    }
    /**
     * Read the value
     */
    get value() {
        return this.tagValue;
    }
}
function decodeUnsignedInteger(data, argument, index) {
    return decodeLength(data, argument, index);
}
function decodeNegativeInteger(data, argument, index) {
    const [value, length] = decodeUnsignedInteger(data, argument, index);
    return [-value - 1, length];
}
function decodeByteString(data, argument, index) {
    const [lengthValue, lengthConsumed] = decodeLength(data, argument, index);
    const dataStartIndex = index + lengthConsumed;
    return [
        new Uint8Array(data.buffer.slice(dataStartIndex, dataStartIndex + lengthValue)),
        lengthConsumed + lengthValue,
    ];
}
const TEXT_DECODER = new TextDecoder();
function decodeString(data, argument, index) {
    const [value, length] = decodeByteString(data, argument, index);
    return [TEXT_DECODER.decode(value), length];
}
function decodeArray(data, argument, index) {
    if (argument === 0) {
        return [[], 1];
    }
    const [length, lengthConsumed] = decodeLength(data, argument, index);
    let consumedLength = lengthConsumed;
    const value = [];
    for (let i = 0; i < length; i++) {
        const remainingDataLength = data.byteLength - index - consumedLength;
        if (remainingDataLength <= 0) {
            throw new Error("array is not supported or well formed");
        }
        const [decodedValue, consumed] = decodeNext(data, index + consumedLength);
        value.push(decodedValue);
        consumedLength += consumed;
    }
    return [value, consumedLength];
}
const MAP_ERROR = "Map is not supported or well formed";
function decodeMap(data, argument, index) {
    if (argument === 0) {
        return [new Map(), 1];
    }
    const [length, lengthConsumed] = decodeLength(data, argument, index);
    let consumedLength = lengthConsumed;
    const result = new Map();
    for (let i = 0; i < length; i++) {
        let remainingDataLength = data.byteLength - index - consumedLength;
        if (remainingDataLength <= 0) {
            throw new Error(MAP_ERROR);
        }
        // Load key
        const [key, keyConsumed] = decodeNext(data, index + consumedLength);
        consumedLength += keyConsumed;
        remainingDataLength -= keyConsumed;
        // Check that there's enough to have a value
        if (remainingDataLength <= 0) {
            throw new Error(MAP_ERROR);
        }
        // Technically CBOR maps can have any type as the key, and so can JS Maps
        // However, JS Maps can only reference such keys as references which would
        // require key iteration and pattern matching.
        // For simplicity, since such keys are not in use with WebAuthn, this
        // capability is not implemented and the types are restricted to strings
        // and numbers.
        if (typeof key !== "string" && typeof key !== "number") {
            throw new Error(MAP_ERROR);
        }
        // CBOR Maps are not well formed if there are duplicate keys
        if (result.has(key)) {
            throw new Error(MAP_ERROR);
        }
        // Load value
        const [value, valueConsumed] = decodeNext(data, index + consumedLength);
        consumedLength += valueConsumed;
        result.set(key, value);
    }
    return [result, consumedLength];
}
function decodeFloat16(data, index) {
    if (index + 3 > data.byteLength) {
        throw new Error("CBOR stream ended before end of Float 16");
    }
    // Skip the first byte
    const result = data.getUint16(index + 1, false);
    // A minimal selection of supported values
    if (result == 0x7c00) {
        return [Infinity, 3];
    }
    else if (result == 0x7e00) {
        return [NaN, 3];
    }
    else if (result == 0xfc00) {
        return [-Infinity, 3];
    }
    throw new Error("Float16 data is unsupported");
}
function decodeFloat32(data, index) {
    if (index + 5 > data.byteLength) {
        throw new Error("CBOR stream ended before end of Float 32");
    }
    // Skip the first byte
    const result = data.getFloat32(index + 1, false);
    // First byte + 4 byte float
    return [result, 5];
}
function decodeFloat64(data, index) {
    if (index + 9 > data.byteLength) {
        throw new Error("CBOR stream ended before end of Float 64");
    }
    // Skip the first byte
    const result = data.getFloat64(index + 1, false);
    // First byte + 8 byte float
    return [result, 9];
}
function decodeTag(data, argument, index) {
    const [tag, tagBytes] = decodeLength(data, argument, index);
    const [value, valueBytes] = decodeNext(data, index + tagBytes);
    return [new CBORTag(tag, value), tagBytes + valueBytes];
}
function decodeNext(data, index) {
    if (index >= data.byteLength) {
        throw new Error("CBOR stream ended before tag value");
    }
    const byte = data.getUint8(index);
    const majorType = byte >> 5;
    const argument = byte & 0x1f;
    switch (majorType) {
        case MAJOR_TYPE_UNSIGNED_INTEGER: {
            return decodeUnsignedInteger(data, argument, index);
        }
        case MAJOR_TYPE_NEGATIVE_INTEGER: {
            return decodeNegativeInteger(data, argument, index);
        }
        case MAJOR_TYPE_BYTE_STRING: {
            return decodeByteString(data, argument, index);
        }
        case MAJOR_TYPE_TEXT_STRING: {
            return decodeString(data, argument, index);
        }
        case MAJOR_TYPE_ARRAY: {
            return decodeArray(data, argument, index);
        }
        case MAJOR_TYPE_MAP: {
            return decodeMap(data, argument, index);
        }
        case MAJOR_TYPE_TAG: {
            return decodeTag(data, argument, index);
        }
        case MAJOR_TYPE_SIMPLE_OR_FLOAT: {
            switch (argument) {
                case 20:
                    return [false, 1];
                case 21:
                    return [true, 1];
                case 22:
                    return [null, 1];
                case 23:
                    return [undefined, 1];
                // 24: Simple value (value 32..255 in following byte)
                case 25: // IEEE 754 Half-Precision Float (16 bits follow)
                    return decodeFloat16(data, index);
                case 26: // IEEE 754 Single-Precision Float (32 bits follow)
                    return decodeFloat32(data, index);
                case 27: // IEEE 754 Double-Precision Float (64 bits follow)
                    return decodeFloat64(data, index);
                // 28-30: Reserved, not well-formed in the present document
                // 31: "break" stop code for indefinite-length items
            }
        }
    }
    throw new Error(`Unsupported or not well formed at ${index}`);
}
function encodeSimple(data) {
    if (data === true) {
        return 0xf5;
    }
    else if (data === false) {
        return 0xf4;
    }
    else if (data === null) {
        return 0xf6;
    }
    // Else undefined
    return 0xf7;
}
function encodeFloat(data) {
    if (Math.fround(data) == data || !Number.isFinite(data) || Number.isNaN(data)) {
        // Float32
        const output = new Uint8Array(5);
        output[0] = 0xfa;
        const view = new DataView(output.buffer);
        view.setFloat32(1, data, false);
        return output;
    }
    else {
        // Float64
        const output = new Uint8Array(9);
        output[0] = 0xfb;
        const view = new DataView(output.buffer);
        view.setFloat64(1, data, false);
        return output;
    }
}
function encodeNumber(data) {
    if (typeof data == "number") {
        if (Number.isSafeInteger(data)) {
            // Encode integer
            if (data < 0) {
                return encodeLength(MAJOR_TYPE_NEGATIVE_INTEGER, Math.abs(data));
            }
            else {
                return encodeLength(MAJOR_TYPE_UNSIGNED_INTEGER, data);
            }
        }
        return [encodeFloat(data)];
    }
    else {
        if (data < 0n) {
            return encodeLength(MAJOR_TYPE_NEGATIVE_INTEGER, data * -1n);
        }
        else {
            return encodeLength(MAJOR_TYPE_UNSIGNED_INTEGER, data);
        }
    }
}
const ENCODER = new TextEncoder();
function encodeString(data, output) {
    output.push(...encodeLength(MAJOR_TYPE_TEXT_STRING, data.length));
    output.push(ENCODER.encode(data));
}
function encodeBytes(data, output) {
    output.push(...encodeLength(MAJOR_TYPE_BYTE_STRING, data.length));
    output.push(data);
}
function encodeArray(data, output) {
    output.push(...encodeLength(MAJOR_TYPE_ARRAY, data.length));
    for (const element of data) {
        encodePartialCBOR(element, output);
    }
}
function encodeMap(data, output) {
    output.push(new Uint8Array(encodeLength(MAJOR_TYPE_MAP, data.size)));
    for (const [key, value] of data.entries()) {
        encodePartialCBOR(key, output);
        encodePartialCBOR(value, output);
    }
}
function encodeTag(tag, output) {
    output.push(...encodeLength(MAJOR_TYPE_TAG, tag.tag));
    encodePartialCBOR(tag.value, output);
}
function encodePartialCBOR(data, output) {
    if (typeof data == "boolean" || data === null || data == undefined) {
        output.push(encodeSimple(data));
        return;
    }
    if (typeof data == "number" || typeof data == "bigint") {
        output.push(...encodeNumber(data));
        return;
    }
    if (typeof data == "string") {
        encodeString(data, output);
        return;
    }
    if (data instanceof Uint8Array) {
        encodeBytes(data, output);
        return;
    }
    if (Array.isArray(data)) {
        encodeArray(data, output);
        return;
    }
    if (data instanceof Map) {
        encodeMap(data, output);
        return;
    }
    if (data instanceof CBORTag) {
        encodeTag(data, output);
        return;
    }
    throw new Error("Not implemented");
}
/**
 * Like {decodeCBOR}, but the length of the data is unknown and there is likely
 * more -- possibly unrelated non-CBOR -- data afterwards.
 *
 * Examples:
 *
 * ```ts
 * import {decodePartialCBOR} from './cbor.ts'
 * decodePartialCBOR(new Uint8Array([1, 2, 245, 3, 4]), 2)
 * // returns [true, 1]
 * // It did not decode the leading [1, 2] or trailing [3, 4]
 * ```
 *
 * @param data a data stream to read data from
 * @param index where to start reading in the data stream
 * @returns a tuple of the value followed by bytes read.
 * @throws {Error}
 *   When the data stream ends early or the CBOR data is not well formed
 */
function decodePartialCBOR(data, index) {
    if (data.byteLength === 0 || data.byteLength <= index || index < 0) {
        throw new Error("No data");
    }
    if (data instanceof Uint8Array) {
        return decodeNext(new DataView(data.buffer), index);
    }
    else if (data instanceof ArrayBuffer) {
        return decodeNext(new DataView(data), index);
    }
    // otherwise, it is a data view
    return decodeNext(data, index);
}
/**
 * Encode a supported structure to a CBOR byte string.
 *
 * Example:
 *
 * ```ts
 * import {encodeCBOR, CBORType, CBORTag} from './cbor.ts'
 * encodeCBOR(new Map<string | number, CBORType>([
 *   ["key", "value"],
 *   [1, "another value"]
 * ]));
 * // returns new Uint8Array([162, 99, 107, 101, 121, 101, 118, 97, 108, 117, 101, 1, 109, 97, 110, 111, 116, 104, 101, 114, 32 118, 97, 108, 117, 101])
 *
 * encodeCBOR(new CBORTag(1234, "hello"))
 * // returns new UInt8Array([217, 4, 210, 101, 104, 101, 108, 108, 111])
 * ```
 *
 * @param data Data to encode
 * @returns A byte string as a Uint8Array
 * @throws Error
 *   if unsupported data is found during encoding
 */
function encodeCBOR(data) {
    const results = [];
    encodePartialCBOR(data, results);
    let length = 0;
    for (const result of results) {
        if (typeof result == "number") {
            length += 1;
        }
        else {
            length += result.length;
        }
    }
    const output = new Uint8Array(length);
    let index = 0;
    for (const result of results) {
        if (typeof result == "number") {
            output[index] = result;
            index += 1;
        }
        else {
            output.set(result, index);
            index += result.length;
        }
    }
    return output;
}

/**
 * A runtime-agnostic collection of methods for working with CBOR encoding
 * @module
 */
/**
 * Whatever CBOR encoder is used should keep CBOR data the same length when data is re-encoded
 *
 * MOST CRITICALLY, this means the following needs to be true of whatever CBOR library we use:
 * - CBOR Map type values MUST decode to JavaScript Maps
 * - CBOR tag 64 (uint8 Typed Array) MUST NOT be used when encoding Uint8Arrays back to CBOR
 *
 * So long as these requirements are maintained, then CBOR sequences can be encoded and decoded
 * freely while maintaining their lengths for the most accurate pointer movement across them.
 */
/**
 * Decode and return the first item in a sequence of CBOR-encoded values
 *
 * @param input The CBOR data to decode
 * @param asObject (optional) Whether to convert any CBOR Maps into JavaScript Objects. Defaults to
 * `false`
 */
function decodeFirst(input) {
    // Make a copy so we don't mutate the original
    const _input = new Uint8Array(input);
    const decoded = decodePartialCBOR(_input, 0);
    const [first] = decoded;
    return first;
}
/**
 * Encode data to CBOR
 */
function encode(input) {
    return encodeCBOR(input);
}

/**
 * A type guard for determining if a COSE public key is an OKP key pair
 */
function isCOSEPublicKeyOKP(cosePublicKey) {
    const kty = cosePublicKey.get(COSEKEYS.kty);
    return isCOSEKty(kty) && kty === COSEKTY.OKP;
}
/**
 * A type guard for determining if a COSE public key is an EC2 key pair
 */
function isCOSEPublicKeyEC2(cosePublicKey) {
    const kty = cosePublicKey.get(COSEKEYS.kty);
    return isCOSEKty(kty) && kty === COSEKTY.EC2;
}
/**
 * A type guard for determining if a COSE public key is an RSA key pair
 */
function isCOSEPublicKeyRSA(cosePublicKey) {
    const kty = cosePublicKey.get(COSEKEYS.kty);
    return isCOSEKty(kty) && kty === COSEKTY.RSA;
}
/**
 * COSE Keys
 *
 * https://www.iana.org/assignments/cose/cose.xhtml#key-common-parameters
 * https://www.iana.org/assignments/cose/cose.xhtml#key-type-parameters
 */
var COSEKEYS;
(function (COSEKEYS) {
    COSEKEYS[COSEKEYS["kty"] = 1] = "kty";
    COSEKEYS[COSEKEYS["alg"] = 3] = "alg";
    COSEKEYS[COSEKEYS["crv"] = -1] = "crv";
    COSEKEYS[COSEKEYS["x"] = -2] = "x";
    COSEKEYS[COSEKEYS["y"] = -3] = "y";
    COSEKEYS[COSEKEYS["n"] = -1] = "n";
    COSEKEYS[COSEKEYS["e"] = -2] = "e";
})(COSEKEYS || (COSEKEYS = {}));
/**
 * COSE Key Types
 *
 * https://www.iana.org/assignments/cose/cose.xhtml#key-type
 */
var COSEKTY;
(function (COSEKTY) {
    COSEKTY[COSEKTY["OKP"] = 1] = "OKP";
    COSEKTY[COSEKTY["EC2"] = 2] = "EC2";
    COSEKTY[COSEKTY["RSA"] = 3] = "RSA";
})(COSEKTY || (COSEKTY = {}));
function isCOSEKty(kty) {
    return Object.values(COSEKTY).indexOf(kty) >= 0;
}
/**
 * COSE Curves
 *
 * https://www.iana.org/assignments/cose/cose.xhtml#elliptic-curves
 */
var COSECRV;
(function (COSECRV) {
    COSECRV[COSECRV["P256"] = 1] = "P256";
    COSECRV[COSECRV["P384"] = 2] = "P384";
    COSECRV[COSECRV["P521"] = 3] = "P521";
    COSECRV[COSECRV["ED25519"] = 6] = "ED25519";
    COSECRV[COSECRV["SECP256K1"] = 8] = "SECP256K1";
})(COSECRV || (COSECRV = {}));
function isCOSECrv(crv) {
    return Object.values(COSECRV).indexOf(crv) >= 0;
}
/**
 * COSE Algorithms
 *
 * https://www.iana.org/assignments/cose/cose.xhtml#algorithms
 */
var COSEALG;
(function (COSEALG) {
    COSEALG[COSEALG["ES256"] = -7] = "ES256";
    COSEALG[COSEALG["EdDSA"] = -8] = "EdDSA";
    COSEALG[COSEALG["ES384"] = -35] = "ES384";
    COSEALG[COSEALG["ES512"] = -36] = "ES512";
    COSEALG[COSEALG["PS256"] = -37] = "PS256";
    COSEALG[COSEALG["PS384"] = -38] = "PS384";
    COSEALG[COSEALG["PS512"] = -39] = "PS512";
    COSEALG[COSEALG["ES256K"] = -47] = "ES256K";
    COSEALG[COSEALG["RS256"] = -257] = "RS256";
    COSEALG[COSEALG["RS384"] = -258] = "RS384";
    COSEALG[COSEALG["RS512"] = -259] = "RS512";
    COSEALG[COSEALG["RS1"] = -65535] = "RS1";
})(COSEALG || (COSEALG = {}));
function isCOSEAlg(alg) {
    return Object.values(COSEALG).indexOf(alg) >= 0;
}

/**
 * Convert a COSE alg ID into a corresponding string value that WebCrypto APIs expect
 */
function mapCoseAlgToWebCryptoAlg(alg) {
    if ([COSEALG.RS1].indexOf(alg) >= 0) {
        return 'SHA-1';
    }
    else if ([COSEALG.ES256, COSEALG.PS256, COSEALG.RS256].indexOf(alg) >= 0) {
        return 'SHA-256';
    }
    else if ([COSEALG.ES384, COSEALG.PS384, COSEALG.RS384].indexOf(alg) >= 0) {
        return 'SHA-384';
    }
    else if ([COSEALG.ES512, COSEALG.PS512, COSEALG.RS512, COSEALG.EdDSA].indexOf(alg) >=
        0) {
        return 'SHA-512';
    }
    throw new Error(`Could not map COSE alg value of ${alg} to a WebCrypto alg`);
}

let webCrypto = undefined;
/**
 * Try to get an instance of the Crypto API from the current runtime. Should support Node,
 * as well as others, like Deno, that implement Web APIs.
 */
function getWebCrypto() {
    /**
     * Hello there! If you came here wondering why this method is asynchronous when use of
     * `globalThis.crypto` is not, it's to minimize a bunch of refactor related to making this
     * synchronous. For example, `generateRegistrationOptions()` and `generateAuthenticationOptions()`
     * become synchronous if we make this synchronous (since nothing else in that method is async)
     * which represents a breaking API change in this library's core API.
     *
     * TODO: If it's after February 2025 when you read this then consider whether it still makes sense
     * to keep this method asynchronous.
     */
    const toResolve = new Promise((resolve, reject) => {
        if (webCrypto) {
            return resolve(webCrypto);
        }
        /**
         * Naively attempt to access Crypto as a global object, which popular ESM-centric run-times
         * support (and Node v20+)
         */
        const _globalThisCrypto = _getWebCryptoInternals.stubThisGlobalThisCrypto();
        if (_globalThisCrypto) {
            webCrypto = _globalThisCrypto;
            return resolve(webCrypto);
        }
        // We tried to access it both in Node and globally, so bail out
        return reject(new MissingWebCrypto());
    });
    return toResolve;
}
class MissingWebCrypto extends Error {
    constructor() {
        const message = 'An instance of the Crypto API could not be located';
        super(message);
        this.name = 'MissingWebCrypto';
    }
}
// Make it possible to stub return values during testing
const _getWebCryptoInternals = {
    stubThisGlobalThisCrypto: () => globalThis.crypto,
    // Make it possible to reset the `webCrypto` at the top of the file
    setCachedCrypto: (newCrypto) => {
        webCrypto = newCrypto;
    },
};

/**
 * Generate a digest of the provided data.
 *
 * @param data The data to generate a digest of
 * @param algorithm A COSE algorithm ID that maps to a desired SHA algorithm
 */
async function digest(data, algorithm) {
    const WebCrypto = await getWebCrypto();
    const subtleAlgorithm = mapCoseAlgToWebCryptoAlg(algorithm);
    const hashed = await WebCrypto.subtle.digest(subtleAlgorithm, data);
    return new Uint8Array(hashed);
}

/**
 * Fill up the provided bytes array with random bytes equal to its length.
 *
 * @returns the same bytes array passed into the method
 */
async function getRandomValues(array) {
    const WebCrypto = await getWebCrypto();
    WebCrypto.getRandomValues(array);
    return array;
}

async function importKey(opts) {
    const WebCrypto = await getWebCrypto();
    const { keyData, algorithm } = opts;
    return WebCrypto.subtle.importKey('jwk', keyData, algorithm, false, [
        'verify',
    ]);
}

/**
 * Verify a signature using an EC2 public key
 */
async function verifyEC2(opts) {
    const { cosePublicKey, signature, data, shaHashOverride } = opts;
    const WebCrypto = await getWebCrypto();
    // Import the public key
    const alg = cosePublicKey.get(COSEKEYS.alg);
    const crv = cosePublicKey.get(COSEKEYS.crv);
    const x = cosePublicKey.get(COSEKEYS.x);
    const y = cosePublicKey.get(COSEKEYS.y);
    if (!alg) {
        throw new Error('Public key was missing alg (EC2)');
    }
    if (!crv) {
        throw new Error('Public key was missing crv (EC2)');
    }
    if (!x) {
        throw new Error('Public key was missing x (EC2)');
    }
    if (!y) {
        throw new Error('Public key was missing y (EC2)');
    }
    let _crv;
    if (crv === COSECRV.P256) {
        _crv = 'P-256';
    }
    else if (crv === COSECRV.P384) {
        _crv = 'P-384';
    }
    else if (crv === COSECRV.P521) {
        _crv = 'P-521';
    }
    else {
        throw new Error(`Unexpected COSE crv value of ${crv} (EC2)`);
    }
    const keyData = {
        kty: 'EC',
        crv: _crv,
        x: fromBuffer(x),
        y: fromBuffer(y),
        ext: false,
    };
    const keyAlgorithm = {
        /**
         * Note to future self: you can't use `mapCoseAlgToWebCryptoKeyAlgName()` here because some
         * leaf certs from actual devices specified an RSA SHA value for `alg` (e.g. `-257`) which
         * would then map here to `'RSASSA-PKCS1-v1_5'`. We always want `'ECDSA'` here so we'll
         * hard-code this.
         */
        name: 'ECDSA',
        namedCurve: _crv,
    };
    const key = await importKey({
        keyData,
        algorithm: keyAlgorithm,
    });
    // Determine which SHA algorithm to use for signature verification
    let subtleAlg = mapCoseAlgToWebCryptoAlg(alg);
    if (shaHashOverride) {
        subtleAlg = mapCoseAlgToWebCryptoAlg(shaHashOverride);
    }
    const verifyAlgorithm = {
        name: 'ECDSA',
        hash: { name: subtleAlg },
    };
    return WebCrypto.subtle.verify(verifyAlgorithm, key, signature, data);
}

/**
 * Convert a COSE alg ID into a corresponding key algorithm string value that WebCrypto APIs expect
 */
function mapCoseAlgToWebCryptoKeyAlgName(alg) {
    if ([COSEALG.EdDSA].indexOf(alg) >= 0) {
        return 'Ed25519';
    }
    else if ([COSEALG.ES256, COSEALG.ES384, COSEALG.ES512, COSEALG.ES256K].indexOf(alg) >= 0) {
        return 'ECDSA';
    }
    else if ([COSEALG.RS256, COSEALG.RS384, COSEALG.RS512, COSEALG.RS1].indexOf(alg) >= 0) {
        return 'RSASSA-PKCS1-v1_5';
    }
    else if ([COSEALG.PS256, COSEALG.PS384, COSEALG.PS512].indexOf(alg) >= 0) {
        return 'RSA-PSS';
    }
    throw new Error(`Could not map COSE alg value of ${alg} to a WebCrypto key alg name`);
}

/**
 * Verify a signature using an RSA public key
 */
async function verifyRSA(opts) {
    const { cosePublicKey, signature, data, shaHashOverride } = opts;
    const WebCrypto = await getWebCrypto();
    const alg = cosePublicKey.get(COSEKEYS.alg);
    const n = cosePublicKey.get(COSEKEYS.n);
    const e = cosePublicKey.get(COSEKEYS.e);
    if (!alg) {
        throw new Error('Public key was missing alg (RSA)');
    }
    if (!isCOSEAlg(alg)) {
        throw new Error(`Public key had invalid alg ${alg} (RSA)`);
    }
    if (!n) {
        throw new Error('Public key was missing n (RSA)');
    }
    if (!e) {
        throw new Error('Public key was missing e (RSA)');
    }
    const keyData = {
        kty: 'RSA',
        alg: '',
        n: fromBuffer(n),
        e: fromBuffer(e),
        ext: false,
    };
    const keyAlgorithm = {
        name: mapCoseAlgToWebCryptoKeyAlgName(alg),
        hash: { name: mapCoseAlgToWebCryptoAlg(alg) },
    };
    const verifyAlgorithm = {
        name: mapCoseAlgToWebCryptoKeyAlgName(alg),
    };
    if (shaHashOverride) {
        keyAlgorithm.hash.name = mapCoseAlgToWebCryptoAlg(shaHashOverride);
    }
    if (keyAlgorithm.name === 'RSASSA-PKCS1-v1_5') {
        if (keyAlgorithm.hash.name === 'SHA-256') {
            keyData.alg = 'RS256';
        }
        else if (keyAlgorithm.hash.name === 'SHA-384') {
            keyData.alg = 'RS384';
        }
        else if (keyAlgorithm.hash.name === 'SHA-512') {
            keyData.alg = 'RS512';
        }
        else if (keyAlgorithm.hash.name === 'SHA-1') {
            keyData.alg = 'RS1';
        }
    }
    else if (keyAlgorithm.name === 'RSA-PSS') {
        /**
         * salt length. The default value is 20 but the convention is to use hLen, the length of the
         * output of the hash function in bytes. A salt length of zero is permitted and will result in
         * a deterministic signature value. The actual salt length used can be determined from the
         * signature value.
         *
         * From https://www.cryptosys.net/pki/manpki/pki_rsaschemes.html
         */
        let saltLength = 0;
        if (keyAlgorithm.hash.name === 'SHA-256') {
            keyData.alg = 'PS256';
            saltLength = 32; // 256 bits => 32 bytes
        }
        else if (keyAlgorithm.hash.name === 'SHA-384') {
            keyData.alg = 'PS384';
            saltLength = 48; // 384 bits => 48 bytes
        }
        else if (keyAlgorithm.hash.name === 'SHA-512') {
            keyData.alg = 'PS512';
            saltLength = 64; // 512 bits => 64 bytes
        }
        verifyAlgorithm.saltLength = saltLength;
    }
    else {
        throw new Error(`Unexpected RSA key algorithm ${alg} (${keyAlgorithm.name})`);
    }
    const key = await importKey({
        keyData,
        algorithm: keyAlgorithm,
    });
    return WebCrypto.subtle.verify(verifyAlgorithm, key, signature, data);
}

/**
 * Convert the aaguid buffer in authData into a UUID string
 */
function convertAAGUIDToString(aaguid) {
    // Raw Hex: adce000235bcc60a648b0b25f1f05503
    const hex = toHex(aaguid);
    const segments = [
        hex.slice(0, 8), // 8
        hex.slice(8, 12), // 4
        hex.slice(12, 16), // 4
        hex.slice(16, 20), // 4
        hex.slice(20, 32), // 8
    ];
    // Formatted: adce0002-35bc-c60a-648b-0b25f1f05503
    return segments.join('-');
}

/**
 * Convert buffer to an OpenSSL-compatible PEM text format.
 */
function convertCertBufferToPEM(certBuffer) {
    let b64cert;
    /**
     * Get certBuffer to a base64 representation
     */
    if (typeof certBuffer === 'string') {
        if (isBase64URL(certBuffer)) {
            b64cert = toBase64(certBuffer);
        }
        else if (isBase64(certBuffer)) {
            b64cert = certBuffer;
        }
        else {
            throw new Error('Certificate is not a valid base64 or base64url string');
        }
    }
    else {
        b64cert = fromBuffer(certBuffer, 'base64');
    }
    let PEMKey = '';
    for (let i = 0; i < Math.ceil(b64cert.length / 64); i += 1) {
        const start = 64 * i;
        PEMKey += `${b64cert.substr(start, 64)}\n`;
    }
    PEMKey = `-----BEGIN CERTIFICATE-----\n${PEMKey}-----END CERTIFICATE-----\n`;
    return PEMKey;
}

/**
 * Takes COSE-encoded public key and converts it to PKCS key
 */
function convertCOSEtoPKCS(cosePublicKey) {
    // This is a little sloppy, I'm using COSEPublicKeyEC2 since it could have both x and y, but when
    // there's no y it means it's probably better typed as COSEPublicKeyOKP. I'll leave this for now
    // and revisit it later if it ever becomes an actual problem.
    const struct = decodeFirst(cosePublicKey);
    const tag = Uint8Array.from([0x04]);
    const x = struct.get(COSEKEYS.x);
    const y = struct.get(COSEKEYS.y);
    if (!x) {
        throw new Error('COSE public key was missing x');
    }
    if (y) {
        return concat([tag, x, y]);
    }
    return concat([tag, x]);
}

/**
 * Convert an AttestationObject buffer to a proper object
 *
 * @param base64AttestationObject Attestation Object buffer
 */
function decodeAttestationObject(attestationObject) {
    return _decodeAttestationObjectInternals.stubThis(decodeFirst(attestationObject));
}
/**
 * Make it possible to stub the return value during testing
 * @ignore Don't include this in docs output
 */
const _decodeAttestationObjectInternals = {
    stubThis: (value) => value,
};

/**
 * Decode an authenticator's base64url-encoded clientDataJSON to JSON
 */
function decodeClientDataJSON(data) {
    const toString = toUTF8String$1(data);
    const clientData = JSON.parse(toString);
    return _decodeClientDataJSONInternals.stubThis(clientData);
}
/**
 * Make it possible to stub the return value during testing
 * @ignore Don't include this in docs output
 */
const _decodeClientDataJSONInternals = {
    stubThis: (value) => value,
};

function decodeCredentialPublicKey(publicKey) {
    return _decodeCredentialPublicKeyInternals.stubThis(decodeFirst(publicKey));
}
/**
 * Make it possible to stub the return value during testing
 * @ignore Don't include this in docs output
 */
const _decodeCredentialPublicKeyInternals = {
    stubThis: (value) => value,
};

/**
 * Generate a suitably random value to be used as user ID
 */
async function generateUserID() {
    /**
     * WebAuthn spec says user.id has a max length of 64 bytes. I prefer how 32 random bytes look
     * after they're base64url-encoded so I'm choosing to go with that here.
     */
    const newUserID = new Uint8Array(32);
    await getRandomValues(newUserID);
    return _generateUserIDInternals.stubThis(newUserID);
}
/**
 * Make it possible to stub the return value during testing
 * @ignore Don't include this in docs output
 */
const _generateUserIDInternals = {
    stubThis: (value) => value,
};

/*!
 * MIT License
 * 
 * Copyright (c) 2017-2024 Peculiar Ventures, LLC
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * 
 */

const ARRAY_BUFFER_NAME = "[object ArrayBuffer]";
class BufferSourceConverter {
    static isArrayBuffer(data) {
        return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME;
    }
    static toArrayBuffer(data) {
        if (this.isArrayBuffer(data)) {
            return data;
        }
        if (data.byteLength === data.buffer.byteLength) {
            return data.buffer;
        }
        if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
            return data.buffer;
        }
        return this.toUint8Array(data.buffer)
            .slice(data.byteOffset, data.byteOffset + data.byteLength)
            .buffer;
    }
    static toUint8Array(data) {
        return this.toView(data, Uint8Array);
    }
    static toView(data, type) {
        if (data.constructor === type) {
            return data;
        }
        if (this.isArrayBuffer(data)) {
            return new type(data);
        }
        if (this.isArrayBufferView(data)) {
            return new type(data.buffer, data.byteOffset, data.byteLength);
        }
        throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");
    }
    static isBufferSource(data) {
        return this.isArrayBufferView(data)
            || this.isArrayBuffer(data);
    }
    static isArrayBufferView(data) {
        return ArrayBuffer.isView(data)
            || (data && this.isArrayBuffer(data.buffer));
    }
    static isEqual(a, b) {
        const aView = BufferSourceConverter.toUint8Array(a);
        const bView = BufferSourceConverter.toUint8Array(b);
        if (aView.length !== bView.byteLength) {
            return false;
        }
        for (let i = 0; i < aView.length; i++) {
            if (aView[i] !== bView[i]) {
                return false;
            }
        }
        return true;
    }
    static concat(...args) {
        let buffers;
        if (Array.isArray(args[0]) && !(args[1] instanceof Function)) {
            buffers = args[0];
        }
        else if (Array.isArray(args[0]) && args[1] instanceof Function) {
            buffers = args[0];
        }
        else {
            if (args[args.length - 1] instanceof Function) {
                buffers = args.slice(0, args.length - 1);
            }
            else {
                buffers = args;
            }
        }
        let size = 0;
        for (const buffer of buffers) {
            size += buffer.byteLength;
        }
        const res = new Uint8Array(size);
        let offset = 0;
        for (const buffer of buffers) {
            const view = this.toUint8Array(buffer);
            res.set(view, offset);
            offset += view.length;
        }
        if (args[args.length - 1] instanceof Function) {
            return this.toView(res, args[args.length - 1]);
        }
        return res.buffer;
    }
}

const STRING_TYPE = "string";
const HEX_REGEX = /^[0-9a-f\s]+$/i;
const BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
const BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/;
class Utf8Converter {
    static fromString(text) {
        const s = unescape(encodeURIComponent(text));
        const uintArray = new Uint8Array(s.length);
        for (let i = 0; i < s.length; i++) {
            uintArray[i] = s.charCodeAt(i);
        }
        return uintArray.buffer;
    }
    static toString(buffer) {
        const buf = BufferSourceConverter.toUint8Array(buffer);
        let encodedString = "";
        for (let i = 0; i < buf.length; i++) {
            encodedString += String.fromCharCode(buf[i]);
        }
        const decodedString = decodeURIComponent(escape(encodedString));
        return decodedString;
    }
}
class Utf16Converter {
    static toString(buffer, littleEndian = false) {
        const arrayBuffer = BufferSourceConverter.toArrayBuffer(buffer);
        const dataView = new DataView(arrayBuffer);
        let res = "";
        for (let i = 0; i < arrayBuffer.byteLength; i += 2) {
            const code = dataView.getUint16(i, littleEndian);
            res += String.fromCharCode(code);
        }
        return res;
    }
    static fromString(text, littleEndian = false) {
        const res = new ArrayBuffer(text.length * 2);
        const dataView = new DataView(res);
        for (let i = 0; i < text.length; i++) {
            dataView.setUint16(i * 2, text.charCodeAt(i), littleEndian);
        }
        return res;
    }
}
class Convert {
    static isHex(data) {
        return typeof data === STRING_TYPE
            && HEX_REGEX.test(data);
    }
    static isBase64(data) {
        return typeof data === STRING_TYPE
            && BASE64_REGEX.test(data);
    }
    static isBase64Url(data) {
        return typeof data === STRING_TYPE
            && BASE64URL_REGEX.test(data);
    }
    static ToString(buffer, enc = "utf8") {
        const buf = BufferSourceConverter.toUint8Array(buffer);
        switch (enc.toLowerCase()) {
            case "utf8":
                return this.ToUtf8String(buf);
            case "binary":
                return this.ToBinary(buf);
            case "hex":
                return this.ToHex(buf);
            case "base64":
                return this.ToBase64(buf);
            case "base64url":
                return this.ToBase64Url(buf);
            case "utf16le":
                return Utf16Converter.toString(buf, true);
            case "utf16":
            case "utf16be":
                return Utf16Converter.toString(buf);
            default:
                throw new Error(`Unknown type of encoding '${enc}'`);
        }
    }
    static FromString(str, enc = "utf8") {
        if (!str) {
            return new ArrayBuffer(0);
        }
        switch (enc.toLowerCase()) {
            case "utf8":
                return this.FromUtf8String(str);
            case "binary":
                return this.FromBinary(str);
            case "hex":
                return this.FromHex(str);
            case "base64":
                return this.FromBase64(str);
            case "base64url":
                return this.FromBase64Url(str);
            case "utf16le":
                return Utf16Converter.fromString(str, true);
            case "utf16":
            case "utf16be":
                return Utf16Converter.fromString(str);
            default:
                throw new Error(`Unknown type of encoding '${enc}'`);
        }
    }
    static ToBase64(buffer) {
        const buf = BufferSourceConverter.toUint8Array(buffer);
        if (typeof btoa !== "undefined") {
            const binary = this.ToString(buf, "binary");
            return btoa(binary);
        }
        else {
            return Buffer.from(buf).toString("base64");
        }
    }
    static FromBase64(base64) {
        const formatted = this.formatString(base64);
        if (!formatted) {
            return new ArrayBuffer(0);
        }
        if (!Convert.isBase64(formatted)) {
            throw new TypeError("Argument 'base64Text' is not Base64 encoded");
        }
        if (typeof atob !== "undefined") {
            return this.FromBinary(atob(formatted));
        }
        else {
            return new Uint8Array(Buffer.from(formatted, "base64")).buffer;
        }
    }
    static FromBase64Url(base64url) {
        const formatted = this.formatString(base64url);
        if (!formatted) {
            return new ArrayBuffer(0);
        }
        if (!Convert.isBase64Url(formatted)) {
            throw new TypeError("Argument 'base64url' is not Base64Url encoded");
        }
        return this.FromBase64(this.Base64Padding(formatted.replace(/\-/g, "+").replace(/\_/g, "/")));
    }
    static ToBase64Url(data) {
        return this.ToBase64(data).replace(/\+/g, "-").replace(/\//g, "_").replace(/\=/g, "");
    }
    static FromUtf8String(text, encoding = Convert.DEFAULT_UTF8_ENCODING) {
        switch (encoding) {
            case "ascii":
                return this.FromBinary(text);
            case "utf8":
                return Utf8Converter.fromString(text);
            case "utf16":
            case "utf16be":
                return Utf16Converter.fromString(text);
            case "utf16le":
            case "usc2":
                return Utf16Converter.fromString(text, true);
            default:
                throw new Error(`Unknown type of encoding '${encoding}'`);
        }
    }
    static ToUtf8String(buffer, encoding = Convert.DEFAULT_UTF8_ENCODING) {
        switch (encoding) {
            case "ascii":
                return this.ToBinary(buffer);
            case "utf8":
                return Utf8Converter.toString(buffer);
            case "utf16":
            case "utf16be":
                return Utf16Converter.toString(buffer);
            case "utf16le":
            case "usc2":
                return Utf16Converter.toString(buffer, true);
            default:
                throw new Error(`Unknown type of encoding '${encoding}'`);
        }
    }
    static FromBinary(text) {
        const stringLength = text.length;
        const resultView = new Uint8Array(stringLength);
        for (let i = 0; i < stringLength; i++) {
            resultView[i] = text.charCodeAt(i);
        }
        return resultView.buffer;
    }
    static ToBinary(buffer) {
        const buf = BufferSourceConverter.toUint8Array(buffer);
        let res = "";
        for (let i = 0; i < buf.length; i++) {
            res += String.fromCharCode(buf[i]);
        }
        return res;
    }
    static ToHex(buffer) {
        const buf = BufferSourceConverter.toUint8Array(buffer);
        let result = "";
        const len = buf.length;
        for (let i = 0; i < len; i++) {
            const byte = buf[i];
            if (byte < 16) {
                result += "0";
            }
            result += byte.toString(16);
        }
        return result;
    }
    static FromHex(hexString) {
        let formatted = this.formatString(hexString);
        if (!formatted) {
            return new ArrayBuffer(0);
        }
        if (!Convert.isHex(formatted)) {
            throw new TypeError("Argument 'hexString' is not HEX encoded");
        }
        if (formatted.length % 2) {
            formatted = `0${formatted}`;
        }
        const res = new Uint8Array(formatted.length / 2);
        for (let i = 0; i < formatted.length; i = i + 2) {
            const c = formatted.slice(i, i + 2);
            res[i / 2] = parseInt(c, 16);
        }
        return res.buffer;
    }
    static ToUtf16String(buffer, littleEndian = false) {
        return Utf16Converter.toString(buffer, littleEndian);
    }
    static FromUtf16String(text, littleEndian = false) {
        return Utf16Converter.fromString(text, littleEndian);
    }
    static Base64Padding(base64) {
        const padCount = 4 - (base64.length % 4);
        if (padCount < 4) {
            for (let i = 0; i < padCount; i++) {
                base64 += "=";
            }
        }
        return base64;
    }
    static formatString(data) {
        return (data === null || data === void 0 ? void 0 : data.replace(/[\n\r\t ]/g, "")) || "";
    }
}
Convert.DEFAULT_UTF8_ENCODING = "utf8";
function combine(...buf) {
    const totalByteLength = buf.map((item) => item.byteLength).reduce((prev, cur) => prev + cur);
    const res = new Uint8Array(totalByteLength);
    let currentPos = 0;
    buf.map((item) => new Uint8Array(item)).forEach((arr) => {
        for (const item2 of arr) {
            res[currentPos++] = item2;
        }
    });
    return res.buffer;
}
function isEqual(bytes1, bytes2) {
    if (!(bytes1 && bytes2)) {
        return false;
    }
    if (bytes1.byteLength !== bytes2.byteLength) {
        return false;
    }
    const b1 = new Uint8Array(bytes1);
    const b2 = new Uint8Array(bytes2);
    for (let i = 0; i < bytes1.byteLength; i++) {
        if (b1[i] !== b2[i]) {
            return false;
        }
    }
    return true;
}

/*!
 Copyright (c) Peculiar Ventures, LLC
*/

function utilFromBase(inputBuffer, inputBase) {
    let result = 0;
    if (inputBuffer.length === 1) {
        return inputBuffer[0];
    }
    for (let i = (inputBuffer.length - 1); i >= 0; i--) {
        result += inputBuffer[(inputBuffer.length - 1) - i] * Math.pow(2, inputBase * i);
    }
    return result;
}
function utilToBase(value, base, reserved = (-1)) {
    const internalReserved = reserved;
    let internalValue = value;
    let result = 0;
    let biggest = Math.pow(2, base);
    for (let i = 1; i < 8; i++) {
        if (value < biggest) {
            let retBuf;
            if (internalReserved < 0) {
                retBuf = new ArrayBuffer(i);
                result = i;
            }
            else {
                if (internalReserved < i) {
                    return (new ArrayBuffer(0));
                }
                retBuf = new ArrayBuffer(internalReserved);
                result = internalReserved;
            }
            const retView = new Uint8Array(retBuf);
            for (let j = (i - 1); j >= 0; j--) {
                const basis = Math.pow(2, j * base);
                retView[result - j - 1] = Math.floor(internalValue / basis);
                internalValue -= (retView[result - j - 1]) * basis;
            }
            return retBuf;
        }
        biggest *= Math.pow(2, base);
    }
    return new ArrayBuffer(0);
}
function utilConcatView(...views) {
    let outputLength = 0;
    let prevLength = 0;
    for (const view of views) {
        outputLength += view.length;
    }
    const retBuf = new ArrayBuffer(outputLength);
    const retView = new Uint8Array(retBuf);
    for (const view of views) {
        retView.set(view, prevLength);
        prevLength += view.length;
    }
    return retView;
}
function utilDecodeTC() {
    const buf = new Uint8Array(this.valueHex);
    if (this.valueHex.byteLength >= 2) {
        const condition1 = (buf[0] === 0xFF) && (buf[1] & 0x80);
        const condition2 = (buf[0] === 0x00) && ((buf[1] & 0x80) === 0x00);
        if (condition1 || condition2) {
            this.warnings.push("Needlessly long format");
        }
    }
    const bigIntBuffer = new ArrayBuffer(this.valueHex.byteLength);
    const bigIntView = new Uint8Array(bigIntBuffer);
    for (let i = 0; i < this.valueHex.byteLength; i++) {
        bigIntView[i] = 0;
    }
    bigIntView[0] = (buf[0] & 0x80);
    const bigInt = utilFromBase(bigIntView, 8);
    const smallIntBuffer = new ArrayBuffer(this.valueHex.byteLength);
    const smallIntView = new Uint8Array(smallIntBuffer);
    for (let j = 0; j < this.valueHex.byteLength; j++) {
        smallIntView[j] = buf[j];
    }
    smallIntView[0] &= 0x7F;
    const smallInt = utilFromBase(smallIntView, 8);
    return (smallInt - bigInt);
}
function utilEncodeTC(value) {
    const modValue = (value < 0) ? (value * (-1)) : value;
    let bigInt = 128;
    for (let i = 1; i < 8; i++) {
        if (modValue <= bigInt) {
            if (value < 0) {
                const smallInt = bigInt - modValue;
                const retBuf = utilToBase(smallInt, 8, i);
                const retView = new Uint8Array(retBuf);
                retView[0] |= 0x80;
                return retBuf;
            }
            let retBuf = utilToBase(modValue, 8, i);
            let retView = new Uint8Array(retBuf);
            if (retView[0] & 0x80) {
                const tempBuf = retBuf.slice(0);
                const tempView = new Uint8Array(tempBuf);
                retBuf = new ArrayBuffer(retBuf.byteLength + 1);
                retView = new Uint8Array(retBuf);
                for (let k = 0; k < tempBuf.byteLength; k++) {
                    retView[k + 1] = tempView[k];
                }
                retView[0] = 0x00;
            }
            return retBuf;
        }
        bigInt *= Math.pow(2, 8);
    }
    return (new ArrayBuffer(0));
}
function isEqualBuffer(inputBuffer1, inputBuffer2) {
    if (inputBuffer1.byteLength !== inputBuffer2.byteLength) {
        return false;
    }
    const view1 = new Uint8Array(inputBuffer1);
    const view2 = new Uint8Array(inputBuffer2);
    for (let i = 0; i < view1.length; i++) {
        if (view1[i] !== view2[i]) {
            return false;
        }
    }
    return true;
}
function padNumber(inputNumber, fullLength) {
    const str = inputNumber.toString(10);
    if (fullLength < str.length) {
        return "";
    }
    const dif = fullLength - str.length;
    const padding = new Array(dif);
    for (let i = 0; i < dif; i++) {
        padding[i] = "0";
    }
    const paddingString = padding.join("");
    return paddingString.concat(str);
}

/*!
 * Copyright (c) 2014, GMO GlobalSign
 * Copyright (c) 2015-2022, Peculiar Ventures
 * All rights reserved.
 * 
 * Author 2014-2019, Yury Strozhevsky
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 * 
 * * Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 * 
 * * Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 */


function assertBigInt() {
    if (typeof BigInt === "undefined") {
        throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.");
    }
}
function concat$1(buffers) {
    let outputLength = 0;
    let prevLength = 0;
    for (let i = 0; i < buffers.length; i++) {
        const buffer = buffers[i];
        outputLength += buffer.byteLength;
    }
    const retView = new Uint8Array(outputLength);
    for (let i = 0; i < buffers.length; i++) {
        const buffer = buffers[i];
        retView.set(new Uint8Array(buffer), prevLength);
        prevLength += buffer.byteLength;
    }
    return retView.buffer;
}
function checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) {
    if (!(inputBuffer instanceof Uint8Array)) {
        baseBlock.error = "Wrong parameter: inputBuffer must be 'Uint8Array'";
        return false;
    }
    if (!inputBuffer.byteLength) {
        baseBlock.error = "Wrong parameter: inputBuffer has zero length";
        return false;
    }
    if (inputOffset < 0) {
        baseBlock.error = "Wrong parameter: inputOffset less than zero";
        return false;
    }
    if (inputLength < 0) {
        baseBlock.error = "Wrong parameter: inputLength less than zero";
        return false;
    }
    if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) {
        baseBlock.error = "End of input reached before message was fully decoded (inconsistent offset and length values)";
        return false;
    }
    return true;
}

class ViewWriter {
    constructor() {
        this.items = [];
    }
    write(buf) {
        this.items.push(buf);
    }
    final() {
        return concat$1(this.items);
    }
}

const powers2 = [new Uint8Array([1])];
const digitsString = "0123456789";
const NAME$1 = "name";
const VALUE_HEX_VIEW = "valueHexView";
const IS_HEX_ONLY = "isHexOnly";
const ID_BLOCK = "idBlock";
const TAG_CLASS = "tagClass";
const TAG_NUMBER = "tagNumber";
const IS_CONSTRUCTED = "isConstructed";
const FROM_BER = "fromBER";
const TO_BER = "toBER";
const LOCAL = "local";
const EMPTY_STRING = "";
const EMPTY_BUFFER = new ArrayBuffer(0);
const EMPTY_VIEW = new Uint8Array(0);
const END_OF_CONTENT_NAME = "EndOfContent";
const OCTET_STRING_NAME = "OCTET STRING";
const BIT_STRING_NAME = "BIT STRING";

function HexBlock(BaseClass) {
    var _a;
    return _a = class Some extends BaseClass {
            get valueHex() {
                return this.valueHexView.slice().buffer;
            }
            set valueHex(value) {
                this.valueHexView = new Uint8Array(value);
            }
            constructor(...args) {
                var _b;
                super(...args);
                const params = args[0] || {};
                this.isHexOnly = (_b = params.isHexOnly) !== null && _b !== void 0 ? _b : false;
                this.valueHexView = params.valueHex ? BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW;
            }
            fromBER(inputBuffer, inputOffset, inputLength) {
                const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;
                if (!checkBufferParams(this, view, inputOffset, inputLength)) {
                    return -1;
                }
                const endLength = inputOffset + inputLength;
                this.valueHexView = view.subarray(inputOffset, endLength);
                if (!this.valueHexView.length) {
                    this.warnings.push("Zero buffer length");
                    return inputOffset;
                }
                this.blockLength = inputLength;
                return endLength;
            }
            toBER(sizeOnly = false) {
                if (!this.isHexOnly) {
                    this.error = "Flag 'isHexOnly' is not set, abort";
                    return EMPTY_BUFFER;
                }
                if (sizeOnly) {
                    return new ArrayBuffer(this.valueHexView.byteLength);
                }
                return (this.valueHexView.byteLength === this.valueHexView.buffer.byteLength)
                    ? this.valueHexView.buffer
                    : this.valueHexView.slice().buffer;
            }
            toJSON() {
                return {
                    ...super.toJSON(),
                    isHexOnly: this.isHexOnly,
                    valueHex: Convert.ToHex(this.valueHexView),
                };
            }
        },
        _a.NAME = "hexBlock",
        _a;
}

class LocalBaseBlock {
    static blockName() {
        return this.NAME;
    }
    get valueBeforeDecode() {
        return this.valueBeforeDecodeView.slice().buffer;
    }
    set valueBeforeDecode(value) {
        this.valueBeforeDecodeView = new Uint8Array(value);
    }
    constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW, } = {}) {
        this.blockLength = blockLength;
        this.error = error;
        this.warnings = warnings;
        this.valueBeforeDecodeView = BufferSourceConverter.toUint8Array(valueBeforeDecode);
    }
    toJSON() {
        return {
            blockName: this.constructor.NAME,
            blockLength: this.blockLength,
            error: this.error,
            warnings: this.warnings,
            valueBeforeDecode: Convert.ToHex(this.valueBeforeDecodeView),
        };
    }
}
LocalBaseBlock.NAME = "baseBlock";

class ValueBlock extends LocalBaseBlock {
    fromBER(_inputBuffer, _inputOffset, _inputLength) {
        throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'");
    }
    toBER(_sizeOnly, _writer) {
        throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'");
    }
}
ValueBlock.NAME = "valueBlock";

class LocalIdentificationBlock extends HexBlock(LocalBaseBlock) {
    constructor({ idBlock = {} } = {}) {
        var _a, _b, _c, _d;
        super();
        if (idBlock) {
            this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false;
            this.valueHexView = idBlock.valueHex
                ? BufferSourceConverter.toUint8Array(idBlock.valueHex)
                : EMPTY_VIEW;
            this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1;
            this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1;
            this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false;
        }
        else {
            this.tagClass = -1;
            this.tagNumber = -1;
            this.isConstructed = false;
        }
    }
    toBER(sizeOnly = false) {
        let firstOctet = 0;
        switch (this.tagClass) {
            case 1:
                firstOctet |= 0x00;
                break;
            case 2:
                firstOctet |= 0x40;
                break;
            case 3:
                firstOctet |= 0x80;
                break;
            case 4:
                firstOctet |= 0xC0;
                break;
            default:
                this.error = "Unknown tag class";
                return EMPTY_BUFFER;
        }
        if (this.isConstructed)
            firstOctet |= 0x20;
        if (this.tagNumber < 31 && !this.isHexOnly) {
            const retView = new Uint8Array(1);
            if (!sizeOnly) {
                let number = this.tagNumber;
                number &= 0x1F;
                firstOctet |= number;
                retView[0] = firstOctet;
            }
            return retView.buffer;
        }
        if (!this.isHexOnly) {
            const encodedBuf = utilToBase(this.tagNumber, 7);
            const encodedView = new Uint8Array(encodedBuf);
            const size = encodedBuf.byteLength;
            const retView = new Uint8Array(size + 1);
            retView[0] = (firstOctet | 0x1F);
            if (!sizeOnly) {
                for (let i = 0; i < (size - 1); i++)
                    retView[i + 1] = encodedView[i] | 0x80;
                retView[size] = encodedView[size - 1];
            }
            return retView.buffer;
        }
        const retView = new Uint8Array(this.valueHexView.byteLength + 1);
        retView[0] = (firstOctet | 0x1F);
        if (!sizeOnly) {
            const curView = this.valueHexView;
            for (let i = 0; i < (curView.length - 1); i++)
                retView[i + 1] = curView[i] | 0x80;
            retView[this.valueHexView.byteLength] = curView[curView.length - 1];
        }
        return retView.buffer;
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        const inputView = BufferSourceConverter.toUint8Array(inputBuffer);
        if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {
            return -1;
        }
        const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);
        if (intBuffer.length === 0) {
            this.error = "Zero buffer length";
            return -1;
        }
        const tagClassMask = intBuffer[0] & 0xC0;
        switch (tagClassMask) {
            case 0x00:
                this.tagClass = (1);
                break;
            case 0x40:
                this.tagClass = (2);
                break;
            case 0x80:
                this.tagClass = (3);
                break;
            case 0xC0:
                this.tagClass = (4);
                break;
            default:
                this.error = "Unknown tag class";
                return -1;
        }
        this.isConstructed = (intBuffer[0] & 0x20) === 0x20;
        this.isHexOnly = false;
        const tagNumberMask = intBuffer[0] & 0x1F;
        if (tagNumberMask !== 0x1F) {
            this.tagNumber = (tagNumberMask);
            this.blockLength = 1;
        }
        else {
            let count = 1;
            let intTagNumberBuffer = this.valueHexView = new Uint8Array(255);
            let tagNumberBufferMaxLength = 255;
            while (intBuffer[count] & 0x80) {
                intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F;
                count++;
                if (count >= intBuffer.length) {
                    this.error = "End of input reached before message was fully decoded";
                    return -1;
                }
                if (count === tagNumberBufferMaxLength) {
                    tagNumberBufferMaxLength += 255;
                    const tempBufferView = new Uint8Array(tagNumberBufferMaxLength);
                    for (let i = 0; i < intTagNumberBuffer.length; i++)
                        tempBufferView[i] = intTagNumberBuffer[i];
                    intTagNumberBuffer = this.valueHexView = new Uint8Array(tagNumberBufferMaxLength);
                }
            }
            this.blockLength = (count + 1);
            intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F;
            const tempBufferView = new Uint8Array(count);
            for (let i = 0; i < count; i++)
                tempBufferView[i] = intTagNumberBuffer[i];
            intTagNumberBuffer = this.valueHexView = new Uint8Array(count);
            intTagNumberBuffer.set(tempBufferView);
            if (this.blockLength <= 9)
                this.tagNumber = utilFromBase(intTagNumberBuffer, 7);
            else {
                this.isHexOnly = true;
                this.warnings.push("Tag too long, represented as hex-coded");
            }
        }
        if (((this.tagClass === 1))
            && (this.isConstructed)) {
            switch (this.tagNumber) {
                case 1:
                case 2:
                case 5:
                case 6:
                case 9:
                case 13:
                case 14:
                case 23:
                case 24:
                case 31:
                case 32:
                case 33:
                case 34:
                    this.error = "Constructed encoding used for primitive type";
                    return -1;
            }
        }
        return (inputOffset + this.blockLength);
    }
    toJSON() {
        return {
            ...super.toJSON(),
            tagClass: this.tagClass,
            tagNumber: this.tagNumber,
            isConstructed: this.isConstructed,
        };
    }
}
LocalIdentificationBlock.NAME = "identificationBlock";

class LocalLengthBlock extends LocalBaseBlock {
    constructor({ lenBlock = {} } = {}) {
        var _a, _b, _c;
        super();
        this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false;
        this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false;
        this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0;
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        const view = BufferSourceConverter.toUint8Array(inputBuffer);
        if (!checkBufferParams(this, view, inputOffset, inputLength)) {
            return -1;
        }
        const intBuffer = view.subarray(inputOffset, inputOffset + inputLength);
        if (intBuffer.length === 0) {
            this.error = "Zero buffer length";
            return -1;
        }
        if (intBuffer[0] === 0xFF) {
            this.error = "Length block 0xFF is reserved by standard";
            return -1;
        }
        this.isIndefiniteForm = intBuffer[0] === 0x80;
        if (this.isIndefiniteForm) {
            this.blockLength = 1;
            return (inputOffset + this.blockLength);
        }
        this.longFormUsed = !!(intBuffer[0] & 0x80);
        if (this.longFormUsed === false) {
            this.length = (intBuffer[0]);
            this.blockLength = 1;
            return (inputOffset + this.blockLength);
        }
        const count = intBuffer[0] & 0x7F;
        if (count > 8) {
            this.error = "Too big integer";
            return -1;
        }
        if ((count + 1) > intBuffer.length) {
            this.error = "End of input reached before message was fully decoded";
            return -1;
        }
        const lenOffset = inputOffset + 1;
        const lengthBufferView = view.subarray(lenOffset, lenOffset + count);
        if (lengthBufferView[count - 1] === 0x00)
            this.warnings.push("Needlessly long encoded length");
        this.length = utilFromBase(lengthBufferView, 8);
        if (this.longFormUsed && (this.length <= 127))
            this.warnings.push("Unnecessary usage of long length form");
        this.blockLength = count + 1;
        return (inputOffset + this.blockLength);
    }
    toBER(sizeOnly = false) {
        let retBuf;
        let retView;
        if (this.length > 127)
            this.longFormUsed = true;
        if (this.isIndefiniteForm) {
            retBuf = new ArrayBuffer(1);
            if (sizeOnly === false) {
                retView = new Uint8Array(retBuf);
                retView[0] = 0x80;
            }
            return retBuf;
        }
        if (this.longFormUsed) {
            const encodedBuf = utilToBase(this.length, 8);
            if (encodedBuf.byteLength > 127) {
                this.error = "Too big length";
                return (EMPTY_BUFFER);
            }
            retBuf = new ArrayBuffer(encodedBuf.byteLength + 1);
            if (sizeOnly)
                return retBuf;
            const encodedView = new Uint8Array(encodedBuf);
            retView = new Uint8Array(retBuf);
            retView[0] = encodedBuf.byteLength | 0x80;
            for (let i = 0; i < encodedBuf.byteLength; i++)
                retView[i + 1] = encodedView[i];
            return retBuf;
        }
        retBuf = new ArrayBuffer(1);
        if (sizeOnly === false) {
            retView = new Uint8Array(retBuf);
            retView[0] = this.length;
        }
        return retBuf;
    }
    toJSON() {
        return {
            ...super.toJSON(),
            isIndefiniteForm: this.isIndefiniteForm,
            longFormUsed: this.longFormUsed,
            length: this.length,
        };
    }
}
LocalLengthBlock.NAME = "lengthBlock";

const typeStore = {};

class BaseBlock extends LocalBaseBlock {
    constructor({ name = EMPTY_STRING, optional = false, primitiveSchema, ...parameters } = {}, valueBlockType) {
        super(parameters);
        this.name = name;
        this.optional = optional;
        if (primitiveSchema) {
            this.primitiveSchema = primitiveSchema;
        }
        this.idBlock = new LocalIdentificationBlock(parameters);
        this.lenBlock = new LocalLengthBlock(parameters);
        this.valueBlock = valueBlockType ? new valueBlockType(parameters) : new ValueBlock(parameters);
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm)
            ? inputLength
            : this.lenBlock.length);
        if (resultOffset === -1) {
            this.error = this.valueBlock.error;
            return resultOffset;
        }
        if (!this.idBlock.error.length)
            this.blockLength += this.idBlock.blockLength;
        if (!this.lenBlock.error.length)
            this.blockLength += this.lenBlock.blockLength;
        if (!this.valueBlock.error.length)
            this.blockLength += this.valueBlock.blockLength;
        return resultOffset;
    }
    toBER(sizeOnly, writer) {
        const _writer = writer || new ViewWriter();
        if (!writer) {
            prepareIndefiniteForm(this);
        }
        const idBlockBuf = this.idBlock.toBER(sizeOnly);
        _writer.write(idBlockBuf);
        if (this.lenBlock.isIndefiniteForm) {
            _writer.write(new Uint8Array([0x80]).buffer);
            this.valueBlock.toBER(sizeOnly, _writer);
            _writer.write(new ArrayBuffer(2));
        }
        else {
            const valueBlockBuf = this.valueBlock.toBER(sizeOnly);
            this.lenBlock.length = valueBlockBuf.byteLength;
            const lenBlockBuf = this.lenBlock.toBER(sizeOnly);
            _writer.write(lenBlockBuf);
            _writer.write(valueBlockBuf);
        }
        if (!writer) {
            return _writer.final();
        }
        return EMPTY_BUFFER;
    }
    toJSON() {
        const object = {
            ...super.toJSON(),
            idBlock: this.idBlock.toJSON(),
            lenBlock: this.lenBlock.toJSON(),
            valueBlock: this.valueBlock.toJSON(),
            name: this.name,
            optional: this.optional,
        };
        if (this.primitiveSchema)
            object.primitiveSchema = this.primitiveSchema.toJSON();
        return object;
    }
    toString(encoding = "ascii") {
        if (encoding === "ascii") {
            return this.onAsciiEncoding();
        }
        return Convert.ToHex(this.toBER());
    }
    onAsciiEncoding() {
        const name = this.constructor.NAME;
        const value = Convert.ToHex(this.valueBlock.valueBeforeDecodeView);
        return `${name} : ${value}`;
    }
    isEqual(other) {
        if (this === other) {
            return true;
        }
        if (!(other instanceof this.constructor)) {
            return false;
        }
        const thisRaw = this.toBER();
        const otherRaw = other.toBER();
        return isEqualBuffer(thisRaw, otherRaw);
    }
}
BaseBlock.NAME = "BaseBlock";
function prepareIndefiniteForm(baseBlock) {
    var _a;
    if (baseBlock instanceof typeStore.Constructed) {
        for (const value of baseBlock.valueBlock.value) {
            if (prepareIndefiniteForm(value)) {
                baseBlock.lenBlock.isIndefiniteForm = true;
            }
        }
    }
    return !!((_a = baseBlock.lenBlock) === null || _a === void 0 ? void 0 : _a.isIndefiniteForm);
}

class BaseStringBlock extends BaseBlock {
    getValue() {
        return this.valueBlock.value;
    }
    setValue(value) {
        this.valueBlock.value = value;
    }
    constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) {
        super(parameters, stringValueBlockType);
        if (value) {
            this.fromString(value);
        }
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm)
            ? inputLength
            : this.lenBlock.length);
        if (resultOffset === -1) {
            this.error = this.valueBlock.error;
            return resultOffset;
        }
        this.fromBuffer(this.valueBlock.valueHexView);
        if (!this.idBlock.error.length)
            this.blockLength += this.idBlock.blockLength;
        if (!this.lenBlock.error.length)
            this.blockLength += this.lenBlock.blockLength;
        if (!this.valueBlock.error.length)
            this.blockLength += this.valueBlock.blockLength;
        return resultOffset;
    }
    onAsciiEncoding() {
        return `${this.constructor.NAME} : '${this.valueBlock.value}'`;
    }
}
BaseStringBlock.NAME = "BaseStringBlock";

class LocalPrimitiveValueBlock extends HexBlock(ValueBlock) {
    constructor({ isHexOnly = true, ...parameters } = {}) {
        super(parameters);
        this.isHexOnly = isHexOnly;
    }
}
LocalPrimitiveValueBlock.NAME = "PrimitiveValueBlock";

var _a$w;
class Primitive extends BaseBlock {
    constructor(parameters = {}) {
        super(parameters, LocalPrimitiveValueBlock);
        this.idBlock.isConstructed = false;
    }
}
_a$w = Primitive;
(() => {
    typeStore.Primitive = _a$w;
})();
Primitive.NAME = "PRIMITIVE";

function localChangeType(inputObject, newType) {
    if (inputObject instanceof newType) {
        return inputObject;
    }
    const newObject = new newType();
    newObject.idBlock = inputObject.idBlock;
    newObject.lenBlock = inputObject.lenBlock;
    newObject.warnings = inputObject.warnings;
    newObject.valueBeforeDecodeView = inputObject.valueBeforeDecodeView;
    return newObject;
}
function localFromBER(inputBuffer, inputOffset = 0, inputLength = inputBuffer.length) {
    const incomingOffset = inputOffset;
    let returnObject = new BaseBlock({}, ValueBlock);
    const baseBlock = new LocalBaseBlock();
    if (!checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength)) {
        returnObject.error = baseBlock.error;
        return {
            offset: -1,
            result: returnObject,
        };
    }
    const intBuffer = inputBuffer.subarray(inputOffset, inputOffset + inputLength);
    if (!intBuffer.length) {
        returnObject.error = "Zero buffer length";
        return {
            offset: -1,
            result: returnObject,
        };
    }
    let resultOffset = returnObject.idBlock.fromBER(inputBuffer, inputOffset, inputLength);
    if (returnObject.idBlock.warnings.length) {
        returnObject.warnings.concat(returnObject.idBlock.warnings);
    }
    if (resultOffset === -1) {
        returnObject.error = returnObject.idBlock.error;
        return {
            offset: -1,
            result: returnObject,
        };
    }
    inputOffset = resultOffset;
    inputLength -= returnObject.idBlock.blockLength;
    resultOffset = returnObject.lenBlock.fromBER(inputBuffer, inputOffset, inputLength);
    if (returnObject.lenBlock.warnings.length) {
        returnObject.warnings.concat(returnObject.lenBlock.warnings);
    }
    if (resultOffset === -1) {
        returnObject.error = returnObject.lenBlock.error;
        return {
            offset: -1,
            result: returnObject,
        };
    }
    inputOffset = resultOffset;
    inputLength -= returnObject.lenBlock.blockLength;
    if (!returnObject.idBlock.isConstructed
        && returnObject.lenBlock.isIndefiniteForm) {
        returnObject.error = "Indefinite length form used for primitive encoding form";
        return {
            offset: -1,
            result: returnObject,
        };
    }
    let newASN1Type = BaseBlock;
    switch (returnObject.idBlock.tagClass) {
        case 1:
            if ((returnObject.idBlock.tagNumber >= 37)
                && (returnObject.idBlock.isHexOnly === false)) {
                returnObject.error = "UNIVERSAL 37 and upper tags are reserved by ASN.1 standard";
                return {
                    offset: -1,
                    result: returnObject,
                };
            }
            switch (returnObject.idBlock.tagNumber) {
                case 0:
                    if ((returnObject.idBlock.isConstructed)
                        && (returnObject.lenBlock.length > 0)) {
                        returnObject.error = "Type [UNIVERSAL 0] is reserved";
                        return {
                            offset: -1,
                            result: returnObject,
                        };
                    }
                    newASN1Type = typeStore.EndOfContent;
                    break;
                case 1:
                    newASN1Type = typeStore.Boolean;
                    break;
                case 2:
                    newASN1Type = typeStore.Integer;
                    break;
                case 3:
                    newASN1Type = typeStore.BitString;
                    break;
                case 4:
                    newASN1Type = typeStore.OctetString;
                    break;
                case 5:
                    newASN1Type = typeStore.Null;
                    break;
                case 6:
                    newASN1Type = typeStore.ObjectIdentifier;
                    break;
                case 10:
                    newASN1Type = typeStore.Enumerated;
                    break;
                case 12:
                    newASN1Type = typeStore.Utf8String;
                    break;
                case 13:
                    newASN1Type = typeStore.RelativeObjectIdentifier;
                    break;
                case 14:
                    newASN1Type = typeStore.TIME;
                    break;
                case 15:
                    returnObject.error = "[UNIVERSAL 15] is reserved by ASN.1 standard";
                    return {
                        offset: -1,
                        result: returnObject,
                    };
                case 16:
                    newASN1Type = typeStore.Sequence;
                    break;
                case 17:
                    newASN1Type = typeStore.Set;
                    break;
                case 18:
                    newASN1Type = typeStore.NumericString;
                    break;
                case 19:
                    newASN1Type = typeStore.PrintableString;
                    break;
                case 20:
                    newASN1Type = typeStore.TeletexString;
                    break;
                case 21:
                    newASN1Type = typeStore.VideotexString;
                    break;
                case 22:
                    newASN1Type = typeStore.IA5String;
                    break;
                case 23:
                    newASN1Type = typeStore.UTCTime;
                    break;
                case 24:
                    newASN1Type = typeStore.GeneralizedTime;
                    break;
                case 25:
                    newASN1Type = typeStore.GraphicString;
                    break;
                case 26:
                    newASN1Type = typeStore.VisibleString;
                    break;
                case 27:
                    newASN1Type = typeStore.GeneralString;
                    break;
                case 28:
                    newASN1Type = typeStore.UniversalString;
                    break;
                case 29:
                    newASN1Type = typeStore.CharacterString;
                    break;
                case 30:
                    newASN1Type = typeStore.BmpString;
                    break;
                case 31:
                    newASN1Type = typeStore.DATE;
                    break;
                case 32:
                    newASN1Type = typeStore.TimeOfDay;
                    break;
                case 33:
                    newASN1Type = typeStore.DateTime;
                    break;
                case 34:
                    newASN1Type = typeStore.Duration;
                    break;
                default: {
                    const newObject = returnObject.idBlock.isConstructed
                        ? new typeStore.Constructed()
                        : new typeStore.Primitive();
                    newObject.idBlock = returnObject.idBlock;
                    newObject.lenBlock = returnObject.lenBlock;
                    newObject.warnings = returnObject.warnings;
                    returnObject = newObject;
                }
            }
            break;
        case 2:
        case 3:
        case 4:
        default: {
            newASN1Type = returnObject.idBlock.isConstructed
                ? typeStore.Constructed
                : typeStore.Primitive;
        }
    }
    returnObject = localChangeType(returnObject, newASN1Type);
    resultOffset = returnObject.fromBER(inputBuffer, inputOffset, returnObject.lenBlock.isIndefiniteForm ? inputLength : returnObject.lenBlock.length);
    returnObject.valueBeforeDecodeView = inputBuffer.subarray(incomingOffset, incomingOffset + returnObject.blockLength);
    return {
        offset: resultOffset,
        result: returnObject,
    };
}
function fromBER(inputBuffer) {
    if (!inputBuffer.byteLength) {
        const result = new BaseBlock({}, ValueBlock);
        result.error = "Input buffer has zero length";
        return {
            offset: -1,
            result,
        };
    }
    return localFromBER(BufferSourceConverter.toUint8Array(inputBuffer).slice(), 0, inputBuffer.byteLength);
}

function checkLen(indefiniteLength, length) {
    if (indefiniteLength) {
        return 1;
    }
    return length;
}
class LocalConstructedValueBlock extends ValueBlock {
    constructor({ value = [], isIndefiniteForm = false, ...parameters } = {}) {
        super(parameters);
        this.value = value;
        this.isIndefiniteForm = isIndefiniteForm;
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        const view = BufferSourceConverter.toUint8Array(inputBuffer);
        if (!checkBufferParams(this, view, inputOffset, inputLength)) {
            return -1;
        }
        this.valueBeforeDecodeView = view.subarray(inputOffset, inputOffset + inputLength);
        if (this.valueBeforeDecodeView.length === 0) {
            this.warnings.push("Zero buffer length");
            return inputOffset;
        }
        let currentOffset = inputOffset;
        while (checkLen(this.isIndefiniteForm, inputLength) > 0) {
            const returnObject = localFromBER(view, currentOffset, inputLength);
            if (returnObject.offset === -1) {
                this.error = returnObject.result.error;
                this.warnings.concat(returnObject.result.warnings);
                return -1;
            }
            currentOffset = returnObject.offset;
            this.blockLength += returnObject.result.blockLength;
            inputLength -= returnObject.result.blockLength;
            this.value.push(returnObject.result);
            if (this.isIndefiniteForm && returnObject.result.constructor.NAME === END_OF_CONTENT_NAME) {
                break;
            }
        }
        if (this.isIndefiniteForm) {
            if (this.value[this.value.length - 1].constructor.NAME === END_OF_CONTENT_NAME) {
                this.value.pop();
            }
            else {
                this.warnings.push("No EndOfContent block encoded");
            }
        }
        return currentOffset;
    }
    toBER(sizeOnly, writer) {
        const _writer = writer || new ViewWriter();
        for (let i = 0; i < this.value.length; i++) {
            this.value[i].toBER(sizeOnly, _writer);
        }
        if (!writer) {
            return _writer.final();
        }
        return EMPTY_BUFFER;
    }
    toJSON() {
        const object = {
            ...super.toJSON(),
            isIndefiniteForm: this.isIndefiniteForm,
            value: [],
        };
        for (const value of this.value) {
            object.value.push(value.toJSON());
        }
        return object;
    }
}
LocalConstructedValueBlock.NAME = "ConstructedValueBlock";

var _a$v;
class Constructed extends BaseBlock {
    constructor(parameters = {}) {
        super(parameters, LocalConstructedValueBlock);
        this.idBlock.isConstructed = true;
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;
        const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);
        if (resultOffset === -1) {
            this.error = this.valueBlock.error;
            return resultOffset;
        }
        if (!this.idBlock.error.length)
            this.blockLength += this.idBlock.blockLength;
        if (!this.lenBlock.error.length)
            this.blockLength += this.lenBlock.blockLength;
        if (!this.valueBlock.error.length)
            this.blockLength += this.valueBlock.blockLength;
        return resultOffset;
    }
    onAsciiEncoding() {
        const values = [];
        for (const value of this.valueBlock.value) {
            values.push(value.toString("ascii").split("\n").map((o) => `  ${o}`).join("\n"));
        }
        const blockName = this.idBlock.tagClass === 3
            ? `[${this.idBlock.tagNumber}]`
            : this.constructor.NAME;
        return values.length
            ? `${blockName} :\n${values.join("\n")}`
            : `${blockName} :`;
    }
}
_a$v = Constructed;
(() => {
    typeStore.Constructed = _a$v;
})();
Constructed.NAME = "CONSTRUCTED";

class LocalEndOfContentValueBlock extends ValueBlock {
    fromBER(inputBuffer, inputOffset, _inputLength) {
        return inputOffset;
    }
    toBER(_sizeOnly) {
        return EMPTY_BUFFER;
    }
}
LocalEndOfContentValueBlock.override = "EndOfContentValueBlock";

var _a$u;
class EndOfContent extends BaseBlock {
    constructor(parameters = {}) {
        super(parameters, LocalEndOfContentValueBlock);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 0;
    }
}
_a$u = EndOfContent;
(() => {
    typeStore.EndOfContent = _a$u;
})();
EndOfContent.NAME = END_OF_CONTENT_NAME;

var _a$t;
class Null extends BaseBlock {
    constructor(parameters = {}) {
        super(parameters, ValueBlock);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 5;
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        if (this.lenBlock.length > 0)
            this.warnings.push("Non-zero length of value block for Null type");
        if (!this.idBlock.error.length)
            this.blockLength += this.idBlock.blockLength;
        if (!this.lenBlock.error.length)
            this.blockLength += this.lenBlock.blockLength;
        this.blockLength += inputLength;
        if ((inputOffset + inputLength) > inputBuffer.byteLength) {
            this.error = "End of input reached before message was fully decoded (inconsistent offset and length values)";
            return -1;
        }
        return (inputOffset + inputLength);
    }
    toBER(sizeOnly, writer) {
        const retBuf = new ArrayBuffer(2);
        if (!sizeOnly) {
            const retView = new Uint8Array(retBuf);
            retView[0] = 0x05;
            retView[1] = 0x00;
        }
        if (writer) {
            writer.write(retBuf);
        }
        return retBuf;
    }
    onAsciiEncoding() {
        return `${this.constructor.NAME}`;
    }
}
_a$t = Null;
(() => {
    typeStore.Null = _a$t;
})();
Null.NAME = "NULL";

class LocalBooleanValueBlock extends HexBlock(ValueBlock) {
    get value() {
        for (const octet of this.valueHexView) {
            if (octet > 0) {
                return true;
            }
        }
        return false;
    }
    set value(value) {
        this.valueHexView[0] = value ? 0xFF : 0x00;
    }
    constructor({ value, ...parameters } = {}) {
        super(parameters);
        if (parameters.valueHex) {
            this.valueHexView = BufferSourceConverter.toUint8Array(parameters.valueHex);
        }
        else {
            this.valueHexView = new Uint8Array(1);
        }
        if (value) {
            this.value = value;
        }
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        const inputView = BufferSourceConverter.toUint8Array(inputBuffer);
        if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {
            return -1;
        }
        this.valueHexView = inputView.subarray(inputOffset, inputOffset + inputLength);
        if (inputLength > 1)
            this.warnings.push("Boolean value encoded in more then 1 octet");
        this.isHexOnly = true;
        utilDecodeTC.call(this);
        this.blockLength = inputLength;
        return (inputOffset + inputLength);
    }
    toBER() {
        return this.valueHexView.slice();
    }
    toJSON() {
        return {
            ...super.toJSON(),
            value: this.value,
        };
    }
}
LocalBooleanValueBlock.NAME = "BooleanValueBlock";

var _a$s;
let Boolean$1 = class Boolean extends BaseBlock {
    getValue() {
        return this.valueBlock.value;
    }
    setValue(value) {
        this.valueBlock.value = value;
    }
    constructor(parameters = {}) {
        super(parameters, LocalBooleanValueBlock);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 1;
    }
    onAsciiEncoding() {
        return `${this.constructor.NAME} : ${this.getValue}`;
    }
};
_a$s = Boolean$1;
(() => {
    typeStore.Boolean = _a$s;
})();
Boolean$1.NAME = "BOOLEAN";

class LocalOctetStringValueBlock extends HexBlock(LocalConstructedValueBlock) {
    constructor({ isConstructed = false, ...parameters } = {}) {
        super(parameters);
        this.isConstructed = isConstructed;
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        let resultOffset = 0;
        if (this.isConstructed) {
            this.isHexOnly = false;
            resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);
            if (resultOffset === -1)
                return resultOffset;
            for (let i = 0; i < this.value.length; i++) {
                const currentBlockName = this.value[i].constructor.NAME;
                if (currentBlockName === END_OF_CONTENT_NAME) {
                    if (this.isIndefiniteForm)
                        break;
                    else {
                        this.error = "EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only";
                        return -1;
                    }
                }
                if (currentBlockName !== OCTET_STRING_NAME) {
                    this.error = "OCTET STRING may consists of OCTET STRINGs only";
                    return -1;
                }
            }
        }
        else {
            this.isHexOnly = true;
            resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);
            this.blockLength = inputLength;
        }
        return resultOffset;
    }
    toBER(sizeOnly, writer) {
        if (this.isConstructed)
            return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);
        return sizeOnly
            ? new ArrayBuffer(this.valueHexView.byteLength)
            : this.valueHexView.slice().buffer;
    }
    toJSON() {
        return {
            ...super.toJSON(),
            isConstructed: this.isConstructed,
        };
    }
}
LocalOctetStringValueBlock.NAME = "OctetStringValueBlock";

var _a$r;
let OctetString$1 = class OctetString extends BaseBlock {
    constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
        var _b, _c;
        (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));
        super({
            idBlock: {
                isConstructed: parameters.isConstructed,
                ...idBlock,
            },
            lenBlock: {
                ...lenBlock,
                isIndefiniteForm: !!parameters.isIndefiniteForm,
            },
            ...parameters,
        }, LocalOctetStringValueBlock);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 4;
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        this.valueBlock.isConstructed = this.idBlock.isConstructed;
        this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;
        if (inputLength === 0) {
            if (this.idBlock.error.length === 0)
                this.blockLength += this.idBlock.blockLength;
            if (this.lenBlock.error.length === 0)
                this.blockLength += this.lenBlock.blockLength;
            return inputOffset;
        }
        if (!this.valueBlock.isConstructed) {
            const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;
            const buf = view.subarray(inputOffset, inputOffset + inputLength);
            try {
                if (buf.byteLength) {
                    const asn = localFromBER(buf, 0, buf.byteLength);
                    if (asn.offset !== -1 && asn.offset === inputLength) {
                        this.valueBlock.value = [asn.result];
                    }
                }
            }
            catch {
            }
        }
        return super.fromBER(inputBuffer, inputOffset, inputLength);
    }
    onAsciiEncoding() {
        if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) {
            return Constructed.prototype.onAsciiEncoding.call(this);
        }
        const name = this.constructor.NAME;
        const value = Convert.ToHex(this.valueBlock.valueHexView);
        return `${name} : ${value}`;
    }
    getValue() {
        if (!this.idBlock.isConstructed) {
            return this.valueBlock.valueHexView.slice().buffer;
        }
        const array = [];
        for (const content of this.valueBlock.value) {
            if (content instanceof _a$r) {
                array.push(content.valueBlock.valueHexView);
            }
        }
        return BufferSourceConverter.concat(array);
    }
};
_a$r = OctetString$1;
(() => {
    typeStore.OctetString = _a$r;
})();
OctetString$1.NAME = OCTET_STRING_NAME;

class LocalBitStringValueBlock extends HexBlock(LocalConstructedValueBlock) {
    constructor({ unusedBits = 0, isConstructed = false, ...parameters } = {}) {
        super(parameters);
        this.unusedBits = unusedBits;
        this.isConstructed = isConstructed;
        this.blockLength = this.valueHexView.byteLength;
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        if (!inputLength) {
            return inputOffset;
        }
        let resultOffset = -1;
        if (this.isConstructed) {
            resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);
            if (resultOffset === -1)
                return resultOffset;
            for (const value of this.value) {
                const currentBlockName = value.constructor.NAME;
                if (currentBlockName === END_OF_CONTENT_NAME) {
                    if (this.isIndefiniteForm)
                        break;
                    else {
                        this.error = "EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only";
                        return -1;
                    }
                }
                if (currentBlockName !== BIT_STRING_NAME) {
                    this.error = "BIT STRING may consists of BIT STRINGs only";
                    return -1;
                }
                const valueBlock = value.valueBlock;
                if ((this.unusedBits > 0) && (valueBlock.unusedBits > 0)) {
                    this.error = "Using of \"unused bits\" inside constructive BIT STRING allowed for least one only";
                    return -1;
                }
                this.unusedBits = valueBlock.unusedBits;
            }
            return resultOffset;
        }
        const inputView = BufferSourceConverter.toUint8Array(inputBuffer);
        if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {
            return -1;
        }
        const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);
        this.unusedBits = intBuffer[0];
        if (this.unusedBits > 7) {
            this.error = "Unused bits for BitString must be in range 0-7";
            return -1;
        }
        if (!this.unusedBits) {
            const buf = intBuffer.subarray(1);
            try {
                if (buf.byteLength) {
                    const asn = localFromBER(buf, 0, buf.byteLength);
                    if (asn.offset !== -1 && asn.offset === (inputLength - 1)) {
                        this.value = [asn.result];
                    }
                }
            }
            catch {
            }
        }
        this.valueHexView = intBuffer.subarray(1);
        this.blockLength = intBuffer.length;
        return (inputOffset + inputLength);
    }
    toBER(sizeOnly, writer) {
        if (this.isConstructed) {
            return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);
        }
        if (sizeOnly) {
            return new ArrayBuffer(this.valueHexView.byteLength + 1);
        }
        if (!this.valueHexView.byteLength) {
            return EMPTY_BUFFER;
        }
        const retView = new Uint8Array(this.valueHexView.length + 1);
        retView[0] = this.unusedBits;
        retView.set(this.valueHexView, 1);
        return retView.buffer;
    }
    toJSON() {
        return {
            ...super.toJSON(),
            unusedBits: this.unusedBits,
            isConstructed: this.isConstructed,
        };
    }
}
LocalBitStringValueBlock.NAME = "BitStringValueBlock";

var _a$q;
let BitString$1 = class BitString extends BaseBlock {
    constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
        var _b, _c;
        (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));
        super({
            idBlock: {
                isConstructed: parameters.isConstructed,
                ...idBlock,
            },
            lenBlock: {
                ...lenBlock,
                isIndefiniteForm: !!parameters.isIndefiniteForm,
            },
            ...parameters,
        }, LocalBitStringValueBlock);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 3;
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        this.valueBlock.isConstructed = this.idBlock.isConstructed;
        this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;
        return super.fromBER(inputBuffer, inputOffset, inputLength);
    }
    onAsciiEncoding() {
        if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) {
            return Constructed.prototype.onAsciiEncoding.call(this);
        }
        else {
            const bits = [];
            const valueHex = this.valueBlock.valueHexView;
            for (const byte of valueHex) {
                bits.push(byte.toString(2).padStart(8, "0"));
            }
            const bitsStr = bits.join("");
            const name = this.constructor.NAME;
            const value = bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits);
            return `${name} : ${value}`;
        }
    }
};
_a$q = BitString$1;
(() => {
    typeStore.BitString = _a$q;
})();
BitString$1.NAME = BIT_STRING_NAME;

var _a$p;
function viewAdd(first, second) {
    const c = new Uint8Array([0]);
    const firstView = new Uint8Array(first);
    const secondView = new Uint8Array(second);
    let firstViewCopy = firstView.slice(0);
    const firstViewCopyLength = firstViewCopy.length - 1;
    const secondViewCopy = secondView.slice(0);
    const secondViewCopyLength = secondViewCopy.length - 1;
    let value = 0;
    const max = (secondViewCopyLength < firstViewCopyLength) ? firstViewCopyLength : secondViewCopyLength;
    let counter = 0;
    for (let i = max; i >= 0; i--, counter++) {
        switch (true) {
            case (counter < secondViewCopy.length):
                value = firstViewCopy[firstViewCopyLength - counter] + secondViewCopy[secondViewCopyLength - counter] + c[0];
                break;
            default:
                value = firstViewCopy[firstViewCopyLength - counter] + c[0];
        }
        c[0] = value / 10;
        switch (true) {
            case (counter >= firstViewCopy.length):
                firstViewCopy = utilConcatView(new Uint8Array([value % 10]), firstViewCopy);
                break;
            default:
                firstViewCopy[firstViewCopyLength - counter] = value % 10;
        }
    }
    if (c[0] > 0)
        firstViewCopy = utilConcatView(c, firstViewCopy);
    return firstViewCopy;
}
function power2(n) {
    if (n >= powers2.length) {
        for (let p = powers2.length; p <= n; p++) {
            const c = new Uint8Array([0]);
            let digits = (powers2[p - 1]).slice(0);
            for (let i = (digits.length - 1); i >= 0; i--) {
                const newValue = new Uint8Array([(digits[i] << 1) + c[0]]);
                c[0] = newValue[0] / 10;
                digits[i] = newValue[0] % 10;
            }
            if (c[0] > 0)
                digits = utilConcatView(c, digits);
            powers2.push(digits);
        }
    }
    return powers2[n];
}
function viewSub(first, second) {
    let b = 0;
    const firstView = new Uint8Array(first);
    const secondView = new Uint8Array(second);
    const firstViewCopy = firstView.slice(0);
    const firstViewCopyLength = firstViewCopy.length - 1;
    const secondViewCopy = secondView.slice(0);
    const secondViewCopyLength = secondViewCopy.length - 1;
    let value;
    let counter = 0;
    for (let i = secondViewCopyLength; i >= 0; i--, counter++) {
        value = firstViewCopy[firstViewCopyLength - counter] - secondViewCopy[secondViewCopyLength - counter] - b;
        switch (true) {
            case (value < 0):
                b = 1;
                firstViewCopy[firstViewCopyLength - counter] = value + 10;
                break;
            default:
                b = 0;
                firstViewCopy[firstViewCopyLength - counter] = value;
        }
    }
    if (b > 0) {
        for (let i = (firstViewCopyLength - secondViewCopyLength + 1); i >= 0; i--, counter++) {
            value = firstViewCopy[firstViewCopyLength - counter] - b;
            if (value < 0) {
                b = 1;
                firstViewCopy[firstViewCopyLength - counter] = value + 10;
            }
            else {
                b = 0;
                firstViewCopy[firstViewCopyLength - counter] = value;
                break;
            }
        }
    }
    return firstViewCopy.slice();
}
class LocalIntegerValueBlock extends HexBlock(ValueBlock) {
    setValueHex() {
        if (this.valueHexView.length >= 4) {
            this.warnings.push("Too big Integer for decoding, hex only");
            this.isHexOnly = true;
            this._valueDec = 0;
        }
        else {
            this.isHexOnly = false;
            if (this.valueHexView.length > 0) {
                this._valueDec = utilDecodeTC.call(this);
            }
        }
    }
    constructor({ value, ...parameters } = {}) {
        super(parameters);
        this._valueDec = 0;
        if (parameters.valueHex) {
            this.setValueHex();
        }
        if (value !== undefined) {
            this.valueDec = value;
        }
    }
    set valueDec(v) {
        this._valueDec = v;
        this.isHexOnly = false;
        this.valueHexView = new Uint8Array(utilEncodeTC(v));
    }
    get valueDec() {
        return this._valueDec;
    }
    fromDER(inputBuffer, inputOffset, inputLength, expectedLength = 0) {
        const offset = this.fromBER(inputBuffer, inputOffset, inputLength);
        if (offset === -1)
            return offset;
        const view = this.valueHexView;
        if ((view[0] === 0x00) && ((view[1] & 0x80) !== 0)) {
            this.valueHexView = view.subarray(1);
        }
        else {
            if (expectedLength !== 0) {
                if (view.length < expectedLength) {
                    if ((expectedLength - view.length) > 1)
                        expectedLength = view.length + 1;
                    this.valueHexView = view.subarray(expectedLength - view.length);
                }
            }
        }
        return offset;
    }
    toDER(sizeOnly = false) {
        const view = this.valueHexView;
        switch (true) {
            case ((view[0] & 0x80) !== 0):
                {
                    const updatedView = new Uint8Array(this.valueHexView.length + 1);
                    updatedView[0] = 0x00;
                    updatedView.set(view, 1);
                    this.valueHexView = updatedView;
                }
                break;
            case ((view[0] === 0x00) && ((view[1] & 0x80) === 0)):
                {
                    this.valueHexView = this.valueHexView.subarray(1);
                }
                break;
        }
        return this.toBER(sizeOnly);
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        const resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);
        if (resultOffset === -1) {
            return resultOffset;
        }
        this.setValueHex();
        return resultOffset;
    }
    toBER(sizeOnly) {
        return sizeOnly
            ? new ArrayBuffer(this.valueHexView.length)
            : this.valueHexView.slice().buffer;
    }
    toJSON() {
        return {
            ...super.toJSON(),
            valueDec: this.valueDec,
        };
    }
    toString() {
        const firstBit = (this.valueHexView.length * 8) - 1;
        let digits = new Uint8Array((this.valueHexView.length * 8) / 3);
        let bitNumber = 0;
        let currentByte;
        const asn1View = this.valueHexView;
        let result = "";
        let flag = false;
        for (let byteNumber = (asn1View.byteLength - 1); byteNumber >= 0; byteNumber--) {
            currentByte = asn1View[byteNumber];
            for (let i = 0; i < 8; i++) {
                if ((currentByte & 1) === 1) {
                    switch (bitNumber) {
                        case firstBit:
                            digits = viewSub(power2(bitNumber), digits);
                            result = "-";
                            break;
                        default:
                            digits = viewAdd(digits, power2(bitNumber));
                    }
                }
                bitNumber++;
                currentByte >>= 1;
            }
        }
        for (let i = 0; i < digits.length; i++) {
            if (digits[i])
                flag = true;
            if (flag)
                result += digitsString.charAt(digits[i]);
        }
        if (flag === false)
            result += digitsString.charAt(0);
        return result;
    }
}
_a$p = LocalIntegerValueBlock;
LocalIntegerValueBlock.NAME = "IntegerValueBlock";
(() => {
    Object.defineProperty(_a$p.prototype, "valueHex", {
        set: function (v) {
            this.valueHexView = new Uint8Array(v);
            this.setValueHex();
        },
        get: function () {
            return this.valueHexView.slice().buffer;
        },
    });
})();

var _a$o;
class Integer extends BaseBlock {
    constructor(parameters = {}) {
        super(parameters, LocalIntegerValueBlock);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 2;
    }
    toBigInt() {
        assertBigInt();
        return BigInt(this.valueBlock.toString());
    }
    static fromBigInt(value) {
        assertBigInt();
        const bigIntValue = BigInt(value);
        const writer = new ViewWriter();
        const hex = bigIntValue.toString(16).replace(/^-/, "");
        const view = new Uint8Array(Convert.FromHex(hex));
        if (bigIntValue < 0) {
            const first = new Uint8Array(view.length + (view[0] & 0x80 ? 1 : 0));
            first[0] |= 0x80;
            const firstInt = BigInt(`0x${Convert.ToHex(first)}`);
            const secondInt = firstInt + bigIntValue;
            const second = BufferSourceConverter.toUint8Array(Convert.FromHex(secondInt.toString(16)));
            second[0] |= 0x80;
            writer.write(second);
        }
        else {
            if (view[0] & 0x80) {
                writer.write(new Uint8Array([0]));
            }
            writer.write(view);
        }
        const res = new _a$o({ valueHex: writer.final() });
        return res;
    }
    convertToDER() {
        const integer = new _a$o({ valueHex: this.valueBlock.valueHexView });
        integer.valueBlock.toDER();
        return integer;
    }
    convertFromDER() {
        return new _a$o({
            valueHex: this.valueBlock.valueHexView[0] === 0
                ? this.valueBlock.valueHexView.subarray(1)
                : this.valueBlock.valueHexView,
        });
    }
    onAsciiEncoding() {
        return `${this.constructor.NAME} : ${this.valueBlock.toString()}`;
    }
}
_a$o = Integer;
(() => {
    typeStore.Integer = _a$o;
})();
Integer.NAME = "INTEGER";

var _a$n;
class Enumerated extends Integer {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 10;
    }
}
_a$n = Enumerated;
(() => {
    typeStore.Enumerated = _a$n;
})();
Enumerated.NAME = "ENUMERATED";

class LocalSidValueBlock extends HexBlock(ValueBlock) {
    constructor({ valueDec = -1, isFirstSid = false, ...parameters } = {}) {
        super(parameters);
        this.valueDec = valueDec;
        this.isFirstSid = isFirstSid;
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        if (!inputLength) {
            return inputOffset;
        }
        const inputView = BufferSourceConverter.toUint8Array(inputBuffer);
        if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {
            return -1;
        }
        const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);
        this.valueHexView = new Uint8Array(inputLength);
        for (let i = 0; i < inputLength; i++) {
            this.valueHexView[i] = intBuffer[i] & 0x7F;
            this.blockLength++;
            if ((intBuffer[i] & 0x80) === 0x00)
                break;
        }
        const tempView = new Uint8Array(this.blockLength);
        for (let i = 0; i < this.blockLength; i++) {
            tempView[i] = this.valueHexView[i];
        }
        this.valueHexView = tempView;
        if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) {
            this.error = "End of input reached before message was fully decoded";
            return -1;
        }
        if (this.valueHexView[0] === 0x00)
            this.warnings.push("Needlessly long format of SID encoding");
        if (this.blockLength <= 8)
            this.valueDec = utilFromBase(this.valueHexView, 7);
        else {
            this.isHexOnly = true;
            this.warnings.push("Too big SID for decoding, hex only");
        }
        return (inputOffset + this.blockLength);
    }
    set valueBigInt(value) {
        assertBigInt();
        let bits = BigInt(value).toString(2);
        while (bits.length % 7) {
            bits = "0" + bits;
        }
        const bytes = new Uint8Array(bits.length / 7);
        for (let i = 0; i < bytes.length; i++) {
            bytes[i] = parseInt(bits.slice(i * 7, i * 7 + 7), 2) + (i + 1 < bytes.length ? 0x80 : 0);
        }
        this.fromBER(bytes.buffer, 0, bytes.length);
    }
    toBER(sizeOnly) {
        if (this.isHexOnly) {
            if (sizeOnly)
                return (new ArrayBuffer(this.valueHexView.byteLength));
            const curView = this.valueHexView;
            const retView = new Uint8Array(this.blockLength);
            for (let i = 0; i < (this.blockLength - 1); i++)
                retView[i] = curView[i] | 0x80;
            retView[this.blockLength - 1] = curView[this.blockLength - 1];
            return retView.buffer;
        }
        const encodedBuf = utilToBase(this.valueDec, 7);
        if (encodedBuf.byteLength === 0) {
            this.error = "Error during encoding SID value";
            return EMPTY_BUFFER;
        }
        const retView = new Uint8Array(encodedBuf.byteLength);
        if (!sizeOnly) {
            const encodedView = new Uint8Array(encodedBuf);
            const len = encodedBuf.byteLength - 1;
            for (let i = 0; i < len; i++)
                retView[i] = encodedView[i] | 0x80;
            retView[len] = encodedView[len];
        }
        return retView;
    }
    toString() {
        let result = "";
        if (this.isHexOnly)
            result = Convert.ToHex(this.valueHexView);
        else {
            if (this.isFirstSid) {
                let sidValue = this.valueDec;
                if (this.valueDec <= 39)
                    result = "0.";
                else {
                    if (this.valueDec <= 79) {
                        result = "1.";
                        sidValue -= 40;
                    }
                    else {
                        result = "2.";
                        sidValue -= 80;
                    }
                }
                result += sidValue.toString();
            }
            else
                result = this.valueDec.toString();
        }
        return result;
    }
    toJSON() {
        return {
            ...super.toJSON(),
            valueDec: this.valueDec,
            isFirstSid: this.isFirstSid,
        };
    }
}
LocalSidValueBlock.NAME = "sidBlock";

class LocalObjectIdentifierValueBlock extends ValueBlock {
    constructor({ value = EMPTY_STRING, ...parameters } = {}) {
        super(parameters);
        this.value = [];
        if (value) {
            this.fromString(value);
        }
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        let resultOffset = inputOffset;
        while (inputLength > 0) {
            const sidBlock = new LocalSidValueBlock();
            resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);
            if (resultOffset === -1) {
                this.blockLength = 0;
                this.error = sidBlock.error;
                return resultOffset;
            }
            if (this.value.length === 0)
                sidBlock.isFirstSid = true;
            this.blockLength += sidBlock.blockLength;
            inputLength -= sidBlock.blockLength;
            this.value.push(sidBlock);
        }
        return resultOffset;
    }
    toBER(sizeOnly) {
        const retBuffers = [];
        for (let i = 0; i < this.value.length; i++) {
            const valueBuf = this.value[i].toBER(sizeOnly);
            if (valueBuf.byteLength === 0) {
                this.error = this.value[i].error;
                return EMPTY_BUFFER;
            }
            retBuffers.push(valueBuf);
        }
        return concat$1(retBuffers);
    }
    fromString(string) {
        this.value = [];
        let pos1 = 0;
        let pos2 = 0;
        let sid = "";
        let flag = false;
        do {
            pos2 = string.indexOf(".", pos1);
            if (pos2 === -1)
                sid = string.substring(pos1);
            else
                sid = string.substring(pos1, pos2);
            pos1 = pos2 + 1;
            if (flag) {
                const sidBlock = this.value[0];
                let plus = 0;
                switch (sidBlock.valueDec) {
                    case 0:
                        break;
                    case 1:
                        plus = 40;
                        break;
                    case 2:
                        plus = 80;
                        break;
                    default:
                        this.value = [];
                        return;
                }
                const parsedSID = parseInt(sid, 10);
                if (isNaN(parsedSID))
                    return;
                sidBlock.valueDec = parsedSID + plus;
                flag = false;
            }
            else {
                const sidBlock = new LocalSidValueBlock();
                if (sid > Number.MAX_SAFE_INTEGER) {
                    assertBigInt();
                    const sidValue = BigInt(sid);
                    sidBlock.valueBigInt = sidValue;
                }
                else {
                    sidBlock.valueDec = parseInt(sid, 10);
                    if (isNaN(sidBlock.valueDec))
                        return;
                }
                if (!this.value.length) {
                    sidBlock.isFirstSid = true;
                    flag = true;
                }
                this.value.push(sidBlock);
            }
        } while (pos2 !== -1);
    }
    toString() {
        let result = "";
        let isHexOnly = false;
        for (let i = 0; i < this.value.length; i++) {
            isHexOnly = this.value[i].isHexOnly;
            let sidStr = this.value[i].toString();
            if (i !== 0)
                result = `${result}.`;
            if (isHexOnly) {
                sidStr = `{${sidStr}}`;
                if (this.value[i].isFirstSid)
                    result = `2.{${sidStr} - 80}`;
                else
                    result += sidStr;
            }
            else
                result += sidStr;
        }
        return result;
    }
    toJSON() {
        const object = {
            ...super.toJSON(),
            value: this.toString(),
            sidArray: [],
        };
        for (let i = 0; i < this.value.length; i++) {
            object.sidArray.push(this.value[i].toJSON());
        }
        return object;
    }
}
LocalObjectIdentifierValueBlock.NAME = "ObjectIdentifierValueBlock";

var _a$m;
class ObjectIdentifier extends BaseBlock {
    getValue() {
        return this.valueBlock.toString();
    }
    setValue(value) {
        this.valueBlock.fromString(value);
    }
    constructor(parameters = {}) {
        super(parameters, LocalObjectIdentifierValueBlock);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 6;
    }
    onAsciiEncoding() {
        return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`;
    }
    toJSON() {
        return {
            ...super.toJSON(),
            value: this.getValue(),
        };
    }
}
_a$m = ObjectIdentifier;
(() => {
    typeStore.ObjectIdentifier = _a$m;
})();
ObjectIdentifier.NAME = "OBJECT IDENTIFIER";

class LocalRelativeSidValueBlock extends HexBlock(LocalBaseBlock) {
    constructor({ valueDec = 0, ...parameters } = {}) {
        super(parameters);
        this.valueDec = valueDec;
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        if (inputLength === 0)
            return inputOffset;
        const inputView = BufferSourceConverter.toUint8Array(inputBuffer);
        if (!checkBufferParams(this, inputView, inputOffset, inputLength))
            return -1;
        const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);
        this.valueHexView = new Uint8Array(inputLength);
        for (let i = 0; i < inputLength; i++) {
            this.valueHexView[i] = intBuffer[i] & 0x7F;
            this.blockLength++;
            if ((intBuffer[i] & 0x80) === 0x00)
                break;
        }
        const tempView = new Uint8Array(this.blockLength);
        for (let i = 0; i < this.blockLength; i++)
            tempView[i] = this.valueHexView[i];
        this.valueHexView = tempView;
        if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) {
            this.error = "End of input reached before message was fully decoded";
            return -1;
        }
        if (this.valueHexView[0] === 0x00)
            this.warnings.push("Needlessly long format of SID encoding");
        if (this.blockLength <= 8)
            this.valueDec = utilFromBase(this.valueHexView, 7);
        else {
            this.isHexOnly = true;
            this.warnings.push("Too big SID for decoding, hex only");
        }
        return (inputOffset + this.blockLength);
    }
    toBER(sizeOnly) {
        if (this.isHexOnly) {
            if (sizeOnly)
                return (new ArrayBuffer(this.valueHexView.byteLength));
            const curView = this.valueHexView;
            const retView = new Uint8Array(this.blockLength);
            for (let i = 0; i < (this.blockLength - 1); i++)
                retView[i] = curView[i] | 0x80;
            retView[this.blockLength - 1] = curView[this.blockLength - 1];
            return retView.buffer;
        }
        const encodedBuf = utilToBase(this.valueDec, 7);
        if (encodedBuf.byteLength === 0) {
            this.error = "Error during encoding SID value";
            return EMPTY_BUFFER;
        }
        const retView = new Uint8Array(encodedBuf.byteLength);
        if (!sizeOnly) {
            const encodedView = new Uint8Array(encodedBuf);
            const len = encodedBuf.byteLength - 1;
            for (let i = 0; i < len; i++)
                retView[i] = encodedView[i] | 0x80;
            retView[len] = encodedView[len];
        }
        return retView.buffer;
    }
    toString() {
        let result = "";
        if (this.isHexOnly)
            result = Convert.ToHex(this.valueHexView);
        else {
            result = this.valueDec.toString();
        }
        return result;
    }
    toJSON() {
        return {
            ...super.toJSON(),
            valueDec: this.valueDec,
        };
    }
}
LocalRelativeSidValueBlock.NAME = "relativeSidBlock";

class LocalRelativeObjectIdentifierValueBlock extends ValueBlock {
    constructor({ value = EMPTY_STRING, ...parameters } = {}) {
        super(parameters);
        this.value = [];
        if (value) {
            this.fromString(value);
        }
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        let resultOffset = inputOffset;
        while (inputLength > 0) {
            const sidBlock = new LocalRelativeSidValueBlock();
            resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);
            if (resultOffset === -1) {
                this.blockLength = 0;
                this.error = sidBlock.error;
                return resultOffset;
            }
            this.blockLength += sidBlock.blockLength;
            inputLength -= sidBlock.blockLength;
            this.value.push(sidBlock);
        }
        return resultOffset;
    }
    toBER(sizeOnly, _writer) {
        const retBuffers = [];
        for (let i = 0; i < this.value.length; i++) {
            const valueBuf = this.value[i].toBER(sizeOnly);
            if (valueBuf.byteLength === 0) {
                this.error = this.value[i].error;
                return EMPTY_BUFFER;
            }
            retBuffers.push(valueBuf);
        }
        return concat$1(retBuffers);
    }
    fromString(string) {
        this.value = [];
        let pos1 = 0;
        let pos2 = 0;
        let sid = "";
        do {
            pos2 = string.indexOf(".", pos1);
            if (pos2 === -1)
                sid = string.substring(pos1);
            else
                sid = string.substring(pos1, pos2);
            pos1 = pos2 + 1;
            const sidBlock = new LocalRelativeSidValueBlock();
            sidBlock.valueDec = parseInt(sid, 10);
            if (isNaN(sidBlock.valueDec))
                return true;
            this.value.push(sidBlock);
        } while (pos2 !== -1);
        return true;
    }
    toString() {
        let result = "";
        let isHexOnly = false;
        for (let i = 0; i < this.value.length; i++) {
            isHexOnly = this.value[i].isHexOnly;
            let sidStr = this.value[i].toString();
            if (i !== 0)
                result = `${result}.`;
            if (isHexOnly) {
                sidStr = `{${sidStr}}`;
                result += sidStr;
            }
            else
                result += sidStr;
        }
        return result;
    }
    toJSON() {
        const object = {
            ...super.toJSON(),
            value: this.toString(),
            sidArray: [],
        };
        for (let i = 0; i < this.value.length; i++)
            object.sidArray.push(this.value[i].toJSON());
        return object;
    }
}
LocalRelativeObjectIdentifierValueBlock.NAME = "RelativeObjectIdentifierValueBlock";

var _a$l;
class RelativeObjectIdentifier extends BaseBlock {
    getValue() {
        return this.valueBlock.toString();
    }
    setValue(value) {
        this.valueBlock.fromString(value);
    }
    constructor(parameters = {}) {
        super(parameters, LocalRelativeObjectIdentifierValueBlock);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 13;
    }
    onAsciiEncoding() {
        return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`;
    }
    toJSON() {
        return {
            ...super.toJSON(),
            value: this.getValue(),
        };
    }
}
_a$l = RelativeObjectIdentifier;
(() => {
    typeStore.RelativeObjectIdentifier = _a$l;
})();
RelativeObjectIdentifier.NAME = "RelativeObjectIdentifier";

var _a$k;
class Sequence extends Constructed {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 16;
    }
}
_a$k = Sequence;
(() => {
    typeStore.Sequence = _a$k;
})();
Sequence.NAME = "SEQUENCE";

var _a$j;
let Set$1 = class Set extends Constructed {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 17;
    }
};
_a$j = Set$1;
(() => {
    typeStore.Set = _a$j;
})();
Set$1.NAME = "SET";

class LocalStringValueBlock extends HexBlock(ValueBlock) {
    constructor({ ...parameters } = {}) {
        super(parameters);
        this.isHexOnly = true;
        this.value = EMPTY_STRING;
    }
    toJSON() {
        return {
            ...super.toJSON(),
            value: this.value,
        };
    }
}
LocalStringValueBlock.NAME = "StringValueBlock";

class LocalSimpleStringValueBlock extends LocalStringValueBlock {
}
LocalSimpleStringValueBlock.NAME = "SimpleStringValueBlock";

class LocalSimpleStringBlock extends BaseStringBlock {
    constructor({ ...parameters } = {}) {
        super(parameters, LocalSimpleStringValueBlock);
    }
    fromBuffer(inputBuffer) {
        this.valueBlock.value = String.fromCharCode.apply(null, BufferSourceConverter.toUint8Array(inputBuffer));
    }
    fromString(inputString) {
        const strLen = inputString.length;
        const view = this.valueBlock.valueHexView = new Uint8Array(strLen);
        for (let i = 0; i < strLen; i++)
            view[i] = inputString.charCodeAt(i);
        this.valueBlock.value = inputString;
    }
}
LocalSimpleStringBlock.NAME = "SIMPLE STRING";

class LocalUtf8StringValueBlock extends LocalSimpleStringBlock {
    fromBuffer(inputBuffer) {
        this.valueBlock.valueHexView = BufferSourceConverter.toUint8Array(inputBuffer);
        try {
            this.valueBlock.value = Convert.ToUtf8String(inputBuffer);
        }
        catch (ex) {
            this.warnings.push(`Error during "decodeURIComponent": ${ex}, using raw string`);
            this.valueBlock.value = Convert.ToBinary(inputBuffer);
        }
    }
    fromString(inputString) {
        this.valueBlock.valueHexView = new Uint8Array(Convert.FromUtf8String(inputString));
        this.valueBlock.value = inputString;
    }
}
LocalUtf8StringValueBlock.NAME = "Utf8StringValueBlock";

var _a$i;
class Utf8String extends LocalUtf8StringValueBlock {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 12;
    }
}
_a$i = Utf8String;
(() => {
    typeStore.Utf8String = _a$i;
})();
Utf8String.NAME = "UTF8String";

class LocalBmpStringValueBlock extends LocalSimpleStringBlock {
    fromBuffer(inputBuffer) {
        this.valueBlock.value = Convert.ToUtf16String(inputBuffer);
        this.valueBlock.valueHexView = BufferSourceConverter.toUint8Array(inputBuffer);
    }
    fromString(inputString) {
        this.valueBlock.value = inputString;
        this.valueBlock.valueHexView = new Uint8Array(Convert.FromUtf16String(inputString));
    }
}
LocalBmpStringValueBlock.NAME = "BmpStringValueBlock";

var _a$h;
class BmpString extends LocalBmpStringValueBlock {
    constructor({ ...parameters } = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 30;
    }
}
_a$h = BmpString;
(() => {
    typeStore.BmpString = _a$h;
})();
BmpString.NAME = "BMPString";

class LocalUniversalStringValueBlock extends LocalSimpleStringBlock {
    fromBuffer(inputBuffer) {
        const copyBuffer = ArrayBuffer.isView(inputBuffer) ? inputBuffer.slice().buffer : inputBuffer.slice(0);
        const valueView = new Uint8Array(copyBuffer);
        for (let i = 0; i < valueView.length; i += 4) {
            valueView[i] = valueView[i + 3];
            valueView[i + 1] = valueView[i + 2];
            valueView[i + 2] = 0x00;
            valueView[i + 3] = 0x00;
        }
        this.valueBlock.value = String.fromCharCode.apply(null, new Uint32Array(copyBuffer));
    }
    fromString(inputString) {
        const strLength = inputString.length;
        const valueHexView = this.valueBlock.valueHexView = new Uint8Array(strLength * 4);
        for (let i = 0; i < strLength; i++) {
            const codeBuf = utilToBase(inputString.charCodeAt(i), 8);
            const codeView = new Uint8Array(codeBuf);
            if (codeView.length > 4)
                continue;
            const dif = 4 - codeView.length;
            for (let j = (codeView.length - 1); j >= 0; j--)
                valueHexView[i * 4 + j + dif] = codeView[j];
        }
        this.valueBlock.value = inputString;
    }
}
LocalUniversalStringValueBlock.NAME = "UniversalStringValueBlock";

var _a$g;
class UniversalString extends LocalUniversalStringValueBlock {
    constructor({ ...parameters } = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 28;
    }
}
_a$g = UniversalString;
(() => {
    typeStore.UniversalString = _a$g;
})();
UniversalString.NAME = "UniversalString";

var _a$f;
class NumericString extends LocalSimpleStringBlock {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 18;
    }
}
_a$f = NumericString;
(() => {
    typeStore.NumericString = _a$f;
})();
NumericString.NAME = "NumericString";

var _a$e;
class PrintableString extends LocalSimpleStringBlock {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 19;
    }
}
_a$e = PrintableString;
(() => {
    typeStore.PrintableString = _a$e;
})();
PrintableString.NAME = "PrintableString";

var _a$d;
class TeletexString extends LocalSimpleStringBlock {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 20;
    }
}
_a$d = TeletexString;
(() => {
    typeStore.TeletexString = _a$d;
})();
TeletexString.NAME = "TeletexString";

var _a$c;
class VideotexString extends LocalSimpleStringBlock {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 21;
    }
}
_a$c = VideotexString;
(() => {
    typeStore.VideotexString = _a$c;
})();
VideotexString.NAME = "VideotexString";

var _a$b;
class IA5String extends LocalSimpleStringBlock {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 22;
    }
}
_a$b = IA5String;
(() => {
    typeStore.IA5String = _a$b;
})();
IA5String.NAME = "IA5String";

var _a$a;
class GraphicString extends LocalSimpleStringBlock {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 25;
    }
}
_a$a = GraphicString;
(() => {
    typeStore.GraphicString = _a$a;
})();
GraphicString.NAME = "GraphicString";

var _a$9;
class VisibleString extends LocalSimpleStringBlock {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 26;
    }
}
_a$9 = VisibleString;
(() => {
    typeStore.VisibleString = _a$9;
})();
VisibleString.NAME = "VisibleString";

var _a$8;
class GeneralString extends LocalSimpleStringBlock {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 27;
    }
}
_a$8 = GeneralString;
(() => {
    typeStore.GeneralString = _a$8;
})();
GeneralString.NAME = "GeneralString";

var _a$7;
class CharacterString extends LocalSimpleStringBlock {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 29;
    }
}
_a$7 = CharacterString;
(() => {
    typeStore.CharacterString = _a$7;
})();
CharacterString.NAME = "CharacterString";

var _a$6;
class UTCTime extends VisibleString {
    constructor({ value, valueDate, ...parameters } = {}) {
        super(parameters);
        this.year = 0;
        this.month = 0;
        this.day = 0;
        this.hour = 0;
        this.minute = 0;
        this.second = 0;
        if (value) {
            this.fromString(value);
            this.valueBlock.valueHexView = new Uint8Array(value.length);
            for (let i = 0; i < value.length; i++)
                this.valueBlock.valueHexView[i] = value.charCodeAt(i);
        }
        if (valueDate) {
            this.fromDate(valueDate);
            this.valueBlock.valueHexView = new Uint8Array(this.toBuffer());
        }
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 23;
    }
    fromBuffer(inputBuffer) {
        this.fromString(String.fromCharCode.apply(null, BufferSourceConverter.toUint8Array(inputBuffer)));
    }
    toBuffer() {
        const str = this.toString();
        const buffer = new ArrayBuffer(str.length);
        const view = new Uint8Array(buffer);
        for (let i = 0; i < str.length; i++)
            view[i] = str.charCodeAt(i);
        return buffer;
    }
    fromDate(inputDate) {
        this.year = inputDate.getUTCFullYear();
        this.month = inputDate.getUTCMonth() + 1;
        this.day = inputDate.getUTCDate();
        this.hour = inputDate.getUTCHours();
        this.minute = inputDate.getUTCMinutes();
        this.second = inputDate.getUTCSeconds();
    }
    toDate() {
        return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second)));
    }
    fromString(inputString) {
        const parser = /(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig;
        const parserArray = parser.exec(inputString);
        if (parserArray === null) {
            this.error = "Wrong input string for conversion";
            return;
        }
        const year = parseInt(parserArray[1], 10);
        if (year >= 50)
            this.year = 1900 + year;
        else
            this.year = 2000 + year;
        this.month = parseInt(parserArray[2], 10);
        this.day = parseInt(parserArray[3], 10);
        this.hour = parseInt(parserArray[4], 10);
        this.minute = parseInt(parserArray[5], 10);
        this.second = parseInt(parserArray[6], 10);
    }
    toString(encoding = "iso") {
        if (encoding === "iso") {
            const outputArray = new Array(7);
            outputArray[0] = padNumber(((this.year < 2000) ? (this.year - 1900) : (this.year - 2000)), 2);
            outputArray[1] = padNumber(this.month, 2);
            outputArray[2] = padNumber(this.day, 2);
            outputArray[3] = padNumber(this.hour, 2);
            outputArray[4] = padNumber(this.minute, 2);
            outputArray[5] = padNumber(this.second, 2);
            outputArray[6] = "Z";
            return outputArray.join("");
        }
        return super.toString(encoding);
    }
    onAsciiEncoding() {
        return `${this.constructor.NAME} : ${this.toDate().toISOString()}`;
    }
    toJSON() {
        return {
            ...super.toJSON(),
            year: this.year,
            month: this.month,
            day: this.day,
            hour: this.hour,
            minute: this.minute,
            second: this.second,
        };
    }
}
_a$6 = UTCTime;
(() => {
    typeStore.UTCTime = _a$6;
})();
UTCTime.NAME = "UTCTime";

var _a$5;
class GeneralizedTime extends UTCTime {
    constructor(parameters = {}) {
        var _b;
        super(parameters);
        (_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 24;
    }
    fromDate(inputDate) {
        super.fromDate(inputDate);
        this.millisecond = inputDate.getUTCMilliseconds();
    }
    toDate() {
        const utcDate = Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond);
        return (new Date(utcDate));
    }
    fromString(inputString) {
        let isUTC = false;
        let timeString = "";
        let dateTimeString = "";
        let fractionPart = 0;
        let parser;
        let hourDifference = 0;
        let minuteDifference = 0;
        if (inputString[inputString.length - 1] === "Z") {
            timeString = inputString.substring(0, inputString.length - 1);
            isUTC = true;
        }
        else {
            const number = new Number(inputString[inputString.length - 1]);
            if (isNaN(number.valueOf()))
                throw new Error("Wrong input string for conversion");
            timeString = inputString;
        }
        if (isUTC) {
            if (timeString.indexOf("+") !== -1)
                throw new Error("Wrong input string for conversion");
            if (timeString.indexOf("-") !== -1)
                throw new Error("Wrong input string for conversion");
        }
        else {
            let multiplier = 1;
            let differencePosition = timeString.indexOf("+");
            let differenceString = "";
            if (differencePosition === -1) {
                differencePosition = timeString.indexOf("-");
                multiplier = -1;
            }
            if (differencePosition !== -1) {
                differenceString = timeString.substring(differencePosition + 1);
                timeString = timeString.substring(0, differencePosition);
                if ((differenceString.length !== 2) && (differenceString.length !== 4))
                    throw new Error("Wrong input string for conversion");
                let number = parseInt(differenceString.substring(0, 2), 10);
                if (isNaN(number.valueOf()))
                    throw new Error("Wrong input string for conversion");
                hourDifference = multiplier * number;
                if (differenceString.length === 4) {
                    number = parseInt(differenceString.substring(2, 4), 10);
                    if (isNaN(number.valueOf()))
                        throw new Error("Wrong input string for conversion");
                    minuteDifference = multiplier * number;
                }
            }
        }
        let fractionPointPosition = timeString.indexOf(".");
        if (fractionPointPosition === -1)
            fractionPointPosition = timeString.indexOf(",");
        if (fractionPointPosition !== -1) {
            const fractionPartCheck = new Number(`0${timeString.substring(fractionPointPosition)}`);
            if (isNaN(fractionPartCheck.valueOf()))
                throw new Error("Wrong input string for conversion");
            fractionPart = fractionPartCheck.valueOf();
            dateTimeString = timeString.substring(0, fractionPointPosition);
        }
        else
            dateTimeString = timeString;
        switch (true) {
            case (dateTimeString.length === 8):
                parser = /(\d{4})(\d{2})(\d{2})/ig;
                if (fractionPointPosition !== -1)
                    throw new Error("Wrong input string for conversion");
                break;
            case (dateTimeString.length === 10):
                parser = /(\d{4})(\d{2})(\d{2})(\d{2})/ig;
                if (fractionPointPosition !== -1) {
                    let fractionResult = 60 * fractionPart;
                    this.minute = Math.floor(fractionResult);
                    fractionResult = 60 * (fractionResult - this.minute);
                    this.second = Math.floor(fractionResult);
                    fractionResult = 1000 * (fractionResult - this.second);
                    this.millisecond = Math.floor(fractionResult);
                }
                break;
            case (dateTimeString.length === 12):
                parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig;
                if (fractionPointPosition !== -1) {
                    let fractionResult = 60 * fractionPart;
                    this.second = Math.floor(fractionResult);
                    fractionResult = 1000 * (fractionResult - this.second);
                    this.millisecond = Math.floor(fractionResult);
                }
                break;
            case (dateTimeString.length === 14):
                parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig;
                if (fractionPointPosition !== -1) {
                    const fractionResult = 1000 * fractionPart;
                    this.millisecond = Math.floor(fractionResult);
                }
                break;
            default:
                throw new Error("Wrong input string for conversion");
        }
        const parserArray = parser.exec(dateTimeString);
        if (parserArray === null)
            throw new Error("Wrong input string for conversion");
        for (let j = 1; j < parserArray.length; j++) {
            switch (j) {
                case 1:
                    this.year = parseInt(parserArray[j], 10);
                    break;
                case 2:
                    this.month = parseInt(parserArray[j], 10);
                    break;
                case 3:
                    this.day = parseInt(parserArray[j], 10);
                    break;
                case 4:
                    this.hour = parseInt(parserArray[j], 10) + hourDifference;
                    break;
                case 5:
                    this.minute = parseInt(parserArray[j], 10) + minuteDifference;
                    break;
                case 6:
                    this.second = parseInt(parserArray[j], 10);
                    break;
                default:
                    throw new Error("Wrong input string for conversion");
            }
        }
        if (isUTC === false) {
            const tempDate = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);
            this.year = tempDate.getUTCFullYear();
            this.month = tempDate.getUTCMonth();
            this.day = tempDate.getUTCDay();
            this.hour = tempDate.getUTCHours();
            this.minute = tempDate.getUTCMinutes();
            this.second = tempDate.getUTCSeconds();
            this.millisecond = tempDate.getUTCMilliseconds();
        }
    }
    toString(encoding = "iso") {
        if (encoding === "iso") {
            const outputArray = [];
            outputArray.push(padNumber(this.year, 4));
            outputArray.push(padNumber(this.month, 2));
            outputArray.push(padNumber(this.day, 2));
            outputArray.push(padNumber(this.hour, 2));
            outputArray.push(padNumber(this.minute, 2));
            outputArray.push(padNumber(this.second, 2));
            if (this.millisecond !== 0) {
                outputArray.push(".");
                outputArray.push(padNumber(this.millisecond, 3));
            }
            outputArray.push("Z");
            return outputArray.join("");
        }
        return super.toString(encoding);
    }
    toJSON() {
        return {
            ...super.toJSON(),
            millisecond: this.millisecond,
        };
    }
}
_a$5 = GeneralizedTime;
(() => {
    typeStore.GeneralizedTime = _a$5;
})();
GeneralizedTime.NAME = "GeneralizedTime";

var _a$4;
class DATE extends Utf8String {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 31;
    }
}
_a$4 = DATE;
(() => {
    typeStore.DATE = _a$4;
})();
DATE.NAME = "DATE";

var _a$3;
class TimeOfDay extends Utf8String {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 32;
    }
}
_a$3 = TimeOfDay;
(() => {
    typeStore.TimeOfDay = _a$3;
})();
TimeOfDay.NAME = "TimeOfDay";

var _a$2;
class DateTime extends Utf8String {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 33;
    }
}
_a$2 = DateTime;
(() => {
    typeStore.DateTime = _a$2;
})();
DateTime.NAME = "DateTime";

var _a$1;
class Duration extends Utf8String {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 34;
    }
}
_a$1 = Duration;
(() => {
    typeStore.Duration = _a$1;
})();
Duration.NAME = "Duration";

var _a$x;
class TIME extends Utf8String {
    constructor(parameters = {}) {
        super(parameters);
        this.idBlock.tagClass = 1;
        this.idBlock.tagNumber = 14;
    }
}
_a$x = TIME;
(() => {
    typeStore.TIME = _a$x;
})();
TIME.NAME = "TIME";

class Any {
    constructor({ name = EMPTY_STRING, optional = false } = {}) {
        this.name = name;
        this.optional = optional;
    }
}

class Choice extends Any {
    constructor({ value = [], ...parameters } = {}) {
        super(parameters);
        this.value = value;
    }
}

class Repeated extends Any {
    constructor({ value = new Any(), local = false, ...parameters } = {}) {
        super(parameters);
        this.value = value;
        this.local = local;
    }
}

class RawData {
    get data() {
        return this.dataView.slice().buffer;
    }
    set data(value) {
        this.dataView = BufferSourceConverter.toUint8Array(value);
    }
    constructor({ data = EMPTY_VIEW } = {}) {
        this.dataView = BufferSourceConverter.toUint8Array(data);
    }
    fromBER(inputBuffer, inputOffset, inputLength) {
        const endLength = inputOffset + inputLength;
        this.dataView = BufferSourceConverter.toUint8Array(inputBuffer).subarray(inputOffset, endLength);
        return endLength;
    }
    toBER(_sizeOnly) {
        return this.dataView.slice().buffer;
    }
}

function compareSchema(root, inputData, inputSchema) {
    if (inputSchema instanceof Choice) {
        for (const element of inputSchema.value) {
            const result = compareSchema(root, inputData, element);
            if (result.verified) {
                return {
                    verified: true,
                    result: root,
                };
            }
        }
        {
            const _result = {
                verified: false,
                result: { error: "Wrong values for Choice type" },
            };
            if (inputSchema.hasOwnProperty(NAME$1))
                _result.name = inputSchema.name;
            return _result;
        }
    }
    if (inputSchema instanceof Any) {
        if (inputSchema.hasOwnProperty(NAME$1))
            root[inputSchema.name] = inputData;
        return {
            verified: true,
            result: root,
        };
    }
    if ((root instanceof Object) === false) {
        return {
            verified: false,
            result: { error: "Wrong root object" },
        };
    }
    if ((inputData instanceof Object) === false) {
        return {
            verified: false,
            result: { error: "Wrong ASN.1 data" },
        };
    }
    if ((inputSchema instanceof Object) === false) {
        return {
            verified: false,
            result: { error: "Wrong ASN.1 schema" },
        };
    }
    if ((ID_BLOCK in inputSchema) === false) {
        return {
            verified: false,
            result: { error: "Wrong ASN.1 schema" },
        };
    }
    if ((FROM_BER in inputSchema.idBlock) === false) {
        return {
            verified: false,
            result: { error: "Wrong ASN.1 schema" },
        };
    }
    if ((TO_BER in inputSchema.idBlock) === false) {
        return {
            verified: false,
            result: { error: "Wrong ASN.1 schema" },
        };
    }
    const encodedId = inputSchema.idBlock.toBER(false);
    if (encodedId.byteLength === 0) {
        return {
            verified: false,
            result: { error: "Error encoding idBlock for ASN.1 schema" },
        };
    }
    const decodedOffset = inputSchema.idBlock.fromBER(encodedId, 0, encodedId.byteLength);
    if (decodedOffset === -1) {
        return {
            verified: false,
            result: { error: "Error decoding idBlock for ASN.1 schema" },
        };
    }
    if (inputSchema.idBlock.hasOwnProperty(TAG_CLASS) === false) {
        return {
            verified: false,
            result: { error: "Wrong ASN.1 schema" },
        };
    }
    if (inputSchema.idBlock.tagClass !== inputData.idBlock.tagClass) {
        return {
            verified: false,
            result: root,
        };
    }
    if (inputSchema.idBlock.hasOwnProperty(TAG_NUMBER) === false) {
        return {
            verified: false,
            result: { error: "Wrong ASN.1 schema" },
        };
    }
    if (inputSchema.idBlock.tagNumber !== inputData.idBlock.tagNumber) {
        return {
            verified: false,
            result: root,
        };
    }
    if (inputSchema.idBlock.hasOwnProperty(IS_CONSTRUCTED) === false) {
        return {
            verified: false,
            result: { error: "Wrong ASN.1 schema" },
        };
    }
    if (inputSchema.idBlock.isConstructed !== inputData.idBlock.isConstructed) {
        return {
            verified: false,
            result: root,
        };
    }
    if (!(IS_HEX_ONLY in inputSchema.idBlock)) {
        return {
            verified: false,
            result: { error: "Wrong ASN.1 schema" },
        };
    }
    if (inputSchema.idBlock.isHexOnly !== inputData.idBlock.isHexOnly) {
        return {
            verified: false,
            result: root,
        };
    }
    if (inputSchema.idBlock.isHexOnly) {
        if ((VALUE_HEX_VIEW in inputSchema.idBlock) === false) {
            return {
                verified: false,
                result: { error: "Wrong ASN.1 schema" },
            };
        }
        const schemaView = inputSchema.idBlock.valueHexView;
        const asn1View = inputData.idBlock.valueHexView;
        if (schemaView.length !== asn1View.length) {
            return {
                verified: false,
                result: root,
            };
        }
        for (let i = 0; i < schemaView.length; i++) {
            if (schemaView[i] !== asn1View[1]) {
                return {
                    verified: false,
                    result: root,
                };
            }
        }
    }
    if (inputSchema.name) {
        inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
        if (inputSchema.name)
            root[inputSchema.name] = inputData;
    }
    if (inputSchema instanceof typeStore.Constructed) {
        let admission = 0;
        let result = {
            verified: false,
            result: { error: "Unknown error" },
        };
        let maxLength = inputSchema.valueBlock.value.length;
        if (maxLength > 0) {
            if (inputSchema.valueBlock.value[0] instanceof Repeated) {
                maxLength = inputData.valueBlock.value.length;
            }
        }
        if (maxLength === 0) {
            return {
                verified: true,
                result: root,
            };
        }
        if ((inputData.valueBlock.value.length === 0)
            && (inputSchema.valueBlock.value.length !== 0)) {
            let _optional = true;
            for (let i = 0; i < inputSchema.valueBlock.value.length; i++)
                _optional = _optional && (inputSchema.valueBlock.value[i].optional || false);
            if (_optional) {
                return {
                    verified: true,
                    result: root,
                };
            }
            if (inputSchema.name) {
                inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
                if (inputSchema.name)
                    delete root[inputSchema.name];
            }
            root.error = "Inconsistent object length";
            return {
                verified: false,
                result: root,
            };
        }
        for (let i = 0; i < maxLength; i++) {
            if ((i - admission) >= inputData.valueBlock.value.length) {
                if (inputSchema.valueBlock.value[i].optional === false) {
                    const _result = {
                        verified: false,
                        result: root,
                    };
                    root.error = "Inconsistent length between ASN.1 data and schema";
                    if (inputSchema.name) {
                        inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
                        if (inputSchema.name) {
                            delete root[inputSchema.name];
                            _result.name = inputSchema.name;
                        }
                    }
                    return _result;
                }
            }
            else {
                if (inputSchema.valueBlock.value[0] instanceof Repeated) {
                    result = compareSchema(root, inputData.valueBlock.value[i], inputSchema.valueBlock.value[0].value);
                    if (result.verified === false) {
                        if (inputSchema.valueBlock.value[0].optional)
                            admission++;
                        else {
                            if (inputSchema.name) {
                                inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
                                if (inputSchema.name)
                                    delete root[inputSchema.name];
                            }
                            return result;
                        }
                    }
                    if ((NAME$1 in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].name.length > 0)) {
                        let arrayRoot = {};
                        if ((LOCAL in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].local))
                            arrayRoot = inputData;
                        else
                            arrayRoot = root;
                        if (typeof arrayRoot[inputSchema.valueBlock.value[0].name] === "undefined")
                            arrayRoot[inputSchema.valueBlock.value[0].name] = [];
                        arrayRoot[inputSchema.valueBlock.value[0].name].push(inputData.valueBlock.value[i]);
                    }
                }
                else {
                    result = compareSchema(root, inputData.valueBlock.value[i - admission], inputSchema.valueBlock.value[i]);
                    if (result.verified === false) {
                        if (inputSchema.valueBlock.value[i].optional)
                            admission++;
                        else {
                            if (inputSchema.name) {
                                inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
                                if (inputSchema.name)
                                    delete root[inputSchema.name];
                            }
                            return result;
                        }
                    }
                }
            }
        }
        if (result.verified === false) {
            const _result = {
                verified: false,
                result: root,
            };
            if (inputSchema.name) {
                inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
                if (inputSchema.name) {
                    delete root[inputSchema.name];
                    _result.name = inputSchema.name;
                }
            }
            return _result;
        }
        return {
            verified: true,
            result: root,
        };
    }
    if (inputSchema.primitiveSchema
        && (VALUE_HEX_VIEW in inputData.valueBlock)) {
        const asn1 = localFromBER(inputData.valueBlock.valueHexView);
        if (asn1.offset === -1) {
            const _result = {
                verified: false,
                result: asn1.result,
            };
            if (inputSchema.name) {
                inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
                if (inputSchema.name) {
                    delete root[inputSchema.name];
                    _result.name = inputSchema.name;
                }
            }
            return _result;
        }
        return compareSchema(root, asn1.result, inputSchema.primitiveSchema);
    }
    return {
        verified: true,
        result: root,
    };
}
function verifySchema(inputBuffer, inputSchema) {
    if ((inputSchema instanceof Object) === false) {
        return {
            verified: false,
            result: { error: "Wrong ASN.1 schema type" },
        };
    }
    const asn1 = localFromBER(BufferSourceConverter.toUint8Array(inputBuffer));
    if (asn1.offset === -1) {
        return {
            verified: false,
            result: asn1.result,
        };
    }
    return compareSchema(asn1.result, asn1.result, inputSchema);
}

const asn1js = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
    __proto__: null,
    Any,
    BaseBlock,
    BaseStringBlock,
    BitString: BitString$1,
    BmpString,
    Boolean: Boolean$1,
    CharacterString,
    Choice,
    Constructed,
    DATE,
    DateTime,
    Duration,
    EndOfContent,
    Enumerated,
    GeneralString,
    GeneralizedTime,
    GraphicString,
    HexBlock,
    IA5String,
    Integer,
    Null,
    NumericString,
    ObjectIdentifier,
    OctetString: OctetString$1,
    Primitive,
    PrintableString,
    RawData,
    RelativeObjectIdentifier,
    Repeated,
    Sequence,
    Set: Set$1,
    TIME,
    TeletexString,
    TimeOfDay,
    UTCTime,
    UniversalString,
    Utf8String,
    ValueBlock,
    VideotexString,
    ViewWriter,
    VisibleString,
    compareSchema,
    fromBER,
    verifySchema
}, Symbol.toStringTag, { value: 'Module' }));

var AsnTypeTypes;
(function (AsnTypeTypes) {
    AsnTypeTypes[AsnTypeTypes["Sequence"] = 0] = "Sequence";
    AsnTypeTypes[AsnTypeTypes["Set"] = 1] = "Set";
    AsnTypeTypes[AsnTypeTypes["Choice"] = 2] = "Choice";
})(AsnTypeTypes || (AsnTypeTypes = {}));
var AsnPropTypes;
(function (AsnPropTypes) {
    AsnPropTypes[AsnPropTypes["Any"] = 1] = "Any";
    AsnPropTypes[AsnPropTypes["Boolean"] = 2] = "Boolean";
    AsnPropTypes[AsnPropTypes["OctetString"] = 3] = "OctetString";
    AsnPropTypes[AsnPropTypes["BitString"] = 4] = "BitString";
    AsnPropTypes[AsnPropTypes["Integer"] = 5] = "Integer";
    AsnPropTypes[AsnPropTypes["Enumerated"] = 6] = "Enumerated";
    AsnPropTypes[AsnPropTypes["ObjectIdentifier"] = 7] = "ObjectIdentifier";
    AsnPropTypes[AsnPropTypes["Utf8String"] = 8] = "Utf8String";
    AsnPropTypes[AsnPropTypes["BmpString"] = 9] = "BmpString";
    AsnPropTypes[AsnPropTypes["UniversalString"] = 10] = "UniversalString";
    AsnPropTypes[AsnPropTypes["NumericString"] = 11] = "NumericString";
    AsnPropTypes[AsnPropTypes["PrintableString"] = 12] = "PrintableString";
    AsnPropTypes[AsnPropTypes["TeletexString"] = 13] = "TeletexString";
    AsnPropTypes[AsnPropTypes["VideotexString"] = 14] = "VideotexString";
    AsnPropTypes[AsnPropTypes["IA5String"] = 15] = "IA5String";
    AsnPropTypes[AsnPropTypes["GraphicString"] = 16] = "GraphicString";
    AsnPropTypes[AsnPropTypes["VisibleString"] = 17] = "VisibleString";
    AsnPropTypes[AsnPropTypes["GeneralString"] = 18] = "GeneralString";
    AsnPropTypes[AsnPropTypes["CharacterString"] = 19] = "CharacterString";
    AsnPropTypes[AsnPropTypes["UTCTime"] = 20] = "UTCTime";
    AsnPropTypes[AsnPropTypes["GeneralizedTime"] = 21] = "GeneralizedTime";
    AsnPropTypes[AsnPropTypes["DATE"] = 22] = "DATE";
    AsnPropTypes[AsnPropTypes["TimeOfDay"] = 23] = "TimeOfDay";
    AsnPropTypes[AsnPropTypes["DateTime"] = 24] = "DateTime";
    AsnPropTypes[AsnPropTypes["Duration"] = 25] = "Duration";
    AsnPropTypes[AsnPropTypes["TIME"] = 26] = "TIME";
    AsnPropTypes[AsnPropTypes["Null"] = 27] = "Null";
})(AsnPropTypes || (AsnPropTypes = {}));

class BitString {
    constructor(params, unusedBits = 0) {
        this.unusedBits = 0;
        this.value = new ArrayBuffer(0);
        if (params) {
            if (typeof params === "number") {
                this.fromNumber(params);
            }
            else if (BufferSourceConverter.isBufferSource(params)) {
                this.unusedBits = unusedBits;
                this.value = BufferSourceConverter.toArrayBuffer(params);
            }
            else {
                throw TypeError("Unsupported type of 'params' argument for BitString");
            }
        }
    }
    fromASN(asn) {
        if (!(asn instanceof BitString$1)) {
            throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");
        }
        this.unusedBits = asn.valueBlock.unusedBits;
        this.value = asn.valueBlock.valueHex;
        return this;
    }
    toASN() {
        return new BitString$1({ unusedBits: this.unusedBits, valueHex: this.value });
    }
    toSchema(name) {
        return new BitString$1({ name });
    }
    toNumber() {
        let res = "";
        const uintArray = new Uint8Array(this.value);
        for (const octet of uintArray) {
            res += octet.toString(2).padStart(8, "0");
        }
        res = res.split("").reverse().join("");
        if (this.unusedBits) {
            res = res.slice(this.unusedBits).padStart(this.unusedBits, "0");
        }
        return parseInt(res, 2);
    }
    fromNumber(value) {
        let bits = value.toString(2);
        const octetSize = (bits.length + 7) >> 3;
        this.unusedBits = (octetSize << 3) - bits.length;
        const octets = new Uint8Array(octetSize);
        bits = bits
            .padStart(octetSize << 3, "0")
            .split("")
            .reverse()
            .join("");
        let index = 0;
        while (index < octetSize) {
            octets[index] = parseInt(bits.slice(index << 3, (index << 3) + 8), 2);
            index++;
        }
        this.value = octets.buffer;
    }
}

class OctetString {
    get byteLength() {
        return this.buffer.byteLength;
    }
    get byteOffset() {
        return 0;
    }
    constructor(param) {
        if (typeof param === "number") {
            this.buffer = new ArrayBuffer(param);
        }
        else {
            if (BufferSourceConverter.isBufferSource(param)) {
                this.buffer = BufferSourceConverter.toArrayBuffer(param);
            }
            else if (Array.isArray(param)) {
                this.buffer = new Uint8Array(param);
            }
            else {
                this.buffer = new ArrayBuffer(0);
            }
        }
    }
    fromASN(asn) {
        if (!(asn instanceof OctetString$1)) {
            throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");
        }
        this.buffer = asn.valueBlock.valueHex;
        return this;
    }
    toASN() {
        return new OctetString$1({ valueHex: this.buffer });
    }
    toSchema(name) {
        return new OctetString$1({ name });
    }
}

const AsnAnyConverter = {
    fromASN: (value) => value instanceof Null ? null : value.valueBeforeDecodeView,
    toASN: (value) => {
        if (value === null) {
            return new Null();
        }
        const schema = fromBER(value);
        if (schema.result.error) {
            throw new Error(schema.result.error);
        }
        return schema.result;
    },
};
const AsnIntegerConverter = {
    fromASN: (value) => value.valueBlock.valueHexView.byteLength >= 4
        ? value.valueBlock.toString()
        : value.valueBlock.valueDec,
    toASN: (value) => new Integer({ value: +value }),
};
const AsnEnumeratedConverter = {
    fromASN: (value) => value.valueBlock.valueDec,
    toASN: (value) => new Enumerated({ value }),
};
const AsnIntegerArrayBufferConverter = {
    fromASN: (value) => value.valueBlock.valueHexView,
    toASN: (value) => new Integer({ valueHex: value }),
};
const AsnBitStringConverter = {
    fromASN: (value) => value.valueBlock.valueHexView,
    toASN: (value) => new BitString$1({ valueHex: value }),
};
const AsnObjectIdentifierConverter = {
    fromASN: (value) => value.valueBlock.toString(),
    toASN: (value) => new ObjectIdentifier({ value }),
};
const AsnBooleanConverter = {
    fromASN: (value) => value.valueBlock.value,
    toASN: (value) => new Boolean$1({ value }),
};
const AsnOctetStringConverter = {
    fromASN: (value) => value.valueBlock.valueHexView,
    toASN: (value) => new OctetString$1({ valueHex: value }),
};
const AsnConstructedOctetStringConverter = {
    fromASN: (value) => new OctetString(value.getValue()),
    toASN: (value) => value.toASN(),
};
function createStringConverter(Asn1Type) {
    return {
        fromASN: (value) => value.valueBlock.value,
        toASN: (value) => new Asn1Type({ value }),
    };
}
const AsnUtf8StringConverter = createStringConverter(Utf8String);
const AsnBmpStringConverter = createStringConverter(BmpString);
const AsnUniversalStringConverter = createStringConverter(UniversalString);
const AsnNumericStringConverter = createStringConverter(NumericString);
const AsnPrintableStringConverter = createStringConverter(PrintableString);
const AsnTeletexStringConverter = createStringConverter(TeletexString);
const AsnVideotexStringConverter = createStringConverter(VideotexString);
const AsnIA5StringConverter = createStringConverter(IA5String);
const AsnGraphicStringConverter = createStringConverter(GraphicString);
const AsnVisibleStringConverter = createStringConverter(VisibleString);
const AsnGeneralStringConverter = createStringConverter(GeneralString);
const AsnCharacterStringConverter = createStringConverter(CharacterString);
const AsnUTCTimeConverter = {
    fromASN: (value) => value.toDate(),
    toASN: (value) => new UTCTime({ valueDate: value }),
};
const AsnGeneralizedTimeConverter = {
    fromASN: (value) => value.toDate(),
    toASN: (value) => new GeneralizedTime({ valueDate: value }),
};
const AsnNullConverter = {
    fromASN: () => null,
    toASN: () => {
        return new Null();
    },
};
function defaultConverter(type) {
    switch (type) {
        case AsnPropTypes.Any:
            return AsnAnyConverter;
        case AsnPropTypes.BitString:
            return AsnBitStringConverter;
        case AsnPropTypes.BmpString:
            return AsnBmpStringConverter;
        case AsnPropTypes.Boolean:
            return AsnBooleanConverter;
        case AsnPropTypes.CharacterString:
            return AsnCharacterStringConverter;
        case AsnPropTypes.Enumerated:
            return AsnEnumeratedConverter;
        case AsnPropTypes.GeneralString:
            return AsnGeneralStringConverter;
        case AsnPropTypes.GeneralizedTime:
            return AsnGeneralizedTimeConverter;
        case AsnPropTypes.GraphicString:
            return AsnGraphicStringConverter;
        case AsnPropTypes.IA5String:
            return AsnIA5StringConverter;
        case AsnPropTypes.Integer:
            return AsnIntegerConverter;
        case AsnPropTypes.Null:
            return AsnNullConverter;
        case AsnPropTypes.NumericString:
            return AsnNumericStringConverter;
        case AsnPropTypes.ObjectIdentifier:
            return AsnObjectIdentifierConverter;
        case AsnPropTypes.OctetString:
            return AsnOctetStringConverter;
        case AsnPropTypes.PrintableString:
            return AsnPrintableStringConverter;
        case AsnPropTypes.TeletexString:
            return AsnTeletexStringConverter;
        case AsnPropTypes.UTCTime:
            return AsnUTCTimeConverter;
        case AsnPropTypes.UniversalString:
            return AsnUniversalStringConverter;
        case AsnPropTypes.Utf8String:
            return AsnUtf8StringConverter;
        case AsnPropTypes.VideotexString:
            return AsnVideotexStringConverter;
        case AsnPropTypes.VisibleString:
            return AsnVisibleStringConverter;
        default:
            return null;
    }
}

function isConvertible(target) {
    if (typeof target === "function" && target.prototype) {
        if (target.prototype.toASN && target.prototype.fromASN) {
            return true;
        }
        else {
            return isConvertible(target.prototype);
        }
    }
    else {
        return !!(target && typeof target === "object" && "toASN" in target && "fromASN" in target);
    }
}
function isTypeOfArray(target) {
    var _a;
    if (target) {
        const proto = Object.getPrototypeOf(target);
        if (((_a = proto === null || proto === void 0 ? void 0 : proto.prototype) === null || _a === void 0 ? void 0 : _a.constructor) === Array) {
            return true;
        }
        return isTypeOfArray(proto);
    }
    return false;
}
function isArrayEqual(bytes1, bytes2) {
    if (!(bytes1 && bytes2)) {
        return false;
    }
    if (bytes1.byteLength !== bytes2.byteLength) {
        return false;
    }
    const b1 = new Uint8Array(bytes1);
    const b2 = new Uint8Array(bytes2);
    for (let i = 0; i < bytes1.byteLength; i++) {
        if (b1[i] !== b2[i]) {
            return false;
        }
    }
    return true;
}

class AsnSchemaStorage {
    constructor() {
        this.items = new WeakMap();
    }
    has(target) {
        return this.items.has(target);
    }
    get(target, checkSchema = false) {
        const schema = this.items.get(target);
        if (!schema) {
            throw new Error(`Cannot get schema for '${target.prototype.constructor.name}' target`);
        }
        if (checkSchema && !schema.schema) {
            throw new Error(`Schema '${target.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);
        }
        return schema;
    }
    cache(target) {
        const schema = this.get(target);
        if (!schema.schema) {
            schema.schema = this.create(target, true);
        }
    }
    createDefault(target) {
        const schema = { type: AsnTypeTypes.Sequence, items: {} };
        const parentSchema = this.findParentSchema(target);
        if (parentSchema) {
            Object.assign(schema, parentSchema);
            schema.items = Object.assign({}, schema.items, parentSchema.items);
        }
        return schema;
    }
    create(target, useNames) {
        const schema = this.items.get(target) || this.createDefault(target);
        const asn1Value = [];
        for (const key in schema.items) {
            const item = schema.items[key];
            const name = useNames ? key : "";
            let asn1Item;
            if (typeof item.type === "number") {
                const Asn1TypeName = AsnPropTypes[item.type];
                const Asn1Type = asn1js[Asn1TypeName];
                if (!Asn1Type) {
                    throw new Error(`Cannot get ASN1 class by name '${Asn1TypeName}'`);
                }
                asn1Item = new Asn1Type({ name });
            }
            else if (isConvertible(item.type)) {
                const instance = new item.type();
                asn1Item = instance.toSchema(name);
            }
            else if (item.optional) {
                const itemSchema = this.get(item.type);
                if (itemSchema.type === AsnTypeTypes.Choice) {
                    asn1Item = new Any({ name });
                }
                else {
                    asn1Item = this.create(item.type, false);
                    asn1Item.name = name;
                }
            }
            else {
                asn1Item = new Any({ name });
            }
            const optional = !!item.optional || item.defaultValue !== undefined;
            if (item.repeated) {
                asn1Item.name = "";
                const Container = item.repeated === "set" ? Set$1 : Sequence;
                asn1Item = new Container({
                    name: "",
                    value: [new Repeated({ name, value: asn1Item })],
                });
            }
            if (item.context !== null && item.context !== undefined) {
                if (item.implicit) {
                    if (typeof item.type === "number" || isConvertible(item.type)) {
                        const Container = item.repeated ? Constructed : Primitive;
                        asn1Value.push(new Container({ name, optional, idBlock: { tagClass: 3, tagNumber: item.context } }));
                    }
                    else {
                        this.cache(item.type);
                        const isRepeated = !!item.repeated;
                        let value = !isRepeated ? this.get(item.type, true).schema : asn1Item;
                        value =
                            "valueBlock" in value
                                ? value.valueBlock.value
                                :
                                    value.value;
                        asn1Value.push(new Constructed({
                            name: !isRepeated ? name : "",
                            optional,
                            idBlock: { tagClass: 3, tagNumber: item.context },
                            value: value,
                        }));
                    }
                }
                else {
                    asn1Value.push(new Constructed({
                        optional,
                        idBlock: { tagClass: 3, tagNumber: item.context },
                        value: [asn1Item],
                    }));
                }
            }
            else {
                asn1Item.optional = optional;
                asn1Value.push(asn1Item);
            }
        }
        switch (schema.type) {
            case AsnTypeTypes.Sequence:
                return new Sequence({ value: asn1Value, name: "" });
            case AsnTypeTypes.Set:
                return new Set$1({ value: asn1Value, name: "" });
            case AsnTypeTypes.Choice:
                return new Choice({ value: asn1Value, name: "" });
            default:
                throw new Error(`Unsupported ASN1 type in use`);
        }
    }
    set(target, schema) {
        this.items.set(target, schema);
        return this;
    }
    findParentSchema(target) {
        const parent = Object.getPrototypeOf(target);
        if (parent) {
            const schema = this.items.get(parent);
            return schema || this.findParentSchema(parent);
        }
        return null;
    }
}

const schemaStorage = new AsnSchemaStorage();

const AsnType = (options) => (target) => {
    let schema;
    if (!schemaStorage.has(target)) {
        schema = schemaStorage.createDefault(target);
        schemaStorage.set(target, schema);
    }
    else {
        schema = schemaStorage.get(target);
    }
    Object.assign(schema, options);
};
const AsnProp = (options) => (target, propertyKey) => {
    let schema;
    if (!schemaStorage.has(target.constructor)) {
        schema = schemaStorage.createDefault(target.constructor);
        schemaStorage.set(target.constructor, schema);
    }
    else {
        schema = schemaStorage.get(target.constructor);
    }
    const copyOptions = Object.assign({}, options);
    if (typeof copyOptions.type === "number" && !copyOptions.converter) {
        const defaultConverter$1 = defaultConverter(options.type);
        if (!defaultConverter$1) {
            throw new Error(`Cannot get default converter for property '${propertyKey}' of ${target.constructor.name}`);
        }
        copyOptions.converter = defaultConverter$1;
    }
    copyOptions.raw = options.raw;
    schema.items[propertyKey] = copyOptions;
};

class AsnSchemaValidationError extends Error {
    constructor() {
        super(...arguments);
        this.schemas = [];
    }
}

class AsnParser {
    static parse(data, target) {
        const asn1Parsed = fromBER(data);
        if (asn1Parsed.result.error) {
            throw new Error(asn1Parsed.result.error);
        }
        const res = this.fromASN(asn1Parsed.result, target);
        return res;
    }
    static fromASN(asn1Schema, target) {
        try {
            if (isConvertible(target)) {
                const value = new target();
                return value.fromASN(asn1Schema);
            }
            const schema = schemaStorage.get(target);
            schemaStorage.cache(target);
            let targetSchema = schema.schema;
            const choiceResult = this.handleChoiceTypes(asn1Schema, schema, target, targetSchema);
            if (choiceResult === null || choiceResult === void 0 ? void 0 : choiceResult.result) {
                return choiceResult.result;
            }
            if (choiceResult === null || choiceResult === void 0 ? void 0 : choiceResult.targetSchema) {
                targetSchema = choiceResult.targetSchema;
            }
            const sequenceResult = this.handleSequenceTypes(asn1Schema, schema, target, targetSchema);
            const res = new target();
            if (isTypeOfArray(target)) {
                return this.handleArrayTypes(asn1Schema, schema, target);
            }
            this.processSchemaItems(schema, sequenceResult, res);
            return res;
        }
        catch (error) {
            if (error instanceof AsnSchemaValidationError) {
                error.schemas.push(target.name);
            }
            throw error;
        }
    }
    static handleChoiceTypes(asn1Schema, schema, target, targetSchema) {
        if (asn1Schema.constructor === Constructed &&
            schema.type === AsnTypeTypes.Choice &&
            asn1Schema.idBlock.tagClass === 3) {
            for (const key in schema.items) {
                const schemaItem = schema.items[key];
                if (schemaItem.context === asn1Schema.idBlock.tagNumber && schemaItem.implicit) {
                    if (typeof schemaItem.type === "function" &&
                        schemaStorage.has(schemaItem.type)) {
                        const fieldSchema = schemaStorage.get(schemaItem.type);
                        if (fieldSchema && fieldSchema.type === AsnTypeTypes.Sequence) {
                            const newSeq = new Sequence();
                            if ("value" in asn1Schema.valueBlock &&
                                Array.isArray(asn1Schema.valueBlock.value) &&
                                "value" in newSeq.valueBlock) {
                                newSeq.valueBlock.value = asn1Schema.valueBlock.value;
                                const fieldValue = this.fromASN(newSeq, schemaItem.type);
                                const res = new target();
                                res[key] = fieldValue;
                                return { result: res };
                            }
                        }
                    }
                }
            }
        }
        else if (asn1Schema.constructor === Constructed &&
            schema.type !== AsnTypeTypes.Choice) {
            const newTargetSchema = new Constructed({
                idBlock: {
                    tagClass: 3,
                    tagNumber: asn1Schema.idBlock.tagNumber,
                },
                value: schema.schema.valueBlock.value,
            });
            for (const key in schema.items) {
                delete asn1Schema[key];
            }
            return { targetSchema: newTargetSchema };
        }
        return null;
    }
    static handleSequenceTypes(asn1Schema, schema, target, targetSchema) {
        if (schema.type === AsnTypeTypes.Sequence) {
            const asn1ComparedSchema = compareSchema({}, asn1Schema, targetSchema);
            if (!asn1ComparedSchema.verified) {
                throw new AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema.${asn1ComparedSchema.result.error ? ` ${asn1ComparedSchema.result.error}` : ""}`);
            }
            return asn1ComparedSchema;
        }
        else {
            const asn1ComparedSchema = compareSchema({}, asn1Schema, targetSchema);
            if (!asn1ComparedSchema.verified) {
                throw new AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema.${asn1ComparedSchema.result.error ? ` ${asn1ComparedSchema.result.error}` : ""}`);
            }
            return asn1ComparedSchema;
        }
    }
    static processRepeatedField(asn1Elements, asn1Index, schemaItem) {
        let elementsToProcess = asn1Elements.slice(asn1Index);
        if (elementsToProcess.length === 1 && elementsToProcess[0].constructor.name === "Sequence") {
            const seq = elementsToProcess[0];
            if (seq.valueBlock && seq.valueBlock.value && Array.isArray(seq.valueBlock.value)) {
                elementsToProcess = seq.valueBlock.value;
            }
        }
        if (typeof schemaItem.type === "number") {
            const converter = defaultConverter(schemaItem.type);
            if (!converter)
                throw new Error(`No converter for ASN.1 type ${schemaItem.type}`);
            return elementsToProcess
                .filter((el) => el && el.valueBlock)
                .map((el) => {
                try {
                    return converter.fromASN(el);
                }
                catch {
                    return undefined;
                }
            })
                .filter((v) => v !== undefined);
        }
        else {
            return elementsToProcess
                .filter((el) => el && el.valueBlock)
                .map((el) => {
                try {
                    return this.fromASN(el, schemaItem.type);
                }
                catch {
                    return undefined;
                }
            })
                .filter((v) => v !== undefined);
        }
    }
    static processPrimitiveField(asn1Element, schemaItem) {
        const converter = defaultConverter(schemaItem.type);
        if (!converter)
            throw new Error(`No converter for ASN.1 type ${schemaItem.type}`);
        return converter.fromASN(asn1Element);
    }
    static isOptionalChoiceField(schemaItem) {
        return (schemaItem.optional &&
            typeof schemaItem.type === "function" &&
            schemaStorage.has(schemaItem.type) &&
            schemaStorage.get(schemaItem.type).type === AsnTypeTypes.Choice);
    }
    static processOptionalChoiceField(asn1Element, schemaItem) {
        try {
            const value = this.fromASN(asn1Element, schemaItem.type);
            return { processed: true, value };
        }
        catch (err) {
            if (err instanceof AsnSchemaValidationError &&
                /Wrong values for Choice type/.test(err.message)) {
                return { processed: false };
            }
            throw err;
        }
    }
    static handleArrayTypes(asn1Schema, schema, target) {
        if (!("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value))) {
            throw new Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);
        }
        const itemType = schema.itemType;
        if (typeof itemType === "number") {
            const converter = defaultConverter(itemType);
            if (!converter) {
                throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`);
            }
            return target.from(asn1Schema.valueBlock.value, (element) => converter.fromASN(element));
        }
        else {
            return target.from(asn1Schema.valueBlock.value, (element) => this.fromASN(element, itemType));
        }
    }
    static processSchemaItems(schema, asn1ComparedSchema, res) {
        for (const key in schema.items) {
            const asn1SchemaValue = asn1ComparedSchema.result[key];
            if (!asn1SchemaValue) {
                continue;
            }
            const schemaItem = schema.items[key];
            const schemaItemType = schemaItem.type;
            let parsedValue;
            if (typeof schemaItemType === "number" || isConvertible(schemaItemType)) {
                parsedValue = this.processPrimitiveSchemaItem(asn1SchemaValue, schemaItem, schemaItemType);
            }
            else {
                parsedValue = this.processComplexSchemaItem(asn1SchemaValue, schemaItem, schemaItemType);
            }
            if (parsedValue &&
                typeof parsedValue === "object" &&
                "value" in parsedValue &&
                "raw" in parsedValue) {
                res[key] = parsedValue.value;
                res[`${key}Raw`] = parsedValue.raw;
            }
            else {
                res[key] = parsedValue;
            }
        }
    }
    static processPrimitiveSchemaItem(asn1SchemaValue, schemaItem, schemaItemType) {
        var _a;
        const converter = (_a = schemaItem.converter) !== null && _a !== void 0 ? _a : (isConvertible(schemaItemType)
            ? new schemaItemType()
            : null);
        if (!converter) {
            throw new Error("Converter is empty");
        }
        if (schemaItem.repeated) {
            return this.processRepeatedPrimitiveItem(asn1SchemaValue, schemaItem, converter);
        }
        else {
            return this.processSinglePrimitiveItem(asn1SchemaValue, schemaItem, schemaItemType, converter);
        }
    }
    static processRepeatedPrimitiveItem(asn1SchemaValue, schemaItem, converter) {
        if (schemaItem.implicit) {
            const Container = schemaItem.repeated === "sequence" ? Sequence : Set$1;
            const newItem = new Container();
            newItem.valueBlock = asn1SchemaValue.valueBlock;
            const newItemAsn = fromBER(newItem.toBER(false));
            if (newItemAsn.offset === -1) {
                throw new Error(`Cannot parse the child item. ${newItemAsn.result.error}`);
            }
            if (!("value" in newItemAsn.result.valueBlock &&
                Array.isArray(newItemAsn.result.valueBlock.value))) {
                throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");
            }
            const value = newItemAsn.result.valueBlock.value;
            return Array.from(value, (element) => converter.fromASN(element));
        }
        else {
            return Array.from(asn1SchemaValue, (element) => converter.fromASN(element));
        }
    }
    static processSinglePrimitiveItem(asn1SchemaValue, schemaItem, schemaItemType, converter) {
        let value = asn1SchemaValue;
        if (schemaItem.implicit) {
            let newItem;
            if (isConvertible(schemaItemType)) {
                newItem = new schemaItemType().toSchema("");
            }
            else {
                const Asn1TypeName = AsnPropTypes[schemaItemType];
                const Asn1Type = asn1js[Asn1TypeName];
                if (!Asn1Type) {
                    throw new Error(`Cannot get '${Asn1TypeName}' class from asn1js module`);
                }
                newItem = new Asn1Type();
            }
            newItem.valueBlock = value.valueBlock;
            value = fromBER(newItem.toBER(false)).result;
        }
        return converter.fromASN(value);
    }
    static processComplexSchemaItem(asn1SchemaValue, schemaItem, schemaItemType) {
        if (schemaItem.repeated) {
            if (!Array.isArray(asn1SchemaValue)) {
                throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");
            }
            return Array.from(asn1SchemaValue, (element) => this.fromASN(element, schemaItemType));
        }
        else {
            const valueToProcess = this.handleImplicitTagging(asn1SchemaValue, schemaItem, schemaItemType);
            if (this.isOptionalChoiceField(schemaItem)) {
                try {
                    return this.fromASN(valueToProcess, schemaItemType);
                }
                catch (err) {
                    if (err instanceof AsnSchemaValidationError &&
                        /Wrong values for Choice type/.test(err.message)) {
                        return undefined;
                    }
                    throw err;
                }
            }
            else {
                const parsedValue = this.fromASN(valueToProcess, schemaItemType);
                if (schemaItem.raw) {
                    return {
                        value: parsedValue,
                        raw: asn1SchemaValue.valueBeforeDecodeView,
                    };
                }
                return parsedValue;
            }
        }
    }
    static handleImplicitTagging(asn1SchemaValue, schemaItem, schemaItemType) {
        if (schemaItem.implicit && typeof schemaItem.context === "number") {
            const schema = schemaStorage.get(schemaItemType);
            if (schema.type === AsnTypeTypes.Sequence) {
                const newSeq = new Sequence();
                if ("value" in asn1SchemaValue.valueBlock &&
                    Array.isArray(asn1SchemaValue.valueBlock.value) &&
                    "value" in newSeq.valueBlock) {
                    newSeq.valueBlock.value = asn1SchemaValue.valueBlock.value;
                    return newSeq;
                }
            }
            else if (schema.type === AsnTypeTypes.Set) {
                const newSet = new Set$1();
                if ("value" in asn1SchemaValue.valueBlock &&
                    Array.isArray(asn1SchemaValue.valueBlock.value) &&
                    "value" in newSet.valueBlock) {
                    newSet.valueBlock.value = asn1SchemaValue.valueBlock.value;
                    return newSet;
                }
            }
        }
        return asn1SchemaValue;
    }
}

class AsnSerializer {
    static serialize(obj) {
        if (obj instanceof BaseBlock) {
            return obj.toBER(false);
        }
        return this.toASN(obj).toBER(false);
    }
    static toASN(obj) {
        if (obj && typeof obj === "object" && isConvertible(obj)) {
            return obj.toASN();
        }
        if (!(obj && typeof obj === "object")) {
            throw new TypeError("Parameter 1 should be type of Object.");
        }
        const target = obj.constructor;
        const schema = schemaStorage.get(target);
        schemaStorage.cache(target);
        let asn1Value = [];
        if (schema.itemType) {
            if (!Array.isArray(obj)) {
                throw new TypeError("Parameter 1 should be type of Array.");
            }
            if (typeof schema.itemType === "number") {
                const converter = defaultConverter(schema.itemType);
                if (!converter) {
                    throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`);
                }
                asn1Value = obj.map((o) => converter.toASN(o));
            }
            else {
                asn1Value = obj.map((o) => this.toAsnItem({ type: schema.itemType }, "[]", target, o));
            }
        }
        else {
            for (const key in schema.items) {
                const schemaItem = schema.items[key];
                const objProp = obj[key];
                if (objProp === undefined ||
                    schemaItem.defaultValue === objProp ||
                    (typeof schemaItem.defaultValue === "object" &&
                        typeof objProp === "object" &&
                        isArrayEqual(this.serialize(schemaItem.defaultValue), this.serialize(objProp)))) {
                    continue;
                }
                const asn1Item = AsnSerializer.toAsnItem(schemaItem, key, target, objProp);
                if (typeof schemaItem.context === "number") {
                    if (schemaItem.implicit) {
                        if (!schemaItem.repeated &&
                            (typeof schemaItem.type === "number" || isConvertible(schemaItem.type))) {
                            const value = {};
                            value.valueHex =
                                asn1Item instanceof Null
                                    ? asn1Item.valueBeforeDecodeView
                                    : asn1Item.valueBlock.toBER();
                            asn1Value.push(new Primitive({
                                optional: schemaItem.optional,
                                idBlock: {
                                    tagClass: 3,
                                    tagNumber: schemaItem.context,
                                },
                                ...value,
                            }));
                        }
                        else {
                            asn1Value.push(new Constructed({
                                optional: schemaItem.optional,
                                idBlock: {
                                    tagClass: 3,
                                    tagNumber: schemaItem.context,
                                },
                                value: asn1Item.valueBlock.value,
                            }));
                        }
                    }
                    else {
                        asn1Value.push(new Constructed({
                            optional: schemaItem.optional,
                            idBlock: {
                                tagClass: 3,
                                tagNumber: schemaItem.context,
                            },
                            value: [asn1Item],
                        }));
                    }
                }
                else if (schemaItem.repeated) {
                    asn1Value = asn1Value.concat(asn1Item);
                }
                else {
                    asn1Value.push(asn1Item);
                }
            }
        }
        let asnSchema;
        switch (schema.type) {
            case AsnTypeTypes.Sequence:
                asnSchema = new Sequence({ value: asn1Value });
                break;
            case AsnTypeTypes.Set:
                asnSchema = new Set$1({ value: asn1Value });
                break;
            case AsnTypeTypes.Choice:
                if (!asn1Value[0]) {
                    throw new Error(`Schema '${target.name}' has wrong data. Choice cannot be empty.`);
                }
                asnSchema = asn1Value[0];
                break;
        }
        return asnSchema;
    }
    static toAsnItem(schemaItem, key, target, objProp) {
        let asn1Item;
        if (typeof schemaItem.type === "number") {
            const converter = schemaItem.converter;
            if (!converter) {
                throw new Error(`Property '${key}' doesn't have converter for type ${AsnPropTypes[schemaItem.type]} in schema '${target.name}'`);
            }
            if (schemaItem.repeated) {
                if (!Array.isArray(objProp)) {
                    throw new TypeError("Parameter 'objProp' should be type of Array.");
                }
                const items = Array.from(objProp, (element) => converter.toASN(element));
                const Container = schemaItem.repeated === "sequence" ? Sequence : Set$1;
                asn1Item = new Container({
                    value: items,
                });
            }
            else {
                asn1Item = converter.toASN(objProp);
            }
        }
        else {
            if (schemaItem.repeated) {
                if (!Array.isArray(objProp)) {
                    throw new TypeError("Parameter 'objProp' should be type of Array.");
                }
                const items = Array.from(objProp, (element) => this.toASN(element));
                const Container = schemaItem.repeated === "sequence" ? Sequence : Set$1;
                asn1Item = new Container({
                    value: items,
                });
            }
            else {
                asn1Item = this.toASN(objProp);
            }
        }
        return asn1Item;
    }
}

class AsnArray extends Array {
    constructor(items = []) {
        if (typeof items === "number") {
            super(items);
        }
        else {
            super();
            for (const item of items) {
                this.push(item);
            }
        }
    }
}

class AsnConvert {
    static serialize(obj) {
        return AsnSerializer.serialize(obj);
    }
    static parse(data, target) {
        return AsnParser.parse(data, target);
    }
    static toString(data) {
        const buf = BufferSourceConverter.isBufferSource(data)
            ? BufferSourceConverter.toArrayBuffer(data)
            : AsnConvert.serialize(data);
        const asn = fromBER(buf);
        if (asn.offset === -1) {
            throw new Error(`Cannot decode ASN.1 data. ${asn.result.error}`);
        }
        return asn.result.toString();
    }
}

var tslib$3 = {exports: {}};

/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */

var hasRequiredTslib$1;

function requireTslib$1 () {
	if (hasRequiredTslib$1) return tslib$3.exports;
	hasRequiredTslib$1 = 1;
	(function (module) {
		/* global global, define, Symbol, Reflect, Promise, SuppressedError, Iterator */
		var __extends;
		var __assign;
		var __rest;
		var __decorate;
		var __param;
		var __esDecorate;
		var __runInitializers;
		var __propKey;
		var __setFunctionName;
		var __metadata;
		var __awaiter;
		var __generator;
		var __exportStar;
		var __values;
		var __read;
		var __spread;
		var __spreadArrays;
		var __spreadArray;
		var __await;
		var __asyncGenerator;
		var __asyncDelegator;
		var __asyncValues;
		var __makeTemplateObject;
		var __importStar;
		var __importDefault;
		var __classPrivateFieldGet;
		var __classPrivateFieldSet;
		var __classPrivateFieldIn;
		var __createBinding;
		var __addDisposableResource;
		var __disposeResources;
		var __rewriteRelativeImportExtension;
		(function (factory) {
		    var root = typeof commonjsGlobal === "object" ? commonjsGlobal : typeof self === "object" ? self : typeof this === "object" ? this : {};
		    {
		        factory(createExporter(root, createExporter(module.exports)));
		    }
		    function createExporter(exports$1, previous) {
		        if (exports$1 !== root) {
		            if (typeof Object.create === "function") {
		                Object.defineProperty(exports$1, "__esModule", { value: true });
		            }
		            else {
		                exports$1.__esModule = true;
		            }
		        }
		        return function (id, v) { return exports$1[id] = previous ? previous(id, v) : v; };
		    }
		})
		(function (exporter) {
		    var extendStatics = Object.setPrototypeOf ||
		        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
		        function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };

		    __extends = function (d, b) {
		        if (typeof b !== "function" && b !== null)
		            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
		        extendStatics(d, b);
		        function __() { this.constructor = d; }
		        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
		    };

		    __assign = Object.assign || function (t) {
		        for (var s, i = 1, n = arguments.length; i < n; i++) {
		            s = arguments[i];
		            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
		        }
		        return t;
		    };

		    __rest = function (s, e) {
		        var t = {};
		        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
		            t[p] = s[p];
		        if (s != null && typeof Object.getOwnPropertySymbols === "function")
		            for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
		                if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
		                    t[p[i]] = s[p[i]];
		            }
		        return t;
		    };

		    __decorate = function (decorators, target, key, desc) {
		        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
		        if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
		        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
		        return c > 3 && r && Object.defineProperty(target, key, r), r;
		    };

		    __param = function (paramIndex, decorator) {
		        return function (target, key) { decorator(target, key, paramIndex); }
		    };

		    __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
		        function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
		        var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
		        var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
		        var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
		        var _, done = false;
		        for (var i = decorators.length - 1; i >= 0; i--) {
		            var context = {};
		            for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
		            for (var p in contextIn.access) context.access[p] = contextIn.access[p];
		            context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
		            var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
		            if (kind === "accessor") {
		                if (result === void 0) continue;
		                if (result === null || typeof result !== "object") throw new TypeError("Object expected");
		                if (_ = accept(result.get)) descriptor.get = _;
		                if (_ = accept(result.set)) descriptor.set = _;
		                if (_ = accept(result.init)) initializers.unshift(_);
		            }
		            else if (_ = accept(result)) {
		                if (kind === "field") initializers.unshift(_);
		                else descriptor[key] = _;
		            }
		        }
		        if (target) Object.defineProperty(target, contextIn.name, descriptor);
		        done = true;
		    };

		    __runInitializers = function (thisArg, initializers, value) {
		        var useValue = arguments.length > 2;
		        for (var i = 0; i < initializers.length; i++) {
		            value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
		        }
		        return useValue ? value : void 0;
		    };

		    __propKey = function (x) {
		        return typeof x === "symbol" ? x : "".concat(x);
		    };

		    __setFunctionName = function (f, name, prefix) {
		        if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
		        return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
		    };

		    __metadata = function (metadataKey, metadataValue) {
		        if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
		    };

		    __awaiter = function (thisArg, _arguments, P, generator) {
		        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
		        return new (P || (P = Promise))(function (resolve, reject) {
		            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
		            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
		            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
		            step((generator = generator.apply(thisArg, _arguments || [])).next());
		        });
		    };

		    __generator = function (thisArg, body) {
		        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
		        return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
		        function verb(n) { return function (v) { return step([n, v]); }; }
		        function step(op) {
		            if (f) throw new TypeError("Generator is already executing.");
		            while (g && (g = 0, op[0] && (_ = 0)), _) try {
		                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
		                if (y = 0, t) op = [op[0] & 2, t.value];
		                switch (op[0]) {
		                    case 0: case 1: t = op; break;
		                    case 4: _.label++; return { value: op[1], done: false };
		                    case 5: _.label++; y = op[1]; op = [0]; continue;
		                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
		                    default:
		                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
		                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
		                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
		                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
		                        if (t[2]) _.ops.pop();
		                        _.trys.pop(); continue;
		                }
		                op = body.call(thisArg, _);
		            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
		            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
		        }
		    };

		    __exportStar = function(m, o) {
		        for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
		    };

		    __createBinding = Object.create ? (function(o, m, k, k2) {
		        if (k2 === undefined) k2 = k;
		        var desc = Object.getOwnPropertyDescriptor(m, k);
		        if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
		            desc = { enumerable: true, get: function() { return m[k]; } };
		        }
		        Object.defineProperty(o, k2, desc);
		    }) : (function(o, m, k, k2) {
		        if (k2 === undefined) k2 = k;
		        o[k2] = m[k];
		    });

		    __values = function (o) {
		        var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
		        if (m) return m.call(o);
		        if (o && typeof o.length === "number") return {
		            next: function () {
		                if (o && i >= o.length) o = void 0;
		                return { value: o && o[i++], done: !o };
		            }
		        };
		        throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
		    };

		    __read = function (o, n) {
		        var m = typeof Symbol === "function" && o[Symbol.iterator];
		        if (!m) return o;
		        var i = m.call(o), r, ar = [], e;
		        try {
		            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
		        }
		        catch (error) { e = { error: error }; }
		        finally {
		            try {
		                if (r && !r.done && (m = i["return"])) m.call(i);
		            }
		            finally { if (e) throw e.error; }
		        }
		        return ar;
		    };

		    /** @deprecated */
		    __spread = function () {
		        for (var ar = [], i = 0; i < arguments.length; i++)
		            ar = ar.concat(__read(arguments[i]));
		        return ar;
		    };

		    /** @deprecated */
		    __spreadArrays = function () {
		        for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
		        for (var r = Array(s), k = 0, i = 0; i < il; i++)
		            for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
		                r[k] = a[j];
		        return r;
		    };

		    __spreadArray = function (to, from, pack) {
		        if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
		            if (ar || !(i in from)) {
		                if (!ar) ar = Array.prototype.slice.call(from, 0, i);
		                ar[i] = from[i];
		            }
		        }
		        return to.concat(ar || Array.prototype.slice.call(from));
		    };

		    __await = function (v) {
		        return this instanceof __await ? (this.v = v, this) : new __await(v);
		    };

		    __asyncGenerator = function (thisArg, _arguments, generator) {
		        if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
		        var g = generator.apply(thisArg, _arguments || []), i, q = [];
		        return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
		        function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
		        function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
		        function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
		        function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
		        function fulfill(value) { resume("next", value); }
		        function reject(value) { resume("throw", value); }
		        function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
		    };

		    __asyncDelegator = function (o) {
		        var i, p;
		        return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
		        function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
		    };

		    __asyncValues = function (o) {
		        if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
		        var m = o[Symbol.asyncIterator], i;
		        return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
		        function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
		        function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
		    };

		    __makeTemplateObject = function (cooked, raw) {
		        if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
		        return cooked;
		    };

		    var __setModuleDefault = Object.create ? (function(o, v) {
		        Object.defineProperty(o, "default", { enumerable: true, value: v });
		    }) : function(o, v) {
		        o["default"] = v;
		    };

		    var ownKeys = function(o) {
		        ownKeys = Object.getOwnPropertyNames || function (o) {
		            var ar = [];
		            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
		            return ar;
		        };
		        return ownKeys(o);
		    };

		    __importStar = function (mod) {
		        if (mod && mod.__esModule) return mod;
		        var result = {};
		        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
		        __setModuleDefault(result, mod);
		        return result;
		    };

		    __importDefault = function (mod) {
		        return (mod && mod.__esModule) ? mod : { "default": mod };
		    };

		    __classPrivateFieldGet = function (receiver, state, kind, f) {
		        if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
		        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
		        return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
		    };

		    __classPrivateFieldSet = function (receiver, state, value, kind, f) {
		        if (kind === "m") throw new TypeError("Private method is not writable");
		        if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
		        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
		        return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
		    };

		    __classPrivateFieldIn = function (state, receiver) {
		        if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
		        return typeof state === "function" ? receiver === state : state.has(receiver);
		    };

		    __addDisposableResource = function (env, value, async) {
		        if (value !== null && value !== void 0) {
		            if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
		            var dispose, inner;
		            if (async) {
		                if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
		                dispose = value[Symbol.asyncDispose];
		            }
		            if (dispose === void 0) {
		                if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
		                dispose = value[Symbol.dispose];
		                if (async) inner = dispose;
		            }
		            if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
		            if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
		            env.stack.push({ value: value, dispose: dispose, async: async });
		        }
		        else if (async) {
		            env.stack.push({ async: true });
		        }
		        return value;
		    };

		    var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
		        var e = new Error(message);
		        return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
		    };

		    __disposeResources = function (env) {
		        function fail(e) {
		            env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
		            env.hasError = true;
		        }
		        var r, s = 0;
		        function next() {
		            while (r = env.stack.pop()) {
		                try {
		                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
		                    if (r.dispose) {
		                        var result = r.dispose.call(r.value);
		                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
		                    }
		                    else s |= 1;
		                }
		                catch (e) {
		                    fail(e);
		                }
		            }
		            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
		            if (env.hasError) throw env.error;
		        }
		        return next();
		    };

		    __rewriteRelativeImportExtension = function (path, preserveJsx) {
		        if (typeof path === "string" && /^\.\.?\//.test(path)) {
		            return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
		                return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
		            });
		        }
		        return path;
		    };

		    exporter("__extends", __extends);
		    exporter("__assign", __assign);
		    exporter("__rest", __rest);
		    exporter("__decorate", __decorate);
		    exporter("__param", __param);
		    exporter("__esDecorate", __esDecorate);
		    exporter("__runInitializers", __runInitializers);
		    exporter("__propKey", __propKey);
		    exporter("__setFunctionName", __setFunctionName);
		    exporter("__metadata", __metadata);
		    exporter("__awaiter", __awaiter);
		    exporter("__generator", __generator);
		    exporter("__exportStar", __exportStar);
		    exporter("__createBinding", __createBinding);
		    exporter("__values", __values);
		    exporter("__read", __read);
		    exporter("__spread", __spread);
		    exporter("__spreadArrays", __spreadArrays);
		    exporter("__spreadArray", __spreadArray);
		    exporter("__await", __await);
		    exporter("__asyncGenerator", __asyncGenerator);
		    exporter("__asyncDelegator", __asyncDelegator);
		    exporter("__asyncValues", __asyncValues);
		    exporter("__makeTemplateObject", __makeTemplateObject);
		    exporter("__importStar", __importStar);
		    exporter("__importDefault", __importDefault);
		    exporter("__classPrivateFieldGet", __classPrivateFieldGet);
		    exporter("__classPrivateFieldSet", __classPrivateFieldSet);
		    exporter("__classPrivateFieldIn", __classPrivateFieldIn);
		    exporter("__addDisposableResource", __addDisposableResource);
		    exporter("__disposeResources", __disposeResources);
		    exporter("__rewriteRelativeImportExtension", __rewriteRelativeImportExtension);
		});
	} (tslib$3));
	return tslib$3.exports;
}

var tslibExports$1 = /*@__PURE__*/ requireTslib$1();
const tslib$2 = /*@__PURE__*/getDefaultExportFromCjs(tslibExports$1);

const {
    __extends: __extends$1,
    __assign: __assign$1,
    __rest: __rest$1,
    __decorate: __decorate$1,
    __param: __param$1,
    __esDecorate,
    __runInitializers,
    __propKey,
    __setFunctionName,
    __metadata: __metadata$1,
    __awaiter: __awaiter$3,
    __generator: __generator$1,
    __exportStar: __exportStar$1,
    __createBinding: __createBinding$1,
    __values: __values$1,
    __read: __read$1,
    __spread: __spread$1,
    __spreadArrays: __spreadArrays$1,
    __spreadArray,
    __await: __await$1,
    __asyncGenerator: __asyncGenerator$1,
    __asyncDelegator: __asyncDelegator$1,
    __asyncValues: __asyncValues$1,
    __makeTemplateObject: __makeTemplateObject$1,
    __importStar: __importStar$1,
    __importDefault: __importDefault$1,
    __classPrivateFieldGet: __classPrivateFieldGet$1,
    __classPrivateFieldSet: __classPrivateFieldSet$1,
    __classPrivateFieldIn,
    __addDisposableResource,
    __disposeResources,
    __rewriteRelativeImportExtension,
} = tslib$2;

class IpConverter {
    static isIPv4(ip) {
        return /^(\d{1,3}\.){3}\d{1,3}$/.test(ip);
    }
    static parseIPv4(ip) {
        const parts = ip.split(".");
        if (parts.length !== 4) {
            throw new Error("Invalid IPv4 address");
        }
        return parts.map((part) => {
            const num = parseInt(part, 10);
            if (isNaN(num) || num < 0 || num > 255) {
                throw new Error("Invalid IPv4 address part");
            }
            return num;
        });
    }
    static parseIPv6(ip) {
        const expandedIP = this.expandIPv6(ip);
        const parts = expandedIP.split(":");
        if (parts.length !== 8) {
            throw new Error("Invalid IPv6 address");
        }
        return parts.reduce((bytes, part) => {
            const num = parseInt(part, 16);
            if (isNaN(num) || num < 0 || num > 0xffff) {
                throw new Error("Invalid IPv6 address part");
            }
            bytes.push((num >> 8) & 0xff);
            bytes.push(num & 0xff);
            return bytes;
        }, []);
    }
    static expandIPv6(ip) {
        if (!ip.includes("::")) {
            return ip;
        }
        const parts = ip.split("::");
        if (parts.length > 2) {
            throw new Error("Invalid IPv6 address");
        }
        const left = parts[0] ? parts[0].split(":") : [];
        const right = parts[1] ? parts[1].split(":") : [];
        const missing = 8 - (left.length + right.length);
        if (missing < 0) {
            throw new Error("Invalid IPv6 address");
        }
        return [...left, ...Array(missing).fill("0"), ...right].join(":");
    }
    static formatIPv6(bytes) {
        const parts = [];
        for (let i = 0; i < 16; i += 2) {
            parts.push(((bytes[i] << 8) | bytes[i + 1]).toString(16));
        }
        return this.compressIPv6(parts.join(":"));
    }
    static compressIPv6(ip) {
        const parts = ip.split(":");
        let longestZeroStart = -1;
        let longestZeroLength = 0;
        let currentZeroStart = -1;
        let currentZeroLength = 0;
        for (let i = 0; i < parts.length; i++) {
            if (parts[i] === "0") {
                if (currentZeroStart === -1) {
                    currentZeroStart = i;
                }
                currentZeroLength++;
            }
            else {
                if (currentZeroLength > longestZeroLength) {
                    longestZeroStart = currentZeroStart;
                    longestZeroLength = currentZeroLength;
                }
                currentZeroStart = -1;
                currentZeroLength = 0;
            }
        }
        if (currentZeroLength > longestZeroLength) {
            longestZeroStart = currentZeroStart;
            longestZeroLength = currentZeroLength;
        }
        if (longestZeroLength > 1) {
            const before = parts.slice(0, longestZeroStart).join(":");
            const after = parts.slice(longestZeroStart + longestZeroLength).join(":");
            return `${before}::${after}`;
        }
        return ip;
    }
    static parseCIDR(text) {
        const [addr, prefixStr] = text.split("/");
        const prefix = parseInt(prefixStr, 10);
        if (this.isIPv4(addr)) {
            if (prefix < 0 || prefix > 32) {
                throw new Error("Invalid IPv4 prefix length");
            }
            return [this.parseIPv4(addr), prefix];
        }
        else {
            if (prefix < 0 || prefix > 128) {
                throw new Error("Invalid IPv6 prefix length");
            }
            return [this.parseIPv6(addr), prefix];
        }
    }
    static decodeIP(value) {
        if (value.length === 64 && parseInt(value, 16) === 0) {
            return "::/0";
        }
        if (value.length !== 16) {
            return value;
        }
        const mask = parseInt(value.slice(8), 16)
            .toString(2)
            .split("")
            .reduce((a, k) => a + +k, 0);
        let ip = value.slice(0, 8).replace(/(.{2})/g, (match) => `${parseInt(match, 16)}.`);
        ip = ip.slice(0, -1);
        return `${ip}/${mask}`;
    }
    static toString(buf) {
        const uint8 = new Uint8Array(buf);
        if (uint8.length === 4) {
            return Array.from(uint8).join(".");
        }
        if (uint8.length === 16) {
            return this.formatIPv6(uint8);
        }
        if (uint8.length === 8 || uint8.length === 32) {
            const half = uint8.length / 2;
            const addrBytes = uint8.slice(0, half);
            const maskBytes = uint8.slice(half);
            const isAllZeros = uint8.every((byte) => byte === 0);
            if (isAllZeros) {
                return uint8.length === 8 ? "0.0.0.0/0" : "::/0";
            }
            const prefixLen = maskBytes.reduce((a, b) => a + (b.toString(2).match(/1/g) || []).length, 0);
            if (uint8.length === 8) {
                const addrStr = Array.from(addrBytes).join(".");
                return `${addrStr}/${prefixLen}`;
            }
            else {
                const addrStr = this.formatIPv6(addrBytes);
                return `${addrStr}/${prefixLen}`;
            }
        }
        return this.decodeIP(Convert.ToHex(buf));
    }
    static fromString(text) {
        if (text.includes("/")) {
            const [addr, prefix] = this.parseCIDR(text);
            const maskBytes = new Uint8Array(addr.length);
            let bitsLeft = prefix;
            for (let i = 0; i < maskBytes.length; i++) {
                if (bitsLeft >= 8) {
                    maskBytes[i] = 0xff;
                    bitsLeft -= 8;
                }
                else if (bitsLeft > 0) {
                    maskBytes[i] = 0xff << (8 - bitsLeft);
                    bitsLeft = 0;
                }
            }
            const out = new Uint8Array(addr.length * 2);
            out.set(addr, 0);
            out.set(maskBytes, addr.length);
            return out.buffer;
        }
        const bytes = this.isIPv4(text) ? this.parseIPv4(text) : this.parseIPv6(text);
        return new Uint8Array(bytes).buffer;
    }
}

var RelativeDistinguishedName_1, RDNSequence_1, Name_1;
let DirectoryString = class DirectoryString {
    constructor(params = {}) {
        Object.assign(this, params);
    }
    toString() {
        return (this.bmpString ||
            this.printableString ||
            this.teletexString ||
            this.universalString ||
            this.utf8String ||
            "");
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.TeletexString })
], DirectoryString.prototype, "teletexString", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.PrintableString })
], DirectoryString.prototype, "printableString", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.UniversalString })
], DirectoryString.prototype, "universalString", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Utf8String })
], DirectoryString.prototype, "utf8String", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.BmpString })
], DirectoryString.prototype, "bmpString", void 0);
DirectoryString = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], DirectoryString);
let AttributeValue = class AttributeValue extends DirectoryString {
    constructor(params = {}) {
        super(params);
        Object.assign(this, params);
    }
    toString() {
        return this.ia5String || (this.anyValue ? Convert.ToHex(this.anyValue) : super.toString());
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.IA5String })
], AttributeValue.prototype, "ia5String", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any })
], AttributeValue.prototype, "anyValue", void 0);
AttributeValue = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], AttributeValue);
class AttributeTypeAndValue {
    constructor(params = {}) {
        this.type = "";
        this.value = new AttributeValue();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], AttributeTypeAndValue.prototype, "type", void 0);
__decorate$1([
    AsnProp({ type: AttributeValue })
], AttributeTypeAndValue.prototype, "value", void 0);
let RelativeDistinguishedName = RelativeDistinguishedName_1 = class RelativeDistinguishedName extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, RelativeDistinguishedName_1.prototype);
    }
};
RelativeDistinguishedName = RelativeDistinguishedName_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Set, itemType: AttributeTypeAndValue })
], RelativeDistinguishedName);
let RDNSequence = RDNSequence_1 = class RDNSequence extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, RDNSequence_1.prototype);
    }
};
RDNSequence = RDNSequence_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: RelativeDistinguishedName })
], RDNSequence);
let Name$1 = Name_1 = class Name extends RDNSequence {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, Name_1.prototype);
    }
};
Name$1 = Name_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], Name$1);

const AsnIpConverter = {
    fromASN: (value) => IpConverter.toString(AsnOctetStringConverter.fromASN(value)),
    toASN: (value) => AsnOctetStringConverter.toASN(IpConverter.fromString(value)),
};
class OtherName {
    constructor(params = {}) {
        this.typeId = "";
        this.value = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], OtherName.prototype, "typeId", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any, context: 0 })
], OtherName.prototype, "value", void 0);
class EDIPartyName {
    constructor(params = {}) {
        this.partyName = new DirectoryString();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: DirectoryString, optional: true, context: 0, implicit: true })
], EDIPartyName.prototype, "nameAssigner", void 0);
__decorate$1([
    AsnProp({ type: DirectoryString, context: 1, implicit: true })
], EDIPartyName.prototype, "partyName", void 0);
let GeneralName$1 = class GeneralName {
    constructor(params = {}) {
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: OtherName, context: 0, implicit: true })
], GeneralName$1.prototype, "otherName", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.IA5String, context: 1, implicit: true })
], GeneralName$1.prototype, "rfc822Name", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.IA5String, context: 2, implicit: true })
], GeneralName$1.prototype, "dNSName", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any, context: 3, implicit: true })
], GeneralName$1.prototype, "x400Address", void 0);
__decorate$1([
    AsnProp({ type: Name$1, context: 4, implicit: false })
], GeneralName$1.prototype, "directoryName", void 0);
__decorate$1([
    AsnProp({ type: EDIPartyName, context: 5 })
], GeneralName$1.prototype, "ediPartyName", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.IA5String, context: 6, implicit: true })
], GeneralName$1.prototype, "uniformResourceIdentifier", void 0);
__decorate$1([
    AsnProp({
        type: AsnPropTypes.OctetString,
        context: 7,
        implicit: true,
        converter: AsnIpConverter,
    })
], GeneralName$1.prototype, "iPAddress", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier, context: 8, implicit: true })
], GeneralName$1.prototype, "registeredID", void 0);
GeneralName$1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], GeneralName$1);

const id_pkix = "1.3.6.1.5.5.7";
const id_pe = `${id_pkix}.1`;
const id_kp = `${id_pkix}.3`;
const id_ad = `${id_pkix}.48`;
const id_ad_ocsp = `${id_ad}.1`;
const id_ad_caIssuers = `${id_ad}.2`;
const id_ad_timeStamping = `${id_ad}.3`;
const id_ad_caRepository = `${id_ad}.5`;
const id_ce = "2.5.29";

var AuthorityInfoAccessSyntax_1;
const id_pe_authorityInfoAccess = `${id_pe}.1`;
class AccessDescription {
    constructor(params = {}) {
        this.accessMethod = "";
        this.accessLocation = new GeneralName$1();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], AccessDescription.prototype, "accessMethod", void 0);
__decorate$1([
    AsnProp({ type: GeneralName$1 })
], AccessDescription.prototype, "accessLocation", void 0);
let AuthorityInfoAccessSyntax = AuthorityInfoAccessSyntax_1 = class AuthorityInfoAccessSyntax extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, AuthorityInfoAccessSyntax_1.prototype);
    }
};
AuthorityInfoAccessSyntax = AuthorityInfoAccessSyntax_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: AccessDescription })
], AuthorityInfoAccessSyntax);

const id_ce_authorityKeyIdentifier = `${id_ce}.35`;
class KeyIdentifier extends OctetString {
}
class AuthorityKeyIdentifier {
    constructor(params = {}) {
        if (params) {
            Object.assign(this, params);
        }
    }
}
__decorate$1([
    AsnProp({ type: KeyIdentifier, context: 0, optional: true, implicit: true })
], AuthorityKeyIdentifier.prototype, "keyIdentifier", void 0);
__decorate$1([
    AsnProp({ type: GeneralName$1, context: 1, optional: true, implicit: true, repeated: "sequence" })
], AuthorityKeyIdentifier.prototype, "authorityCertIssuer", void 0);
__decorate$1([
    AsnProp({
        type: AsnPropTypes.Integer,
        context: 2,
        optional: true,
        implicit: true,
        converter: AsnIntegerArrayBufferConverter,
    })
], AuthorityKeyIdentifier.prototype, "authorityCertSerialNumber", void 0);

const id_ce_basicConstraints = `${id_ce}.19`;
class BasicConstraints {
    constructor(params = {}) {
        this.cA = false;
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Boolean, defaultValue: false })
], BasicConstraints.prototype, "cA", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, optional: true })
], BasicConstraints.prototype, "pathLenConstraint", void 0);

var GeneralNames_1;
let GeneralNames$1 = GeneralNames_1 = class GeneralNames extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, GeneralNames_1.prototype);
    }
};
GeneralNames$1 = GeneralNames_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: GeneralName$1 })
], GeneralNames$1);

var CertificateIssuer_1;
let CertificateIssuer = CertificateIssuer_1 = class CertificateIssuer extends GeneralNames$1 {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, CertificateIssuer_1.prototype);
    }
};
CertificateIssuer = CertificateIssuer_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], CertificateIssuer);

var CertificatePolicies_1;
const id_ce_certificatePolicies = `${id_ce}.32`;
let DisplayText = class DisplayText {
    constructor(params = {}) {
        Object.assign(this, params);
    }
    toString() {
        return this.ia5String || this.visibleString || this.bmpString || this.utf8String || "";
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.IA5String })
], DisplayText.prototype, "ia5String", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.VisibleString })
], DisplayText.prototype, "visibleString", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.BmpString })
], DisplayText.prototype, "bmpString", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Utf8String })
], DisplayText.prototype, "utf8String", void 0);
DisplayText = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], DisplayText);
class NoticeReference {
    constructor(params = {}) {
        this.organization = new DisplayText();
        this.noticeNumbers = [];
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: DisplayText })
], NoticeReference.prototype, "organization", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, repeated: "sequence" })
], NoticeReference.prototype, "noticeNumbers", void 0);
class UserNotice {
    constructor(params = {}) {
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: NoticeReference, optional: true })
], UserNotice.prototype, "noticeRef", void 0);
__decorate$1([
    AsnProp({ type: DisplayText, optional: true })
], UserNotice.prototype, "explicitText", void 0);
let Qualifier = class Qualifier {
    constructor(params = {}) {
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.IA5String })
], Qualifier.prototype, "cPSuri", void 0);
__decorate$1([
    AsnProp({ type: UserNotice })
], Qualifier.prototype, "userNotice", void 0);
Qualifier = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], Qualifier);
class PolicyQualifierInfo {
    constructor(params = {}) {
        this.policyQualifierId = "";
        this.qualifier = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], PolicyQualifierInfo.prototype, "policyQualifierId", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any })
], PolicyQualifierInfo.prototype, "qualifier", void 0);
class PolicyInformation {
    constructor(params = {}) {
        this.policyIdentifier = "";
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], PolicyInformation.prototype, "policyIdentifier", void 0);
__decorate$1([
    AsnProp({ type: PolicyQualifierInfo, repeated: "sequence", optional: true })
], PolicyInformation.prototype, "policyQualifiers", void 0);
let CertificatePolicies = CertificatePolicies_1 = class CertificatePolicies extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, CertificatePolicies_1.prototype);
    }
};
CertificatePolicies = CertificatePolicies_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: PolicyInformation })
], CertificatePolicies);

let CRLNumber = class CRLNumber {
    constructor(value = 0) {
        this.value = value;
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], CRLNumber.prototype, "value", void 0);
CRLNumber = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], CRLNumber);

let BaseCRLNumber = class BaseCRLNumber extends CRLNumber {
};
BaseCRLNumber = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], BaseCRLNumber);

var CRLDistributionPoints_1;
const id_ce_cRLDistributionPoints = `${id_ce}.31`;
var ReasonFlags;
(function (ReasonFlags) {
    ReasonFlags[ReasonFlags["unused"] = 1] = "unused";
    ReasonFlags[ReasonFlags["keyCompromise"] = 2] = "keyCompromise";
    ReasonFlags[ReasonFlags["cACompromise"] = 4] = "cACompromise";
    ReasonFlags[ReasonFlags["affiliationChanged"] = 8] = "affiliationChanged";
    ReasonFlags[ReasonFlags["superseded"] = 16] = "superseded";
    ReasonFlags[ReasonFlags["cessationOfOperation"] = 32] = "cessationOfOperation";
    ReasonFlags[ReasonFlags["certificateHold"] = 64] = "certificateHold";
    ReasonFlags[ReasonFlags["privilegeWithdrawn"] = 128] = "privilegeWithdrawn";
    ReasonFlags[ReasonFlags["aACompromise"] = 256] = "aACompromise";
})(ReasonFlags || (ReasonFlags = {}));
class Reason extends BitString {
    toJSON() {
        const res = [];
        const flags = this.toNumber();
        if (flags & ReasonFlags.aACompromise) {
            res.push("aACompromise");
        }
        if (flags & ReasonFlags.affiliationChanged) {
            res.push("affiliationChanged");
        }
        if (flags & ReasonFlags.cACompromise) {
            res.push("cACompromise");
        }
        if (flags & ReasonFlags.certificateHold) {
            res.push("certificateHold");
        }
        if (flags & ReasonFlags.cessationOfOperation) {
            res.push("cessationOfOperation");
        }
        if (flags & ReasonFlags.keyCompromise) {
            res.push("keyCompromise");
        }
        if (flags & ReasonFlags.privilegeWithdrawn) {
            res.push("privilegeWithdrawn");
        }
        if (flags & ReasonFlags.superseded) {
            res.push("superseded");
        }
        if (flags & ReasonFlags.unused) {
            res.push("unused");
        }
        return res;
    }
    toString() {
        return `[${this.toJSON().join(", ")}]`;
    }
}
let DistributionPointName = class DistributionPointName {
    constructor(params = {}) {
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: GeneralName$1, context: 0, repeated: "sequence", implicit: true })
], DistributionPointName.prototype, "fullName", void 0);
__decorate$1([
    AsnProp({ type: RelativeDistinguishedName, context: 1, implicit: true })
], DistributionPointName.prototype, "nameRelativeToCRLIssuer", void 0);
DistributionPointName = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], DistributionPointName);
class DistributionPoint {
    constructor(params = {}) {
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: DistributionPointName, context: 0, optional: true })
], DistributionPoint.prototype, "distributionPoint", void 0);
__decorate$1([
    AsnProp({ type: Reason, context: 1, optional: true, implicit: true })
], DistributionPoint.prototype, "reasons", void 0);
__decorate$1([
    AsnProp({ type: GeneralName$1, context: 2, optional: true, repeated: "sequence", implicit: true })
], DistributionPoint.prototype, "cRLIssuer", void 0);
let CRLDistributionPoints = CRLDistributionPoints_1 = class CRLDistributionPoints extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, CRLDistributionPoints_1.prototype);
    }
};
CRLDistributionPoints = CRLDistributionPoints_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: DistributionPoint })
], CRLDistributionPoints);

var FreshestCRL_1;
let FreshestCRL = FreshestCRL_1 = class FreshestCRL extends CRLDistributionPoints {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, FreshestCRL_1.prototype);
    }
};
FreshestCRL = FreshestCRL_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: DistributionPoint })
], FreshestCRL);

class IssuingDistributionPoint {
    constructor(params = {}) {
        this.onlyContainsUserCerts = IssuingDistributionPoint.ONLY;
        this.onlyContainsCACerts = IssuingDistributionPoint.ONLY;
        this.indirectCRL = IssuingDistributionPoint.ONLY;
        this.onlyContainsAttributeCerts = IssuingDistributionPoint.ONLY;
        Object.assign(this, params);
    }
}
IssuingDistributionPoint.ONLY = false;
__decorate$1([
    AsnProp({ type: DistributionPointName, context: 0, optional: true })
], IssuingDistributionPoint.prototype, "distributionPoint", void 0);
__decorate$1([
    AsnProp({
        type: AsnPropTypes.Boolean,
        context: 1,
        defaultValue: IssuingDistributionPoint.ONLY,
        implicit: true,
    })
], IssuingDistributionPoint.prototype, "onlyContainsUserCerts", void 0);
__decorate$1([
    AsnProp({
        type: AsnPropTypes.Boolean,
        context: 2,
        defaultValue: IssuingDistributionPoint.ONLY,
        implicit: true,
    })
], IssuingDistributionPoint.prototype, "onlyContainsCACerts", void 0);
__decorate$1([
    AsnProp({ type: Reason, context: 3, optional: true, implicit: true })
], IssuingDistributionPoint.prototype, "onlySomeReasons", void 0);
__decorate$1([
    AsnProp({
        type: AsnPropTypes.Boolean,
        context: 4,
        defaultValue: IssuingDistributionPoint.ONLY,
        implicit: true,
    })
], IssuingDistributionPoint.prototype, "indirectCRL", void 0);
__decorate$1([
    AsnProp({
        type: AsnPropTypes.Boolean,
        context: 5,
        defaultValue: IssuingDistributionPoint.ONLY,
        implicit: true,
    })
], IssuingDistributionPoint.prototype, "onlyContainsAttributeCerts", void 0);

const id_ce_cRLReasons = `${id_ce}.21`;
var CRLReasons;
(function (CRLReasons) {
    CRLReasons[CRLReasons["unspecified"] = 0] = "unspecified";
    CRLReasons[CRLReasons["keyCompromise"] = 1] = "keyCompromise";
    CRLReasons[CRLReasons["cACompromise"] = 2] = "cACompromise";
    CRLReasons[CRLReasons["affiliationChanged"] = 3] = "affiliationChanged";
    CRLReasons[CRLReasons["superseded"] = 4] = "superseded";
    CRLReasons[CRLReasons["cessationOfOperation"] = 5] = "cessationOfOperation";
    CRLReasons[CRLReasons["certificateHold"] = 6] = "certificateHold";
    CRLReasons[CRLReasons["removeFromCRL"] = 8] = "removeFromCRL";
    CRLReasons[CRLReasons["privilegeWithdrawn"] = 9] = "privilegeWithdrawn";
    CRLReasons[CRLReasons["aACompromise"] = 10] = "aACompromise";
})(CRLReasons || (CRLReasons = {}));
let CRLReason = class CRLReason {
    constructor(reason = CRLReasons.unspecified) {
        this.reason = CRLReasons.unspecified;
        this.reason = reason;
    }
    toJSON() {
        return CRLReasons[this.reason];
    }
    toString() {
        return this.toJSON();
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.Enumerated })
], CRLReason.prototype, "reason", void 0);
CRLReason = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], CRLReason);

var ExtendedKeyUsage_1;
const id_ce_extKeyUsage = `${id_ce}.37`;
let ExtendedKeyUsage$1 = ExtendedKeyUsage_1 = class ExtendedKeyUsage extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, ExtendedKeyUsage_1.prototype);
    }
};
ExtendedKeyUsage$1 = ExtendedKeyUsage_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: AsnPropTypes.ObjectIdentifier })
], ExtendedKeyUsage$1);
const id_kp_serverAuth = `${id_kp}.1`;
const id_kp_clientAuth = `${id_kp}.2`;
const id_kp_codeSigning = `${id_kp}.3`;
const id_kp_emailProtection = `${id_kp}.4`;
const id_kp_timeStamping = `${id_kp}.8`;
const id_kp_OCSPSigning = `${id_kp}.9`;

let InhibitAnyPolicy = class InhibitAnyPolicy {
    constructor(value = new ArrayBuffer(0)) {
        this.value = value;
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], InhibitAnyPolicy.prototype, "value", void 0);
InhibitAnyPolicy = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], InhibitAnyPolicy);

const id_ce_invalidityDate = `${id_ce}.24`;
let InvalidityDate = class InvalidityDate {
    constructor(value) {
        this.value = new Date();
        if (value) {
            this.value = value;
        }
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.GeneralizedTime })
], InvalidityDate.prototype, "value", void 0);
InvalidityDate = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], InvalidityDate);

var IssueAlternativeName_1;
const id_ce_issuerAltName = `${id_ce}.18`;
let IssueAlternativeName = IssueAlternativeName_1 = class IssueAlternativeName extends GeneralNames$1 {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, IssueAlternativeName_1.prototype);
    }
};
IssueAlternativeName = IssueAlternativeName_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], IssueAlternativeName);

const id_ce_keyUsage = `${id_ce}.15`;
var KeyUsageFlags$1;
(function (KeyUsageFlags) {
    KeyUsageFlags[KeyUsageFlags["digitalSignature"] = 1] = "digitalSignature";
    KeyUsageFlags[KeyUsageFlags["nonRepudiation"] = 2] = "nonRepudiation";
    KeyUsageFlags[KeyUsageFlags["keyEncipherment"] = 4] = "keyEncipherment";
    KeyUsageFlags[KeyUsageFlags["dataEncipherment"] = 8] = "dataEncipherment";
    KeyUsageFlags[KeyUsageFlags["keyAgreement"] = 16] = "keyAgreement";
    KeyUsageFlags[KeyUsageFlags["keyCertSign"] = 32] = "keyCertSign";
    KeyUsageFlags[KeyUsageFlags["cRLSign"] = 64] = "cRLSign";
    KeyUsageFlags[KeyUsageFlags["encipherOnly"] = 128] = "encipherOnly";
    KeyUsageFlags[KeyUsageFlags["decipherOnly"] = 256] = "decipherOnly";
})(KeyUsageFlags$1 || (KeyUsageFlags$1 = {}));
class KeyUsage extends BitString {
    toJSON() {
        const flag = this.toNumber();
        const res = [];
        if (flag & KeyUsageFlags$1.cRLSign) {
            res.push("crlSign");
        }
        if (flag & KeyUsageFlags$1.dataEncipherment) {
            res.push("dataEncipherment");
        }
        if (flag & KeyUsageFlags$1.decipherOnly) {
            res.push("decipherOnly");
        }
        if (flag & KeyUsageFlags$1.digitalSignature) {
            res.push("digitalSignature");
        }
        if (flag & KeyUsageFlags$1.encipherOnly) {
            res.push("encipherOnly");
        }
        if (flag & KeyUsageFlags$1.keyAgreement) {
            res.push("keyAgreement");
        }
        if (flag & KeyUsageFlags$1.keyCertSign) {
            res.push("keyCertSign");
        }
        if (flag & KeyUsageFlags$1.keyEncipherment) {
            res.push("keyEncipherment");
        }
        if (flag & KeyUsageFlags$1.nonRepudiation) {
            res.push("nonRepudiation");
        }
        return res;
    }
    toString() {
        return `[${this.toJSON().join(", ")}]`;
    }
}

var GeneralSubtrees_1;
class GeneralSubtree {
    constructor(params = {}) {
        this.base = new GeneralName$1();
        this.minimum = 0;
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: GeneralName$1 })
], GeneralSubtree.prototype, "base", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, context: 0, defaultValue: 0, implicit: true })
], GeneralSubtree.prototype, "minimum", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, context: 1, optional: true, implicit: true })
], GeneralSubtree.prototype, "maximum", void 0);
let GeneralSubtrees = GeneralSubtrees_1 = class GeneralSubtrees extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, GeneralSubtrees_1.prototype);
    }
};
GeneralSubtrees = GeneralSubtrees_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: GeneralSubtree })
], GeneralSubtrees);
class NameConstraints {
    constructor(params = {}) {
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: GeneralSubtrees, context: 0, optional: true, implicit: true })
], NameConstraints.prototype, "permittedSubtrees", void 0);
__decorate$1([
    AsnProp({ type: GeneralSubtrees, context: 1, optional: true, implicit: true })
], NameConstraints.prototype, "excludedSubtrees", void 0);

class PolicyConstraints {
    constructor(params = {}) {
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({
        type: AsnPropTypes.Integer,
        context: 0,
        implicit: true,
        optional: true,
        converter: AsnIntegerArrayBufferConverter,
    })
], PolicyConstraints.prototype, "requireExplicitPolicy", void 0);
__decorate$1([
    AsnProp({
        type: AsnPropTypes.Integer,
        context: 1,
        implicit: true,
        optional: true,
        converter: AsnIntegerArrayBufferConverter,
    })
], PolicyConstraints.prototype, "inhibitPolicyMapping", void 0);

var PolicyMappings_1;
class PolicyMapping {
    constructor(params = {}) {
        this.issuerDomainPolicy = "";
        this.subjectDomainPolicy = "";
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], PolicyMapping.prototype, "issuerDomainPolicy", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], PolicyMapping.prototype, "subjectDomainPolicy", void 0);
let PolicyMappings = PolicyMappings_1 = class PolicyMappings extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, PolicyMappings_1.prototype);
    }
};
PolicyMappings = PolicyMappings_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: PolicyMapping })
], PolicyMappings);

var SubjectAlternativeName_1;
const id_ce_subjectAltName = `${id_ce}.17`;
let SubjectAlternativeName = SubjectAlternativeName_1 = class SubjectAlternativeName extends GeneralNames$1 {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, SubjectAlternativeName_1.prototype);
    }
};
SubjectAlternativeName = SubjectAlternativeName_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], SubjectAlternativeName);

let Attribute$2 = class Attribute {
    constructor(params = {}) {
        this.type = "";
        this.values = [];
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], Attribute$2.prototype, "type", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any, repeated: "set" })
], Attribute$2.prototype, "values", void 0);

var SubjectDirectoryAttributes_1;
let SubjectDirectoryAttributes = SubjectDirectoryAttributes_1 = class SubjectDirectoryAttributes extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, SubjectDirectoryAttributes_1.prototype);
    }
};
SubjectDirectoryAttributes = SubjectDirectoryAttributes_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: Attribute$2 })
], SubjectDirectoryAttributes);

const id_ce_subjectKeyIdentifier = `${id_ce}.14`;
class SubjectKeyIdentifier extends KeyIdentifier {
}

class PrivateKeyUsagePeriod {
    constructor(params = {}) {
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.GeneralizedTime, context: 0, implicit: true, optional: true })
], PrivateKeyUsagePeriod.prototype, "notBefore", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.GeneralizedTime, context: 1, implicit: true, optional: true })
], PrivateKeyUsagePeriod.prototype, "notAfter", void 0);

var EntrustInfoFlags;
(function (EntrustInfoFlags) {
    EntrustInfoFlags[EntrustInfoFlags["keyUpdateAllowed"] = 1] = "keyUpdateAllowed";
    EntrustInfoFlags[EntrustInfoFlags["newExtensions"] = 2] = "newExtensions";
    EntrustInfoFlags[EntrustInfoFlags["pKIXCertificate"] = 4] = "pKIXCertificate";
})(EntrustInfoFlags || (EntrustInfoFlags = {}));
class EntrustInfo extends BitString {
    toJSON() {
        const res = [];
        const flags = this.toNumber();
        if (flags & EntrustInfoFlags.pKIXCertificate) {
            res.push("pKIXCertificate");
        }
        if (flags & EntrustInfoFlags.newExtensions) {
            res.push("newExtensions");
        }
        if (flags & EntrustInfoFlags.keyUpdateAllowed) {
            res.push("keyUpdateAllowed");
        }
        return res;
    }
    toString() {
        return `[${this.toJSON().join(", ")}]`;
    }
}
class EntrustVersionInfo {
    constructor(params = {}) {
        this.entrustVers = "";
        this.entrustInfoFlags = new EntrustInfo();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.GeneralString })
], EntrustVersionInfo.prototype, "entrustVers", void 0);
__decorate$1([
    AsnProp({ type: EntrustInfo })
], EntrustVersionInfo.prototype, "entrustInfoFlags", void 0);

var SubjectInfoAccessSyntax_1;
let SubjectInfoAccessSyntax = SubjectInfoAccessSyntax_1 = class SubjectInfoAccessSyntax extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, SubjectInfoAccessSyntax_1.prototype);
    }
};
SubjectInfoAccessSyntax = SubjectInfoAccessSyntax_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: AccessDescription })
], SubjectInfoAccessSyntax);

class AlgorithmIdentifier {
    constructor(params = {}) {
        this.algorithm = "";
        Object.assign(this, params);
    }
    isEqual(data) {
        return (data instanceof AlgorithmIdentifier &&
            data.algorithm == this.algorithm &&
            ((data.parameters &&
                this.parameters &&
                isEqual(data.parameters, this.parameters)) ||
                data.parameters === this.parameters));
    }
}
__decorate$1([
    AsnProp({
        type: AsnPropTypes.ObjectIdentifier,
    })
], AlgorithmIdentifier.prototype, "algorithm", void 0);
__decorate$1([
    AsnProp({
        type: AsnPropTypes.Any,
        optional: true,
    })
], AlgorithmIdentifier.prototype, "parameters", void 0);

class SubjectPublicKeyInfo {
    constructor(params = {}) {
        this.algorithm = new AlgorithmIdentifier();
        this.subjectPublicKey = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier })
], SubjectPublicKeyInfo.prototype, "algorithm", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.BitString })
], SubjectPublicKeyInfo.prototype, "subjectPublicKey", void 0);

let Time = class Time {
    constructor(time) {
        if (time) {
            if (typeof time === "string" || typeof time === "number" || time instanceof Date) {
                const date = new Date(time);
                if (date.getUTCFullYear() > 2049) {
                    this.generalTime = date;
                }
                else {
                    this.utcTime = date;
                }
            }
            else {
                Object.assign(this, time);
            }
        }
    }
    getTime() {
        const time = this.utcTime || this.generalTime;
        if (!time) {
            throw new Error("Cannot get time from CHOICE object");
        }
        return time;
    }
};
__decorate$1([
    AsnProp({
        type: AsnPropTypes.UTCTime,
    })
], Time.prototype, "utcTime", void 0);
__decorate$1([
    AsnProp({
        type: AsnPropTypes.GeneralizedTime,
    })
], Time.prototype, "generalTime", void 0);
Time = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], Time);

class Validity {
    constructor(params) {
        this.notBefore = new Time(new Date());
        this.notAfter = new Time(new Date());
        if (params) {
            this.notBefore = new Time(params.notBefore);
            this.notAfter = new Time(params.notAfter);
        }
    }
}
__decorate$1([
    AsnProp({ type: Time })
], Validity.prototype, "notBefore", void 0);
__decorate$1([
    AsnProp({ type: Time })
], Validity.prototype, "notAfter", void 0);

var Extensions_1;
let Extension$1 = class Extension {
    constructor(params = {}) {
        this.extnID = "";
        this.critical = Extension.CRITICAL;
        this.extnValue = new OctetString();
        Object.assign(this, params);
    }
};
Extension$1.CRITICAL = false;
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], Extension$1.prototype, "extnID", void 0);
__decorate$1([
    AsnProp({
        type: AsnPropTypes.Boolean,
        defaultValue: Extension$1.CRITICAL,
    })
], Extension$1.prototype, "critical", void 0);
__decorate$1([
    AsnProp({ type: OctetString })
], Extension$1.prototype, "extnValue", void 0);
let Extensions = Extensions_1 = class Extensions extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, Extensions_1.prototype);
    }
};
Extensions = Extensions_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: Extension$1 })
], Extensions);

var Version$2;
(function (Version) {
    Version[Version["v1"] = 0] = "v1";
    Version[Version["v2"] = 1] = "v2";
    Version[Version["v3"] = 2] = "v3";
})(Version$2 || (Version$2 = {}));

class TBSCertificate {
    constructor(params = {}) {
        this.version = Version$2.v1;
        this.serialNumber = new ArrayBuffer(0);
        this.signature = new AlgorithmIdentifier();
        this.issuer = new Name$1();
        this.validity = new Validity();
        this.subject = new Name$1();
        this.subjectPublicKeyInfo = new SubjectPublicKeyInfo();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({
        type: AsnPropTypes.Integer,
        context: 0,
        defaultValue: Version$2.v1,
    })
], TBSCertificate.prototype, "version", void 0);
__decorate$1([
    AsnProp({
        type: AsnPropTypes.Integer,
        converter: AsnIntegerArrayBufferConverter,
    })
], TBSCertificate.prototype, "serialNumber", void 0);
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier })
], TBSCertificate.prototype, "signature", void 0);
__decorate$1([
    AsnProp({ type: Name$1 })
], TBSCertificate.prototype, "issuer", void 0);
__decorate$1([
    AsnProp({ type: Validity })
], TBSCertificate.prototype, "validity", void 0);
__decorate$1([
    AsnProp({ type: Name$1 })
], TBSCertificate.prototype, "subject", void 0);
__decorate$1([
    AsnProp({ type: SubjectPublicKeyInfo })
], TBSCertificate.prototype, "subjectPublicKeyInfo", void 0);
__decorate$1([
    AsnProp({
        type: AsnPropTypes.BitString,
        context: 1,
        implicit: true,
        optional: true,
    })
], TBSCertificate.prototype, "issuerUniqueID", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.BitString, context: 2, implicit: true, optional: true })
], TBSCertificate.prototype, "subjectUniqueID", void 0);
__decorate$1([
    AsnProp({ type: Extensions, context: 3, optional: true })
], TBSCertificate.prototype, "extensions", void 0);

class Certificate {
    constructor(params = {}) {
        this.tbsCertificate = new TBSCertificate();
        this.signatureAlgorithm = new AlgorithmIdentifier();
        this.signatureValue = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: TBSCertificate, raw: true })
], Certificate.prototype, "tbsCertificate", void 0);
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier })
], Certificate.prototype, "signatureAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.BitString })
], Certificate.prototype, "signatureValue", void 0);

class RevokedCertificate {
    constructor(params = {}) {
        this.userCertificate = new ArrayBuffer(0);
        this.revocationDate = new Time();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], RevokedCertificate.prototype, "userCertificate", void 0);
__decorate$1([
    AsnProp({ type: Time })
], RevokedCertificate.prototype, "revocationDate", void 0);
__decorate$1([
    AsnProp({ type: Extension$1, optional: true, repeated: "sequence" })
], RevokedCertificate.prototype, "crlEntryExtensions", void 0);
class TBSCertList {
    constructor(params = {}) {
        this.signature = new AlgorithmIdentifier();
        this.issuer = new Name$1();
        this.thisUpdate = new Time();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, optional: true })
], TBSCertList.prototype, "version", void 0);
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier })
], TBSCertList.prototype, "signature", void 0);
__decorate$1([
    AsnProp({ type: Name$1 })
], TBSCertList.prototype, "issuer", void 0);
__decorate$1([
    AsnProp({ type: Time })
], TBSCertList.prototype, "thisUpdate", void 0);
__decorate$1([
    AsnProp({ type: Time, optional: true })
], TBSCertList.prototype, "nextUpdate", void 0);
__decorate$1([
    AsnProp({ type: RevokedCertificate, repeated: "sequence", optional: true })
], TBSCertList.prototype, "revokedCertificates", void 0);
__decorate$1([
    AsnProp({ type: Extension$1, optional: true, context: 0, repeated: "sequence" })
], TBSCertList.prototype, "crlExtensions", void 0);

class CertificateList {
    constructor(params = {}) {
        this.tbsCertList = new TBSCertList();
        this.signatureAlgorithm = new AlgorithmIdentifier();
        this.signature = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: TBSCertList, raw: true })
], CertificateList.prototype, "tbsCertList", void 0);
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier })
], CertificateList.prototype, "signatureAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.BitString })
], CertificateList.prototype, "signature", void 0);

const issuerSubjectIDKey = {
    '2.5.4.6': 'C',
    '2.5.4.10': 'O',
    '2.5.4.11': 'OU',
    '2.5.4.3': 'CN',
};
/**
 * Extract PEM certificate info
 *
 * @param pemCertificate Result from call to `convertASN1toPEM(x5c[0])`
 */
function getCertificateInfo(leafCertBuffer) {
    const x509 = AsnParser.parse(leafCertBuffer, Certificate);
    const parsedCert = x509.tbsCertificate;
    // Issuer
    const issuer = { combined: '' };
    parsedCert.issuer.forEach(([iss]) => {
        const key = issuerSubjectIDKey[iss.type];
        if (key) {
            issuer[key] = iss.value.toString();
        }
    });
    issuer.combined = issuerSubjectToString(issuer);
    // Subject
    const subject = { combined: '' };
    parsedCert.subject.forEach(([iss]) => {
        const key = issuerSubjectIDKey[iss.type];
        if (key) {
            subject[key] = iss.value.toString();
        }
    });
    subject.combined = issuerSubjectToString(subject);
    let basicConstraintsCA = false;
    if (parsedCert.extensions) {
        // console.log(parsedCert.extensions);
        for (const ext of parsedCert.extensions) {
            if (ext.extnID === id_ce_basicConstraints) {
                const basicConstraints = AsnParser.parse(ext.extnValue, BasicConstraints);
                basicConstraintsCA = basicConstraints.cA;
            }
        }
    }
    return {
        issuer,
        subject,
        version: parsedCert.version,
        basicConstraintsCA,
        notBefore: parsedCert.validity.notBefore.getTime(),
        notAfter: parsedCert.validity.notAfter.getTime(),
        parsedCertificate: x509,
    };
}
/**
 * Stringify the parts of Issuer or Subject info for easier comparison of subject issuers with
 * issuer subjects.
 *
 * The order might seem arbitrary, because it is. It should be enough that the two are stringified
 * in the same order.
 */
function issuerSubjectToString(input) {
    const parts = [];
    if (input.C) {
        parts.push(input.C);
    }
    if (input.O) {
        parts.push(input.O);
    }
    if (input.OU) {
        parts.push(input.OU);
    }
    if (input.CN) {
        parts.push(input.CN);
    }
    return parts.join(' : ');
}

class IssuerAndSerialNumber {
    constructor(params = {}) {
        this.issuer = new Name$1();
        this.serialNumber = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: Name$1 })
], IssuerAndSerialNumber.prototype, "issuer", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], IssuerAndSerialNumber.prototype, "serialNumber", void 0);

let SignerIdentifier = class SignerIdentifier {
    constructor(params = {}) {
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: SubjectKeyIdentifier, context: 0, implicit: true })
], SignerIdentifier.prototype, "subjectKeyIdentifier", void 0);
__decorate$1([
    AsnProp({ type: IssuerAndSerialNumber })
], SignerIdentifier.prototype, "issuerAndSerialNumber", void 0);
SignerIdentifier = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], SignerIdentifier);

var CMSVersion;
(function (CMSVersion) {
    CMSVersion[CMSVersion["v0"] = 0] = "v0";
    CMSVersion[CMSVersion["v1"] = 1] = "v1";
    CMSVersion[CMSVersion["v2"] = 2] = "v2";
    CMSVersion[CMSVersion["v3"] = 3] = "v3";
    CMSVersion[CMSVersion["v4"] = 4] = "v4";
    CMSVersion[CMSVersion["v5"] = 5] = "v5";
})(CMSVersion || (CMSVersion = {}));
let DigestAlgorithmIdentifier = class DigestAlgorithmIdentifier extends AlgorithmIdentifier {
};
DigestAlgorithmIdentifier = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], DigestAlgorithmIdentifier);
let SignatureAlgorithmIdentifier = class SignatureAlgorithmIdentifier extends AlgorithmIdentifier {
};
SignatureAlgorithmIdentifier = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], SignatureAlgorithmIdentifier);
let KeyEncryptionAlgorithmIdentifier = class KeyEncryptionAlgorithmIdentifier extends AlgorithmIdentifier {
};
KeyEncryptionAlgorithmIdentifier = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], KeyEncryptionAlgorithmIdentifier);
let ContentEncryptionAlgorithmIdentifier = class ContentEncryptionAlgorithmIdentifier extends AlgorithmIdentifier {
};
ContentEncryptionAlgorithmIdentifier = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], ContentEncryptionAlgorithmIdentifier);
let MessageAuthenticationCodeAlgorithm = class MessageAuthenticationCodeAlgorithm extends AlgorithmIdentifier {
};
MessageAuthenticationCodeAlgorithm = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], MessageAuthenticationCodeAlgorithm);
let KeyDerivationAlgorithmIdentifier = class KeyDerivationAlgorithmIdentifier extends AlgorithmIdentifier {
};
KeyDerivationAlgorithmIdentifier = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], KeyDerivationAlgorithmIdentifier);

let Attribute$1 = class Attribute {
    constructor(params = {}) {
        this.attrType = "";
        this.attrValues = [];
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], Attribute$1.prototype, "attrType", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any, repeated: "set" })
], Attribute$1.prototype, "attrValues", void 0);

var SignerInfos_1;
class SignerInfo {
    constructor(params = {}) {
        this.version = CMSVersion.v0;
        this.sid = new SignerIdentifier();
        this.digestAlgorithm = new DigestAlgorithmIdentifier();
        this.signatureAlgorithm = new SignatureAlgorithmIdentifier();
        this.signature = new OctetString();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], SignerInfo.prototype, "version", void 0);
__decorate$1([
    AsnProp({ type: SignerIdentifier })
], SignerInfo.prototype, "sid", void 0);
__decorate$1([
    AsnProp({ type: DigestAlgorithmIdentifier })
], SignerInfo.prototype, "digestAlgorithm", void 0);
__decorate$1([
    AsnProp({
        type: Attribute$1,
        repeated: "set",
        context: 0,
        implicit: true,
        optional: true,
        raw: true,
    })
], SignerInfo.prototype, "signedAttrs", void 0);
__decorate$1([
    AsnProp({ type: SignatureAlgorithmIdentifier })
], SignerInfo.prototype, "signatureAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: OctetString })
], SignerInfo.prototype, "signature", void 0);
__decorate$1([
    AsnProp({ type: Attribute$1, repeated: "set", context: 1, implicit: true, optional: true })
], SignerInfo.prototype, "unsignedAttrs", void 0);
let SignerInfos = SignerInfos_1 = class SignerInfos extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, SignerInfos_1.prototype);
    }
};
SignerInfos = SignerInfos_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Set, itemType: SignerInfo })
], SignerInfos);

let CounterSignature$1 = class CounterSignature extends SignerInfo {
};
CounterSignature$1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], CounterSignature$1);

let SigningTime$1 = class SigningTime extends Time {
};
SigningTime$1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], SigningTime$1);

class ACClearAttrs {
    constructor(params = {}) {
        this.acIssuer = new GeneralName$1();
        this.acSerial = 0;
        this.attrs = [];
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: GeneralName$1 })
], ACClearAttrs.prototype, "acIssuer", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], ACClearAttrs.prototype, "acSerial", void 0);
__decorate$1([
    AsnProp({ type: Attribute$2, repeated: "sequence" })
], ACClearAttrs.prototype, "attrs", void 0);

var AttrSpec_1;
let AttrSpec = AttrSpec_1 = class AttrSpec extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, AttrSpec_1.prototype);
    }
};
AttrSpec = AttrSpec_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: AsnPropTypes.ObjectIdentifier })
], AttrSpec);

class AAControls {
    constructor(params = {}) {
        this.permitUnSpecified = true;
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, optional: true })
], AAControls.prototype, "pathLenConstraint", void 0);
__decorate$1([
    AsnProp({ type: AttrSpec, implicit: true, context: 0, optional: true })
], AAControls.prototype, "permittedAttrs", void 0);
__decorate$1([
    AsnProp({ type: AttrSpec, implicit: true, context: 1, optional: true })
], AAControls.prototype, "excludedAttrs", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Boolean, defaultValue: true })
], AAControls.prototype, "permitUnSpecified", void 0);

class IssuerSerial {
    constructor(params = {}) {
        this.issuer = new GeneralNames$1();
        this.serial = new ArrayBuffer(0);
        this.issuerUID = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: GeneralNames$1 })
], IssuerSerial.prototype, "issuer", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], IssuerSerial.prototype, "serial", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.BitString, optional: true })
], IssuerSerial.prototype, "issuerUID", void 0);

var DigestedObjectType;
(function (DigestedObjectType) {
    DigestedObjectType[DigestedObjectType["publicKey"] = 0] = "publicKey";
    DigestedObjectType[DigestedObjectType["publicKeyCert"] = 1] = "publicKeyCert";
    DigestedObjectType[DigestedObjectType["otherObjectTypes"] = 2] = "otherObjectTypes";
})(DigestedObjectType || (DigestedObjectType = {}));
class ObjectDigestInfo {
    constructor(params = {}) {
        this.digestedObjectType = DigestedObjectType.publicKey;
        this.digestAlgorithm = new AlgorithmIdentifier();
        this.objectDigest = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Enumerated })
], ObjectDigestInfo.prototype, "digestedObjectType", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier, optional: true })
], ObjectDigestInfo.prototype, "otherObjectTypeID", void 0);
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier })
], ObjectDigestInfo.prototype, "digestAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.BitString })
], ObjectDigestInfo.prototype, "objectDigest", void 0);

class V2Form {
    constructor(params = {}) {
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: GeneralNames$1, optional: true })
], V2Form.prototype, "issuerName", void 0);
__decorate$1([
    AsnProp({ type: IssuerSerial, context: 0, implicit: true, optional: true })
], V2Form.prototype, "baseCertificateID", void 0);
__decorate$1([
    AsnProp({ type: ObjectDigestInfo, context: 1, implicit: true, optional: true })
], V2Form.prototype, "objectDigestInfo", void 0);

let AttCertIssuer = class AttCertIssuer {
    constructor(params = {}) {
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: GeneralName$1, repeated: "sequence" })
], AttCertIssuer.prototype, "v1Form", void 0);
__decorate$1([
    AsnProp({ type: V2Form, context: 0, implicit: true })
], AttCertIssuer.prototype, "v2Form", void 0);
AttCertIssuer = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], AttCertIssuer);

class AttCertValidityPeriod {
    constructor(params = {}) {
        this.notBeforeTime = new Date();
        this.notAfterTime = new Date();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.GeneralizedTime })
], AttCertValidityPeriod.prototype, "notBeforeTime", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.GeneralizedTime })
], AttCertValidityPeriod.prototype, "notAfterTime", void 0);

class Holder {
    constructor(params = {}) {
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: IssuerSerial, implicit: true, context: 0, optional: true })
], Holder.prototype, "baseCertificateID", void 0);
__decorate$1([
    AsnProp({ type: GeneralNames$1, implicit: true, context: 1, optional: true })
], Holder.prototype, "entityName", void 0);
__decorate$1([
    AsnProp({ type: ObjectDigestInfo, implicit: true, context: 2, optional: true })
], Holder.prototype, "objectDigestInfo", void 0);

var AttCertVersion;
(function (AttCertVersion) {
    AttCertVersion[AttCertVersion["v2"] = 1] = "v2";
})(AttCertVersion || (AttCertVersion = {}));
class AttributeCertificateInfo {
    constructor(params = {}) {
        this.version = AttCertVersion.v2;
        this.holder = new Holder();
        this.issuer = new AttCertIssuer();
        this.signature = new AlgorithmIdentifier();
        this.serialNumber = new ArrayBuffer(0);
        this.attrCertValidityPeriod = new AttCertValidityPeriod();
        this.attributes = [];
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], AttributeCertificateInfo.prototype, "version", void 0);
__decorate$1([
    AsnProp({ type: Holder })
], AttributeCertificateInfo.prototype, "holder", void 0);
__decorate$1([
    AsnProp({ type: AttCertIssuer })
], AttributeCertificateInfo.prototype, "issuer", void 0);
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier })
], AttributeCertificateInfo.prototype, "signature", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], AttributeCertificateInfo.prototype, "serialNumber", void 0);
__decorate$1([
    AsnProp({ type: AttCertValidityPeriod })
], AttributeCertificateInfo.prototype, "attrCertValidityPeriod", void 0);
__decorate$1([
    AsnProp({ type: Attribute$2, repeated: "sequence" })
], AttributeCertificateInfo.prototype, "attributes", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.BitString, optional: true })
], AttributeCertificateInfo.prototype, "issuerUniqueID", void 0);
__decorate$1([
    AsnProp({ type: Extensions, optional: true })
], AttributeCertificateInfo.prototype, "extensions", void 0);

class AttributeCertificate {
    constructor(params = {}) {
        this.acinfo = new AttributeCertificateInfo();
        this.signatureAlgorithm = new AlgorithmIdentifier();
        this.signatureValue = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AttributeCertificateInfo })
], AttributeCertificate.prototype, "acinfo", void 0);
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier })
], AttributeCertificate.prototype, "signatureAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.BitString })
], AttributeCertificate.prototype, "signatureValue", void 0);

var ClassListFlags;
(function (ClassListFlags) {
    ClassListFlags[ClassListFlags["unmarked"] = 1] = "unmarked";
    ClassListFlags[ClassListFlags["unclassified"] = 2] = "unclassified";
    ClassListFlags[ClassListFlags["restricted"] = 4] = "restricted";
    ClassListFlags[ClassListFlags["confidential"] = 8] = "confidential";
    ClassListFlags[ClassListFlags["secret"] = 16] = "secret";
    ClassListFlags[ClassListFlags["topSecret"] = 32] = "topSecret";
})(ClassListFlags || (ClassListFlags = {}));
class ClassList extends BitString {
}

class SecurityCategory {
    constructor(params = {}) {
        this.type = "";
        this.value = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier, implicit: true, context: 0 })
], SecurityCategory.prototype, "type", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any, implicit: true, context: 1 })
], SecurityCategory.prototype, "value", void 0);

class Clearance {
    constructor(params = {}) {
        this.policyId = "";
        this.classList = new ClassList(ClassListFlags.unclassified);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], Clearance.prototype, "policyId", void 0);
__decorate$1([
    AsnProp({ type: ClassList, defaultValue: new ClassList(ClassListFlags.unclassified) })
], Clearance.prototype, "classList", void 0);
__decorate$1([
    AsnProp({ type: SecurityCategory, repeated: "set" })
], Clearance.prototype, "securityCategories", void 0);

class IetfAttrSyntaxValueChoices {
    constructor(params = {}) {
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: OctetString })
], IetfAttrSyntaxValueChoices.prototype, "cotets", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], IetfAttrSyntaxValueChoices.prototype, "oid", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Utf8String })
], IetfAttrSyntaxValueChoices.prototype, "string", void 0);
class IetfAttrSyntax {
    constructor(params = {}) {
        this.values = [];
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: GeneralNames$1, implicit: true, context: 0, optional: true })
], IetfAttrSyntax.prototype, "policyAuthority", void 0);
__decorate$1([
    AsnProp({ type: IetfAttrSyntaxValueChoices, repeated: "sequence" })
], IetfAttrSyntax.prototype, "values", void 0);

var Targets_1;
class TargetCert {
    constructor(params = {}) {
        this.targetCertificate = new IssuerSerial();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: IssuerSerial })
], TargetCert.prototype, "targetCertificate", void 0);
__decorate$1([
    AsnProp({ type: GeneralName$1, optional: true })
], TargetCert.prototype, "targetName", void 0);
__decorate$1([
    AsnProp({ type: ObjectDigestInfo, optional: true })
], TargetCert.prototype, "certDigestInfo", void 0);
let Target = class Target {
    constructor(params = {}) {
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: GeneralName$1, context: 0, implicit: true })
], Target.prototype, "targetName", void 0);
__decorate$1([
    AsnProp({ type: GeneralName$1, context: 1, implicit: true })
], Target.prototype, "targetGroup", void 0);
__decorate$1([
    AsnProp({ type: TargetCert, context: 2, implicit: true })
], Target.prototype, "targetCert", void 0);
Target = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], Target);
let Targets = Targets_1 = class Targets extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, Targets_1.prototype);
    }
};
Targets = Targets_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: Target })
], Targets);

var ProxyInfo_1;
let ProxyInfo = ProxyInfo_1 = class ProxyInfo extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, ProxyInfo_1.prototype);
    }
};
ProxyInfo = ProxyInfo_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: Targets })
], ProxyInfo);

class RoleSyntax {
    constructor(params = {}) {
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: GeneralNames$1, implicit: true, context: 0, optional: true })
], RoleSyntax.prototype, "roleAuthority", void 0);
__decorate$1([
    AsnProp({ type: GeneralName$1, implicit: true, context: 1 })
], RoleSyntax.prototype, "roleName", void 0);

class SvceAuthInfo {
    constructor(params = {}) {
        this.service = new GeneralName$1();
        this.ident = new GeneralName$1();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: GeneralName$1 })
], SvceAuthInfo.prototype, "service", void 0);
__decorate$1([
    AsnProp({ type: GeneralName$1 })
], SvceAuthInfo.prototype, "ident", void 0);
__decorate$1([
    AsnProp({ type: OctetString, optional: true })
], SvceAuthInfo.prototype, "authInfo", void 0);

var CertificateSet_1;
class OtherCertificateFormat {
    constructor(params = {}) {
        this.otherCertFormat = "";
        this.otherCert = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], OtherCertificateFormat.prototype, "otherCertFormat", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any })
], OtherCertificateFormat.prototype, "otherCert", void 0);
let CertificateChoices = class CertificateChoices {
    constructor(params = {}) {
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: Certificate })
], CertificateChoices.prototype, "certificate", void 0);
__decorate$1([
    AsnProp({ type: AttributeCertificate, context: 2, implicit: true })
], CertificateChoices.prototype, "v2AttrCert", void 0);
__decorate$1([
    AsnProp({ type: OtherCertificateFormat, context: 3, implicit: true })
], CertificateChoices.prototype, "other", void 0);
CertificateChoices = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], CertificateChoices);
let CertificateSet = CertificateSet_1 = class CertificateSet extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, CertificateSet_1.prototype);
    }
};
CertificateSet = CertificateSet_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Set, itemType: CertificateChoices })
], CertificateSet);

class ContentInfo {
    constructor(params = {}) {
        this.contentType = "";
        this.content = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], ContentInfo.prototype, "contentType", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any, context: 0 })
], ContentInfo.prototype, "content", void 0);

let EncapsulatedContent = class EncapsulatedContent {
    constructor(params = {}) {
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: OctetString })
], EncapsulatedContent.prototype, "single", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any })
], EncapsulatedContent.prototype, "any", void 0);
EncapsulatedContent = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], EncapsulatedContent);
class EncapsulatedContentInfo {
    constructor(params = {}) {
        this.eContentType = "";
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], EncapsulatedContentInfo.prototype, "eContentType", void 0);
__decorate$1([
    AsnProp({ type: EncapsulatedContent, context: 0, optional: true })
], EncapsulatedContentInfo.prototype, "eContent", void 0);

let EncryptedContent = class EncryptedContent {
    constructor(params = {}) {
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: OctetString, context: 0, implicit: true, optional: true })
], EncryptedContent.prototype, "value", void 0);
__decorate$1([
    AsnProp({
        type: OctetString,
        converter: AsnConstructedOctetStringConverter,
        context: 0,
        implicit: true,
        optional: true,
        repeated: "sequence",
    })
], EncryptedContent.prototype, "constructedValue", void 0);
EncryptedContent = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], EncryptedContent);
class EncryptedContentInfo {
    constructor(params = {}) {
        this.contentType = "";
        this.contentEncryptionAlgorithm = new ContentEncryptionAlgorithmIdentifier();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], EncryptedContentInfo.prototype, "contentType", void 0);
__decorate$1([
    AsnProp({ type: ContentEncryptionAlgorithmIdentifier })
], EncryptedContentInfo.prototype, "contentEncryptionAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: EncryptedContent, optional: true })
], EncryptedContentInfo.prototype, "encryptedContent", void 0);

class OtherKeyAttribute {
    constructor(params = {}) {
        this.keyAttrId = "";
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], OtherKeyAttribute.prototype, "keyAttrId", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any, optional: true })
], OtherKeyAttribute.prototype, "keyAttr", void 0);

var RecipientEncryptedKeys_1;
class RecipientKeyIdentifier {
    constructor(params = {}) {
        this.subjectKeyIdentifier = new SubjectKeyIdentifier();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: SubjectKeyIdentifier })
], RecipientKeyIdentifier.prototype, "subjectKeyIdentifier", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.GeneralizedTime, optional: true })
], RecipientKeyIdentifier.prototype, "date", void 0);
__decorate$1([
    AsnProp({ type: OtherKeyAttribute, optional: true })
], RecipientKeyIdentifier.prototype, "other", void 0);
let KeyAgreeRecipientIdentifier = class KeyAgreeRecipientIdentifier {
    constructor(params = {}) {
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: RecipientKeyIdentifier, context: 0, implicit: true, optional: true })
], KeyAgreeRecipientIdentifier.prototype, "rKeyId", void 0);
__decorate$1([
    AsnProp({ type: IssuerAndSerialNumber, optional: true })
], KeyAgreeRecipientIdentifier.prototype, "issuerAndSerialNumber", void 0);
KeyAgreeRecipientIdentifier = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], KeyAgreeRecipientIdentifier);
class RecipientEncryptedKey {
    constructor(params = {}) {
        this.rid = new KeyAgreeRecipientIdentifier();
        this.encryptedKey = new OctetString();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: KeyAgreeRecipientIdentifier })
], RecipientEncryptedKey.prototype, "rid", void 0);
__decorate$1([
    AsnProp({ type: OctetString })
], RecipientEncryptedKey.prototype, "encryptedKey", void 0);
let RecipientEncryptedKeys = RecipientEncryptedKeys_1 = class RecipientEncryptedKeys extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, RecipientEncryptedKeys_1.prototype);
    }
};
RecipientEncryptedKeys = RecipientEncryptedKeys_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: RecipientEncryptedKey })
], RecipientEncryptedKeys);
class OriginatorPublicKey {
    constructor(params = {}) {
        this.algorithm = new AlgorithmIdentifier();
        this.publicKey = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier })
], OriginatorPublicKey.prototype, "algorithm", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.BitString })
], OriginatorPublicKey.prototype, "publicKey", void 0);
let OriginatorIdentifierOrKey = class OriginatorIdentifierOrKey {
    constructor(params = {}) {
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: SubjectKeyIdentifier, context: 0, implicit: true, optional: true })
], OriginatorIdentifierOrKey.prototype, "subjectKeyIdentifier", void 0);
__decorate$1([
    AsnProp({ type: OriginatorPublicKey, context: 1, implicit: true, optional: true })
], OriginatorIdentifierOrKey.prototype, "originatorKey", void 0);
__decorate$1([
    AsnProp({ type: IssuerAndSerialNumber, optional: true })
], OriginatorIdentifierOrKey.prototype, "issuerAndSerialNumber", void 0);
OriginatorIdentifierOrKey = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], OriginatorIdentifierOrKey);
class KeyAgreeRecipientInfo {
    constructor(params = {}) {
        this.version = CMSVersion.v3;
        this.originator = new OriginatorIdentifierOrKey();
        this.keyEncryptionAlgorithm = new KeyEncryptionAlgorithmIdentifier();
        this.recipientEncryptedKeys = new RecipientEncryptedKeys();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], KeyAgreeRecipientInfo.prototype, "version", void 0);
__decorate$1([
    AsnProp({ type: OriginatorIdentifierOrKey, context: 0 })
], KeyAgreeRecipientInfo.prototype, "originator", void 0);
__decorate$1([
    AsnProp({ type: OctetString, context: 1, optional: true })
], KeyAgreeRecipientInfo.prototype, "ukm", void 0);
__decorate$1([
    AsnProp({ type: KeyEncryptionAlgorithmIdentifier })
], KeyAgreeRecipientInfo.prototype, "keyEncryptionAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: RecipientEncryptedKeys })
], KeyAgreeRecipientInfo.prototype, "recipientEncryptedKeys", void 0);

let RecipientIdentifier = class RecipientIdentifier {
    constructor(params = {}) {
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: SubjectKeyIdentifier, context: 0, implicit: true })
], RecipientIdentifier.prototype, "subjectKeyIdentifier", void 0);
__decorate$1([
    AsnProp({ type: IssuerAndSerialNumber })
], RecipientIdentifier.prototype, "issuerAndSerialNumber", void 0);
RecipientIdentifier = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], RecipientIdentifier);
class KeyTransRecipientInfo {
    constructor(params = {}) {
        this.version = CMSVersion.v0;
        this.rid = new RecipientIdentifier();
        this.keyEncryptionAlgorithm = new KeyEncryptionAlgorithmIdentifier();
        this.encryptedKey = new OctetString();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], KeyTransRecipientInfo.prototype, "version", void 0);
__decorate$1([
    AsnProp({ type: RecipientIdentifier })
], KeyTransRecipientInfo.prototype, "rid", void 0);
__decorate$1([
    AsnProp({ type: KeyEncryptionAlgorithmIdentifier })
], KeyTransRecipientInfo.prototype, "keyEncryptionAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: OctetString })
], KeyTransRecipientInfo.prototype, "encryptedKey", void 0);

class KEKIdentifier {
    constructor(params = {}) {
        this.keyIdentifier = new OctetString();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: OctetString })
], KEKIdentifier.prototype, "keyIdentifier", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.GeneralizedTime, optional: true })
], KEKIdentifier.prototype, "date", void 0);
__decorate$1([
    AsnProp({ type: OtherKeyAttribute, optional: true })
], KEKIdentifier.prototype, "other", void 0);
class KEKRecipientInfo {
    constructor(params = {}) {
        this.version = CMSVersion.v4;
        this.kekid = new KEKIdentifier();
        this.keyEncryptionAlgorithm = new KeyEncryptionAlgorithmIdentifier();
        this.encryptedKey = new OctetString();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], KEKRecipientInfo.prototype, "version", void 0);
__decorate$1([
    AsnProp({ type: KEKIdentifier })
], KEKRecipientInfo.prototype, "kekid", void 0);
__decorate$1([
    AsnProp({ type: KeyEncryptionAlgorithmIdentifier })
], KEKRecipientInfo.prototype, "keyEncryptionAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: OctetString })
], KEKRecipientInfo.prototype, "encryptedKey", void 0);

class PasswordRecipientInfo {
    constructor(params = {}) {
        this.version = CMSVersion.v0;
        this.keyEncryptionAlgorithm = new KeyEncryptionAlgorithmIdentifier();
        this.encryptedKey = new OctetString();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], PasswordRecipientInfo.prototype, "version", void 0);
__decorate$1([
    AsnProp({ type: KeyDerivationAlgorithmIdentifier, context: 0, optional: true })
], PasswordRecipientInfo.prototype, "keyDerivationAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: KeyEncryptionAlgorithmIdentifier })
], PasswordRecipientInfo.prototype, "keyEncryptionAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: OctetString })
], PasswordRecipientInfo.prototype, "encryptedKey", void 0);

class OtherRecipientInfo {
    constructor(params = {}) {
        this.oriType = "";
        this.oriValue = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], OtherRecipientInfo.prototype, "oriType", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any })
], OtherRecipientInfo.prototype, "oriValue", void 0);
let RecipientInfo = class RecipientInfo {
    constructor(params = {}) {
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: KeyTransRecipientInfo, optional: true })
], RecipientInfo.prototype, "ktri", void 0);
__decorate$1([
    AsnProp({ type: KeyAgreeRecipientInfo, context: 1, implicit: true, optional: true })
], RecipientInfo.prototype, "kari", void 0);
__decorate$1([
    AsnProp({ type: KEKRecipientInfo, context: 2, implicit: true, optional: true })
], RecipientInfo.prototype, "kekri", void 0);
__decorate$1([
    AsnProp({ type: PasswordRecipientInfo, context: 3, implicit: true, optional: true })
], RecipientInfo.prototype, "pwri", void 0);
__decorate$1([
    AsnProp({ type: OtherRecipientInfo, context: 4, implicit: true, optional: true })
], RecipientInfo.prototype, "ori", void 0);
RecipientInfo = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], RecipientInfo);

var RecipientInfos_1;
let RecipientInfos = RecipientInfos_1 = class RecipientInfos extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, RecipientInfos_1.prototype);
    }
};
RecipientInfos = RecipientInfos_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Set, itemType: RecipientInfo })
], RecipientInfos);

var RevocationInfoChoices_1;
class OtherRevocationInfoFormat {
    constructor(params = {}) {
        this.otherRevInfoFormat = "";
        this.otherRevInfo = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], OtherRevocationInfoFormat.prototype, "otherRevInfoFormat", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any })
], OtherRevocationInfoFormat.prototype, "otherRevInfo", void 0);
let RevocationInfoChoice = class RevocationInfoChoice {
    constructor(params = {}) {
        this.other = new OtherRevocationInfoFormat();
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: OtherRevocationInfoFormat, context: 1, implicit: true })
], RevocationInfoChoice.prototype, "other", void 0);
RevocationInfoChoice = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], RevocationInfoChoice);
let RevocationInfoChoices = RevocationInfoChoices_1 = class RevocationInfoChoices extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, RevocationInfoChoices_1.prototype);
    }
};
RevocationInfoChoices = RevocationInfoChoices_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Set, itemType: RevocationInfoChoice })
], RevocationInfoChoices);

class OriginatorInfo {
    constructor(params = {}) {
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: CertificateSet, context: 0, implicit: true, optional: true })
], OriginatorInfo.prototype, "certs", void 0);
__decorate$1([
    AsnProp({ type: RevocationInfoChoices, context: 1, implicit: true, optional: true })
], OriginatorInfo.prototype, "crls", void 0);

var UnprotectedAttributes_1;
let UnprotectedAttributes = UnprotectedAttributes_1 = class UnprotectedAttributes extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, UnprotectedAttributes_1.prototype);
    }
};
UnprotectedAttributes = UnprotectedAttributes_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Set, itemType: Attribute$1 })
], UnprotectedAttributes);
class EnvelopedData {
    constructor(params = {}) {
        this.version = CMSVersion.v0;
        this.recipientInfos = new RecipientInfos();
        this.encryptedContentInfo = new EncryptedContentInfo();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], EnvelopedData.prototype, "version", void 0);
__decorate$1([
    AsnProp({ type: OriginatorInfo, context: 0, implicit: true, optional: true })
], EnvelopedData.prototype, "originatorInfo", void 0);
__decorate$1([
    AsnProp({ type: RecipientInfos })
], EnvelopedData.prototype, "recipientInfos", void 0);
__decorate$1([
    AsnProp({ type: EncryptedContentInfo })
], EnvelopedData.prototype, "encryptedContentInfo", void 0);
__decorate$1([
    AsnProp({ type: UnprotectedAttributes, context: 1, implicit: true, optional: true })
], EnvelopedData.prototype, "unprotectedAttrs", void 0);

const id_signedData = "1.2.840.113549.1.7.2";

var DigestAlgorithmIdentifiers_1;
let DigestAlgorithmIdentifiers = DigestAlgorithmIdentifiers_1 = class DigestAlgorithmIdentifiers extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, DigestAlgorithmIdentifiers_1.prototype);
    }
};
DigestAlgorithmIdentifiers = DigestAlgorithmIdentifiers_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Set, itemType: DigestAlgorithmIdentifier })
], DigestAlgorithmIdentifiers);
class SignedData {
    constructor(params = {}) {
        this.version = CMSVersion.v0;
        this.digestAlgorithms = new DigestAlgorithmIdentifiers();
        this.encapContentInfo = new EncapsulatedContentInfo();
        this.signerInfos = new SignerInfos();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], SignedData.prototype, "version", void 0);
__decorate$1([
    AsnProp({ type: DigestAlgorithmIdentifiers })
], SignedData.prototype, "digestAlgorithms", void 0);
__decorate$1([
    AsnProp({ type: EncapsulatedContentInfo })
], SignedData.prototype, "encapContentInfo", void 0);
__decorate$1([
    AsnProp({ type: CertificateSet, context: 0, implicit: true, optional: true })
], SignedData.prototype, "certificates", void 0);
__decorate$1([
    AsnProp({ type: RevocationInfoChoices, context: 1, implicit: true, optional: true })
], SignedData.prototype, "crls", void 0);
__decorate$1([
    AsnProp({ type: SignerInfos })
], SignedData.prototype, "signerInfos", void 0);

const id_ecPublicKey = "1.2.840.10045.2.1";
const id_ecdsaWithSHA1 = "1.2.840.10045.4.1";
const id_ecdsaWithSHA224 = "1.2.840.10045.4.3.1";
const id_ecdsaWithSHA256 = "1.2.840.10045.4.3.2";
const id_ecdsaWithSHA384 = "1.2.840.10045.4.3.3";
const id_ecdsaWithSHA512 = "1.2.840.10045.4.3.4";
const id_secp256r1 = "1.2.840.10045.3.1.7";
const id_secp384r1 = "1.3.132.0.34";
const id_secp521r1 = "1.3.132.0.35";

function create$1(algorithm) {
    return new AlgorithmIdentifier({ algorithm });
}
const ecdsaWithSHA1 = create$1(id_ecdsaWithSHA1);
create$1(id_ecdsaWithSHA224);
const ecdsaWithSHA256 = create$1(id_ecdsaWithSHA256);
const ecdsaWithSHA384 = create$1(id_ecdsaWithSHA384);
const ecdsaWithSHA512 = create$1(id_ecdsaWithSHA512);

let FieldID = class FieldID {
    constructor(params = {}) {
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], FieldID.prototype, "fieldType", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any })
], FieldID.prototype, "parameters", void 0);
FieldID = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], FieldID);
class ECPoint extends OctetString {
}
let Curve = class Curve {
    constructor(params = {}) {
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.OctetString })
], Curve.prototype, "a", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.OctetString })
], Curve.prototype, "b", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.BitString, optional: true })
], Curve.prototype, "seed", void 0);
Curve = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], Curve);
var ECPVer;
(function (ECPVer) {
    ECPVer[ECPVer["ecpVer1"] = 1] = "ecpVer1";
})(ECPVer || (ECPVer = {}));
let SpecifiedECDomain = class SpecifiedECDomain {
    constructor(params = {}) {
        this.version = ECPVer.ecpVer1;
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], SpecifiedECDomain.prototype, "version", void 0);
__decorate$1([
    AsnProp({ type: FieldID })
], SpecifiedECDomain.prototype, "fieldID", void 0);
__decorate$1([
    AsnProp({ type: Curve })
], SpecifiedECDomain.prototype, "curve", void 0);
__decorate$1([
    AsnProp({ type: ECPoint })
], SpecifiedECDomain.prototype, "base", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], SpecifiedECDomain.prototype, "order", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, optional: true })
], SpecifiedECDomain.prototype, "cofactor", void 0);
SpecifiedECDomain = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], SpecifiedECDomain);

let ECParameters = class ECParameters {
    constructor(params = {}) {
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], ECParameters.prototype, "namedCurve", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Null })
], ECParameters.prototype, "implicitCurve", void 0);
__decorate$1([
    AsnProp({ type: SpecifiedECDomain })
], ECParameters.prototype, "specifiedCurve", void 0);
ECParameters = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], ECParameters);

class ECPrivateKey {
    constructor(params = {}) {
        this.version = 1;
        this.privateKey = new OctetString();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], ECPrivateKey.prototype, "version", void 0);
__decorate$1([
    AsnProp({ type: OctetString })
], ECPrivateKey.prototype, "privateKey", void 0);
__decorate$1([
    AsnProp({ type: ECParameters, context: 0, optional: true })
], ECPrivateKey.prototype, "parameters", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.BitString, context: 1, optional: true })
], ECPrivateKey.prototype, "publicKey", void 0);

class ECDSASigValue {
    constructor(params = {}) {
        this.r = new ArrayBuffer(0);
        this.s = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], ECDSASigValue.prototype, "r", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], ECDSASigValue.prototype, "s", void 0);

const id_pkcs_1 = "1.2.840.113549.1.1";
const id_rsaEncryption = `${id_pkcs_1}.1`;
const id_RSAES_OAEP = `${id_pkcs_1}.7`;
const id_pSpecified = `${id_pkcs_1}.9`;
const id_RSASSA_PSS = `${id_pkcs_1}.10`;
const id_md2WithRSAEncryption = `${id_pkcs_1}.2`;
const id_md5WithRSAEncryption = `${id_pkcs_1}.4`;
const id_sha1WithRSAEncryption = `${id_pkcs_1}.5`;
const id_sha224WithRSAEncryption = `${id_pkcs_1}.14`;
const id_sha256WithRSAEncryption = `${id_pkcs_1}.11`;
const id_sha384WithRSAEncryption = `${id_pkcs_1}.12`;
const id_sha512WithRSAEncryption = `${id_pkcs_1}.13`;
const id_sha512_224WithRSAEncryption = `${id_pkcs_1}.15`;
const id_sha512_256WithRSAEncryption = `${id_pkcs_1}.16`;
const id_sha1 = "1.3.14.3.2.26";
const id_sha224 = "2.16.840.1.101.3.4.2.4";
const id_sha256 = "2.16.840.1.101.3.4.2.1";
const id_sha384 = "2.16.840.1.101.3.4.2.2";
const id_sha512 = "2.16.840.1.101.3.4.2.3";
const id_sha512_224 = "2.16.840.1.101.3.4.2.5";
const id_sha512_256 = "2.16.840.1.101.3.4.2.6";
const id_md2 = "1.2.840.113549.2.2";
const id_md5 = "1.2.840.113549.2.5";
const id_mgf1 = `${id_pkcs_1}.8`;

function create(algorithm) {
    return new AlgorithmIdentifier({ algorithm, parameters: null });
}
create(id_md2);
create(id_md5);
const sha1 = create(id_sha1);
create(id_sha224);
create(id_sha256);
create(id_sha384);
create(id_sha512);
create(id_sha512_224);
create(id_sha512_256);
const mgf1SHA1 = new AlgorithmIdentifier({
    algorithm: id_mgf1,
    parameters: AsnConvert.serialize(sha1),
});
const pSpecifiedEmpty = new AlgorithmIdentifier({
    algorithm: id_pSpecified,
    parameters: AsnConvert.serialize(AsnOctetStringConverter.toASN(new Uint8Array([
        0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60, 0x18,
        0x90, 0xaf, 0xd8, 0x07, 0x09,
    ]).buffer)),
});
create(id_rsaEncryption);
create(id_md2WithRSAEncryption);
create(id_md5WithRSAEncryption);
create(id_sha1WithRSAEncryption);
create(id_sha512_224WithRSAEncryption);
create(id_sha512_256WithRSAEncryption);
create(id_sha384WithRSAEncryption);
create(id_sha512WithRSAEncryption);
create(id_sha512_224WithRSAEncryption);
create(id_sha512_256WithRSAEncryption);

class RsaEsOaepParams {
    constructor(params = {}) {
        this.hashAlgorithm = new AlgorithmIdentifier(sha1);
        this.maskGenAlgorithm = new AlgorithmIdentifier({
            algorithm: id_mgf1,
            parameters: AsnConvert.serialize(sha1),
        });
        this.pSourceAlgorithm = new AlgorithmIdentifier(pSpecifiedEmpty);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier, context: 0, defaultValue: sha1 })
], RsaEsOaepParams.prototype, "hashAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier, context: 1, defaultValue: mgf1SHA1 })
], RsaEsOaepParams.prototype, "maskGenAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier, context: 2, defaultValue: pSpecifiedEmpty })
], RsaEsOaepParams.prototype, "pSourceAlgorithm", void 0);
new AlgorithmIdentifier({
    algorithm: id_RSAES_OAEP,
    parameters: AsnConvert.serialize(new RsaEsOaepParams()),
});

class RsaSaPssParams {
    constructor(params = {}) {
        this.hashAlgorithm = new AlgorithmIdentifier(sha1);
        this.maskGenAlgorithm = new AlgorithmIdentifier({
            algorithm: id_mgf1,
            parameters: AsnConvert.serialize(sha1),
        });
        this.saltLength = 20;
        this.trailerField = 1;
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier, context: 0, defaultValue: sha1 })
], RsaSaPssParams.prototype, "hashAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier, context: 1, defaultValue: mgf1SHA1 })
], RsaSaPssParams.prototype, "maskGenAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, context: 2, defaultValue: 20 })
], RsaSaPssParams.prototype, "saltLength", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, context: 3, defaultValue: 1 })
], RsaSaPssParams.prototype, "trailerField", void 0);
new AlgorithmIdentifier({
    algorithm: id_RSASSA_PSS,
    parameters: AsnConvert.serialize(new RsaSaPssParams()),
});

class DigestInfo {
    constructor(params = {}) {
        this.digestAlgorithm = new AlgorithmIdentifier();
        this.digest = new OctetString();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier })
], DigestInfo.prototype, "digestAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: OctetString })
], DigestInfo.prototype, "digest", void 0);

var OtherPrimeInfos_1;
class OtherPrimeInfo {
    constructor(params = {}) {
        this.prime = new ArrayBuffer(0);
        this.exponent = new ArrayBuffer(0);
        this.coefficient = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], OtherPrimeInfo.prototype, "prime", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], OtherPrimeInfo.prototype, "exponent", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], OtherPrimeInfo.prototype, "coefficient", void 0);
let OtherPrimeInfos = OtherPrimeInfos_1 = class OtherPrimeInfos extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, OtherPrimeInfos_1.prototype);
    }
};
OtherPrimeInfos = OtherPrimeInfos_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: OtherPrimeInfo })
], OtherPrimeInfos);

class RSAPrivateKey {
    constructor(params = {}) {
        this.version = 0;
        this.modulus = new ArrayBuffer(0);
        this.publicExponent = new ArrayBuffer(0);
        this.privateExponent = new ArrayBuffer(0);
        this.prime1 = new ArrayBuffer(0);
        this.prime2 = new ArrayBuffer(0);
        this.exponent1 = new ArrayBuffer(0);
        this.exponent2 = new ArrayBuffer(0);
        this.coefficient = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], RSAPrivateKey.prototype, "version", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], RSAPrivateKey.prototype, "modulus", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], RSAPrivateKey.prototype, "publicExponent", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], RSAPrivateKey.prototype, "privateExponent", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], RSAPrivateKey.prototype, "prime1", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], RSAPrivateKey.prototype, "prime2", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], RSAPrivateKey.prototype, "exponent1", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], RSAPrivateKey.prototype, "exponent2", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], RSAPrivateKey.prototype, "coefficient", void 0);
__decorate$1([
    AsnProp({ type: OtherPrimeInfos, optional: true })
], RSAPrivateKey.prototype, "otherPrimeInfos", void 0);

class RSAPublicKey {
    constructor(params = {}) {
        this.modulus = new ArrayBuffer(0);
        this.publicExponent = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], RSAPublicKey.prototype, "modulus", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
], RSAPublicKey.prototype, "publicExponent", void 0);

var Lifecycle;
(function (Lifecycle) {
    Lifecycle[Lifecycle["Transient"] = 0] = "Transient";
    Lifecycle[Lifecycle["Singleton"] = 1] = "Singleton";
    Lifecycle[Lifecycle["ResolutionScoped"] = 2] = "ResolutionScoped";
    Lifecycle[Lifecycle["ContainerScoped"] = 3] = "ContainerScoped";
})(Lifecycle || (Lifecycle = {}));
const Lifecycle$1 = Lifecycle;

var tslib$1 = {exports: {}};

/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */

var hasRequiredTslib;

function requireTslib () {
	if (hasRequiredTslib) return tslib$1.exports;
	hasRequiredTslib = 1;
	(function (module) {
		/* global global, define, System, Reflect, Promise */
		var __extends;
		var __assign;
		var __rest;
		var __decorate;
		var __param;
		var __metadata;
		var __awaiter;
		var __generator;
		var __exportStar;
		var __values;
		var __read;
		var __spread;
		var __spreadArrays;
		var __await;
		var __asyncGenerator;
		var __asyncDelegator;
		var __asyncValues;
		var __makeTemplateObject;
		var __importStar;
		var __importDefault;
		var __classPrivateFieldGet;
		var __classPrivateFieldSet;
		var __createBinding;
		(function (factory) {
		    var root = typeof commonjsGlobal === "object" ? commonjsGlobal : typeof self === "object" ? self : typeof this === "object" ? this : {};
		    {
		        factory(createExporter(root, createExporter(module.exports)));
		    }
		    function createExporter(exports$1, previous) {
		        if (exports$1 !== root) {
		            if (typeof Object.create === "function") {
		                Object.defineProperty(exports$1, "__esModule", { value: true });
		            }
		            else {
		                exports$1.__esModule = true;
		            }
		        }
		        return function (id, v) { return exports$1[id] = previous ? previous(id, v) : v; };
		    }
		})
		(function (exporter) {
		    var extendStatics = Object.setPrototypeOf ||
		        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
		        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };

		    __extends = function (d, b) {
		        extendStatics(d, b);
		        function __() { this.constructor = d; }
		        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
		    };

		    __assign = Object.assign || function (t) {
		        for (var s, i = 1, n = arguments.length; i < n; i++) {
		            s = arguments[i];
		            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
		        }
		        return t;
		    };

		    __rest = function (s, e) {
		        var t = {};
		        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
		            t[p] = s[p];
		        if (s != null && typeof Object.getOwnPropertySymbols === "function")
		            for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
		                if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
		                    t[p[i]] = s[p[i]];
		            }
		        return t;
		    };

		    __decorate = function (decorators, target, key, desc) {
		        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
		        if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
		        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
		        return c > 3 && r && Object.defineProperty(target, key, r), r;
		    };

		    __param = function (paramIndex, decorator) {
		        return function (target, key) { decorator(target, key, paramIndex); }
		    };

		    __metadata = function (metadataKey, metadataValue) {
		        if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
		    };

		    __awaiter = function (thisArg, _arguments, P, generator) {
		        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
		        return new (P || (P = Promise))(function (resolve, reject) {
		            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
		            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
		            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
		            step((generator = generator.apply(thisArg, _arguments || [])).next());
		        });
		    };

		    __generator = function (thisArg, body) {
		        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
		        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
		        function verb(n) { return function (v) { return step([n, v]); }; }
		        function step(op) {
		            if (f) throw new TypeError("Generator is already executing.");
		            while (_) try {
		                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
		                if (y = 0, t) op = [op[0] & 2, t.value];
		                switch (op[0]) {
		                    case 0: case 1: t = op; break;
		                    case 4: _.label++; return { value: op[1], done: false };
		                    case 5: _.label++; y = op[1]; op = [0]; continue;
		                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
		                    default:
		                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
		                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
		                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
		                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
		                        if (t[2]) _.ops.pop();
		                        _.trys.pop(); continue;
		                }
		                op = body.call(thisArg, _);
		            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
		            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
		        }
		    };

		    __createBinding = function(o, m, k, k2) {
		        if (k2 === undefined) k2 = k;
		        o[k2] = m[k];
		    };

		    __exportStar = function (m, exports$1) {
		        for (var p in m) if (p !== "default" && !exports$1.hasOwnProperty(p)) exports$1[p] = m[p];
		    };

		    __values = function (o) {
		        var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
		        if (m) return m.call(o);
		        if (o && typeof o.length === "number") return {
		            next: function () {
		                if (o && i >= o.length) o = void 0;
		                return { value: o && o[i++], done: !o };
		            }
		        };
		        throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
		    };

		    __read = function (o, n) {
		        var m = typeof Symbol === "function" && o[Symbol.iterator];
		        if (!m) return o;
		        var i = m.call(o), r, ar = [], e;
		        try {
		            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
		        }
		        catch (error) { e = { error: error }; }
		        finally {
		            try {
		                if (r && !r.done && (m = i["return"])) m.call(i);
		            }
		            finally { if (e) throw e.error; }
		        }
		        return ar;
		    };

		    __spread = function () {
		        for (var ar = [], i = 0; i < arguments.length; i++)
		            ar = ar.concat(__read(arguments[i]));
		        return ar;
		    };

		    __spreadArrays = function () {
		        for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
		        for (var r = Array(s), k = 0, i = 0; i < il; i++)
		            for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
		                r[k] = a[j];
		        return r;
		    };

		    __await = function (v) {
		        return this instanceof __await ? (this.v = v, this) : new __await(v);
		    };

		    __asyncGenerator = function (thisArg, _arguments, generator) {
		        if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
		        var g = generator.apply(thisArg, _arguments || []), i, q = [];
		        return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
		        function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
		        function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
		        function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);  }
		        function fulfill(value) { resume("next", value); }
		        function reject(value) { resume("throw", value); }
		        function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
		    };

		    __asyncDelegator = function (o) {
		        var i, p;
		        return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
		        function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
		    };

		    __asyncValues = function (o) {
		        if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
		        var m = o[Symbol.asyncIterator], i;
		        return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
		        function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
		        function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
		    };

		    __makeTemplateObject = function (cooked, raw) {
		        if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
		        return cooked;
		    };

		    __importStar = function (mod) {
		        if (mod && mod.__esModule) return mod;
		        var result = {};
		        if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
		        result["default"] = mod;
		        return result;
		    };

		    __importDefault = function (mod) {
		        return (mod && mod.__esModule) ? mod : { "default": mod };
		    };

		    __classPrivateFieldGet = function (receiver, privateMap) {
		        if (!privateMap.has(receiver)) {
		            throw new TypeError("attempted to get private field on non-instance");
		        }
		        return privateMap.get(receiver);
		    };

		    __classPrivateFieldSet = function (receiver, privateMap, value) {
		        if (!privateMap.has(receiver)) {
		            throw new TypeError("attempted to set private field on non-instance");
		        }
		        privateMap.set(receiver, value);
		        return value;
		    };

		    exporter("__extends", __extends);
		    exporter("__assign", __assign);
		    exporter("__rest", __rest);
		    exporter("__decorate", __decorate);
		    exporter("__param", __param);
		    exporter("__metadata", __metadata);
		    exporter("__awaiter", __awaiter);
		    exporter("__generator", __generator);
		    exporter("__exportStar", __exportStar);
		    exporter("__createBinding", __createBinding);
		    exporter("__values", __values);
		    exporter("__read", __read);
		    exporter("__spread", __spread);
		    exporter("__spreadArrays", __spreadArrays);
		    exporter("__await", __await);
		    exporter("__asyncGenerator", __asyncGenerator);
		    exporter("__asyncDelegator", __asyncDelegator);
		    exporter("__asyncValues", __asyncValues);
		    exporter("__makeTemplateObject", __makeTemplateObject);
		    exporter("__importStar", __importStar);
		    exporter("__importDefault", __importDefault);
		    exporter("__classPrivateFieldGet", __classPrivateFieldGet);
		    exporter("__classPrivateFieldSet", __classPrivateFieldSet);
		}); 
	} (tslib$1));
	return tslib$1.exports;
}

var tslibExports = /*@__PURE__*/ requireTslib();
const tslib = /*@__PURE__*/getDefaultExportFromCjs(tslibExports);

const {
    __extends,
    __assign,
    __rest,
    __decorate,
    __param,
    __metadata,
    __awaiter,
    __generator,
    __exportStar,
    __createBinding,
    __values,
    __read,
    __spread,
    __spreadArrays,
    __await,
    __asyncGenerator,
    __asyncDelegator,
    __asyncValues,
    __makeTemplateObject,
    __importStar,
    __importDefault,
    __classPrivateFieldGet,
    __classPrivateFieldSet,
} = tslib;

var INJECTION_TOKEN_METADATA_KEY = "injectionTokens";
function getParamInfo(target) {
    var params = Reflect.getMetadata("design:paramtypes", target) || [];
    var injectionTokens = Reflect.getOwnMetadata(INJECTION_TOKEN_METADATA_KEY, target) || {};
    Object.keys(injectionTokens).forEach(function (key) {
        params[+key] = injectionTokens[key];
    });
    return params;
}

function isClassProvider(provider) {
    return !!provider.useClass;
}

function isFactoryProvider(provider) {
    return !!provider.useFactory;
}

var DelayedConstructor = (function () {
    function DelayedConstructor(wrap) {
        this.wrap = wrap;
        this.reflectMethods = [
            "get",
            "getPrototypeOf",
            "setPrototypeOf",
            "getOwnPropertyDescriptor",
            "defineProperty",
            "has",
            "set",
            "deleteProperty",
            "apply",
            "construct",
            "ownKeys"
        ];
    }
    DelayedConstructor.prototype.createProxy = function (createObject) {
        var _this = this;
        var target = {};
        var init = false;
        var value;
        var delayedObject = function () {
            if (!init) {
                value = createObject(_this.wrap());
                init = true;
            }
            return value;
        };
        return new Proxy(target, this.createHandler(delayedObject));
    };
    DelayedConstructor.prototype.createHandler = function (delayedObject) {
        var handler = {};
        var install = function (name) {
            handler[name] = function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                args[0] = delayedObject();
                var method = Reflect[name];
                return method.apply(void 0, __spread(args));
            };
        };
        this.reflectMethods.forEach(install);
        return handler;
    };
    return DelayedConstructor;
}());

function isNormalToken(token) {
    return typeof token === "string" || typeof token === "symbol";
}
function isTokenDescriptor(descriptor) {
    return (typeof descriptor === "object" &&
        "token" in descriptor &&
        "multiple" in descriptor);
}
function isTransformDescriptor(descriptor) {
    return (typeof descriptor === "object" &&
        "token" in descriptor &&
        "transform" in descriptor);
}
function isConstructorToken(token) {
    return typeof token === "function" || token instanceof DelayedConstructor;
}

function isTokenProvider(provider) {
    return !!provider.useToken;
}

function isValueProvider(provider) {
    return provider.useValue != undefined;
}

function isProvider(provider) {
    return (isClassProvider(provider) ||
        isValueProvider(provider) ||
        isTokenProvider(provider) ||
        isFactoryProvider(provider));
}

var RegistryBase = (function () {
    function RegistryBase() {
        this._registryMap = new Map();
    }
    RegistryBase.prototype.entries = function () {
        return this._registryMap.entries();
    };
    RegistryBase.prototype.getAll = function (key) {
        this.ensure(key);
        return this._registryMap.get(key);
    };
    RegistryBase.prototype.get = function (key) {
        this.ensure(key);
        var value = this._registryMap.get(key);
        return value[value.length - 1] || null;
    };
    RegistryBase.prototype.set = function (key, value) {
        this.ensure(key);
        this._registryMap.get(key).push(value);
    };
    RegistryBase.prototype.setAll = function (key, value) {
        this._registryMap.set(key, value);
    };
    RegistryBase.prototype.has = function (key) {
        this.ensure(key);
        return this._registryMap.get(key).length > 0;
    };
    RegistryBase.prototype.clear = function () {
        this._registryMap.clear();
    };
    RegistryBase.prototype.ensure = function (key) {
        if (!this._registryMap.has(key)) {
            this._registryMap.set(key, []);
        }
    };
    return RegistryBase;
}());

var Registry = (function (_super) {
    __extends(Registry, _super);
    function Registry() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return Registry;
}(RegistryBase));

var ResolutionContext = (function () {
    function ResolutionContext() {
        this.scopedResolutions = new Map();
    }
    return ResolutionContext;
}());

function formatDependency(params, idx) {
    if (params === null) {
        return "at position #" + idx;
    }
    var argName = params.split(",")[idx].trim();
    return "\"" + argName + "\" at position #" + idx;
}
function composeErrorMessage(msg, e, indent) {
    if (indent === void 0) { indent = "    "; }
    return __spread([msg], e.message.split("\n").map(function (l) { return indent + l; })).join("\n");
}
function formatErrorCtor(ctor, paramIdx, error) {
    var _a = __read(ctor.toString().match(/constructor\(([\w, ]+)\)/) || [], 2), _b = _a[1], params = _b === void 0 ? null : _b;
    var dep = formatDependency(params, paramIdx);
    return composeErrorMessage("Cannot inject the dependency " + dep + " of \"" + ctor.name + "\" constructor. Reason:", error);
}

function isDisposable(value) {
    if (typeof value.dispose !== "function")
        return false;
    var disposeFun = value.dispose;
    if (disposeFun.length > 0) {
        return false;
    }
    return true;
}

var PreResolutionInterceptors = (function (_super) {
    __extends(PreResolutionInterceptors, _super);
    function PreResolutionInterceptors() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return PreResolutionInterceptors;
}(RegistryBase));
var PostResolutionInterceptors = (function (_super) {
    __extends(PostResolutionInterceptors, _super);
    function PostResolutionInterceptors() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return PostResolutionInterceptors;
}(RegistryBase));
var Interceptors = (function () {
    function Interceptors() {
        this.preResolution = new PreResolutionInterceptors();
        this.postResolution = new PostResolutionInterceptors();
    }
    return Interceptors;
}());

var typeInfo = new Map();
var InternalDependencyContainer = (function () {
    function InternalDependencyContainer(parent) {
        this.parent = parent;
        this._registry = new Registry();
        this.interceptors = new Interceptors();
        this.disposed = false;
        this.disposables = new Set();
    }
    InternalDependencyContainer.prototype.register = function (token, providerOrConstructor, options) {
        if (options === void 0) { options = { lifecycle: Lifecycle$1.Transient }; }
        this.ensureNotDisposed();
        var provider;
        if (!isProvider(providerOrConstructor)) {
            provider = { useClass: providerOrConstructor };
        }
        else {
            provider = providerOrConstructor;
        }
        if (isTokenProvider(provider)) {
            var path = [token];
            var tokenProvider = provider;
            while (tokenProvider != null) {
                var currentToken = tokenProvider.useToken;
                if (path.includes(currentToken)) {
                    throw new Error("Token registration cycle detected! " + __spread(path, [currentToken]).join(" -> "));
                }
                path.push(currentToken);
                var registration = this._registry.get(currentToken);
                if (registration && isTokenProvider(registration.provider)) {
                    tokenProvider = registration.provider;
                }
                else {
                    tokenProvider = null;
                }
            }
        }
        if (options.lifecycle === Lifecycle$1.Singleton ||
            options.lifecycle == Lifecycle$1.ContainerScoped ||
            options.lifecycle == Lifecycle$1.ResolutionScoped) {
            if (isValueProvider(provider) || isFactoryProvider(provider)) {
                throw new Error("Cannot use lifecycle \"" + Lifecycle$1[options.lifecycle] + "\" with ValueProviders or FactoryProviders");
            }
        }
        this._registry.set(token, { provider: provider, options: options });
        return this;
    };
    InternalDependencyContainer.prototype.registerType = function (from, to) {
        this.ensureNotDisposed();
        if (isNormalToken(to)) {
            return this.register(from, {
                useToken: to
            });
        }
        return this.register(from, {
            useClass: to
        });
    };
    InternalDependencyContainer.prototype.registerInstance = function (token, instance) {
        this.ensureNotDisposed();
        return this.register(token, {
            useValue: instance
        });
    };
    InternalDependencyContainer.prototype.registerSingleton = function (from, to) {
        this.ensureNotDisposed();
        if (isNormalToken(from)) {
            if (isNormalToken(to)) {
                return this.register(from, {
                    useToken: to
                }, { lifecycle: Lifecycle$1.Singleton });
            }
            else if (to) {
                return this.register(from, {
                    useClass: to
                }, { lifecycle: Lifecycle$1.Singleton });
            }
            throw new Error('Cannot register a type name as a singleton without a "to" token');
        }
        var useClass = from;
        if (to && !isNormalToken(to)) {
            useClass = to;
        }
        return this.register(from, {
            useClass: useClass
        }, { lifecycle: Lifecycle$1.Singleton });
    };
    InternalDependencyContainer.prototype.resolve = function (token, context, isOptional) {
        if (context === void 0) { context = new ResolutionContext(); }
        if (isOptional === void 0) { isOptional = false; }
        this.ensureNotDisposed();
        var registration = this.getRegistration(token);
        if (!registration && isNormalToken(token)) {
            if (isOptional) {
                return undefined;
            }
            throw new Error("Attempted to resolve unregistered dependency token: \"" + token.toString() + "\"");
        }
        this.executePreResolutionInterceptor(token, "Single");
        if (registration) {
            var result = this.resolveRegistration(registration, context);
            this.executePostResolutionInterceptor(token, result, "Single");
            return result;
        }
        if (isConstructorToken(token)) {
            var result = this.construct(token, context);
            this.executePostResolutionInterceptor(token, result, "Single");
            return result;
        }
        throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.");
    };
    InternalDependencyContainer.prototype.executePreResolutionInterceptor = function (token, resolutionType) {
        var e_1, _a;
        if (this.interceptors.preResolution.has(token)) {
            var remainingInterceptors = [];
            try {
                for (var _b = __values(this.interceptors.preResolution.getAll(token)), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var interceptor = _c.value;
                    if (interceptor.options.frequency != "Once") {
                        remainingInterceptors.push(interceptor);
                    }
                    interceptor.callback(token, resolutionType);
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
            this.interceptors.preResolution.setAll(token, remainingInterceptors);
        }
    };
    InternalDependencyContainer.prototype.executePostResolutionInterceptor = function (token, result, resolutionType) {
        var e_2, _a;
        if (this.interceptors.postResolution.has(token)) {
            var remainingInterceptors = [];
            try {
                for (var _b = __values(this.interceptors.postResolution.getAll(token)), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var interceptor = _c.value;
                    if (interceptor.options.frequency != "Once") {
                        remainingInterceptors.push(interceptor);
                    }
                    interceptor.callback(token, result, resolutionType);
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_2) throw e_2.error; }
            }
            this.interceptors.postResolution.setAll(token, remainingInterceptors);
        }
    };
    InternalDependencyContainer.prototype.resolveRegistration = function (registration, context) {
        this.ensureNotDisposed();
        if (registration.options.lifecycle === Lifecycle$1.ResolutionScoped &&
            context.scopedResolutions.has(registration)) {
            return context.scopedResolutions.get(registration);
        }
        var isSingleton = registration.options.lifecycle === Lifecycle$1.Singleton;
        var isContainerScoped = registration.options.lifecycle === Lifecycle$1.ContainerScoped;
        var returnInstance = isSingleton || isContainerScoped;
        var resolved;
        if (isValueProvider(registration.provider)) {
            resolved = registration.provider.useValue;
        }
        else if (isTokenProvider(registration.provider)) {
            resolved = returnInstance
                ? registration.instance ||
                    (registration.instance = this.resolve(registration.provider.useToken, context))
                : this.resolve(registration.provider.useToken, context);
        }
        else if (isClassProvider(registration.provider)) {
            resolved = returnInstance
                ? registration.instance ||
                    (registration.instance = this.construct(registration.provider.useClass, context))
                : this.construct(registration.provider.useClass, context);
        }
        else if (isFactoryProvider(registration.provider)) {
            resolved = registration.provider.useFactory(this);
        }
        else {
            resolved = this.construct(registration.provider, context);
        }
        if (registration.options.lifecycle === Lifecycle$1.ResolutionScoped) {
            context.scopedResolutions.set(registration, resolved);
        }
        return resolved;
    };
    InternalDependencyContainer.prototype.resolveAll = function (token, context, isOptional) {
        var _this = this;
        if (context === void 0) { context = new ResolutionContext(); }
        if (isOptional === void 0) { isOptional = false; }
        this.ensureNotDisposed();
        var registrations = this.getAllRegistrations(token);
        if (!registrations && isNormalToken(token)) {
            if (isOptional) {
                return [];
            }
            throw new Error("Attempted to resolve unregistered dependency token: \"" + token.toString() + "\"");
        }
        this.executePreResolutionInterceptor(token, "All");
        if (registrations) {
            var result_1 = registrations.map(function (item) {
                return _this.resolveRegistration(item, context);
            });
            this.executePostResolutionInterceptor(token, result_1, "All");
            return result_1;
        }
        var result = [this.construct(token, context)];
        this.executePostResolutionInterceptor(token, result, "All");
        return result;
    };
    InternalDependencyContainer.prototype.isRegistered = function (token, recursive) {
        if (recursive === void 0) { recursive = false; }
        this.ensureNotDisposed();
        return (this._registry.has(token) ||
            (recursive &&
                (this.parent || false) &&
                this.parent.isRegistered(token, true)));
    };
    InternalDependencyContainer.prototype.reset = function () {
        this.ensureNotDisposed();
        this._registry.clear();
        this.interceptors.preResolution.clear();
        this.interceptors.postResolution.clear();
    };
    InternalDependencyContainer.prototype.clearInstances = function () {
        var e_3, _a;
        this.ensureNotDisposed();
        try {
            for (var _b = __values(this._registry.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
                var _d = __read(_c.value, 2), token = _d[0], registrations = _d[1];
                this._registry.setAll(token, registrations
                    .filter(function (registration) { return !isValueProvider(registration.provider); })
                    .map(function (registration) {
                    registration.instance = undefined;
                    return registration;
                }));
            }
        }
        catch (e_3_1) { e_3 = { error: e_3_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_3) throw e_3.error; }
        }
    };
    InternalDependencyContainer.prototype.createChildContainer = function () {
        var e_4, _a;
        this.ensureNotDisposed();
        var childContainer = new InternalDependencyContainer(this);
        try {
            for (var _b = __values(this._registry.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
                var _d = __read(_c.value, 2), token = _d[0], registrations = _d[1];
                if (registrations.some(function (_a) {
                    var options = _a.options;
                    return options.lifecycle === Lifecycle$1.ContainerScoped;
                })) {
                    childContainer._registry.setAll(token, registrations.map(function (registration) {
                        if (registration.options.lifecycle === Lifecycle$1.ContainerScoped) {
                            return {
                                provider: registration.provider,
                                options: registration.options
                            };
                        }
                        return registration;
                    }));
                }
            }
        }
        catch (e_4_1) { e_4 = { error: e_4_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_4) throw e_4.error; }
        }
        return childContainer;
    };
    InternalDependencyContainer.prototype.beforeResolution = function (token, callback, options) {
        if (options === void 0) { options = { frequency: "Always" }; }
        this.interceptors.preResolution.set(token, {
            callback: callback,
            options: options
        });
    };
    InternalDependencyContainer.prototype.afterResolution = function (token, callback, options) {
        if (options === void 0) { options = { frequency: "Always" }; }
        this.interceptors.postResolution.set(token, {
            callback: callback,
            options: options
        });
    };
    InternalDependencyContainer.prototype.dispose = function () {
        return __awaiter(this, void 0, void 0, function () {
            var promises;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.disposed = true;
                        promises = [];
                        this.disposables.forEach(function (disposable) {
                            var maybePromise = disposable.dispose();
                            if (maybePromise) {
                                promises.push(maybePromise);
                            }
                        });
                        return [4, Promise.all(promises)];
                    case 1:
                        _a.sent();
                        return [2];
                }
            });
        });
    };
    InternalDependencyContainer.prototype.getRegistration = function (token) {
        if (this.isRegistered(token)) {
            return this._registry.get(token);
        }
        if (this.parent) {
            return this.parent.getRegistration(token);
        }
        return null;
    };
    InternalDependencyContainer.prototype.getAllRegistrations = function (token) {
        if (this.isRegistered(token)) {
            return this._registry.getAll(token);
        }
        if (this.parent) {
            return this.parent.getAllRegistrations(token);
        }
        return null;
    };
    InternalDependencyContainer.prototype.construct = function (ctor, context) {
        var _this = this;
        if (ctor instanceof DelayedConstructor) {
            return ctor.createProxy(function (target) {
                return _this.resolve(target, context);
            });
        }
        var instance = (function () {
            var paramInfo = typeInfo.get(ctor);
            if (!paramInfo || paramInfo.length === 0) {
                if (ctor.length === 0) {
                    return new ctor();
                }
                else {
                    throw new Error("TypeInfo not known for \"" + ctor.name + "\"");
                }
            }
            var params = paramInfo.map(_this.resolveParams(context, ctor));
            return new (ctor.bind.apply(ctor, __spread([void 0], params)))();
        })();
        if (isDisposable(instance)) {
            this.disposables.add(instance);
        }
        return instance;
    };
    InternalDependencyContainer.prototype.resolveParams = function (context, ctor) {
        var _this = this;
        return function (param, idx) {
            var _a, _b, _c;
            try {
                if (isTokenDescriptor(param)) {
                    if (isTransformDescriptor(param)) {
                        return param.multiple
                            ? (_a = _this.resolve(param.transform)).transform.apply(_a, __spread([_this.resolveAll(param.token, new ResolutionContext(), param.isOptional)], param.transformArgs)) : (_b = _this.resolve(param.transform)).transform.apply(_b, __spread([_this.resolve(param.token, context, param.isOptional)], param.transformArgs));
                    }
                    else {
                        return param.multiple
                            ? _this.resolveAll(param.token, new ResolutionContext(), param.isOptional)
                            : _this.resolve(param.token, context, param.isOptional);
                    }
                }
                else if (isTransformDescriptor(param)) {
                    return (_c = _this.resolve(param.transform, context)).transform.apply(_c, __spread([_this.resolve(param.token, context)], param.transformArgs));
                }
                return _this.resolve(param, context);
            }
            catch (e) {
                throw new Error(formatErrorCtor(ctor, idx, e));
            }
        };
    };
    InternalDependencyContainer.prototype.ensureNotDisposed = function () {
        if (this.disposed) {
            throw new Error("This container has been disposed, you cannot interact with a disposed container");
        }
    };
    return InternalDependencyContainer;
}());
var instance = new InternalDependencyContainer();

function injectable(options) {
    return function (target) {
        typeInfo.set(target, getParamInfo(target));
    };
}

if (typeof Reflect === "undefined" || !Reflect.getMetadata) {
    throw new Error("tsyringe requires a reflect polyfill. Please add 'import \"reflect-metadata\"' to the top of your entry point.");
}

var PKCS12AttrSet_1;
class PKCS12Attribute {
    constructor(params = {}) {
        this.attrId = "";
        this.attrValues = [];
        Object.assign(params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], PKCS12Attribute.prototype, "attrId", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any, repeated: "set" })
], PKCS12Attribute.prototype, "attrValues", void 0);
let PKCS12AttrSet = PKCS12AttrSet_1 = class PKCS12AttrSet extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, PKCS12AttrSet_1.prototype);
    }
};
PKCS12AttrSet = PKCS12AttrSet_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: PKCS12Attribute })
], PKCS12AttrSet);

var AuthenticatedSafe_1;
let AuthenticatedSafe = AuthenticatedSafe_1 = class AuthenticatedSafe extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, AuthenticatedSafe_1.prototype);
    }
};
AuthenticatedSafe = AuthenticatedSafe_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: ContentInfo })
], AuthenticatedSafe);

class CertBag {
    constructor(params = {}) {
        this.certId = "";
        this.certValue = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], CertBag.prototype, "certId", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any, context: 0 })
], CertBag.prototype, "certValue", void 0);

class CRLBag {
    constructor(params = {}) {
        this.crlId = "";
        this.crltValue = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], CRLBag.prototype, "crlId", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any, context: 0 })
], CRLBag.prototype, "crltValue", void 0);

class EncryptedData extends OctetString {
}
let EncryptedPrivateKeyInfo$1 = class EncryptedPrivateKeyInfo {
    constructor(params = {}) {
        this.encryptionAlgorithm = new AlgorithmIdentifier();
        this.encryptedData = new EncryptedData();
        Object.assign(this, params);
    }
};
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier })
], EncryptedPrivateKeyInfo$1.prototype, "encryptionAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: EncryptedData })
], EncryptedPrivateKeyInfo$1.prototype, "encryptedData", void 0);

var Attributes_1$1;
var Version$1;
(function (Version) {
    Version[Version["v1"] = 0] = "v1";
})(Version$1 || (Version$1 = {}));
class PrivateKey extends OctetString {
}
let Attributes$1 = Attributes_1$1 = class Attributes extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, Attributes_1$1.prototype);
    }
};
Attributes$1 = Attributes_1$1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: Attribute$2 })
], Attributes$1);
class PrivateKeyInfo {
    constructor(params = {}) {
        this.version = Version$1.v1;
        this.privateKeyAlgorithm = new AlgorithmIdentifier();
        this.privateKey = new PrivateKey();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], PrivateKeyInfo.prototype, "version", void 0);
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier })
], PrivateKeyInfo.prototype, "privateKeyAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: PrivateKey })
], PrivateKeyInfo.prototype, "privateKey", void 0);
__decorate$1([
    AsnProp({ type: Attributes$1, implicit: true, context: 0, optional: true })
], PrivateKeyInfo.prototype, "attributes", void 0);

let KeyBag = class KeyBag extends PrivateKeyInfo {
};
KeyBag = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], KeyBag);

let PKCS8ShroudedKeyBag = class PKCS8ShroudedKeyBag extends EncryptedPrivateKeyInfo$1 {
};
PKCS8ShroudedKeyBag = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], PKCS8ShroudedKeyBag);

class SecretBag {
    constructor(params = {}) {
        this.secretTypeId = "";
        this.secretValue = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], SecretBag.prototype, "secretTypeId", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any, context: 0 })
], SecretBag.prototype, "secretValue", void 0);

class MacData {
    constructor(params = {}) {
        this.mac = new DigestInfo();
        this.macSalt = new OctetString();
        this.iterations = 1;
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: DigestInfo })
], MacData.prototype, "mac", void 0);
__decorate$1([
    AsnProp({ type: OctetString })
], MacData.prototype, "macSalt", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer, defaultValue: 1 })
], MacData.prototype, "iterations", void 0);

class PFX {
    constructor(params = {}) {
        this.version = 3;
        this.authSafe = new ContentInfo();
        this.macData = new MacData();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], PFX.prototype, "version", void 0);
__decorate$1([
    AsnProp({ type: ContentInfo })
], PFX.prototype, "authSafe", void 0);
__decorate$1([
    AsnProp({ type: MacData, optional: true })
], PFX.prototype, "macData", void 0);

var SafeContents_1;
class SafeBag {
    constructor(params = {}) {
        this.bagId = "";
        this.bagValue = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], SafeBag.prototype, "bagId", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Any, context: 0 })
], SafeBag.prototype, "bagValue", void 0);
__decorate$1([
    AsnProp({ type: PKCS12Attribute, repeated: "set", optional: true })
], SafeBag.prototype, "bagAttributes", void 0);
let SafeContents = SafeContents_1 = class SafeContents extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, SafeContents_1.prototype);
    }
};
SafeContents = SafeContents_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: SafeBag })
], SafeContents);

var ExtensionRequest_1, ExtendedCertificateAttributes_1, SMIMECapabilities_1;
const id_pkcs9 = "1.2.840.113549.1.9";
const id_pkcs9_at_challengePassword = `${id_pkcs9}.7`;
const id_pkcs9_at_extensionRequest = `${id_pkcs9}.14`;
let PKCS9String = class PKCS9String extends DirectoryString {
    constructor(params = {}) {
        super(params);
    }
    toString() {
        return this.ia5String || super.toString();
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.IA5String })
], PKCS9String.prototype, "ia5String", void 0);
PKCS9String = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], PKCS9String);
let Pkcs7PDU = class Pkcs7PDU extends ContentInfo {
};
Pkcs7PDU = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], Pkcs7PDU);
let UserPKCS12 = class UserPKCS12 extends PFX {
};
UserPKCS12 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], UserPKCS12);
let EncryptedPrivateKeyInfo = class EncryptedPrivateKeyInfo extends EncryptedPrivateKeyInfo$1 {
};
EncryptedPrivateKeyInfo = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], EncryptedPrivateKeyInfo);
let EmailAddress = class EmailAddress {
    constructor(value = "") {
        this.value = value;
    }
    toString() {
        return this.value;
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.IA5String })
], EmailAddress.prototype, "value", void 0);
EmailAddress = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], EmailAddress);
let UnstructuredName = class UnstructuredName extends PKCS9String {
};
UnstructuredName = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], UnstructuredName);
let UnstructuredAddress = class UnstructuredAddress extends DirectoryString {
};
UnstructuredAddress = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], UnstructuredAddress);
let DateOfBirth = class DateOfBirth {
    constructor(value = new Date()) {
        this.value = value;
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.GeneralizedTime })
], DateOfBirth.prototype, "value", void 0);
DateOfBirth = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], DateOfBirth);
let PlaceOfBirth = class PlaceOfBirth extends DirectoryString {
};
PlaceOfBirth = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], PlaceOfBirth);
let Gender = class Gender {
    constructor(value = "M") {
        this.value = value;
    }
    toString() {
        return this.value;
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.PrintableString })
], Gender.prototype, "value", void 0);
Gender = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], Gender);
let CountryOfCitizenship = class CountryOfCitizenship {
    constructor(value = "") {
        this.value = value;
    }
    toString() {
        return this.value;
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.PrintableString })
], CountryOfCitizenship.prototype, "value", void 0);
CountryOfCitizenship = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], CountryOfCitizenship);
let CountryOfResidence = class CountryOfResidence extends CountryOfCitizenship {
};
CountryOfResidence = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], CountryOfResidence);
let Pseudonym = class Pseudonym extends DirectoryString {
};
Pseudonym = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], Pseudonym);
let ContentType = class ContentType {
    constructor(value = "") {
        this.value = value;
    }
    toString() {
        return this.value;
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.ObjectIdentifier })
], ContentType.prototype, "value", void 0);
ContentType = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], ContentType);
let SigningTime = class SigningTime extends Time {
};
SigningTime = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], SigningTime);
let SequenceNumber = class SequenceNumber {
    constructor(value = 0) {
        this.value = value;
    }
    toString() {
        return this.value.toString();
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], SequenceNumber.prototype, "value", void 0);
SequenceNumber = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], SequenceNumber);
let CounterSignature = class CounterSignature extends SignerInfo {
};
CounterSignature = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], CounterSignature);
let ChallengePassword = class ChallengePassword extends DirectoryString {
};
ChallengePassword = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], ChallengePassword);
let ExtensionRequest = ExtensionRequest_1 = class ExtensionRequest extends Extensions {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, ExtensionRequest_1.prototype);
    }
};
ExtensionRequest = ExtensionRequest_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], ExtensionRequest);
let ExtendedCertificateAttributes = ExtendedCertificateAttributes_1 = class ExtendedCertificateAttributes extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, ExtendedCertificateAttributes_1.prototype);
    }
};
ExtendedCertificateAttributes = ExtendedCertificateAttributes_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Set, itemType: Attribute$1 })
], ExtendedCertificateAttributes);
let FriendlyName = class FriendlyName {
    constructor(value = "") {
        this.value = value;
    }
    toString() {
        return this.value;
    }
};
__decorate$1([
    AsnProp({ type: AsnPropTypes.BmpString })
], FriendlyName.prototype, "value", void 0);
FriendlyName = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], FriendlyName);
let SMIMECapability = class SMIMECapability extends AlgorithmIdentifier {
};
SMIMECapability = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], SMIMECapability);
let SMIMECapabilities = SMIMECapabilities_1 = class SMIMECapabilities extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, SMIMECapabilities_1.prototype);
    }
};
SMIMECapabilities = SMIMECapabilities_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: SMIMECapability })
], SMIMECapabilities);

var Attributes_1;
let Attributes = Attributes_1 = class Attributes extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, Attributes_1.prototype);
    }
};
Attributes = Attributes_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: Attribute$2 })
], Attributes);

class CertificationRequestInfo {
    constructor(params = {}) {
        this.version = 0;
        this.subject = new Name$1();
        this.subjectPKInfo = new SubjectPublicKeyInfo();
        this.attributes = new Attributes();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], CertificationRequestInfo.prototype, "version", void 0);
__decorate$1([
    AsnProp({ type: Name$1 })
], CertificationRequestInfo.prototype, "subject", void 0);
__decorate$1([
    AsnProp({ type: SubjectPublicKeyInfo })
], CertificationRequestInfo.prototype, "subjectPKInfo", void 0);
__decorate$1([
    AsnProp({ type: Attributes, implicit: true, context: 0, optional: true })
], CertificationRequestInfo.prototype, "attributes", void 0);

class CertificationRequest {
    constructor(params = {}) {
        this.certificationRequestInfo = new CertificationRequestInfo();
        this.signatureAlgorithm = new AlgorithmIdentifier();
        this.signature = new ArrayBuffer(0);
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: CertificationRequestInfo, raw: true })
], CertificationRequest.prototype, "certificationRequestInfo", void 0);
__decorate$1([
    AsnProp({ type: AlgorithmIdentifier })
], CertificationRequest.prototype, "signatureAlgorithm", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.BitString })
], CertificationRequest.prototype, "signature", void 0);

/*!
 * MIT License
 * 
 * Copyright (c) Peculiar Ventures. All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * 
 */

const diAlgorithm = "crypto.algorithm";
class AlgorithmProvider {
    getAlgorithms() {
        return instance.resolveAll(diAlgorithm);
    }
    toAsnAlgorithm(alg) {
        ({ ...alg });
        for (const algorithm of this.getAlgorithms()) {
            const res = algorithm.toAsnAlgorithm(alg);
            if (res) {
                return res;
            }
        }
        if (/^[0-9.]+$/.test(alg.name)) {
            const res = new AlgorithmIdentifier({ algorithm: alg.name });
            if ("parameters" in alg) {
                const unknown = alg;
                res.parameters = unknown.parameters;
            }
            return res;
        }
        throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm");
    }
    toWebAlgorithm(alg) {
        for (const algorithm of this.getAlgorithms()) {
            const res = algorithm.toWebAlgorithm(alg);
            if (res) {
                return res;
            }
        }
        const unknown = {
            name: alg.algorithm,
            parameters: alg.parameters,
        };
        return unknown;
    }
}
const diAlgorithmProvider = "crypto.algorithmProvider";
instance.registerSingleton(diAlgorithmProvider, AlgorithmProvider);

var EcAlgorithm_1;
const idVersionOne = "1.3.36.3.3.2.8.1.1";
const idBrainpoolP160r1 = `${idVersionOne}.1`;
const idBrainpoolP160t1 = `${idVersionOne}.2`;
const idBrainpoolP192r1 = `${idVersionOne}.3`;
const idBrainpoolP192t1 = `${idVersionOne}.4`;
const idBrainpoolP224r1 = `${idVersionOne}.5`;
const idBrainpoolP224t1 = `${idVersionOne}.6`;
const idBrainpoolP256r1 = `${idVersionOne}.7`;
const idBrainpoolP256t1 = `${idVersionOne}.8`;
const idBrainpoolP320r1 = `${idVersionOne}.9`;
const idBrainpoolP320t1 = `${idVersionOne}.10`;
const idBrainpoolP384r1 = `${idVersionOne}.11`;
const idBrainpoolP384t1 = `${idVersionOne}.12`;
const idBrainpoolP512r1 = `${idVersionOne}.13`;
const idBrainpoolP512t1 = `${idVersionOne}.14`;
const brainpoolP160r1 = "brainpoolP160r1";
const brainpoolP160t1 = "brainpoolP160t1";
const brainpoolP192r1 = "brainpoolP192r1";
const brainpoolP192t1 = "brainpoolP192t1";
const brainpoolP224r1 = "brainpoolP224r1";
const brainpoolP224t1 = "brainpoolP224t1";
const brainpoolP256r1 = "brainpoolP256r1";
const brainpoolP256t1 = "brainpoolP256t1";
const brainpoolP320r1 = "brainpoolP320r1";
const brainpoolP320t1 = "brainpoolP320t1";
const brainpoolP384r1 = "brainpoolP384r1";
const brainpoolP384t1 = "brainpoolP384t1";
const brainpoolP512r1 = "brainpoolP512r1";
const brainpoolP512t1 = "brainpoolP512t1";
const ECDSA = "ECDSA";
let EcAlgorithm = EcAlgorithm_1 = class EcAlgorithm {
    toAsnAlgorithm(alg) {
        switch (alg.name.toLowerCase()) {
            case ECDSA.toLowerCase():
                if ("hash" in alg) {
                    const hash = typeof alg.hash === "string" ? alg.hash : alg.hash.name;
                    switch (hash.toLowerCase()) {
                        case "sha-1":
                            return ecdsaWithSHA1;
                        case "sha-256":
                            return ecdsaWithSHA256;
                        case "sha-384":
                            return ecdsaWithSHA384;
                        case "sha-512":
                            return ecdsaWithSHA512;
                    }
                }
                else if ("namedCurve" in alg) {
                    let parameters = "";
                    switch (alg.namedCurve) {
                        case "P-256":
                            parameters = id_secp256r1;
                            break;
                        case "K-256":
                            parameters = EcAlgorithm_1.SECP256K1;
                            break;
                        case "P-384":
                            parameters = id_secp384r1;
                            break;
                        case "P-521":
                            parameters = id_secp521r1;
                            break;
                        case brainpoolP160r1:
                            parameters = idBrainpoolP160r1;
                            break;
                        case brainpoolP160t1:
                            parameters = idBrainpoolP160t1;
                            break;
                        case brainpoolP192r1:
                            parameters = idBrainpoolP192r1;
                            break;
                        case brainpoolP192t1:
                            parameters = idBrainpoolP192t1;
                            break;
                        case brainpoolP224r1:
                            parameters = idBrainpoolP224r1;
                            break;
                        case brainpoolP224t1:
                            parameters = idBrainpoolP224t1;
                            break;
                        case brainpoolP256r1:
                            parameters = idBrainpoolP256r1;
                            break;
                        case brainpoolP256t1:
                            parameters = idBrainpoolP256t1;
                            break;
                        case brainpoolP320r1:
                            parameters = idBrainpoolP320r1;
                            break;
                        case brainpoolP320t1:
                            parameters = idBrainpoolP320t1;
                            break;
                        case brainpoolP384r1:
                            parameters = idBrainpoolP384r1;
                            break;
                        case brainpoolP384t1:
                            parameters = idBrainpoolP384t1;
                            break;
                        case brainpoolP512r1:
                            parameters = idBrainpoolP512r1;
                            break;
                        case brainpoolP512t1:
                            parameters = idBrainpoolP512t1;
                            break;
                    }
                    if (parameters) {
                        return new AlgorithmIdentifier({
                            algorithm: id_ecPublicKey,
                            parameters: AsnConvert.serialize(new ECParameters({ namedCurve: parameters })),
                        });
                    }
                }
        }
        return null;
    }
    toWebAlgorithm(alg) {
        switch (alg.algorithm) {
            case id_ecdsaWithSHA1:
                return {
                    name: ECDSA, hash: { name: "SHA-1" },
                };
            case id_ecdsaWithSHA256:
                return {
                    name: ECDSA, hash: { name: "SHA-256" },
                };
            case id_ecdsaWithSHA384:
                return {
                    name: ECDSA, hash: { name: "SHA-384" },
                };
            case id_ecdsaWithSHA512:
                return {
                    name: ECDSA, hash: { name: "SHA-512" },
                };
            case id_ecPublicKey: {
                if (!alg.parameters) {
                    throw new TypeError("Cannot get required parameters from EC algorithm");
                }
                const parameters = AsnConvert.parse(alg.parameters, ECParameters);
                switch (parameters.namedCurve) {
                    case id_secp256r1:
                        return {
                            name: ECDSA, namedCurve: "P-256",
                        };
                    case EcAlgorithm_1.SECP256K1:
                        return {
                            name: ECDSA, namedCurve: "K-256",
                        };
                    case id_secp384r1:
                        return {
                            name: ECDSA, namedCurve: "P-384",
                        };
                    case id_secp521r1:
                        return {
                            name: ECDSA, namedCurve: "P-521",
                        };
                    case idBrainpoolP160r1:
                        return {
                            name: ECDSA, namedCurve: brainpoolP160r1,
                        };
                    case idBrainpoolP160t1:
                        return {
                            name: ECDSA, namedCurve: brainpoolP160t1,
                        };
                    case idBrainpoolP192r1:
                        return {
                            name: ECDSA, namedCurve: brainpoolP192r1,
                        };
                    case idBrainpoolP192t1:
                        return {
                            name: ECDSA, namedCurve: brainpoolP192t1,
                        };
                    case idBrainpoolP224r1:
                        return {
                            name: ECDSA, namedCurve: brainpoolP224r1,
                        };
                    case idBrainpoolP224t1:
                        return {
                            name: ECDSA, namedCurve: brainpoolP224t1,
                        };
                    case idBrainpoolP256r1:
                        return {
                            name: ECDSA, namedCurve: brainpoolP256r1,
                        };
                    case idBrainpoolP256t1:
                        return {
                            name: ECDSA, namedCurve: brainpoolP256t1,
                        };
                    case idBrainpoolP320r1:
                        return {
                            name: ECDSA, namedCurve: brainpoolP320r1,
                        };
                    case idBrainpoolP320t1:
                        return {
                            name: ECDSA, namedCurve: brainpoolP320t1,
                        };
                    case idBrainpoolP384r1:
                        return {
                            name: ECDSA, namedCurve: brainpoolP384r1,
                        };
                    case idBrainpoolP384t1:
                        return {
                            name: ECDSA, namedCurve: brainpoolP384t1,
                        };
                    case idBrainpoolP512r1:
                        return {
                            name: ECDSA, namedCurve: brainpoolP512r1,
                        };
                    case idBrainpoolP512t1:
                        return {
                            name: ECDSA, namedCurve: brainpoolP512t1,
                        };
                }
            }
        }
        return null;
    }
};
EcAlgorithm.SECP256K1 = "1.3.132.0.10";
EcAlgorithm = EcAlgorithm_1 = __decorate$1([
    injectable()
], EcAlgorithm);
instance.registerSingleton(diAlgorithm, EcAlgorithm);

const NAME = Symbol("name");
const VALUE = Symbol("value");
class TextObject {
    constructor(name, items = {}, value = "") {
        this[NAME] = name;
        this[VALUE] = value;
        for (const key in items) {
            this[key] = items[key];
        }
    }
}
TextObject.NAME = NAME;
TextObject.VALUE = VALUE;
class DefaultAlgorithmSerializer {
    static toTextObject(alg) {
        const obj = new TextObject("Algorithm Identifier", {}, OidSerializer.toString(alg.algorithm));
        if (alg.parameters) {
            switch (alg.algorithm) {
                case id_ecPublicKey: {
                    const ecAlg = new EcAlgorithm().toWebAlgorithm(alg);
                    if (ecAlg && "namedCurve" in ecAlg) {
                        obj["Named Curve"] = ecAlg.namedCurve;
                    }
                    else {
                        obj["Parameters"] = alg.parameters;
                    }
                    break;
                }
                default:
                    obj["Parameters"] = alg.parameters;
            }
        }
        return obj;
    }
}
class OidSerializer {
    static toString(oid) {
        const name = this.items[oid];
        if (name) {
            return name;
        }
        return oid;
    }
}
OidSerializer.items = {
    [id_sha1]: "sha1",
    [id_sha224]: "sha224",
    [id_sha256]: "sha256",
    [id_sha384]: "sha384",
    [id_sha512]: "sha512",
    [id_rsaEncryption]: "rsaEncryption",
    [id_sha1WithRSAEncryption]: "sha1WithRSAEncryption",
    [id_sha224WithRSAEncryption]: "sha224WithRSAEncryption",
    [id_sha256WithRSAEncryption]: "sha256WithRSAEncryption",
    [id_sha384WithRSAEncryption]: "sha384WithRSAEncryption",
    [id_sha512WithRSAEncryption]: "sha512WithRSAEncryption",
    [id_ecPublicKey]: "ecPublicKey",
    [id_ecdsaWithSHA1]: "ecdsaWithSHA1",
    [id_ecdsaWithSHA224]: "ecdsaWithSHA224",
    [id_ecdsaWithSHA256]: "ecdsaWithSHA256",
    [id_ecdsaWithSHA384]: "ecdsaWithSHA384",
    [id_ecdsaWithSHA512]: "ecdsaWithSHA512",
    [id_kp_serverAuth]: "TLS WWW server authentication",
    [id_kp_clientAuth]: "TLS WWW client authentication",
    [id_kp_codeSigning]: "Code Signing",
    [id_kp_emailProtection]: "E-mail Protection",
    [id_kp_timeStamping]: "Time Stamping",
    [id_kp_OCSPSigning]: "OCSP Signing",
    [id_signedData]: "Signed Data",
};
class TextConverter {
    static serialize(obj) {
        return this.serializeObj(obj).join("\n");
    }
    static pad(deep = 0) {
        return "".padStart(2 * deep, " ");
    }
    static serializeObj(obj, deep = 0) {
        const res = [];
        let pad = this.pad(deep++);
        let value = "";
        const objValue = obj[TextObject.VALUE];
        if (objValue) {
            value = ` ${objValue}`;
        }
        res.push(`${pad}${obj[TextObject.NAME]}:${value}`);
        pad = this.pad(deep);
        for (const key in obj) {
            if (typeof key === "symbol") {
                continue;
            }
            const value = obj[key];
            const keyValue = key ? `${key}: ` : "";
            if (typeof value === "string"
                || typeof value === "number"
                || typeof value === "boolean") {
                res.push(`${pad}${keyValue}${value}`);
            }
            else if (value instanceof Date) {
                res.push(`${pad}${keyValue}${value.toUTCString()}`);
            }
            else if (Array.isArray(value)) {
                for (const obj of value) {
                    obj[TextObject.NAME] = key;
                    res.push(...this.serializeObj(obj, deep));
                }
            }
            else if (value instanceof TextObject) {
                value[TextObject.NAME] = key;
                res.push(...this.serializeObj(value, deep));
            }
            else if (BufferSourceConverter.isBufferSource(value)) {
                if (key) {
                    res.push(`${pad}${keyValue}`);
                    res.push(...this.serializeBufferSource(value, deep + 1));
                }
                else {
                    res.push(...this.serializeBufferSource(value, deep));
                }
            }
            else if ("toTextObject" in value) {
                const obj = value.toTextObject();
                obj[TextObject.NAME] = key;
                res.push(...this.serializeObj(obj, deep));
            }
            else {
                throw new TypeError("Cannot serialize data in text format. Unsupported type.");
            }
        }
        return res;
    }
    static serializeBufferSource(buffer, deep = 0) {
        const pad = this.pad(deep);
        const view = BufferSourceConverter.toUint8Array(buffer);
        const res = [];
        for (let i = 0; i < view.length;) {
            const row = [];
            for (let j = 0; j < 16 && i < view.length; j++) {
                if (j === 8) {
                    row.push("");
                }
                const hex = view[i++].toString(16).padStart(2, "0");
                row.push(hex);
            }
            res.push(`${pad}${row.join(" ")}`);
        }
        return res;
    }
    static serializeAlgorithm(alg) {
        return this.algorithmSerializer.toTextObject(alg);
    }
}
TextConverter.oidSerializer = OidSerializer;
TextConverter.algorithmSerializer = DefaultAlgorithmSerializer;

var _AsnData_rawData;
class AsnData {
    get rawData() {
        if (!__classPrivateFieldGet$1(this, _AsnData_rawData, "f")) {
            __classPrivateFieldSet$1(this, _AsnData_rawData, AsnConvert.serialize(this.asn), "f");
        }
        return __classPrivateFieldGet$1(this, _AsnData_rawData, "f");
    }
    constructor(...args) {
        _AsnData_rawData.set(this, void 0);
        if (BufferSourceConverter.isBufferSource(args[0])) {
            this.asn = AsnConvert.parse(args[0], args[1]);
            __classPrivateFieldSet$1(this, _AsnData_rawData, BufferSourceConverter.toArrayBuffer(args[0]), "f");
            this.onInit(this.asn);
        }
        else {
            this.asn = args[0];
            this.onInit(this.asn);
        }
    }
    equal(data) {
        if (data instanceof AsnData) {
            return isEqual(data.rawData, this.rawData);
        }
        return false;
    }
    toString(format = "text") {
        switch (format) {
            case "asn":
                return AsnConvert.toString(this.rawData);
            case "text":
                return TextConverter.serialize(this.toTextObject());
            case "hex":
                return Convert.ToHex(this.rawData);
            case "base64":
                return Convert.ToBase64(this.rawData);
            case "base64url":
                return Convert.ToBase64Url(this.rawData);
            default:
                throw TypeError("Argument 'format' is unsupported value");
        }
    }
    getTextName() {
        const constructor = this.constructor;
        return constructor.NAME;
    }
    toTextObject() {
        const obj = this.toTextObjectEmpty();
        obj[""] = this.rawData;
        return obj;
    }
    toTextObjectEmpty(value) {
        return new TextObject(this.getTextName(), {}, value);
    }
}
_AsnData_rawData = new WeakMap();
AsnData.NAME = "ASN";

class Extension extends AsnData {
    constructor(...args) {
        let raw;
        if (BufferSourceConverter.isBufferSource(args[0])) {
            raw = BufferSourceConverter.toArrayBuffer(args[0]);
        }
        else {
            raw = AsnConvert.serialize(new Extension$1({
                extnID: args[0],
                critical: args[1],
                extnValue: new OctetString(BufferSourceConverter.toArrayBuffer(args[2])),
            }));
        }
        super(raw, Extension$1);
    }
    onInit(asn) {
        this.type = asn.extnID;
        this.critical = asn.critical;
        this.value = asn.extnValue.buffer;
    }
    toTextObject() {
        const obj = this.toTextObjectWithoutValue();
        obj[""] = this.value;
        return obj;
    }
    toTextObjectWithoutValue() {
        const obj = this.toTextObjectEmpty(this.critical ? "critical" : undefined);
        if (obj[TextObject.NAME] === Extension.NAME) {
            obj[TextObject.NAME] = OidSerializer.toString(this.type);
        }
        return obj;
    }
}

var _a;
class CryptoProvider {
    static isCryptoKeyPair(data) {
        return data && data.privateKey && data.publicKey;
    }
    static isCryptoKey(data) {
        return data && data.usages && data.type && data.algorithm && data.extractable !== undefined;
    }
    constructor() {
        this.items = new Map();
        this[_a] = "CryptoProvider";
        if (typeof self !== "undefined" && typeof crypto !== "undefined") {
            this.set(CryptoProvider.DEFAULT, crypto);
        }
        else if (typeof global !== "undefined" && global.crypto && global.crypto.subtle) {
            this.set(CryptoProvider.DEFAULT, global.crypto);
        }
    }
    clear() {
        this.items.clear();
    }
    delete(key) {
        return this.items.delete(key);
    }
    forEach(callbackfn, thisArg) {
        return this.items.forEach(callbackfn, thisArg);
    }
    has(key) {
        return this.items.has(key);
    }
    get size() {
        return this.items.size;
    }
    entries() {
        return this.items.entries();
    }
    keys() {
        return this.items.keys();
    }
    values() {
        return this.items.values();
    }
    [Symbol.iterator]() {
        return this.items[Symbol.iterator]();
    }
    get(key = CryptoProvider.DEFAULT) {
        const crypto = this.items.get(key.toLowerCase());
        if (!crypto) {
            throw new Error(`Cannot get Crypto by name '${key}'`);
        }
        return crypto;
    }
    set(key, value) {
        if (typeof key === "string") {
            if (!value) {
                throw new TypeError("Argument 'value' is required");
            }
            this.items.set(key.toLowerCase(), value);
        }
        else {
            this.items.set(CryptoProvider.DEFAULT, key);
        }
        return this;
    }
}
_a = Symbol.toStringTag;
CryptoProvider.DEFAULT = "default";
const cryptoProvider = new CryptoProvider();

const OID_REGEX = /^[0-2](?:\.[1-9][0-9]*)+$/;
function isOID(id) {
    return new RegExp(OID_REGEX).test(id);
}
class NameIdentifier {
    constructor(names = {}) {
        this.items = {};
        for (const id in names) {
            this.register(id, names[id]);
        }
    }
    get(idOrName) {
        return this.items[idOrName] || null;
    }
    findId(idOrName) {
        if (!isOID(idOrName)) {
            return this.get(idOrName);
        }
        return idOrName;
    }
    register(id, name) {
        this.items[id] = name;
        this.items[name] = id;
    }
}
const names = new NameIdentifier();
names.register("CN", "2.5.4.3");
names.register("L", "2.5.4.7");
names.register("ST", "2.5.4.8");
names.register("O", "2.5.4.10");
names.register("OU", "2.5.4.11");
names.register("C", "2.5.4.6");
names.register("DC", "0.9.2342.19200300.100.1.25");
names.register("E", "1.2.840.113549.1.9.1");
names.register("G", "2.5.4.42");
names.register("I", "2.5.4.43");
names.register("SN", "2.5.4.4");
names.register("T", "2.5.4.12");
function replaceUnknownCharacter(text, char) {
    return `\\${Convert.ToHex(Convert.FromUtf8String(char)).toUpperCase()}`;
}
function escape$1(data) {
    return data
        .replace(/([,+"\\<>;])/g, "\\$1")
        .replace(/^([ #])/, "\\$1")
        .replace(/([ ]$)/, "\\$1")
        .replace(/([\r\n\t])/, replaceUnknownCharacter);
}
class Name {
    static isASCII(text) {
        for (let i = 0; i < text.length; i++) {
            const code = text.charCodeAt(i);
            if (code > 0xFF) {
                return false;
            }
        }
        return true;
    }
    static isPrintableString(text) {
        return /^[A-Za-z0-9 '()+,-./:=?]*$/g.test(text);
    }
    constructor(data, extraNames = {}) {
        this.extraNames = new NameIdentifier();
        this.asn = new Name$1();
        for (const key in extraNames) {
            if (Object.prototype.hasOwnProperty.call(extraNames, key)) {
                const value = extraNames[key];
                this.extraNames.register(key, value);
            }
        }
        if (typeof data === "string") {
            this.asn = this.fromString(data);
        }
        else if (data instanceof Name$1) {
            this.asn = data;
        }
        else if (BufferSourceConverter.isBufferSource(data)) {
            this.asn = AsnConvert.parse(data, Name$1);
        }
        else {
            this.asn = this.fromJSON(data);
        }
    }
    getField(idOrName) {
        const id = this.extraNames.findId(idOrName) || names.findId(idOrName);
        const res = [];
        for (const name of this.asn) {
            for (const rdn of name) {
                if (rdn.type === id) {
                    res.push(rdn.value.toString());
                }
            }
        }
        return res;
    }
    getName(idOrName) {
        return this.extraNames.get(idOrName) || names.get(idOrName);
    }
    toString() {
        return this.asn.map((rdn) => rdn.map((o) => {
            const type = this.getName(o.type) || o.type;
            const value = o.value.anyValue
                ? `#${Convert.ToHex(o.value.anyValue)}`
                : escape$1(o.value.toString());
            return `${type}=${value}`;
        })
            .join("+"))
            .join(", ");
    }
    toJSON() {
        var _a;
        const json = [];
        for (const rdn of this.asn) {
            const jsonItem = {};
            for (const attr of rdn) {
                const type = this.getName(attr.type) || attr.type;
                (_a = jsonItem[type]) !== null && _a !== void 0 ? _a : (jsonItem[type] = []);
                jsonItem[type].push(attr.value.anyValue ? `#${Convert.ToHex(attr.value.anyValue)}` : attr.value.toString());
            }
            json.push(jsonItem);
        }
        return json;
    }
    fromString(data) {
        const asn = new Name$1();
        const regex = /(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;
        let matches = null;
        let level = ",";
        while (matches = regex.exec(`${data},`)) {
            let [, type, value] = matches;
            const lastChar = value[value.length - 1];
            if (lastChar === "," || lastChar === "+") {
                value = value.slice(0, value.length - 1);
                matches[3] = lastChar;
            }
            const next = matches[3];
            type = this.getTypeOid(type);
            const attr = this.createAttribute(type, value);
            if (level === "+") {
                asn[asn.length - 1].push(attr);
            }
            else {
                asn.push(new RelativeDistinguishedName([attr]));
            }
            level = next;
        }
        return asn;
    }
    fromJSON(data) {
        const asn = new Name$1();
        for (const item of data) {
            const asnRdn = new RelativeDistinguishedName();
            for (const type in item) {
                const typeId = this.getTypeOid(type);
                const values = item[type];
                for (const value of values) {
                    const asnAttr = this.createAttribute(typeId, value);
                    asnRdn.push(asnAttr);
                }
            }
            asn.push(asnRdn);
        }
        return asn;
    }
    getTypeOid(type) {
        if (!/[\d.]+/.test(type)) {
            type = this.getName(type) || "";
        }
        if (!type) {
            throw new Error(`Cannot get OID for name type '${type}'`);
        }
        return type;
    }
    createAttribute(type, value) {
        const attr = new AttributeTypeAndValue({ type });
        if (typeof value === "object") {
            for (const key in value) {
                switch (key) {
                    case "ia5String":
                        attr.value.ia5String = value[key];
                        break;
                    case "utf8String":
                        attr.value.utf8String = value[key];
                        break;
                    case "universalString":
                        attr.value.universalString = value[key];
                        break;
                    case "bmpString":
                        attr.value.bmpString = value[key];
                        break;
                    case "printableString":
                        attr.value.printableString = value[key];
                        break;
                }
            }
        }
        else if (value[0] === "#") {
            attr.value.anyValue = Convert.FromHex(value.slice(1));
        }
        else {
            const processedValue = this.processStringValue(value);
            if (type === this.getName("E") || type === this.getName("DC")) {
                attr.value.ia5String = processedValue;
            }
            else {
                if (Name.isPrintableString(processedValue)) {
                    attr.value.printableString = processedValue;
                }
                else {
                    attr.value.utf8String = processedValue;
                }
            }
        }
        return attr;
    }
    processStringValue(value) {
        const quotedMatches = /"(.*?[^\\])?"/.exec(value);
        if (quotedMatches) {
            value = quotedMatches[1];
        }
        return value
            .replace(/\\0a/ig, "\n")
            .replace(/\\0d/ig, "\r")
            .replace(/\\0g/ig, "\t")
            .replace(/\\(.)/g, "$1");
    }
    toArrayBuffer() {
        return AsnConvert.serialize(this.asn);
    }
    async getThumbprint(...args) {
        var _a;
        let crypto;
        let algorithm = "SHA-1";
        if (args.length >= 1 && !((_a = args[0]) === null || _a === void 0 ? void 0 : _a.subtle)) {
            algorithm = args[0] || algorithm;
            crypto = args[1] || cryptoProvider.get();
        }
        else {
            crypto = args[0] || cryptoProvider.get();
        }
        return await crypto.subtle.digest(algorithm, this.toArrayBuffer());
    }
}

const ERR_GN_CONSTRUCTOR = "Cannot initialize GeneralName from ASN.1 data.";
const ERR_GN_STRING_FORMAT = `${ERR_GN_CONSTRUCTOR} Unsupported string format in use.`;
const ERR_GUID = `${ERR_GN_CONSTRUCTOR} Value doesn't match to GUID regular expression.`;
const GUID_REGEX = /^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i;
const id_GUID = "1.3.6.1.4.1.311.25.1";
const id_UPN = "1.3.6.1.4.1.311.20.2.3";
const DNS = "dns";
const DN = "dn";
const EMAIL = "email";
const IP = "ip";
const URL$1 = "url";
const GUID = "guid";
const UPN = "upn";
const REGISTERED_ID = "id";
class GeneralName extends AsnData {
    constructor(...args) {
        let name;
        if (args.length === 2) {
            switch (args[0]) {
                case DN: {
                    const derName = new Name(args[1]).toArrayBuffer();
                    const asnName = AsnConvert.parse(derName, Name$1);
                    name = new GeneralName$1({ directoryName: asnName });
                    break;
                }
                case DNS:
                    name = new GeneralName$1({ dNSName: args[1] });
                    break;
                case EMAIL:
                    name = new GeneralName$1({ rfc822Name: args[1] });
                    break;
                case GUID: {
                    const matches = new RegExp(GUID_REGEX, "i").exec(args[1]);
                    if (!matches) {
                        throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");
                    }
                    const hex = matches
                        .slice(1)
                        .map((o, i) => {
                        if (i < 3) {
                            return Convert.ToHex(new Uint8Array(Convert.FromHex(o)).reverse());
                        }
                        return o;
                    })
                        .join("");
                    name = new GeneralName$1({
                        otherName: new OtherName({
                            typeId: id_GUID,
                            value: AsnConvert.serialize(new OctetString(Convert.FromHex(hex))),
                        }),
                    });
                    break;
                }
                case IP:
                    name = new GeneralName$1({ iPAddress: args[1] });
                    break;
                case REGISTERED_ID:
                    name = new GeneralName$1({ registeredID: args[1] });
                    break;
                case UPN: {
                    name = new GeneralName$1({
                        otherName: new OtherName({
                            typeId: id_UPN,
                            value: AsnConvert.serialize(AsnUtf8StringConverter.toASN(args[1])),
                        }),
                    });
                    break;
                }
                case URL$1:
                    name = new GeneralName$1({ uniformResourceIdentifier: args[1] });
                    break;
                default:
                    throw new Error("Cannot create GeneralName. Unsupported type of the name");
            }
        }
        else if (BufferSourceConverter.isBufferSource(args[0])) {
            name = AsnConvert.parse(args[0], GeneralName$1);
        }
        else {
            name = args[0];
        }
        super(name);
    }
    onInit(asn) {
        if (asn.dNSName != undefined) {
            this.type = DNS;
            this.value = asn.dNSName;
        }
        else if (asn.rfc822Name != undefined) {
            this.type = EMAIL;
            this.value = asn.rfc822Name;
        }
        else if (asn.iPAddress != undefined) {
            this.type = IP;
            this.value = asn.iPAddress;
        }
        else if (asn.uniformResourceIdentifier != undefined) {
            this.type = URL$1;
            this.value = asn.uniformResourceIdentifier;
        }
        else if (asn.registeredID != undefined) {
            this.type = REGISTERED_ID;
            this.value = asn.registeredID;
        }
        else if (asn.directoryName != undefined) {
            this.type = DN;
            this.value = new Name(asn.directoryName).toString();
        }
        else if (asn.otherName != undefined) {
            if (asn.otherName.typeId === id_GUID) {
                this.type = GUID;
                const guid = AsnConvert.parse(asn.otherName.value, OctetString);
                const matches = new RegExp(GUID_REGEX, "i").exec(Convert.ToHex(guid));
                if (!matches) {
                    throw new Error(ERR_GUID);
                }
                this.value = matches
                    .slice(1)
                    .map((o, i) => {
                    if (i < 3) {
                        return Convert.ToHex(new Uint8Array(Convert.FromHex(o)).reverse());
                    }
                    return o;
                })
                    .join("-");
            }
            else if (asn.otherName.typeId === id_UPN) {
                this.type = UPN;
                this.value = AsnConvert.parse(asn.otherName.value, DirectoryString).toString();
            }
            else {
                throw new Error(ERR_GN_STRING_FORMAT);
            }
        }
        else {
            throw new Error(ERR_GN_STRING_FORMAT);
        }
    }
    toJSON() {
        return {
            type: this.type,
            value: this.value,
        };
    }
    toTextObject() {
        let type;
        switch (this.type) {
            case DN:
            case DNS:
            case GUID:
            case IP:
            case REGISTERED_ID:
            case UPN:
            case URL$1:
                type = this.type.toUpperCase();
                break;
            case EMAIL:
                type = "Email";
                break;
            default:
                throw new Error("Unsupported GeneralName type");
        }
        let value = this.value;
        if (this.type === REGISTERED_ID) {
            value = OidSerializer.toString(value);
        }
        return new TextObject(type, undefined, value);
    }
}
class GeneralNames extends AsnData {
    constructor(params) {
        let names;
        if (params instanceof GeneralNames$1) {
            names = params;
        }
        else if (Array.isArray(params)) {
            const items = [];
            for (const name of params) {
                if (name instanceof GeneralName$1) {
                    items.push(name);
                }
                else {
                    const asnName = AsnConvert.parse(new GeneralName(name.type, name.value).rawData, GeneralName$1);
                    items.push(asnName);
                }
            }
            names = new GeneralNames$1(items);
        }
        else if (BufferSourceConverter.isBufferSource(params)) {
            names = AsnConvert.parse(params, GeneralNames$1);
        }
        else {
            throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");
        }
        super(names);
    }
    onInit(asn) {
        const items = [];
        for (const asnName of asn) {
            let name = null;
            try {
                name = new GeneralName(asnName);
            }
            catch {
                continue;
            }
            items.push(name);
        }
        this.items = items;
    }
    toJSON() {
        return this.items.map((o) => o.toJSON());
    }
    toTextObject() {
        const res = super.toTextObjectEmpty();
        for (const name of this.items) {
            const nameObj = name.toTextObject();
            let field = res[nameObj[TextObject.NAME]];
            if (!Array.isArray(field)) {
                field = [];
                res[nameObj[TextObject.NAME]] = field;
            }
            field.push(nameObj);
        }
        return res;
    }
}
GeneralNames.NAME = "GeneralNames";

const rPaddingTag = "-{5}";
const rEolChars = "\\n";
const rNameTag = `[^${rEolChars}]+`;
const rBeginTag = `${rPaddingTag}BEGIN (${rNameTag}(?=${rPaddingTag}))${rPaddingTag}`;
const rEndTag = `${rPaddingTag}END \\1${rPaddingTag}`;
const rEolGroup = "\\n";
const rHeaderKey = `[^:${rEolChars}]+`;
const rHeaderValue = `(?:[^${rEolChars}]+${rEolGroup}(?: +[^${rEolChars}]+${rEolGroup})*)`;
const rBase64Chars = "[a-zA-Z0-9=+/]+";
const rBase64 = `(?:${rBase64Chars}${rEolGroup})+`;
const rPem = `${rBeginTag}${rEolGroup}(?:((?:${rHeaderKey}: ${rHeaderValue})+))?${rEolGroup}?(${rBase64})${rEndTag}`;
class PemConverter {
    static isPem(data) {
        return typeof data === "string"
            && new RegExp(rPem, "g").test(data.replace(/\r/g, ""));
    }
    static decodeWithHeaders(pem) {
        pem = pem.replace(/\r/g, "");
        const pattern = new RegExp(rPem, "g");
        const res = [];
        let matches = null;
        while (matches = pattern.exec(pem)) {
            const base64 = matches[3]
                .replace(new RegExp(`[${rEolChars}]+`, "g"), "");
            const pemStruct = {
                type: matches[1],
                headers: [],
                rawData: Convert.FromBase64(base64),
            };
            const headersString = matches[2];
            if (headersString) {
                const headers = headersString.split(new RegExp(rEolGroup, "g"));
                let lastHeader = null;
                for (const header of headers) {
                    const [key, value] = header.split(/:(.*)/);
                    if (value === undefined) {
                        if (!lastHeader) {
                            throw new Error("Cannot parse PEM string. Incorrect header value");
                        }
                        lastHeader.value += key.trim();
                    }
                    else {
                        if (lastHeader) {
                            pemStruct.headers.push(lastHeader);
                        }
                        lastHeader = {
                            key, value: value.trim(),
                        };
                    }
                }
                if (lastHeader) {
                    pemStruct.headers.push(lastHeader);
                }
            }
            res.push(pemStruct);
        }
        return res;
    }
    static decode(pem) {
        const blocks = this.decodeWithHeaders(pem);
        return blocks.map((o) => o.rawData);
    }
    static decodeFirst(pem) {
        const items = this.decode(pem);
        if (!items.length) {
            throw new RangeError("PEM string doesn't contain any objects");
        }
        return items[0];
    }
    static encode(rawData, tag) {
        if (Array.isArray(rawData)) {
            const raws = new Array();
            if (tag) {
                rawData.forEach((element) => {
                    if (!BufferSourceConverter.isBufferSource(element)) {
                        throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");
                    }
                    raws.push(this.encodeStruct({
                        type: tag,
                        rawData: BufferSourceConverter.toArrayBuffer(element),
                    }));
                });
            }
            else {
                rawData.forEach((element) => {
                    if (!("type" in element)) {
                        throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");
                    }
                    raws.push(this.encodeStruct(element));
                });
            }
            return raws.join("\n");
        }
        else {
            if (!tag) {
                throw new Error("Required argument 'tag' is missed");
            }
            return this.encodeStruct({
                type: tag,
                rawData: BufferSourceConverter.toArrayBuffer(rawData),
            });
        }
    }
    static encodeStruct(pem) {
        var _a;
        const upperCaseType = pem.type.toLocaleUpperCase();
        const res = [];
        res.push(`-----BEGIN ${upperCaseType}-----`);
        if ((_a = pem.headers) === null || _a === void 0 ? void 0 : _a.length) {
            for (const header of pem.headers) {
                res.push(`${header.key}: ${header.value}`);
            }
            res.push("");
        }
        const base64 = Convert.ToBase64(pem.rawData);
        let sliced;
        let offset = 0;
        const rows = Array();
        while (offset < base64.length) {
            if (base64.length - offset < 64) {
                sliced = base64.substring(offset);
            }
            else {
                sliced = base64.substring(offset, offset + 64);
                offset += 64;
            }
            if (sliced.length !== 0) {
                rows.push(sliced);
                if (sliced.length < 64) {
                    break;
                }
            }
            else {
                break;
            }
        }
        res.push(...rows);
        res.push(`-----END ${upperCaseType}-----`);
        return res.join("\n");
    }
}
PemConverter.CertificateTag = "CERTIFICATE";
PemConverter.CrlTag = "CRL";
PemConverter.CertificateRequestTag = "CERTIFICATE REQUEST";
PemConverter.PublicKeyTag = "PUBLIC KEY";
PemConverter.PrivateKeyTag = "PRIVATE KEY";

class PemData extends AsnData {
    static isAsnEncoded(data) {
        return BufferSourceConverter.isBufferSource(data) || typeof data === "string";
    }
    static toArrayBuffer(raw) {
        if (typeof raw === "string") {
            if (PemConverter.isPem(raw)) {
                return PemConverter.decode(raw)[0];
            }
            else if (Convert.isHex(raw)) {
                return Convert.FromHex(raw);
            }
            else if (Convert.isBase64(raw)) {
                return Convert.FromBase64(raw);
            }
            else if (Convert.isBase64Url(raw)) {
                return Convert.FromBase64Url(raw);
            }
            else {
                throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url");
            }
        }
        else {
            const buffer = BufferSourceConverter.toUint8Array(raw);
            if (buffer.length > 0 && buffer[0] === 0x30) {
                return BufferSourceConverter.toArrayBuffer(raw);
            }
            const stringRaw = Convert.ToBinary(raw);
            if (PemConverter.isPem(stringRaw)) {
                return PemConverter.decode(stringRaw)[0];
            }
            else if (Convert.isHex(stringRaw)) {
                return Convert.FromHex(stringRaw);
            }
            else if (Convert.isBase64(stringRaw)) {
                return Convert.FromBase64(stringRaw);
            }
            else if (Convert.isBase64Url(stringRaw)) {
                return Convert.FromBase64Url(stringRaw);
            }
            throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url");
        }
    }
    constructor(...args) {
        if (PemData.isAsnEncoded(args[0])) {
            super(PemData.toArrayBuffer(args[0]), args[1]);
        }
        else {
            super(args[0]);
        }
    }
    toString(format = "pem") {
        switch (format) {
            case "pem":
                return PemConverter.encode(this.rawData, this.tag);
            default:
                return super.toString(format);
        }
    }
}

class PublicKey extends PemData {
    static async create(data, crypto = cryptoProvider.get()) {
        if (data instanceof PublicKey) {
            return data;
        }
        else if (CryptoProvider.isCryptoKey(data)) {
            if (data.type !== "public") {
                throw new TypeError("Public key is required");
            }
            const spki = await crypto.subtle.exportKey("spki", data);
            return new PublicKey(spki);
        }
        else if (data.publicKey) {
            return data.publicKey;
        }
        else if (BufferSourceConverter.isBufferSource(data)) {
            return new PublicKey(data);
        }
        else {
            throw new TypeError("Unsupported PublicKeyType");
        }
    }
    constructor(param) {
        if (PemData.isAsnEncoded(param)) {
            super(param, SubjectPublicKeyInfo);
        }
        else {
            super(param);
        }
        this.tag = PemConverter.PublicKeyTag;
    }
    async export(...args) {
        let crypto;
        let keyUsages = ["verify"];
        let algorithm = {
            hash: "SHA-256", ...this.algorithm,
        };
        if (args.length > 1) {
            algorithm = args[0] || algorithm;
            keyUsages = args[1] || keyUsages;
            crypto = args[2] || cryptoProvider.get();
        }
        else {
            crypto = args[0] || cryptoProvider.get();
        }
        let raw = this.rawData;
        const asnSpki = AsnConvert.parse(this.rawData, SubjectPublicKeyInfo);
        if (asnSpki.algorithm.algorithm === id_RSASSA_PSS) {
            raw = convertSpkiToRsaPkcs1(asnSpki, raw);
        }
        return crypto.subtle.importKey("spki", raw, algorithm, true, keyUsages);
    }
    onInit(asn) {
        const algProv = instance.resolve(diAlgorithmProvider);
        const algorithm = this.algorithm = algProv.toWebAlgorithm(asn.algorithm);
        switch (asn.algorithm.algorithm) {
            case id_rsaEncryption:
                {
                    const rsaPublicKey = AsnConvert.parse(asn.subjectPublicKey, RSAPublicKey);
                    const modulus = BufferSourceConverter.toUint8Array(rsaPublicKey.modulus);
                    algorithm.publicExponent = BufferSourceConverter.toUint8Array(rsaPublicKey.publicExponent);
                    algorithm.modulusLength = (!modulus[0] ? modulus.slice(1) : modulus).byteLength << 3;
                    break;
                }
        }
    }
    async getThumbprint(...args) {
        var _a;
        let crypto;
        let algorithm = "SHA-1";
        if (args.length >= 1 && !((_a = args[0]) === null || _a === void 0 ? void 0 : _a.subtle)) {
            algorithm = args[0] || algorithm;
            crypto = args[1] || cryptoProvider.get();
        }
        else {
            crypto = args[0] || cryptoProvider.get();
        }
        return await crypto.subtle.digest(algorithm, this.rawData);
    }
    async getKeyIdentifier(...args) {
        let crypto;
        let algorithm = "SHA-1";
        if (args.length === 1) {
            if (typeof args[0] === "string") {
                algorithm = args[0];
                crypto = cryptoProvider.get();
            }
            else {
                crypto = args[0];
            }
        }
        else if (args.length === 2) {
            algorithm = args[0];
            crypto = args[1];
        }
        else {
            crypto = cryptoProvider.get();
        }
        const asn = AsnConvert.parse(this.rawData, SubjectPublicKeyInfo);
        return await crypto.subtle.digest(algorithm, asn.subjectPublicKey);
    }
    toTextObject() {
        const obj = this.toTextObjectEmpty();
        const asn = AsnConvert.parse(this.rawData, SubjectPublicKeyInfo);
        obj["Algorithm"] = TextConverter.serializeAlgorithm(asn.algorithm);
        switch (asn.algorithm.algorithm) {
            case id_ecPublicKey:
                obj["EC Point"] = asn.subjectPublicKey;
                break;
            case id_rsaEncryption:
            default:
                obj["Raw Data"] = asn.subjectPublicKey;
        }
        return obj;
    }
}
function convertSpkiToRsaPkcs1(asnSpki, raw) {
    asnSpki.algorithm = new AlgorithmIdentifier({
        algorithm: id_rsaEncryption,
        parameters: null,
    });
    raw = AsnConvert.serialize(asnSpki);
    return raw;
}

class AuthorityKeyIdentifierExtension extends Extension {
    static async create(param, critical = false, crypto = cryptoProvider.get()) {
        if ("name" in param && "serialNumber" in param) {
            return new AuthorityKeyIdentifierExtension(param, critical);
        }
        const key = await PublicKey.create(param, crypto);
        const id = await key.getKeyIdentifier(crypto);
        return new AuthorityKeyIdentifierExtension(Convert.ToHex(id), critical);
    }
    constructor(...args) {
        if (BufferSourceConverter.isBufferSource(args[0])) {
            super(args[0]);
        }
        else if (typeof args[0] === "string") {
            const value = new AuthorityKeyIdentifier({ keyIdentifier: new KeyIdentifier(Convert.FromHex(args[0])) });
            super(id_ce_authorityKeyIdentifier, args[1], AsnConvert.serialize(value));
        }
        else {
            const certId = args[0];
            const certIdName = certId.name instanceof GeneralNames
                ? AsnConvert.parse(certId.name.rawData, GeneralNames$1)
                : certId.name;
            const value = new AuthorityKeyIdentifier({
                authorityCertIssuer: certIdName,
                authorityCertSerialNumber: Convert.FromHex(certId.serialNumber),
            });
            super(id_ce_authorityKeyIdentifier, args[1], AsnConvert.serialize(value));
        }
    }
    onInit(asn) {
        super.onInit(asn);
        const aki = AsnConvert.parse(asn.extnValue, AuthorityKeyIdentifier);
        if (aki.keyIdentifier) {
            this.keyId = Convert.ToHex(aki.keyIdentifier);
        }
        if (aki.authorityCertIssuer || aki.authorityCertSerialNumber) {
            this.certId = {
                name: aki.authorityCertIssuer || [],
                serialNumber: aki.authorityCertSerialNumber ? Convert.ToHex(aki.authorityCertSerialNumber) : "",
            };
        }
    }
    toTextObject() {
        const obj = this.toTextObjectWithoutValue();
        const asn = AsnConvert.parse(this.value, AuthorityKeyIdentifier);
        if (asn.authorityCertIssuer) {
            obj["Authority Issuer"] = new GeneralNames(asn.authorityCertIssuer).toTextObject();
        }
        if (asn.authorityCertSerialNumber) {
            obj["Authority Serial Number"] = asn.authorityCertSerialNumber;
        }
        if (asn.keyIdentifier) {
            obj[""] = asn.keyIdentifier;
        }
        return obj;
    }
}
AuthorityKeyIdentifierExtension.NAME = "Authority Key Identifier";

class BasicConstraintsExtension extends Extension {
    constructor(...args) {
        if (BufferSourceConverter.isBufferSource(args[0])) {
            super(args[0]);
            const value = AsnConvert.parse(this.value, BasicConstraints);
            this.ca = value.cA;
            this.pathLength = value.pathLenConstraint;
        }
        else {
            const value = new BasicConstraints({
                cA: args[0],
                pathLenConstraint: args[1],
            });
            super(id_ce_basicConstraints, args[2], AsnConvert.serialize(value));
            this.ca = args[0];
            this.pathLength = args[1];
        }
    }
    toTextObject() {
        const obj = this.toTextObjectWithoutValue();
        if (this.ca) {
            obj["CA"] = this.ca;
        }
        if (this.pathLength !== undefined) {
            obj["Path Length"] = this.pathLength;
        }
        return obj;
    }
}
BasicConstraintsExtension.NAME = "Basic Constraints";

var ExtendedKeyUsage;
(function (ExtendedKeyUsage) {
    ExtendedKeyUsage["serverAuth"] = "1.3.6.1.5.5.7.3.1";
    ExtendedKeyUsage["clientAuth"] = "1.3.6.1.5.5.7.3.2";
    ExtendedKeyUsage["codeSigning"] = "1.3.6.1.5.5.7.3.3";
    ExtendedKeyUsage["emailProtection"] = "1.3.6.1.5.5.7.3.4";
    ExtendedKeyUsage["timeStamping"] = "1.3.6.1.5.5.7.3.8";
    ExtendedKeyUsage["ocspSigning"] = "1.3.6.1.5.5.7.3.9";
})(ExtendedKeyUsage || (ExtendedKeyUsage = {}));
class ExtendedKeyUsageExtension extends Extension {
    constructor(...args) {
        if (BufferSourceConverter.isBufferSource(args[0])) {
            super(args[0]);
            const value = AsnConvert.parse(this.value, ExtendedKeyUsage$1);
            this.usages = value.map((o) => o);
        }
        else {
            const value = new ExtendedKeyUsage$1(args[0]);
            super(id_ce_extKeyUsage, args[1], AsnConvert.serialize(value));
            this.usages = args[0];
        }
    }
    toTextObject() {
        const obj = this.toTextObjectWithoutValue();
        obj[""] = this.usages.map((o) => OidSerializer.toString(o)).join(", ");
        return obj;
    }
}
ExtendedKeyUsageExtension.NAME = "Extended Key Usages";

var KeyUsageFlags;
(function (KeyUsageFlags) {
    KeyUsageFlags[KeyUsageFlags["digitalSignature"] = 1] = "digitalSignature";
    KeyUsageFlags[KeyUsageFlags["nonRepudiation"] = 2] = "nonRepudiation";
    KeyUsageFlags[KeyUsageFlags["keyEncipherment"] = 4] = "keyEncipherment";
    KeyUsageFlags[KeyUsageFlags["dataEncipherment"] = 8] = "dataEncipherment";
    KeyUsageFlags[KeyUsageFlags["keyAgreement"] = 16] = "keyAgreement";
    KeyUsageFlags[KeyUsageFlags["keyCertSign"] = 32] = "keyCertSign";
    KeyUsageFlags[KeyUsageFlags["cRLSign"] = 64] = "cRLSign";
    KeyUsageFlags[KeyUsageFlags["encipherOnly"] = 128] = "encipherOnly";
    KeyUsageFlags[KeyUsageFlags["decipherOnly"] = 256] = "decipherOnly";
})(KeyUsageFlags || (KeyUsageFlags = {}));
class KeyUsagesExtension extends Extension {
    constructor(...args) {
        if (BufferSourceConverter.isBufferSource(args[0])) {
            super(args[0]);
            const value = AsnConvert.parse(this.value, KeyUsage);
            this.usages = value.toNumber();
        }
        else {
            const value = new KeyUsage(args[0]);
            super(id_ce_keyUsage, args[1], AsnConvert.serialize(value));
            this.usages = args[0];
        }
    }
    toTextObject() {
        const obj = this.toTextObjectWithoutValue();
        const asn = AsnConvert.parse(this.value, KeyUsage);
        obj[""] = asn.toJSON().join(", ");
        return obj;
    }
}
KeyUsagesExtension.NAME = "Key Usages";

class SubjectKeyIdentifierExtension extends Extension {
    static async create(publicKey, critical = false, crypto = cryptoProvider.get()) {
        const key = await PublicKey.create(publicKey, crypto);
        const id = await key.getKeyIdentifier(crypto);
        return new SubjectKeyIdentifierExtension(Convert.ToHex(id), critical);
    }
    constructor(...args) {
        if (BufferSourceConverter.isBufferSource(args[0])) {
            super(args[0]);
            const value = AsnConvert.parse(this.value, SubjectKeyIdentifier);
            this.keyId = Convert.ToHex(value);
        }
        else {
            const identifier = typeof args[0] === "string"
                ? Convert.FromHex(args[0])
                : args[0];
            const value = new SubjectKeyIdentifier(identifier);
            super(id_ce_subjectKeyIdentifier, args[1], AsnConvert.serialize(value));
            this.keyId = Convert.ToHex(identifier);
        }
    }
    toTextObject() {
        const obj = this.toTextObjectWithoutValue();
        const asn = AsnConvert.parse(this.value, SubjectKeyIdentifier);
        obj[""] = asn;
        return obj;
    }
}
SubjectKeyIdentifierExtension.NAME = "Subject Key Identifier";

class SubjectAlternativeNameExtension extends Extension {
    constructor(...args) {
        if (BufferSourceConverter.isBufferSource(args[0])) {
            super(args[0]);
        }
        else {
            super(id_ce_subjectAltName, args[1], new GeneralNames(args[0] || []).rawData);
        }
    }
    onInit(asn) {
        super.onInit(asn);
        const value = AsnConvert.parse(asn.extnValue, SubjectAlternativeName);
        this.names = new GeneralNames(value);
    }
    toTextObject() {
        const obj = this.toTextObjectWithoutValue();
        const namesObj = this.names.toTextObject();
        for (const key in namesObj) {
            obj[key] = namesObj[key];
        }
        return obj;
    }
}
SubjectAlternativeNameExtension.NAME = "Subject Alternative Name";

class ExtensionFactory {
    static register(id, type) {
        this.items.set(id, type);
    }
    static create(data) {
        const extension = new Extension(data);
        const Type = this.items.get(extension.type);
        if (Type) {
            return new Type(data);
        }
        return extension;
    }
}
ExtensionFactory.items = new Map();

class CertificatePolicyExtension extends Extension {
    constructor(...args) {
        var _a;
        if (BufferSourceConverter.isBufferSource(args[0])) {
            super(args[0]);
            const asnPolicies = AsnConvert.parse(this.value, CertificatePolicies);
            this.policies = asnPolicies.map((o) => o.policyIdentifier);
        }
        else {
            const policies = args[0];
            const critical = (_a = args[1]) !== null && _a !== void 0 ? _a : false;
            const value = new CertificatePolicies(policies.map((o) => (new PolicyInformation({ policyIdentifier: o }))));
            super(id_ce_certificatePolicies, critical, AsnConvert.serialize(value));
            this.policies = policies;
        }
    }
    toTextObject() {
        const obj = this.toTextObjectWithoutValue();
        obj["Policy"] = this.policies.map((o) => new TextObject("", {}, OidSerializer.toString(o)));
        return obj;
    }
}
CertificatePolicyExtension.NAME = "Certificate Policies";
ExtensionFactory.register(id_ce_certificatePolicies, CertificatePolicyExtension);

class CRLDistributionPointsExtension extends Extension {
    constructor(...args) {
        var _a;
        if (BufferSourceConverter.isBufferSource(args[0])) {
            super(args[0]);
        }
        else if (Array.isArray(args[0]) && typeof args[0][0] === "string") {
            const urls = args[0];
            const dps = urls.map((url) => {
                return new DistributionPoint({
                    distributionPoint: new DistributionPointName({ fullName: [new GeneralName$1({ uniformResourceIdentifier: url })] }),
                });
            });
            const value = new CRLDistributionPoints(dps);
            super(id_ce_cRLDistributionPoints, args[1], AsnConvert.serialize(value));
        }
        else {
            const value = new CRLDistributionPoints(args[0]);
            super(id_ce_cRLDistributionPoints, args[1], AsnConvert.serialize(value));
        }
        (_a = this.distributionPoints) !== null && _a !== void 0 ? _a : (this.distributionPoints = []);
    }
    onInit(asn) {
        super.onInit(asn);
        const crlExt = AsnConvert.parse(asn.extnValue, CRLDistributionPoints);
        this.distributionPoints = crlExt;
    }
    toTextObject() {
        const obj = this.toTextObjectWithoutValue();
        obj["Distribution Point"] = this.distributionPoints.map((dp) => {
            var _a;
            const dpObj = {};
            if (dp.distributionPoint) {
                dpObj[""] = (_a = dp.distributionPoint.fullName) === null || _a === void 0 ? void 0 : _a.map((name) => new GeneralName(name).toString()).join(", ");
            }
            if (dp.reasons) {
                dpObj["Reasons"] = dp.reasons.toString();
            }
            if (dp.cRLIssuer) {
                dpObj["CRL Issuer"] = dp.cRLIssuer.map((issuer) => issuer.toString()).join(", ");
            }
            return dpObj;
        });
        return obj;
    }
}
CRLDistributionPointsExtension.NAME = "CRL Distribution Points";

class AuthorityInfoAccessExtension extends Extension {
    constructor(...args) {
        var _a, _b, _c, _d;
        if (BufferSourceConverter.isBufferSource(args[0])) {
            super(args[0]);
        }
        else if (args[0] instanceof AuthorityInfoAccessSyntax) {
            const value = new AuthorityInfoAccessSyntax(args[0]);
            super(id_pe_authorityInfoAccess, args[1], AsnConvert.serialize(value));
        }
        else {
            const params = args[0];
            const value = new AuthorityInfoAccessSyntax();
            addAccessDescriptions(value, params, id_ad_ocsp, "ocsp");
            addAccessDescriptions(value, params, id_ad_caIssuers, "caIssuers");
            addAccessDescriptions(value, params, id_ad_timeStamping, "timeStamping");
            addAccessDescriptions(value, params, id_ad_caRepository, "caRepository");
            super(id_pe_authorityInfoAccess, args[1], AsnConvert.serialize(value));
        }
        (_a = this.ocsp) !== null && _a !== void 0 ? _a : (this.ocsp = []);
        (_b = this.caIssuers) !== null && _b !== void 0 ? _b : (this.caIssuers = []);
        (_c = this.timeStamping) !== null && _c !== void 0 ? _c : (this.timeStamping = []);
        (_d = this.caRepository) !== null && _d !== void 0 ? _d : (this.caRepository = []);
    }
    onInit(asn) {
        super.onInit(asn);
        this.ocsp = [];
        this.caIssuers = [];
        this.timeStamping = [];
        this.caRepository = [];
        const aia = AsnConvert.parse(asn.extnValue, AuthorityInfoAccessSyntax);
        aia.forEach((accessDescription) => {
            switch (accessDescription.accessMethod) {
                case id_ad_ocsp:
                    this.ocsp.push(new GeneralName(accessDescription.accessLocation));
                    break;
                case id_ad_caIssuers:
                    this.caIssuers.push(new GeneralName(accessDescription.accessLocation));
                    break;
                case id_ad_timeStamping:
                    this.timeStamping.push(new GeneralName(accessDescription.accessLocation));
                    break;
                case id_ad_caRepository:
                    this.caRepository.push(new GeneralName(accessDescription.accessLocation));
                    break;
            }
        });
    }
    toTextObject() {
        const obj = this.toTextObjectWithoutValue();
        if (this.ocsp.length) {
            addUrlsToObject(obj, "OCSP", this.ocsp);
        }
        if (this.caIssuers.length) {
            addUrlsToObject(obj, "CA Issuers", this.caIssuers);
        }
        if (this.timeStamping.length) {
            addUrlsToObject(obj, "Time Stamping", this.timeStamping);
        }
        if (this.caRepository.length) {
            addUrlsToObject(obj, "CA Repository", this.caRepository);
        }
        return obj;
    }
}
AuthorityInfoAccessExtension.NAME = "Authority Info Access";
function addUrlsToObject(obj, key, urls) {
    if (urls.length === 1) {
        obj[key] = urls[0].toTextObject();
    }
    else {
        const names = new TextObject("");
        urls.forEach((name, index) => {
            const nameObj = name.toTextObject();
            const indexedKey = `${nameObj[TextObject.NAME]} ${index + 1}`;
            let field = names[indexedKey];
            if (!Array.isArray(field)) {
                field = [];
                names[indexedKey] = field;
            }
            field.push(nameObj);
        });
        obj[key] = names;
    }
}
function addAccessDescriptions(value, params, method, key) {
    const items = params[key];
    if (items) {
        const array = Array.isArray(items) ? items : [items];
        array.forEach((url) => {
            if (typeof url === "string") {
                url = new GeneralName("url", url);
            }
            value.push(new AccessDescription({
                accessMethod: method,
                accessLocation: AsnConvert.parse(url.rawData, GeneralName$1),
            }));
        });
    }
}

class IssuerAlternativeNameExtension extends Extension {
    constructor(...args) {
        if (BufferSourceConverter.isBufferSource(args[0])) {
            super(args[0]);
        }
        else {
            super(id_ce_issuerAltName, args[1], new GeneralNames(args[0] || []).rawData);
        }
    }
    onInit(asn) {
        super.onInit(asn);
        const value = AsnConvert.parse(asn.extnValue, GeneralNames$1);
        this.names = new GeneralNames(value);
    }
    toTextObject() {
        const obj = this.toTextObjectWithoutValue();
        const namesObj = this.names.toTextObject();
        for (const key in namesObj) {
            obj[key] = namesObj[key];
        }
        return obj;
    }
}
IssuerAlternativeNameExtension.NAME = "Issuer Alternative Name";

class Attribute extends AsnData {
    constructor(...args) {
        let raw;
        if (BufferSourceConverter.isBufferSource(args[0])) {
            raw = BufferSourceConverter.toArrayBuffer(args[0]);
        }
        else {
            const type = args[0];
            const values = Array.isArray(args[1])
                ? args[1].map((o) => BufferSourceConverter.toArrayBuffer(o))
                : [];
            raw = AsnConvert.serialize(new Attribute$2({
                type, values,
            }));
        }
        super(raw, Attribute$2);
    }
    onInit(asn) {
        this.type = asn.type;
        this.values = asn.values;
    }
    toTextObject() {
        const obj = this.toTextObjectWithoutValue();
        obj["Value"] = this.values.map((o) => new TextObject("", { "": o }));
        return obj;
    }
    toTextObjectWithoutValue() {
        const obj = this.toTextObjectEmpty();
        if (obj[TextObject.NAME] === Attribute.NAME) {
            obj[TextObject.NAME] = OidSerializer.toString(this.type);
        }
        return obj;
    }
}
Attribute.NAME = "Attribute";

class ChallengePasswordAttribute extends Attribute {
    constructor(...args) {
        var _a;
        if (BufferSourceConverter.isBufferSource(args[0])) {
            super(args[0]);
        }
        else {
            const value = new ChallengePassword({ printableString: args[0] });
            super(id_pkcs9_at_challengePassword, [AsnConvert.serialize(value)]);
        }
        (_a = this.password) !== null && _a !== void 0 ? _a : (this.password = "");
    }
    onInit(asn) {
        super.onInit(asn);
        if (this.values[0]) {
            const value = AsnConvert.parse(this.values[0], ChallengePassword);
            this.password = value.toString();
        }
    }
    toTextObject() {
        const obj = this.toTextObjectWithoutValue();
        obj[TextObject.VALUE] = this.password;
        return obj;
    }
}
ChallengePasswordAttribute.NAME = "Challenge Password";

class ExtensionsAttribute extends Attribute {
    constructor(...args) {
        var _a;
        if (BufferSourceConverter.isBufferSource(args[0])) {
            super(args[0]);
        }
        else {
            const extensions = args[0];
            const value = new Extensions();
            for (const extension of extensions) {
                value.push(AsnConvert.parse(extension.rawData, Extension$1));
            }
            super(id_pkcs9_at_extensionRequest, [AsnConvert.serialize(value)]);
        }
        (_a = this.items) !== null && _a !== void 0 ? _a : (this.items = []);
    }
    onInit(asn) {
        super.onInit(asn);
        if (this.values[0]) {
            const value = AsnConvert.parse(this.values[0], Extensions);
            this.items = value.map((o) => ExtensionFactory.create(AsnConvert.serialize(o)));
        }
    }
    toTextObject() {
        const obj = this.toTextObjectWithoutValue();
        const extensions = this.items.map((o) => o.toTextObject());
        for (const extension of extensions) {
            obj[extension[TextObject.NAME]] = extension;
        }
        return obj;
    }
}
ExtensionsAttribute.NAME = "Extensions";

class AttributeFactory {
    static register(id, type) {
        this.items.set(id, type);
    }
    static create(data) {
        const attribute = new Attribute(data);
        const Type = this.items.get(attribute.type);
        if (Type) {
            return new Type(data);
        }
        return attribute;
    }
}
AttributeFactory.items = new Map();

const diAsnSignatureFormatter = "crypto.signatureFormatter";
class AsnDefaultSignatureFormatter {
    toAsnSignature(algorithm, signature) {
        return BufferSourceConverter.toArrayBuffer(signature);
    }
    toWebSignature(algorithm, signature) {
        return BufferSourceConverter.toArrayBuffer(signature);
    }
}

var RsaAlgorithm_1;
let RsaAlgorithm = RsaAlgorithm_1 = class RsaAlgorithm {
    static createPssParams(hash, saltLength) {
        const hashAlgorithm = RsaAlgorithm_1.getHashAlgorithm(hash);
        if (!hashAlgorithm) {
            return null;
        }
        return new RsaSaPssParams({
            hashAlgorithm,
            maskGenAlgorithm: new AlgorithmIdentifier({
                algorithm: id_mgf1,
                parameters: AsnConvert.serialize(hashAlgorithm),
            }),
            saltLength,
        });
    }
    static getHashAlgorithm(alg) {
        const algProv = instance.resolve(diAlgorithmProvider);
        if (typeof alg === "string") {
            return algProv.toAsnAlgorithm({ name: alg });
        }
        if (typeof alg === "object" && alg && "name" in alg) {
            return algProv.toAsnAlgorithm(alg);
        }
        return null;
    }
    toAsnAlgorithm(alg) {
        switch (alg.name.toLowerCase()) {
            case "rsassa-pkcs1-v1_5":
                if ("hash" in alg) {
                    let hash;
                    if (typeof alg.hash === "string") {
                        hash = alg.hash;
                    }
                    else if (alg.hash && typeof alg.hash === "object"
                        && "name" in alg.hash && typeof alg.hash.name === "string") {
                        hash = alg.hash.name.toUpperCase();
                    }
                    else {
                        throw new Error("Cannot get hash algorithm name");
                    }
                    switch (hash.toLowerCase()) {
                        case "sha-1":
                            return new AlgorithmIdentifier({
                                algorithm: id_sha1WithRSAEncryption, parameters: null,
                            });
                        case "sha-256":
                            return new AlgorithmIdentifier({
                                algorithm: id_sha256WithRSAEncryption, parameters: null,
                            });
                        case "sha-384":
                            return new AlgorithmIdentifier({
                                algorithm: id_sha384WithRSAEncryption, parameters: null,
                            });
                        case "sha-512":
                            return new AlgorithmIdentifier({
                                algorithm: id_sha512WithRSAEncryption, parameters: null,
                            });
                    }
                }
                else {
                    return new AlgorithmIdentifier({
                        algorithm: id_rsaEncryption, parameters: null,
                    });
                }
                break;
            case "rsa-pss":
                if ("hash" in alg) {
                    if (!("saltLength" in alg && typeof alg.saltLength === "number")) {
                        throw new Error("Cannot get 'saltLength' from 'alg' argument");
                    }
                    const pssParams = RsaAlgorithm_1.createPssParams(alg.hash, alg.saltLength);
                    if (!pssParams) {
                        throw new Error("Cannot create PSS parameters");
                    }
                    return new AlgorithmIdentifier({
                        algorithm: id_RSASSA_PSS, parameters: AsnConvert.serialize(pssParams),
                    });
                }
                else {
                    return new AlgorithmIdentifier({
                        algorithm: id_RSASSA_PSS, parameters: null,
                    });
                }
        }
        return null;
    }
    toWebAlgorithm(alg) {
        switch (alg.algorithm) {
            case id_rsaEncryption:
                return { name: "RSASSA-PKCS1-v1_5" };
            case id_sha1WithRSAEncryption:
                return {
                    name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-1" },
                };
            case id_sha256WithRSAEncryption:
                return {
                    name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" },
                };
            case id_sha384WithRSAEncryption:
                return {
                    name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-384" },
                };
            case id_sha512WithRSAEncryption:
                return {
                    name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-512" },
                };
            case id_RSASSA_PSS:
                if (alg.parameters) {
                    const pssParams = AsnConvert.parse(alg.parameters, RsaSaPssParams);
                    const algProv = instance.resolve(diAlgorithmProvider);
                    const hashAlg = algProv.toWebAlgorithm(pssParams.hashAlgorithm);
                    return {
                        name: "RSA-PSS",
                        hash: hashAlg,
                        saltLength: pssParams.saltLength,
                    };
                }
                else {
                    return { name: "RSA-PSS" };
                }
        }
        return null;
    }
};
RsaAlgorithm = RsaAlgorithm_1 = __decorate$1([
    injectable()
], RsaAlgorithm);
instance.registerSingleton(diAlgorithm, RsaAlgorithm);

let ShaAlgorithm = class ShaAlgorithm {
    toAsnAlgorithm(alg) {
        switch (alg.name.toLowerCase()) {
            case "sha-1":
                return new AlgorithmIdentifier({ algorithm: id_sha1 });
            case "sha-256":
                return new AlgorithmIdentifier({ algorithm: id_sha256 });
            case "sha-384":
                return new AlgorithmIdentifier({ algorithm: id_sha384 });
            case "sha-512":
                return new AlgorithmIdentifier({ algorithm: id_sha512 });
        }
        return null;
    }
    toWebAlgorithm(alg) {
        switch (alg.algorithm) {
            case id_sha1:
                return { name: "SHA-1" };
            case id_sha256:
                return { name: "SHA-256" };
            case id_sha384:
                return { name: "SHA-384" };
            case id_sha512:
                return { name: "SHA-512" };
        }
        return null;
    }
};
ShaAlgorithm = __decorate$1([
    injectable()
], ShaAlgorithm);
instance.registerSingleton(diAlgorithm, ShaAlgorithm);

class AsnEcSignatureFormatter {
    addPadding(pointSize, data) {
        const bytes = BufferSourceConverter.toUint8Array(data);
        const res = new Uint8Array(pointSize);
        res.set(bytes, pointSize - bytes.length);
        return res.buffer;
    }
    removePadding(data, positive = false) {
        let bytes = BufferSourceConverter.toUint8Array(data);
        for (let i = 0; i < bytes.length; i++) {
            if (!bytes[i]) {
                continue;
            }
            bytes = bytes.slice(i);
            break;
        }
        if (positive && bytes[0] > 127) {
            const result = new Uint8Array(bytes.length + 1);
            result.set(bytes, 1);
            return result.buffer;
        }
        return bytes.buffer;
    }
    toAsnSignature(algorithm, signature) {
        if (algorithm.name === "ECDSA") {
            const namedCurve = algorithm.namedCurve;
            const pointSize = AsnEcSignatureFormatter.namedCurveSize.get(namedCurve)
                || AsnEcSignatureFormatter.defaultNamedCurveSize;
            const ecSignature = new ECDSASigValue();
            const uint8Signature = BufferSourceConverter.toUint8Array(signature);
            ecSignature.r = this.removePadding(uint8Signature.slice(0, pointSize), true);
            ecSignature.s = this.removePadding(uint8Signature.slice(pointSize, pointSize + pointSize), true);
            return AsnConvert.serialize(ecSignature);
        }
        return null;
    }
    toWebSignature(algorithm, signature) {
        if (algorithm.name === "ECDSA") {
            const ecSigValue = AsnConvert.parse(signature, ECDSASigValue);
            const namedCurve = algorithm.namedCurve;
            const pointSize = AsnEcSignatureFormatter.namedCurveSize.get(namedCurve)
                || AsnEcSignatureFormatter.defaultNamedCurveSize;
            const r = this.addPadding(pointSize, this.removePadding(ecSigValue.r));
            const s = this.addPadding(pointSize, this.removePadding(ecSigValue.s));
            return combine(r, s);
        }
        return null;
    }
}
AsnEcSignatureFormatter.namedCurveSize = new Map();
AsnEcSignatureFormatter.defaultNamedCurveSize = 32;

const idX25519 = "1.3.101.110";
const idX448 = "1.3.101.111";
const idEd25519 = "1.3.101.112";
const idEd448 = "1.3.101.113";
let EdAlgorithm = class EdAlgorithm {
    toAsnAlgorithm(alg) {
        let algorithm = null;
        switch (alg.name.toLowerCase()) {
            case "ed25519":
                algorithm = idEd25519;
                break;
            case "x25519":
                algorithm = idX25519;
                break;
            case "eddsa":
                switch (alg.namedCurve.toLowerCase()) {
                    case "ed25519":
                        algorithm = idEd25519;
                        break;
                    case "ed448":
                        algorithm = idEd448;
                        break;
                }
                break;
            case "ecdh-es":
                switch (alg.namedCurve.toLowerCase()) {
                    case "x25519":
                        algorithm = idX25519;
                        break;
                    case "x448":
                        algorithm = idX448;
                        break;
                }
        }
        if (algorithm) {
            return new AlgorithmIdentifier({ algorithm });
        }
        return null;
    }
    toWebAlgorithm(alg) {
        switch (alg.algorithm) {
            case idEd25519:
                return { name: "Ed25519" };
            case idEd448:
                return {
                    name: "EdDSA", namedCurve: "Ed448",
                };
            case idX25519:
                return { name: "X25519" };
            case idX448:
                return {
                    name: "ECDH-ES", namedCurve: "X448",
                };
        }
        return null;
    }
};
EdAlgorithm = __decorate$1([
    injectable()
], EdAlgorithm);
instance.registerSingleton(diAlgorithm, EdAlgorithm);

var _Pkcs10CertificateRequest_tbs, _Pkcs10CertificateRequest_subjectName, _Pkcs10CertificateRequest_subject, _Pkcs10CertificateRequest_signatureAlgorithm, _Pkcs10CertificateRequest_signature, _Pkcs10CertificateRequest_publicKey, _Pkcs10CertificateRequest_attributes, _Pkcs10CertificateRequest_extensions;
class Pkcs10CertificateRequest extends PemData {
    get subjectName() {
        if (!__classPrivateFieldGet$1(this, _Pkcs10CertificateRequest_subjectName, "f")) {
            __classPrivateFieldSet$1(this, _Pkcs10CertificateRequest_subjectName, new Name(this.asn.certificationRequestInfo.subject), "f");
        }
        return __classPrivateFieldGet$1(this, _Pkcs10CertificateRequest_subjectName, "f");
    }
    get subject() {
        if (!__classPrivateFieldGet$1(this, _Pkcs10CertificateRequest_subject, "f")) {
            __classPrivateFieldSet$1(this, _Pkcs10CertificateRequest_subject, this.subjectName.toString(), "f");
        }
        return __classPrivateFieldGet$1(this, _Pkcs10CertificateRequest_subject, "f");
    }
    get signatureAlgorithm() {
        if (!__classPrivateFieldGet$1(this, _Pkcs10CertificateRequest_signatureAlgorithm, "f")) {
            const algProv = instance.resolve(diAlgorithmProvider);
            __classPrivateFieldSet$1(this, _Pkcs10CertificateRequest_signatureAlgorithm, algProv.toWebAlgorithm(this.asn.signatureAlgorithm), "f");
        }
        return __classPrivateFieldGet$1(this, _Pkcs10CertificateRequest_signatureAlgorithm, "f");
    }
    get signature() {
        if (!__classPrivateFieldGet$1(this, _Pkcs10CertificateRequest_signature, "f")) {
            __classPrivateFieldSet$1(this, _Pkcs10CertificateRequest_signature, this.asn.signature, "f");
        }
        return __classPrivateFieldGet$1(this, _Pkcs10CertificateRequest_signature, "f");
    }
    get publicKey() {
        if (!__classPrivateFieldGet$1(this, _Pkcs10CertificateRequest_publicKey, "f")) {
            __classPrivateFieldSet$1(this, _Pkcs10CertificateRequest_publicKey, new PublicKey(this.asn.certificationRequestInfo.subjectPKInfo), "f");
        }
        return __classPrivateFieldGet$1(this, _Pkcs10CertificateRequest_publicKey, "f");
    }
    get attributes() {
        if (!__classPrivateFieldGet$1(this, _Pkcs10CertificateRequest_attributes, "f")) {
            __classPrivateFieldSet$1(this, _Pkcs10CertificateRequest_attributes, this.asn.certificationRequestInfo.attributes
                .map((o) => AttributeFactory.create(AsnConvert.serialize(o))), "f");
        }
        return __classPrivateFieldGet$1(this, _Pkcs10CertificateRequest_attributes, "f");
    }
    get extensions() {
        if (!__classPrivateFieldGet$1(this, _Pkcs10CertificateRequest_extensions, "f")) {
            __classPrivateFieldSet$1(this, _Pkcs10CertificateRequest_extensions, [], "f");
            const extensions = this.getAttribute(id_pkcs9_at_extensionRequest);
            if (extensions instanceof ExtensionsAttribute) {
                __classPrivateFieldSet$1(this, _Pkcs10CertificateRequest_extensions, extensions.items, "f");
            }
        }
        return __classPrivateFieldGet$1(this, _Pkcs10CertificateRequest_extensions, "f");
    }
    get tbs() {
        if (!__classPrivateFieldGet$1(this, _Pkcs10CertificateRequest_tbs, "f")) {
            __classPrivateFieldSet$1(this, _Pkcs10CertificateRequest_tbs, this.asn.certificationRequestInfoRaw
                || AsnConvert.serialize(this.asn.certificationRequestInfo), "f");
        }
        return __classPrivateFieldGet$1(this, _Pkcs10CertificateRequest_tbs, "f");
    }
    constructor(param) {
        const args = PemData.isAsnEncoded(param) ? [param, CertificationRequest] : [param];
        super(args[0], args[1]);
        _Pkcs10CertificateRequest_tbs.set(this, void 0);
        _Pkcs10CertificateRequest_subjectName.set(this, void 0);
        _Pkcs10CertificateRequest_subject.set(this, void 0);
        _Pkcs10CertificateRequest_signatureAlgorithm.set(this, void 0);
        _Pkcs10CertificateRequest_signature.set(this, void 0);
        _Pkcs10CertificateRequest_publicKey.set(this, void 0);
        _Pkcs10CertificateRequest_attributes.set(this, void 0);
        _Pkcs10CertificateRequest_extensions.set(this, void 0);
        this.tag = PemConverter.CertificateRequestTag;
    }
    onInit(_asn) {
    }
    getAttribute(type) {
        for (const attr of this.attributes) {
            if (attr.type === type) {
                return attr;
            }
        }
        return null;
    }
    getAttributes(type) {
        return this.attributes.filter((o) => o.type === type);
    }
    getExtension(type) {
        for (const ext of this.extensions) {
            if (ext.type === type) {
                return ext;
            }
        }
        return null;
    }
    getExtensions(type) {
        return this.extensions.filter((o) => o.type === type);
    }
    async verify(crypto = cryptoProvider.get()) {
        const algorithm = {
            ...this.publicKey.algorithm, ...this.signatureAlgorithm,
        };
        const publicKey = await this.publicKey.export(algorithm, ["verify"], crypto);
        const signatureFormatters = instance
            .resolveAll(diAsnSignatureFormatter)
            .reverse();
        let signature = null;
        for (const signatureFormatter of signatureFormatters) {
            signature = signatureFormatter.toWebSignature(algorithm, this.signature);
            if (signature) {
                break;
            }
        }
        if (!signature) {
            throw Error("Cannot convert WebCrypto signature value to ASN.1 format");
        }
        const ok = await crypto.subtle.verify(this.signatureAlgorithm, publicKey, signature, this.tbs);
        return ok;
    }
    toTextObject() {
        const obj = this.toTextObjectEmpty();
        const req = AsnConvert.parse(this.rawData, CertificationRequest);
        const tbs = req.certificationRequestInfo;
        const data = new TextObject("", {
            Version: `${Version$2[tbs.version]} (${tbs.version})`,
            Subject: this.subject,
            "Subject Public Key Info": this.publicKey,
        });
        if (this.attributes.length) {
            const attrs = new TextObject("");
            for (const ext of this.attributes) {
                const attrObj = ext.toTextObject();
                attrs[attrObj[TextObject.NAME]] = attrObj;
            }
            data["Attributes"] = attrs;
        }
        obj["Data"] = data;
        obj["Signature"] = new TextObject("", {
            Algorithm: TextConverter.serializeAlgorithm(req.signatureAlgorithm),
            "": req.signature,
        });
        return obj;
    }
}
_Pkcs10CertificateRequest_tbs = new WeakMap(), _Pkcs10CertificateRequest_subjectName = new WeakMap(), _Pkcs10CertificateRequest_subject = new WeakMap(), _Pkcs10CertificateRequest_signatureAlgorithm = new WeakMap(), _Pkcs10CertificateRequest_signature = new WeakMap(), _Pkcs10CertificateRequest_publicKey = new WeakMap(), _Pkcs10CertificateRequest_attributes = new WeakMap(), _Pkcs10CertificateRequest_extensions = new WeakMap();
Pkcs10CertificateRequest.NAME = "PKCS#10 Certificate Request";

var _X509Certificate_tbs, _X509Certificate_serialNumber, _X509Certificate_subjectName, _X509Certificate_subject, _X509Certificate_issuerName, _X509Certificate_issuer, _X509Certificate_notBefore, _X509Certificate_notAfter, _X509Certificate_signatureAlgorithm, _X509Certificate_signature, _X509Certificate_extensions, _X509Certificate_publicKey;
class X509Certificate extends PemData {
    get publicKey() {
        if (!__classPrivateFieldGet$1(this, _X509Certificate_publicKey, "f")) {
            __classPrivateFieldSet$1(this, _X509Certificate_publicKey, new PublicKey(this.asn.tbsCertificate.subjectPublicKeyInfo), "f");
        }
        return __classPrivateFieldGet$1(this, _X509Certificate_publicKey, "f");
    }
    get serialNumber() {
        if (!__classPrivateFieldGet$1(this, _X509Certificate_serialNumber, "f")) {
            const tbs = this.asn.tbsCertificate;
            let serialNumberBytes = new Uint8Array(tbs.serialNumber);
            if (serialNumberBytes.length > 1
                && serialNumberBytes[0] === 0x00
                && serialNumberBytes[1] > 0x7F) {
                serialNumberBytes = serialNumberBytes.slice(1);
            }
            __classPrivateFieldSet$1(this, _X509Certificate_serialNumber, Convert.ToHex(serialNumberBytes), "f");
        }
        return __classPrivateFieldGet$1(this, _X509Certificate_serialNumber, "f");
    }
    get subjectName() {
        if (!__classPrivateFieldGet$1(this, _X509Certificate_subjectName, "f")) {
            __classPrivateFieldSet$1(this, _X509Certificate_subjectName, new Name(this.asn.tbsCertificate.subject), "f");
        }
        return __classPrivateFieldGet$1(this, _X509Certificate_subjectName, "f");
    }
    get subject() {
        if (!__classPrivateFieldGet$1(this, _X509Certificate_subject, "f")) {
            __classPrivateFieldSet$1(this, _X509Certificate_subject, this.subjectName.toString(), "f");
        }
        return __classPrivateFieldGet$1(this, _X509Certificate_subject, "f");
    }
    get issuerName() {
        if (!__classPrivateFieldGet$1(this, _X509Certificate_issuerName, "f")) {
            __classPrivateFieldSet$1(this, _X509Certificate_issuerName, new Name(this.asn.tbsCertificate.issuer), "f");
        }
        return __classPrivateFieldGet$1(this, _X509Certificate_issuerName, "f");
    }
    get issuer() {
        if (!__classPrivateFieldGet$1(this, _X509Certificate_issuer, "f")) {
            __classPrivateFieldSet$1(this, _X509Certificate_issuer, this.issuerName.toString(), "f");
        }
        return __classPrivateFieldGet$1(this, _X509Certificate_issuer, "f");
    }
    get notBefore() {
        if (!__classPrivateFieldGet$1(this, _X509Certificate_notBefore, "f")) {
            const notBefore = this.asn.tbsCertificate.validity.notBefore.utcTime
                || this.asn.tbsCertificate.validity.notBefore.generalTime;
            if (!notBefore) {
                throw new Error("Cannot get 'notBefore' value");
            }
            __classPrivateFieldSet$1(this, _X509Certificate_notBefore, notBefore, "f");
        }
        return __classPrivateFieldGet$1(this, _X509Certificate_notBefore, "f");
    }
    get notAfter() {
        if (!__classPrivateFieldGet$1(this, _X509Certificate_notAfter, "f")) {
            const notAfter = this.asn.tbsCertificate.validity.notAfter.utcTime
                || this.asn.tbsCertificate.validity.notAfter.generalTime;
            if (!notAfter) {
                throw new Error("Cannot get 'notAfter' value");
            }
            __classPrivateFieldSet$1(this, _X509Certificate_notAfter, notAfter, "f");
        }
        return __classPrivateFieldGet$1(this, _X509Certificate_notAfter, "f");
    }
    get signatureAlgorithm() {
        if (!__classPrivateFieldGet$1(this, _X509Certificate_signatureAlgorithm, "f")) {
            const algProv = instance.resolve(diAlgorithmProvider);
            __classPrivateFieldSet$1(this, _X509Certificate_signatureAlgorithm, algProv
                .toWebAlgorithm(this.asn.signatureAlgorithm), "f");
        }
        return __classPrivateFieldGet$1(this, _X509Certificate_signatureAlgorithm, "f");
    }
    get signature() {
        if (!__classPrivateFieldGet$1(this, _X509Certificate_signature, "f")) {
            __classPrivateFieldSet$1(this, _X509Certificate_signature, this.asn.signatureValue, "f");
        }
        return __classPrivateFieldGet$1(this, _X509Certificate_signature, "f");
    }
    get extensions() {
        if (!__classPrivateFieldGet$1(this, _X509Certificate_extensions, "f")) {
            __classPrivateFieldSet$1(this, _X509Certificate_extensions, [], "f");
            if (this.asn.tbsCertificate.extensions) {
                __classPrivateFieldSet$1(this, _X509Certificate_extensions, this.asn.tbsCertificate.extensions.map((o) => (ExtensionFactory.create(AsnConvert.serialize(o)))), "f");
            }
        }
        return __classPrivateFieldGet$1(this, _X509Certificate_extensions, "f");
    }
    get tbs() {
        if (!__classPrivateFieldGet$1(this, _X509Certificate_tbs, "f")) {
            __classPrivateFieldSet$1(this, _X509Certificate_tbs, this.asn.tbsCertificateRaw || AsnConvert.serialize(this.asn.tbsCertificate), "f");
        }
        return __classPrivateFieldGet$1(this, _X509Certificate_tbs, "f");
    }
    constructor(param) {
        const args = PemData.isAsnEncoded(param) ? [param, Certificate] : [param];
        super(args[0], args[1]);
        _X509Certificate_tbs.set(this, void 0);
        _X509Certificate_serialNumber.set(this, void 0);
        _X509Certificate_subjectName.set(this, void 0);
        _X509Certificate_subject.set(this, void 0);
        _X509Certificate_issuerName.set(this, void 0);
        _X509Certificate_issuer.set(this, void 0);
        _X509Certificate_notBefore.set(this, void 0);
        _X509Certificate_notAfter.set(this, void 0);
        _X509Certificate_signatureAlgorithm.set(this, void 0);
        _X509Certificate_signature.set(this, void 0);
        _X509Certificate_extensions.set(this, void 0);
        _X509Certificate_publicKey.set(this, void 0);
        this.tag = PemConverter.CertificateTag;
    }
    onInit(_asn) {
    }
    getExtension(type) {
        for (const ext of this.extensions) {
            if (typeof type === "string") {
                if (ext.type === type) {
                    return ext;
                }
            }
            else {
                if (ext instanceof type) {
                    return ext;
                }
            }
        }
        return null;
    }
    getExtensions(type) {
        return this.extensions.filter((o) => {
            if (typeof type === "string") {
                return o.type === type;
            }
            else {
                return o instanceof type;
            }
        });
    }
    async verify(params = {}, crypto = cryptoProvider.get()) {
        let keyAlgorithm;
        let publicKey;
        const paramsKey = params.publicKey;
        try {
            if (!paramsKey) {
                keyAlgorithm = {
                    ...this.publicKey.algorithm, ...this.signatureAlgorithm,
                };
                publicKey = await this.publicKey.export(keyAlgorithm, ["verify"], crypto);
            }
            else if ("publicKey" in paramsKey) {
                keyAlgorithm = {
                    ...paramsKey.publicKey.algorithm, ...this.signatureAlgorithm,
                };
                publicKey = await paramsKey.publicKey.export(keyAlgorithm, ["verify"], crypto);
            }
            else if (paramsKey instanceof PublicKey) {
                keyAlgorithm = {
                    ...paramsKey.algorithm, ...this.signatureAlgorithm,
                };
                publicKey = await paramsKey.export(keyAlgorithm, ["verify"], crypto);
            }
            else if (BufferSourceConverter.isBufferSource(paramsKey)) {
                const key = new PublicKey(paramsKey);
                keyAlgorithm = {
                    ...key.algorithm, ...this.signatureAlgorithm,
                };
                publicKey = await key.export(keyAlgorithm, ["verify"], crypto);
            }
            else {
                keyAlgorithm = {
                    ...paramsKey.algorithm, ...this.signatureAlgorithm,
                };
                publicKey = paramsKey;
            }
        }
        catch {
            return false;
        }
        const signatureFormatters = instance
            .resolveAll(diAsnSignatureFormatter)
            .reverse();
        let signature = null;
        for (const signatureFormatter of signatureFormatters) {
            signature = signatureFormatter.toWebSignature(keyAlgorithm, this.signature);
            if (signature) {
                break;
            }
        }
        if (!signature) {
            throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
        }
        const ok = await crypto.subtle.verify(this.signatureAlgorithm, publicKey, signature, this.tbs);
        if (params.signatureOnly) {
            return ok;
        }
        else {
            const date = params.date || new Date();
            const time = date.getTime();
            return ok && this.notBefore.getTime() < time && time < this.notAfter.getTime();
        }
    }
    async getThumbprint(...args) {
        let crypto;
        let algorithm = "SHA-1";
        if (args[0]) {
            if (!args[0].subtle) {
                algorithm = args[0] || algorithm;
                crypto = args[1];
            }
            else {
                crypto = args[0];
            }
        }
        crypto !== null && crypto !== void 0 ? crypto : (crypto = cryptoProvider.get());
        return await crypto.subtle.digest(algorithm, this.rawData);
    }
    async isSelfSigned(crypto = cryptoProvider.get()) {
        return this.subject === this.issuer && await this.verify({ signatureOnly: true }, crypto);
    }
    toTextObject() {
        const obj = this.toTextObjectEmpty();
        const cert = AsnConvert.parse(this.rawData, Certificate);
        const tbs = cert.tbsCertificate;
        const data = new TextObject("", {
            Version: `${Version$2[tbs.version]} (${tbs.version})`,
            "Serial Number": tbs.serialNumber,
            "Signature Algorithm": TextConverter.serializeAlgorithm(tbs.signature),
            Issuer: this.issuer,
            Validity: new TextObject("", {
                "Not Before": tbs.validity.notBefore.getTime(),
                "Not After": tbs.validity.notAfter.getTime(),
            }),
            Subject: this.subject,
            "Subject Public Key Info": this.publicKey,
        });
        if (tbs.issuerUniqueID) {
            data["Issuer Unique ID"] = tbs.issuerUniqueID;
        }
        if (tbs.subjectUniqueID) {
            data["Subject Unique ID"] = tbs.subjectUniqueID;
        }
        if (this.extensions.length) {
            const extensions = new TextObject("");
            for (const ext of this.extensions) {
                const extObj = ext.toTextObject();
                extensions[extObj[TextObject.NAME]] = extObj;
            }
            data["Extensions"] = extensions;
        }
        obj["Data"] = data;
        obj["Signature"] = new TextObject("", {
            Algorithm: TextConverter.serializeAlgorithm(cert.signatureAlgorithm),
            "": cert.signatureValue,
        });
        return obj;
    }
}
_X509Certificate_tbs = new WeakMap(), _X509Certificate_serialNumber = new WeakMap(), _X509Certificate_subjectName = new WeakMap(), _X509Certificate_subject = new WeakMap(), _X509Certificate_issuerName = new WeakMap(), _X509Certificate_issuer = new WeakMap(), _X509Certificate_notBefore = new WeakMap(), _X509Certificate_notAfter = new WeakMap(), _X509Certificate_signatureAlgorithm = new WeakMap(), _X509Certificate_signature = new WeakMap(), _X509Certificate_extensions = new WeakMap(), _X509Certificate_publicKey = new WeakMap();
X509Certificate.NAME = "Certificate";

function generateCertificateSerialNumber(input, crypto = cryptoProvider.get()) {
    const inputView = BufferSourceConverter.toUint8Array(Convert.FromHex(input || ""));
    let serialNumber = inputView && inputView.length && inputView.some((o) => o > 0)
        ? new Uint8Array(inputView)
        : undefined;
    if (!serialNumber) {
        serialNumber = crypto.getRandomValues(new Uint8Array(16));
    }
    let firstNonZero = 0;
    while (firstNonZero < serialNumber.length - 1 && serialNumber[firstNonZero] === 0) {
        firstNonZero++;
    }
    serialNumber = serialNumber.slice(firstNonZero);
    if (serialNumber[0] > 0x7F) {
        const newSerialNumber = new Uint8Array(serialNumber.length + 1);
        newSerialNumber[0] = 0x00;
        newSerialNumber.set(serialNumber, 1);
        serialNumber = newSerialNumber;
    }
    return serialNumber.buffer;
}

var _X509CrlEntry_serialNumber, _X509CrlEntry_revocationDate, _X509CrlEntry_reason, _X509CrlEntry_invalidity, _X509CrlEntry_extensions;
var X509CrlReason;
(function (X509CrlReason) {
    X509CrlReason[X509CrlReason["unspecified"] = 0] = "unspecified";
    X509CrlReason[X509CrlReason["keyCompromise"] = 1] = "keyCompromise";
    X509CrlReason[X509CrlReason["cACompromise"] = 2] = "cACompromise";
    X509CrlReason[X509CrlReason["affiliationChanged"] = 3] = "affiliationChanged";
    X509CrlReason[X509CrlReason["superseded"] = 4] = "superseded";
    X509CrlReason[X509CrlReason["cessationOfOperation"] = 5] = "cessationOfOperation";
    X509CrlReason[X509CrlReason["certificateHold"] = 6] = "certificateHold";
    X509CrlReason[X509CrlReason["removeFromCRL"] = 8] = "removeFromCRL";
    X509CrlReason[X509CrlReason["privilegeWithdrawn"] = 9] = "privilegeWithdrawn";
    X509CrlReason[X509CrlReason["aACompromise"] = 10] = "aACompromise";
})(X509CrlReason || (X509CrlReason = {}));
class X509CrlEntry extends AsnData {
    get serialNumber() {
        if (!__classPrivateFieldGet$1(this, _X509CrlEntry_serialNumber, "f")) {
            __classPrivateFieldSet$1(this, _X509CrlEntry_serialNumber, Convert.ToHex(this.asn.userCertificate), "f");
        }
        return __classPrivateFieldGet$1(this, _X509CrlEntry_serialNumber, "f");
    }
    get revocationDate() {
        if (!__classPrivateFieldGet$1(this, _X509CrlEntry_revocationDate, "f")) {
            __classPrivateFieldSet$1(this, _X509CrlEntry_revocationDate, this.asn.revocationDate.getTime(), "f");
        }
        return __classPrivateFieldGet$1(this, _X509CrlEntry_revocationDate, "f");
    }
    get reason() {
        if (__classPrivateFieldGet$1(this, _X509CrlEntry_reason, "f") === undefined) {
            void this.extensions;
        }
        return __classPrivateFieldGet$1(this, _X509CrlEntry_reason, "f");
    }
    get invalidity() {
        if (__classPrivateFieldGet$1(this, _X509CrlEntry_invalidity, "f") === undefined) {
            void this.extensions;
        }
        return __classPrivateFieldGet$1(this, _X509CrlEntry_invalidity, "f");
    }
    get extensions() {
        if (!__classPrivateFieldGet$1(this, _X509CrlEntry_extensions, "f")) {
            __classPrivateFieldSet$1(this, _X509CrlEntry_extensions, [], "f");
            if (this.asn.crlEntryExtensions) {
                __classPrivateFieldSet$1(this, _X509CrlEntry_extensions, this.asn.crlEntryExtensions.map((o) => {
                    const extension = ExtensionFactory.create(AsnConvert.serialize(o));
                    switch (extension.type) {
                        case id_ce_cRLReasons:
                            if (__classPrivateFieldGet$1(this, _X509CrlEntry_reason, "f") === undefined) {
                                __classPrivateFieldSet$1(this, _X509CrlEntry_reason, AsnConvert
                                    .parse(extension.value, CRLReason).reason, "f");
                            }
                            break;
                        case id_ce_invalidityDate:
                            if (__classPrivateFieldGet$1(this, _X509CrlEntry_invalidity, "f") === undefined) {
                                __classPrivateFieldSet$1(this, _X509CrlEntry_invalidity, AsnConvert.parse(extension.value, InvalidityDate).value, "f");
                            }
                            break;
                    }
                    return extension;
                }), "f");
            }
        }
        return __classPrivateFieldGet$1(this, _X509CrlEntry_extensions, "f");
    }
    constructor(...args) {
        let raw;
        if (BufferSourceConverter.isBufferSource(args[0])) {
            raw = BufferSourceConverter.toArrayBuffer(args[0]);
        }
        else if (typeof args[0] === "string") {
            raw = AsnConvert.serialize(new RevokedCertificate({
                userCertificate: generateCertificateSerialNumber(args[0]),
                revocationDate: new Time(args[1]),
                crlEntryExtensions: args[2],
            }));
        }
        else if (args[0] instanceof RevokedCertificate) {
            raw = args[0];
        }
        if (!raw) {
            throw new TypeError("Cannot create X509CrlEntry instance. Wrong constructor arguments.");
        }
        super(raw, RevokedCertificate);
        _X509CrlEntry_serialNumber.set(this, void 0);
        _X509CrlEntry_revocationDate.set(this, void 0);
        _X509CrlEntry_reason.set(this, void 0);
        _X509CrlEntry_invalidity.set(this, void 0);
        _X509CrlEntry_extensions.set(this, void 0);
    }
    onInit(_asn) {
    }
}
_X509CrlEntry_serialNumber = new WeakMap(), _X509CrlEntry_revocationDate = new WeakMap(), _X509CrlEntry_reason = new WeakMap(), _X509CrlEntry_invalidity = new WeakMap(), _X509CrlEntry_extensions = new WeakMap();

var _X509Crl_tbs, _X509Crl_signatureAlgorithm, _X509Crl_issuerName, _X509Crl_thisUpdate, _X509Crl_nextUpdate, _X509Crl_entries, _X509Crl_extensions;
class X509Crl extends PemData {
    get version() {
        return this.asn.tbsCertList.version;
    }
    get signatureAlgorithm() {
        if (!__classPrivateFieldGet$1(this, _X509Crl_signatureAlgorithm, "f")) {
            const algProv = instance.resolve(diAlgorithmProvider);
            __classPrivateFieldSet$1(this, _X509Crl_signatureAlgorithm, algProv
                .toWebAlgorithm(this.asn.signatureAlgorithm), "f");
        }
        return __classPrivateFieldGet$1(this, _X509Crl_signatureAlgorithm, "f");
    }
    get signature() {
        return this.asn.signature;
    }
    get issuer() {
        return this.issuerName.toString();
    }
    get issuerName() {
        if (!__classPrivateFieldGet$1(this, _X509Crl_issuerName, "f")) {
            __classPrivateFieldSet$1(this, _X509Crl_issuerName, new Name(this.asn.tbsCertList.issuer), "f");
        }
        return __classPrivateFieldGet$1(this, _X509Crl_issuerName, "f");
    }
    get thisUpdate() {
        if (!__classPrivateFieldGet$1(this, _X509Crl_thisUpdate, "f")) {
            const thisUpdate = this.asn.tbsCertList.thisUpdate.getTime();
            if (!thisUpdate) {
                throw new Error("Cannot get 'thisUpdate' value");
            }
            __classPrivateFieldSet$1(this, _X509Crl_thisUpdate, thisUpdate, "f");
        }
        return __classPrivateFieldGet$1(this, _X509Crl_thisUpdate, "f");
    }
    get nextUpdate() {
        var _a;
        if (__classPrivateFieldGet$1(this, _X509Crl_nextUpdate, "f") === undefined) {
            __classPrivateFieldSet$1(this, _X509Crl_nextUpdate, ((_a = this.asn.tbsCertList.nextUpdate) === null || _a === void 0 ? void 0 : _a.getTime()) || undefined, "f");
        }
        return __classPrivateFieldGet$1(this, _X509Crl_nextUpdate, "f");
    }
    get entries() {
        var _a;
        if (!__classPrivateFieldGet$1(this, _X509Crl_entries, "f")) {
            __classPrivateFieldSet$1(this, _X509Crl_entries, ((_a = this.asn.tbsCertList
                .revokedCertificates) === null || _a === void 0 ? void 0 : _a.map((o) => new X509CrlEntry(o))) || [], "f");
        }
        return __classPrivateFieldGet$1(this, _X509Crl_entries, "f");
    }
    get extensions() {
        if (!__classPrivateFieldGet$1(this, _X509Crl_extensions, "f")) {
            __classPrivateFieldSet$1(this, _X509Crl_extensions, [], "f");
            if (this.asn.tbsCertList.crlExtensions) {
                __classPrivateFieldSet$1(this, _X509Crl_extensions, this.asn.tbsCertList.crlExtensions.map((o) => ExtensionFactory.create(AsnConvert.serialize(o))), "f");
            }
        }
        return __classPrivateFieldGet$1(this, _X509Crl_extensions, "f");
    }
    get tbs() {
        if (!__classPrivateFieldGet$1(this, _X509Crl_tbs, "f")) {
            __classPrivateFieldSet$1(this, _X509Crl_tbs, this.asn.tbsCertListRaw || AsnConvert.serialize(this.asn.tbsCertList), "f");
        }
        return __classPrivateFieldGet$1(this, _X509Crl_tbs, "f");
    }
    get tbsCertListSignatureAlgorithm() {
        return this.asn.tbsCertList.signature;
    }
    get certListSignatureAlgorithm() {
        return this.asn.signatureAlgorithm;
    }
    constructor(param) {
        super(param, PemData.isAsnEncoded(param) ? CertificateList : undefined);
        this.tag = PemConverter.CrlTag;
        _X509Crl_tbs.set(this, void 0);
        _X509Crl_signatureAlgorithm.set(this, void 0);
        _X509Crl_issuerName.set(this, void 0);
        _X509Crl_thisUpdate.set(this, void 0);
        _X509Crl_nextUpdate.set(this, void 0);
        _X509Crl_entries.set(this, void 0);
        _X509Crl_extensions.set(this, void 0);
    }
    onInit(_asn) {
    }
    getExtension(type) {
        for (const ext of this.extensions) {
            if (typeof type === "string") {
                if (ext.type === type) {
                    return ext;
                }
            }
            else {
                if (ext instanceof type) {
                    return ext;
                }
            }
        }
        return null;
    }
    getExtensions(type) {
        return this.extensions.filter((o) => {
            if (typeof type === "string") {
                return o.type === type;
            }
            else {
                return o instanceof type;
            }
        });
    }
    async verify(params, crypto = cryptoProvider.get()) {
        if (!this.certListSignatureAlgorithm.isEqual(this.tbsCertListSignatureAlgorithm)) {
            throw new Error("algorithm identifier in the sequence tbsCertList and CertificateList mismatch");
        }
        let keyAlgorithm;
        let publicKey;
        const paramsKey = params.publicKey;
        try {
            if (paramsKey instanceof X509Certificate) {
                keyAlgorithm = {
                    ...paramsKey.publicKey.algorithm,
                    ...paramsKey.signatureAlgorithm,
                };
                publicKey = await paramsKey.publicKey.export(keyAlgorithm, ["verify"]);
            }
            else if (paramsKey instanceof PublicKey) {
                keyAlgorithm = {
                    ...paramsKey.algorithm, ...this.signatureAlgorithm,
                };
                publicKey = await paramsKey.export(keyAlgorithm, ["verify"]);
            }
            else {
                keyAlgorithm = {
                    ...paramsKey.algorithm, ...this.signatureAlgorithm,
                };
                publicKey = paramsKey;
            }
        }
        catch {
            return false;
        }
        const signatureFormatters = instance
            .resolveAll(diAsnSignatureFormatter)
            .reverse();
        let signature = null;
        for (const signatureFormatter of signatureFormatters) {
            signature = signatureFormatter.toWebSignature(keyAlgorithm, this.signature);
            if (signature) {
                break;
            }
        }
        if (!signature) {
            throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
        }
        return await crypto.subtle.verify(this.signatureAlgorithm, publicKey, signature, this.tbs);
    }
    async getThumbprint(...args) {
        let crypto;
        let algorithm = "SHA-1";
        if (args[0]) {
            if (!args[0].subtle) {
                algorithm = args[0] || algorithm;
                crypto = args[1];
            }
            else {
                crypto = args[0];
            }
        }
        crypto !== null && crypto !== void 0 ? crypto : (crypto = cryptoProvider.get());
        return await crypto.subtle.digest(algorithm, this.rawData);
    }
    findRevoked(certOrSerialNumber) {
        const serialNumber = typeof certOrSerialNumber === "string" ? certOrSerialNumber : certOrSerialNumber.serialNumber;
        const serialBuffer = generateCertificateSerialNumber(serialNumber);
        for (const revoked of this.asn.tbsCertList.revokedCertificates || []) {
            if (BufferSourceConverter.isEqual(revoked.userCertificate, serialBuffer)) {
                return new X509CrlEntry(AsnConvert.serialize(revoked));
            }
        }
        return null;
    }
}
_X509Crl_tbs = new WeakMap(), _X509Crl_signatureAlgorithm = new WeakMap(), _X509Crl_issuerName = new WeakMap(), _X509Crl_thisUpdate = new WeakMap(), _X509Crl_nextUpdate = new WeakMap(), _X509Crl_entries = new WeakMap(), _X509Crl_extensions = new WeakMap();

ExtensionFactory.register(id_ce_basicConstraints, BasicConstraintsExtension);
ExtensionFactory.register(id_ce_extKeyUsage, ExtendedKeyUsageExtension);
ExtensionFactory.register(id_ce_keyUsage, KeyUsagesExtension);
ExtensionFactory.register(id_ce_subjectKeyIdentifier, SubjectKeyIdentifierExtension);
ExtensionFactory.register(id_ce_authorityKeyIdentifier, AuthorityKeyIdentifierExtension);
ExtensionFactory.register(id_ce_subjectAltName, SubjectAlternativeNameExtension);
ExtensionFactory.register(id_ce_cRLDistributionPoints, CRLDistributionPointsExtension);
ExtensionFactory.register(id_pe_authorityInfoAccess, AuthorityInfoAccessExtension);
ExtensionFactory.register(id_ce_issuerAltName, IssuerAlternativeNameExtension);
AttributeFactory.register(id_pkcs9_at_challengePassword, ChallengePasswordAttribute);
AttributeFactory.register(id_pkcs9_at_extensionRequest, ExtensionsAttribute);
instance.registerSingleton(diAsnSignatureFormatter, AsnDefaultSignatureFormatter);
instance.registerSingleton(diAsnSignatureFormatter, AsnEcSignatureFormatter);
AsnEcSignatureFormatter.namedCurveSize.set("P-256", 32);
AsnEcSignatureFormatter.namedCurveSize.set("K-256", 32);
AsnEcSignatureFormatter.namedCurveSize.set("P-384", 48);
AsnEcSignatureFormatter.namedCurveSize.set("P-521", 66);

/**
 * A simple method for requesting data via standard `fetch`. Should work
 * across multiple runtimes.
 */
function fetch$1(url) {
    return _fetchInternals.stubThis(url);
}
/**
 * Make it possible to stub the return value during testing
 * @ignore Don't include this in docs output
 */
const _fetchInternals = {
    stubThis: (url) => globalThis.fetch(url),
};

const cacheRevokedCerts = {};
/**
 * A method to pull a CRL from a certificate and compare its serial number to the list of revoked
 * certificate serial numbers within the CRL.
 *
 * CRL certificate structure referenced from https://tools.ietf.org/html/rfc5280#page-117
 */
async function isCertRevoked(cert) {
    const { extensions } = cert;
    if (!extensions) {
        return false;
    }
    let extAuthorityKeyID;
    let extSubjectKeyID;
    let extCRLDistributionPoints;
    extensions.forEach((ext) => {
        if (ext instanceof AuthorityKeyIdentifierExtension) {
            extAuthorityKeyID = ext;
        }
        else if (ext instanceof SubjectKeyIdentifierExtension) {
            extSubjectKeyID = ext;
        }
        else if (ext instanceof CRLDistributionPointsExtension) {
            extCRLDistributionPoints = ext;
        }
    });
    // Check to see if we've got cached info for the cert's CA
    let keyIdentifier = undefined;
    if (extAuthorityKeyID && extAuthorityKeyID.keyId) {
        keyIdentifier = extAuthorityKeyID.keyId;
    }
    else if (extSubjectKeyID) {
        /**
         * We might be dealing with a self-signed root certificate. Check the
         * Subject key Identifier extension next.
         */
        keyIdentifier = extSubjectKeyID.keyId;
    }
    if (keyIdentifier) {
        const cached = cacheRevokedCerts[keyIdentifier];
        if (cached) {
            const now = new Date();
            // If there's a nextUpdate then make sure we're before it
            if (!cached.nextUpdate || cached.nextUpdate > now) {
                return cached.revokedCerts.indexOf(cert.serialNumber) >= 0;
            }
        }
    }
    const crlURL = extCRLDistributionPoints?.distributionPoints?.[0].distributionPoint?.fullName?.[0]
        .uniformResourceIdentifier;
    // If no URL is provided then we have nothing to check
    if (!crlURL) {
        return false;
    }
    // Download and read the CRL
    let certListBytes;
    try {
        const respCRL = await fetch$1(crlURL);
        certListBytes = await respCRL.arrayBuffer();
    }
    catch (_err) {
        return false;
    }
    let data;
    try {
        data = new X509Crl(certListBytes);
    }
    catch (_err) {
        // Something was malformed with the CRL, so pass
        return false;
    }
    const newCached = {
        revokedCerts: [],
        nextUpdate: undefined,
    };
    // nextUpdate
    if (data.nextUpdate) {
        newCached.nextUpdate = data.nextUpdate;
    }
    // revokedCertificates
    const revokedCerts = data.entries;
    if (revokedCerts) {
        for (const cert of revokedCerts) {
            const revokedHex = cert.serialNumber;
            newCached.revokedCerts.push(revokedHex);
        }
        // Cache the results
        if (keyIdentifier) {
            cacheRevokedCerts[keyIdentifier] = newCached;
        }
        return newCached.revokedCerts.indexOf(cert.serialNumber) >= 0;
    }
    return false;
}

/**
 * Convert authenticator extension data buffer to a proper object
 *
 * @param extensionData Authenticator Extension Data buffer
 */
function decodeAuthenticatorExtensions(extensionData) {
    let toCBOR;
    try {
        toCBOR = decodeFirst(extensionData);
    }
    catch (err) {
        const _err = err;
        throw new Error(`Error decoding authenticator extensions: ${_err.message}`);
    }
    return convertMapToObjectDeep(toCBOR);
}
/**
 * CBOR-encoded extensions can be deeply-nested Maps, which are too deep for a simple
 * `Object.entries()`. This method will recursively make sure that all Maps are converted into
 * basic objects.
 */
function convertMapToObjectDeep(input) {
    const mapped = {};
    for (const [key, value] of input) {
        if (value instanceof Map) {
            mapped[key] = convertMapToObjectDeep(value);
        }
        else {
            mapped[key] = value;
        }
    }
    return mapped;
}

/**
 * Make sense of the authData buffer contained in an Attestation
 */
function parseAuthenticatorData(authData) {
    if (authData.byteLength < 37) {
        throw new Error(`Authenticator data was ${authData.byteLength} bytes, expected at least 37 bytes`);
    }
    let pointer = 0;
    const dataView = toDataView(authData);
    const rpIdHash = authData.slice(pointer, pointer += 32);
    const flagsBuf = authData.slice(pointer, pointer += 1);
    const flagsInt = flagsBuf[0];
    // Bit positions can be referenced here:
    // https://www.w3.org/TR/webauthn-2/#flags
    const flags = {
        up: !!(flagsInt & (1 << 0)), // User Presence
        uv: !!(flagsInt & (1 << 2)), // User Verified
        be: !!(flagsInt & (1 << 3)), // Backup Eligibility
        bs: !!(flagsInt & (1 << 4)), // Backup State
        at: !!(flagsInt & (1 << 6)), // Attested Credential Data Present
        ed: !!(flagsInt & (1 << 7)), // Extension Data Present
        flagsInt,
    };
    const counterBuf = authData.slice(pointer, pointer + 4);
    const counter = dataView.getUint32(pointer, false);
    pointer += 4;
    let aaguid = undefined;
    let credentialID = undefined;
    let credentialPublicKey = undefined;
    if (flags.at) {
        aaguid = authData.slice(pointer, pointer += 16);
        const credIDLen = dataView.getUint16(pointer);
        pointer += 2;
        credentialID = authData.slice(pointer, pointer += credIDLen);
        /**
         * Firefox 117 incorrectly CBOR-encodes authData when EdDSA (-8) is used for the public key.
         * A CBOR "Map of 3 items" (0xa3) should be "Map of 4 items" (0xa4), and if we manually adjust
         * the single byte there's a good chance the authData can be correctly parsed.
         *
         * This browser release also incorrectly uses the string labels "OKP" and "Ed25519" instead of
         * their integer representations for kty and crv respectively. That's why the COSE public key
         * in the hex below looks so odd.
         */
        // Bytes decode to `{ 1: "OKP", 3: -8, -1: "Ed25519" }` (it's missing key -2 a.k.a. COSEKEYS.x)
        const badEdDSACBOR = fromHex('a301634f4b500327206745643235353139');
        const bytesAtCurrentPosition = authData.slice(pointer, pointer + badEdDSACBOR.byteLength);
        let foundBadCBOR = false;
        if (areEqual(badEdDSACBOR, bytesAtCurrentPosition)) {
            // Change the bad CBOR 0xa3 to 0xa4 so that the credential public key can be recognized
            foundBadCBOR = true;
            authData[pointer] = 0xa4;
        }
        // Decode the next CBOR item in the buffer, then re-encode it back to a Buffer
        const firstDecoded = decodeFirst(authData.slice(pointer));
        const firstEncoded = Uint8Array.from(
        /**
         * Casting to `Map` via `as unknown` here because TS doesn't make it possible to define Maps
         * with discrete keys and properties with known types per pair, and CBOR libs typically parse
         * CBOR Major Type 5 to `Map` because you can have numbers for keys. A `COSEPublicKey` can be
         * generalized as "a Map with numbers for keys and either numbers or bytes for values" though.
         * If this presumption falls apart then other parts of verification later on will fail so we
         * should be safe doing this here.
         */
        encode(firstDecoded));
        if (foundBadCBOR) {
            // Restore the bit we changed so that `authData` is the same as it came in and won't break
            // signature verification.
            authData[pointer] = 0xa3;
        }
        credentialPublicKey = firstEncoded;
        pointer += firstEncoded.byteLength;
    }
    let extensionsData = undefined;
    let extensionsDataBuffer = undefined;
    if (flags.ed) {
        const firstDecoded = decodeFirst(authData.slice(pointer));
        extensionsDataBuffer = Uint8Array.from(encode(firstDecoded));
        extensionsData = decodeAuthenticatorExtensions(extensionsDataBuffer);
        pointer += extensionsDataBuffer.byteLength;
    }
    // Pointer should be at the end of the authenticator data, otherwise too much data was sent
    if (authData.byteLength > pointer) {
        throw new Error('Leftover bytes detected while parsing authenticator data');
    }
    return _parseAuthenticatorDataInternals.stubThis({
        rpIdHash,
        flagsBuf,
        flags,
        counter,
        counterBuf,
        aaguid,
        credentialID,
        credentialPublicKey,
        extensionsData,
        extensionsDataBuffer,
    });
}
/**
 * Make it possible to stub the return value during testing
 * @ignore Don't include this in docs output
 */
const _parseAuthenticatorDataInternals = {
    stubThis: (value) => value,
};

/**
 * Returns hash digest of the given data, using the given algorithm when provided. Defaults to using
 * SHA-256.
 */
function toHash(data, algorithm = -7) {
    if (typeof data === 'string') {
        data = fromUTF8String(data);
    }
    const digest$1 = digest(data, algorithm);
    return digest$1;
}

/**
 * Traverse an array of PEM certificates and ensure they form a proper chain
 * @param x5cCertsPEM Typically the result of `x5c.map(convertASN1toPEM)`
 * @param trustAnchorsPEM PEM-formatted certs that an attestation statement x5c may chain back to
 */
async function validateCertificatePath(x5cCertsPEM, trustAnchorsPEM = []) {
    if (trustAnchorsPEM.length === 0) {
        // We have no trust anchors to chain back to, so skip path validation
        return true;
    }
    const WebCrypto = await getWebCrypto();
    // Prepare to work with x5c certs
    const x5cCertsParsed = x5cCertsPEM.map((certPEM) => new X509Certificate(certPEM));
    // Check for any expired or temporally invalid certs in x5c
    for (let i = 0; i < x5cCertsParsed.length; i++) {
        const cert = x5cCertsParsed[i];
        const certPEM = x5cCertsPEM[i];
        try {
            await assertCertNotRevoked(cert);
        }
        catch (_err) {
            throw new Error(`Found revoked certificate in x5c:\n${certPEM}`);
        }
        try {
            assertCertIsWithinValidTimeWindow(cert.notBefore, cert.notAfter);
        }
        catch (_err) {
            throw new Error(`Found certificate out of validity period in x5c:\n${certPEM}`);
        }
    }
    // Prepare to work with trust anchor certs
    const trustAnchorsParsed = trustAnchorsPEM.map((certPEM) => {
        try {
            return new X509Certificate(certPEM);
        }
        catch (err) {
            const _err = err;
            throw new Error(`Could not parse trust anchor certificate:\n${certPEM}`, { cause: _err });
        }
    });
    // Filter out any expired or temporally invalid trust anchors certs
    const validTrustAnchors = [];
    for (let i = 0; i < trustAnchorsParsed.length; i++) {
        const cert = trustAnchorsParsed[i];
        try {
            await assertCertNotRevoked(cert);
        }
        catch (_err) {
            // Continue processing the other certs
            continue;
        }
        try {
            assertCertIsWithinValidTimeWindow(cert.notBefore, cert.notAfter);
        }
        catch (_err) {
            // Continue processing the other certs
            continue;
        }
        validTrustAnchors.push(cert);
    }
    if (validTrustAnchors.length === 0) {
        throw new Error('No specified trust anchor was valid for verifying x5c');
    }
    // Try to verify x5c with each trust anchor
    let invalidSubjectAndIssuerError = false;
    for (const anchor of trustAnchorsParsed) {
        try {
            const x5cWithTrustAnchor = x5cCertsParsed.concat([anchor]);
            if (new Set(x5cWithTrustAnchor).size !== x5cWithTrustAnchor.length) {
                throw new Error('Invalid certificate path: found duplicate certificates');
            }
            // Check signatures, and notBefore and notAfter
            for (let i = 0; i < x5cWithTrustAnchor.length - 1; i++) {
                const subject = x5cWithTrustAnchor[i];
                const issuer = x5cWithTrustAnchor[i + 1];
                // Leaf or intermediate cert, make sure the next cert in the chain signed it
                const issuerSignedSubject = await subject.verify({ publicKey: issuer.publicKey, signatureOnly: true }, WebCrypto);
                if (!issuerSignedSubject) {
                    throw new InvalidSubjectAndIssuer();
                }
                if (issuer.subject === issuer.issuer) {
                    // Root cert detected, make sure it signed itself
                    const issuerSignedIssuer = await issuer.verify({ publicKey: issuer.publicKey, signatureOnly: true }, WebCrypto);
                    if (!issuerSignedIssuer) {
                        throw new InvalidSubjectAndIssuer();
                    }
                    // Don't process anything else after a root cert
                    break;
                }
            }
            // If we successfully validated a path then there's no need to continue. Reset any existing
            // errors that were thrown by earlier trust anchors
            invalidSubjectAndIssuerError = false;
            break;
        }
        catch (err) {
            if (err instanceof InvalidSubjectAndIssuer) {
                invalidSubjectAndIssuerError = true;
            }
            else {
                throw new Error('Unexpected error while validating certificate path', { cause: err });
            }
        }
    }
    // We tried multiple trust anchors and none of them worked
    if (invalidSubjectAndIssuerError) {
        throw new InvalidSubjectAndIssuer();
    }
    return true;
}
/**
 * Check if the certificate is revoked or not. If it is, raise an error
 */
async function assertCertNotRevoked(certificate) {
    // Check for certificate revocation
    const subjectCertRevoked = await isCertRevoked(certificate);
    if (subjectCertRevoked) {
        throw new Error('Found revoked certificate in certificate path');
    }
}
/**
 * Require the cert to be within its notBefore and notAfter time window
 */
function assertCertIsWithinValidTimeWindow(certNotBefore, certNotAfter) {
    const now = new Date(Date.now());
    if (certNotBefore > now || certNotAfter < now) {
        throw new Error('Certificate is not yet valid or expired');
    }
}
// Custom errors to help pass on certain errors
class InvalidSubjectAndIssuer extends Error {
    constructor() {
        const message = 'Subject issuer did not match issuer subject';
        super(message);
        this.name = 'InvalidSubjectAndIssuer';
    }
}

/**
 * Map X.509 signature algorithm OIDs to COSE algorithm IDs
 *
 * - EC2 OIDs: https://oidref.com/1.2.840.10045.4.3
 * - RSA OIDs: https://oidref.com/1.2.840.113549.1.1
 */
function mapX509SignatureAlgToCOSEAlg(signatureAlgorithm) {
    let alg;
    if (signatureAlgorithm === '1.2.840.10045.4.3.2') {
        alg = COSEALG.ES256;
    }
    else if (signatureAlgorithm === '1.2.840.10045.4.3.3') {
        alg = COSEALG.ES384;
    }
    else if (signatureAlgorithm === '1.2.840.10045.4.3.4') {
        alg = COSEALG.ES512;
    }
    else if (signatureAlgorithm === '1.2.840.113549.1.1.11') {
        alg = COSEALG.RS256;
    }
    else if (signatureAlgorithm === '1.2.840.113549.1.1.12') {
        alg = COSEALG.RS384;
    }
    else if (signatureAlgorithm === '1.2.840.113549.1.1.13') {
        alg = COSEALG.RS512;
    }
    else if (signatureAlgorithm === '1.2.840.113549.1.1.5') {
        alg = COSEALG.RS1;
    }
    else {
        throw new Error(`Unable to map X.509 signature algorithm ${signatureAlgorithm} to a COSE algorithm`);
    }
    return alg;
}

function convertX509PublicKeyToCOSE(x509Certificate) {
    let cosePublicKey = new Map();
    /**
     * Time to extract the public key from an X.509 certificate
     */
    const x509 = AsnParser.parse(x509Certificate, Certificate);
    const { tbsCertificate } = x509;
    const { subjectPublicKeyInfo, signature: _tbsSignature } = tbsCertificate;
    const signatureAlgorithm = _tbsSignature.algorithm;
    const publicKeyAlgorithmID = subjectPublicKeyInfo.algorithm.algorithm;
    if (publicKeyAlgorithmID === id_ecPublicKey) {
        /**
         * EC2 Public Key
         */
        if (!subjectPublicKeyInfo.algorithm.parameters) {
            throw new Error('Certificate public key was missing parameters (EC2)');
        }
        const ecParameters = AsnParser.parse(new Uint8Array(subjectPublicKeyInfo.algorithm.parameters), ECParameters);
        let crv = -999;
        const { namedCurve } = ecParameters;
        if (namedCurve === id_secp256r1) {
            crv = COSECRV.P256;
        }
        else if (namedCurve === id_secp384r1) {
            crv = COSECRV.P384;
        }
        else {
            throw new Error(`Certificate public key contained unexpected namedCurve ${namedCurve} (EC2)`);
        }
        const subjectPublicKey = new Uint8Array(subjectPublicKeyInfo.subjectPublicKey);
        let x;
        let y;
        if (subjectPublicKey[0] === 0x04) {
            // Public key is in "uncompressed form", so we can split the remaining bytes in half
            let pointer = 1;
            const halfLength = (subjectPublicKey.length - 1) / 2;
            x = subjectPublicKey.slice(pointer, pointer += halfLength);
            y = subjectPublicKey.slice(pointer);
        }
        else {
            throw new Error('TODO: Figure out how to handle public keys in "compressed form"');
        }
        const coseEC2PubKey = new Map();
        coseEC2PubKey.set(COSEKEYS.kty, COSEKTY.EC2);
        coseEC2PubKey.set(COSEKEYS.alg, mapX509SignatureAlgToCOSEAlg(signatureAlgorithm));
        coseEC2PubKey.set(COSEKEYS.crv, crv);
        coseEC2PubKey.set(COSEKEYS.x, x);
        coseEC2PubKey.set(COSEKEYS.y, y);
        cosePublicKey = coseEC2PubKey;
    }
    else if (publicKeyAlgorithmID === id_rsaEncryption) {
        /**
         * RSA public key
         */
        const rsaPublicKey = AsnParser.parse(subjectPublicKeyInfo.subjectPublicKey, RSAPublicKey);
        const coseRSAPubKey = new Map();
        coseRSAPubKey.set(COSEKEYS.kty, COSEKTY.RSA);
        coseRSAPubKey.set(COSEKEYS.alg, mapX509SignatureAlgToCOSEAlg(signatureAlgorithm));
        coseRSAPubKey.set(COSEKEYS.n, new Uint8Array(rsaPublicKey.modulus));
        coseRSAPubKey.set(COSEKEYS.e, new Uint8Array(rsaPublicKey.publicExponent));
        cosePublicKey = coseRSAPubKey;
    }
    else {
        throw new Error(`Certificate public key contained unexpected algorithm ID ${publicKeyAlgorithmID}`);
    }
    return cosePublicKey;
}

/**
 * Verify an authenticator's signature
 */
function verifySignature(opts) {
    const { signature, data, credentialPublicKey, x509Certificate, hashAlgorithm, } = opts;
    if (!x509Certificate && !credentialPublicKey) {
        throw new Error('Must declare either "leafCert" or "credentialPublicKey"');
    }
    if (x509Certificate && credentialPublicKey) {
        throw new Error('Must not declare both "leafCert" and "credentialPublicKey"');
    }
    let cosePublicKey = new Map();
    if (credentialPublicKey) {
        cosePublicKey = decodeCredentialPublicKey(credentialPublicKey);
    }
    else if (x509Certificate) {
        cosePublicKey = convertX509PublicKeyToCOSE(x509Certificate);
    }
    return _verifySignatureInternals.stubThis(verify({
        cosePublicKey,
        signature,
        data,
        shaHashOverride: hashAlgorithm,
    }));
}
/**
 * Make it possible to stub the return value during testing
 * @ignore Don't include this in docs output
 */
const _verifySignatureInternals = {
    stubThis: (value) => value,
};

async function verifyOKP(opts) {
    const { cosePublicKey, signature, data } = opts;
    const WebCrypto = await getWebCrypto();
    const alg = cosePublicKey.get(COSEKEYS.alg);
    const crv = cosePublicKey.get(COSEKEYS.crv);
    const x = cosePublicKey.get(COSEKEYS.x);
    if (!alg) {
        throw new Error('Public key was missing alg (OKP)');
    }
    if (!isCOSEAlg(alg)) {
        throw new Error(`Public key had invalid alg ${alg} (OKP)`);
    }
    if (!crv) {
        throw new Error('Public key was missing crv (OKP)');
    }
    if (!x) {
        throw new Error('Public key was missing x (OKP)');
    }
    // Pulled key import steps from here:
    // https://wicg.github.io/webcrypto-secure-curves/#ed25519-operations
    let _crv;
    if (crv === COSECRV.ED25519) {
        _crv = 'Ed25519';
    }
    else {
        throw new Error(`Unexpected COSE crv value of ${crv} (OKP)`);
    }
    const keyData = {
        kty: 'OKP',
        crv: _crv,
        alg: 'EdDSA',
        x: fromBuffer(x),
        ext: false,
    };
    const keyAlgorithm = {
        name: _crv,
        namedCurve: _crv,
    };
    const key = await importKey({
        keyData,
        algorithm: keyAlgorithm,
    });
    const verifyAlgorithm = {
        name: _crv,
    };
    return WebCrypto.subtle.verify(verifyAlgorithm, key, signature, data);
}

/**
 * In WebAuthn, EC2 signatures are wrapped in ASN.1 structure so we need to peel r and s apart.
 *
 * See https://www.w3.org/TR/webauthn-2/#sctn-signature-attestation-types
 */
function unwrapEC2Signature(signature, crv) {
    const parsedSignature = AsnParser.parse(signature, ECDSASigValue);
    const rBytes = new Uint8Array(parsedSignature.r);
    const sBytes = new Uint8Array(parsedSignature.s);
    const componentLength = getSignatureComponentLength(crv);
    const rNormalizedBytes = toNormalizedBytes(rBytes, componentLength);
    const sNormalizedBytes = toNormalizedBytes(sBytes, componentLength);
    const finalSignature = concat([
        rNormalizedBytes,
        sNormalizedBytes,
    ]);
    return finalSignature;
}
/**
 * The SubtleCrypto Web Crypto API expects ECDSA signatures with `r` and `s` values to be encoded
 * to a specific length depending on the order of the curve. This function returns the expected
 * byte-length for each of the `r` and `s` signature components.
 *
 * See <https://www.w3.org/TR/WebCryptoAPI/#ecdsa-operations>
 */
function getSignatureComponentLength(crv) {
    switch (crv) {
        case COSECRV.P256:
            return 32;
        case COSECRV.P384:
            return 48;
        case COSECRV.P521:
            return 66;
        default:
            throw new Error(`Unexpected COSE crv value of ${crv} (EC2)`);
    }
}
/**
 * Converts the ASN.1 integer representation to bytes of a specific length `n`.
 *
 * DER encodes integers as big-endian byte arrays, with as small as possible representation and
 * requires a leading `0` byte to disambiguate between negative and positive numbers. This means
 * that `r` and `s` can potentially not be the expected byte-length that is needed by the
 * SubtleCrypto Web Crypto API: if there are leading `0`s it can be shorter than expected, and if
 * it has a leading `1` bit, it can be one byte longer.
 *
 * See <https://www.itu.int/rec/T-REC-X.690-202102-I/en>
 * See <https://www.w3.org/TR/WebCryptoAPI/#ecdsa-operations>
 */
function toNormalizedBytes(bytes, componentLength) {
    let normalizedBytes;
    if (bytes.length < componentLength) {
        // In case the bytes are shorter than expected, we need to pad it with leading `0`s.
        normalizedBytes = new Uint8Array(componentLength);
        normalizedBytes.set(bytes, componentLength - bytes.length);
    }
    else if (bytes.length === componentLength) {
        normalizedBytes = bytes;
    }
    else if (bytes.length === componentLength + 1 && bytes[0] === 0 && (bytes[1] & 0x80) === 0x80) {
        // The bytes contain a leading `0` to encode that the integer is positive. This leading `0`
        // needs to be removed for compatibility with the SubtleCrypto Web Crypto API.
        normalizedBytes = bytes.subarray(1);
    }
    else {
        throw new Error(`Invalid signature component length ${bytes.length}, expected ${componentLength}`);
    }
    return normalizedBytes;
}

/**
 * Verify signatures with their public key. Supports EC2 and RSA public keys.
 */
function verify(opts) {
    const { cosePublicKey, signature, data, shaHashOverride } = opts;
    if (isCOSEPublicKeyEC2(cosePublicKey)) {
        const crv = cosePublicKey.get(COSEKEYS.crv);
        if (!isCOSECrv(crv)) {
            throw new Error(`unknown COSE curve ${crv}`);
        }
        const unwrappedSignature = unwrapEC2Signature(signature, crv);
        return verifyEC2({
            cosePublicKey,
            signature: unwrappedSignature,
            data,
            shaHashOverride,
        });
    }
    else if (isCOSEPublicKeyRSA(cosePublicKey)) {
        return verifyRSA({ cosePublicKey, signature, data, shaHashOverride });
    }
    else if (isCOSEPublicKeyOKP(cosePublicKey)) {
        return verifyOKP({ cosePublicKey, signature, data });
    }
    const kty = cosePublicKey.get(COSEKEYS.kty);
    throw new Error(`Signature verification with public key of kty ${kty} is not supported by this method`);
}

/**
 * A runtime-agnostic collection of methods for working with Uint8Arrays
 * @module
 */
/**
 * Make sure two Uint8Arrays are deeply equivalent
 */
function areEqual(array1, array2) {
    if (array1.length != array2.length) {
        return false;
    }
    return array1.every((val, i) => val === array2[i]);
}
/**
 * Convert a Uint8Array to Hexadecimal.
 *
 * A replacement for `Buffer.toString('hex')`
 */
function toHex(array) {
    const hexParts = Array.from(array, (i) => i.toString(16).padStart(2, '0'));
    // adce000235bcc60a648b0b25f1f05503
    return hexParts.join('');
}
/**
 * Convert a hexadecimal string to isoUint8Array.
 *
 * A replacement for `Buffer.from('...', 'hex')`
 */
function fromHex(hex) {
    const isValid = hex.length !== 0 && hex.length % 2 === 0 &&
        !/[^a-fA-F0-9]/u.test(hex);
    if (!isValid) {
        throw new Error('Invalid hex string');
    }
    const byteStrings = hex.match(/.{1,2}/g) ?? [];
    return Uint8Array.from(byteStrings.map((byte) => parseInt(byte, 16)));
}
/**
 * Combine multiple Uint8Arrays into a single Uint8Array
 */
function concat(arrays) {
    let pointer = 0;
    const totalLength = arrays.reduce((prev, curr) => prev + curr.length, 0);
    const toReturn = new Uint8Array(totalLength);
    arrays.forEach((arr) => {
        toReturn.set(arr, pointer);
        pointer += arr.length;
    });
    return toReturn;
}
/**
 * Convert bytes into a UTF-8 string
 */
function toUTF8String(array) {
    const decoder = new globalThis.TextDecoder('utf-8');
    return decoder.decode(array);
}
/**
 * Convert a UTF-8 string back into bytes
 */
function fromUTF8String(utf8String) {
    const encoder = new globalThis.TextEncoder();
    return encoder.encode(utf8String);
}
/**
 * Convert an ASCII string to Uint8Array
 */
function fromASCIIString(value) {
    return Uint8Array.from(value.split('').map((x) => x.charCodeAt(0)));
}
/**
 * Prepare a DataView we can slice our way around in as we parse the bytes in a Uint8Array
 */
function toDataView(array) {
    return new DataView(array.buffer, array.byteOffset, array.length);
}

/**
 * Generate a suitably random value to be used as an attestation or assertion challenge
 */
async function generateChallenge() {
    /**
     * WebAuthn spec says that 16 bytes is a good minimum:
     *
     * "In order to prevent replay attacks, the challenges MUST contain enough entropy to make
     * guessing them infeasible. Challenges SHOULD therefore be at least 16 bytes long."
     *
     * Just in case, let's double it
     */
    const challenge = new Uint8Array(32);
    await getRandomValues(challenge);
    return _generateChallengeInternals.stubThis(challenge);
}
/**
 * Make it possible to stub the return value during testing
 * @ignore Don't include this in docs output
 */
const _generateChallengeInternals = {
    stubThis: (value) => value,
};

/**
 * Supported crypto algo identifiers
 * See https://w3c.github.io/webauthn/#sctn-alg-identifier
 * and https://www.iana.org/assignments/cose/cose.xhtml#algorithms
 */
const supportedCOSEAlgorithmIdentifiers = [
    // EdDSA (In first position to encourage authenticators to use this over ES256)
    -8,
    // ECDSA w/ SHA-256
    -7,
    // ECDSA w/ SHA-512
    -36,
    // RSASSA-PSS w/ SHA-256
    -37,
    // RSASSA-PSS w/ SHA-384
    -38,
    // RSASSA-PSS w/ SHA-512
    -39,
    // RSASSA-PKCS1-v1_5 w/ SHA-256
    -257,
    // RSASSA-PKCS1-v1_5 w/ SHA-384
    -258,
    // RSASSA-PKCS1-v1_5 w/ SHA-512
    -259,
    // RSASSA-PKCS1-v1_5 w/ SHA-1 (Deprecated; here for legacy support)
    -65535,
];
/**
 * Set up some default authenticator selection options as per the latest spec:
 * https://www.w3.org/TR/webauthn-2/#dictdef-authenticatorselectioncriteria
 *
 * Helps with some older platforms (e.g. Android 7.0 Nougat) that may not be aware of these
 * defaults.
 */
const defaultAuthenticatorSelection = {
    residentKey: 'preferred',
    userVerification: 'preferred',
};
/**
 * Use the most commonly-supported algorithms
 * See the following:
 *   - https://www.iana.org/assignments/cose/cose.xhtml#algorithms
 *   - https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-pubkeycredparams
 */
const defaultSupportedAlgorithmIDs = [-8, -7, -257];
/**
 * Prepare a value to pass into navigator.credentials.create(...) for authenticator registration
 *
 * **Options:**
 *
 * @param rpName - User-visible, "friendly" website/service name
 * @param rpID - Valid domain name (after `https://`)
 * @param userName - User's website-specific username (email, etc...)
 * @param userID **(Optional)** - User's website-specific unique ID. Defaults to generating a random identifier
 * @param challenge **(Optional)** - Random value the authenticator needs to sign and pass back. Defaults to generating a random value
 * @param userDisplayName **(Optional)** - User's actual name. Defaults to `""`
 * @param timeout **(Optional)** - How long (in ms) the user can take to complete attestation. Defaults to `60000`
 * @param attestationType **(Optional)** - Specific attestation statement. Defaults to `"none"`
 * @param excludeCredentials **(Optional)** - Authenticators registered by the user so the user can't register the same credential multiple times. Defaults to `[]`
 * @param authenticatorSelection **(Optional)** - Advanced criteria for restricting the types of authenticators that may be used. Defaults to `{ residentKey: 'preferred', userVerification: 'preferred' }`
 * @param extensions **(Optional)** - Additional plugins the authenticator or browser should use during attestation
 * @param supportedAlgorithmIDs **(Optional)** - Array of numeric COSE algorithm identifiers supported for attestation by this RP. See https://www.iana.org/assignments/cose/cose.xhtml#algorithms. Defaults to `[-8, -7, -257]`
 * @param preferredAuthenticatorType **(Optional)** - Encourage the browser to prompt the user to register a specific type of authenticator
 */
async function generateRegistrationOptions(options) {
    const { rpName, rpID, userName, userID, challenge = await generateChallenge(), userDisplayName = '', timeout = 60000, attestationType = 'none', excludeCredentials = [], authenticatorSelection = defaultAuthenticatorSelection, extensions, supportedAlgorithmIDs = defaultSupportedAlgorithmIDs, preferredAuthenticatorType, } = options;
    /**
     * Prepare pubKeyCredParams from the array of algorithm ID's
     */
    const pubKeyCredParams = supportedAlgorithmIDs.map((id) => ({
        alg: id,
        type: 'public-key',
    }));
    /**
     * Capture some of the nuances of how `residentKey` and `requireResidentKey` how either is set
     * depending on when either is defined in the options
     */
    if (authenticatorSelection.residentKey === undefined) {
        /**
         * `residentKey`: "If no value is given then the effective value is `required` if
         * requireResidentKey is true or `discouraged` if it is false or absent."
         *
         * See https://www.w3.org/TR/webauthn-2/#dom-authenticatorselectioncriteria-residentkey
         */
        if (authenticatorSelection.requireResidentKey) {
            authenticatorSelection.residentKey = 'required';
        }
    }
    else {
        /**
         * `requireResidentKey`: "Relying Parties SHOULD set it to true if, and only if, residentKey is
         * set to "required""
         *
         * Spec says this property defaults to `false` so we should still be okay to assign `false` too
         *
         * See https://www.w3.org/TR/webauthn-2/#dom-authenticatorselectioncriteria-requireresidentkey
         */
        authenticatorSelection.requireResidentKey = authenticatorSelection.residentKey === 'required';
    }
    /**
     * Preserve ability to specify `string` values for challenges
     */
    let _challenge = challenge;
    if (typeof _challenge === 'string') {
        _challenge = fromUTF8String(_challenge);
    }
    /**
     * Explicitly disallow use of strings for userID anymore because `isoBase64URL.fromBuffer()` below
     * will return an empty string if one gets through!
     */
    if (typeof userID === 'string') {
        throw new Error(`String values for \`userID\` are no longer supported. See https://simplewebauthn.dev/docs/advanced/server/custom-user-ids`);
    }
    /**
     * Generate a user ID if one is not provided
     */
    let _userID = userID;
    if (!_userID) {
        _userID = await generateUserID();
    }
    /**
     * Map authenticator preference to hints. Map to authenticatorAttachment as well for
     * backwards-compatibility.
     */
    const hints = [];
    if (preferredAuthenticatorType) {
        if (preferredAuthenticatorType === 'securityKey') {
            hints.push('security-key');
            authenticatorSelection.authenticatorAttachment = 'cross-platform';
        }
        else if (preferredAuthenticatorType === 'localDevice') {
            hints.push('client-device');
            authenticatorSelection.authenticatorAttachment = 'platform';
        }
        else if (preferredAuthenticatorType === 'remoteDevice') {
            hints.push('hybrid');
            authenticatorSelection.authenticatorAttachment = 'cross-platform';
        }
    }
    return {
        challenge: fromBuffer(_challenge),
        rp: {
            name: rpName,
            id: rpID,
        },
        user: {
            id: fromBuffer(_userID),
            name: userName,
            displayName: userDisplayName,
        },
        pubKeyCredParams,
        timeout,
        attestation: attestationType,
        excludeCredentials: excludeCredentials.map((cred) => {
            if (!isBase64URL(cred.id)) {
                throw new Error(`excludeCredential id "${cred.id}" is not a valid base64url string`);
            }
            return {
                ...cred,
                id: trimPadding(cred.id),
                type: 'public-key',
            };
        }),
        authenticatorSelection,
        extensions: {
            ...extensions,
            credProps: true,
        },
        hints,
    };
}

/**
 * Make sense of Bits 3 and 4 in authenticator indicating:
 *
 * - Whether the credential can be used on multiple devices
 * - Whether the credential is backed up or not
 *
 * Invalid configurations will raise an `Error`
 */
function parseBackupFlags({ be, bs }) {
    const credentialBackedUp = bs;
    let credentialDeviceType = 'singleDevice';
    if (be) {
        credentialDeviceType = 'multiDevice';
    }
    if (credentialDeviceType === 'singleDevice' && credentialBackedUp) {
        throw new InvalidBackupFlags('Single-device credential indicated that it was backed up, which should be impossible.');
    }
    return { credentialDeviceType, credentialBackedUp };
}
class InvalidBackupFlags extends Error {
    constructor(message) {
        super(message);
        this.name = 'InvalidBackupFlags';
    }
}

/**
 * Go through each expected RP ID and try to find one that matches. Returns the unhashed RP ID
 * that matched the hash in the response.
 *
 * Raises an `UnexpectedRPIDHash` error if no match is found
 */
async function matchExpectedRPID(rpIDHash, expectedRPIDs) {
    try {
        const matchedRPID = await Promise.any(expectedRPIDs.map((expected) => {
            return new Promise((resolve, reject) => {
                toHash(fromASCIIString(expected)).then((expectedRPIDHash) => {
                    if (areEqual(rpIDHash, expectedRPIDHash)) {
                        resolve(expected);
                    }
                    else {
                        reject();
                    }
                });
            });
        }));
        return matchedRPID;
    }
    catch (err) {
        const _err = err;
        // This means no matches were found
        if (_err.name === 'AggregateError') {
            throw new UnexpectedRPIDHash();
        }
        // An unexpected error occurred
        throw err;
    }
}
class UnexpectedRPIDHash extends Error {
    constructor() {
        const message = 'Unexpected RP ID hash';
        super(message);
        this.name = 'UnexpectedRPIDHash';
    }
}

/**
 * GlobalSign Root CA
 *
 * Downloaded from https://pki.goog/roots.pem
 *
 * Valid until 2028-01-28 @ 04:00 PST
 *
 * SHA256 Fingerprint
 * EB:D4:10:40:E4:BB:3E:C7:42:C9:E3:81:D3:1E:F2:A4:1A:48:B6:68:5C:96:E7:CE:F3:C1:DF:6C:D4:33:1C:99
 */
const GlobalSign_Root_CA = `-----BEGIN CERTIFICATE-----
MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG
A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv
b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw
MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i
YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT
aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ
jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp
xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp
1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG
snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ
U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8
9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E
BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B
AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz
yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE
38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP
AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad
DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME
HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==
-----END CERTIFICATE-----
`;

/**
 * Google Hardware Attestation Root 1
 *
 * Downloaded from https://developer.android.com/training/articles/security-key-attestation#root_certificate
 * (first entry)
 *
 * Valid until 2026-05-24 @ 09:28 PST
 *
 * SHA256 Fingerprint
 * C1:98:4A:3E:F4:5C:1E:2A:91:85:51:DE:10:60:3C:86:F7:05:1B:22:49:C4:89:1C:AE:32:30:EA:BD:0C:97:D5
 */
const Google_Hardware_Attestation_Root_1 = `-----BEGIN CERTIFICATE-----
MIIFYDCCA0igAwIBAgIJAOj6GWMU0voYMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV
BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMTYwNTI2MTYyODUyWhcNMjYwNTI0MTYy
ODUyWjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B
AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS
Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7
tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj
nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq
C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ
oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O
JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg
sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi
igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M
RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E
aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um
AGMCAwEAAaOBpjCBozAdBgNVHQ4EFgQUNmHhAHyIBQlRi0RsR/8aTMnqTxIwHwYD
VR0jBBgwFoAUNmHhAHyIBQlRi0RsR/8aTMnqTxIwDwYDVR0TAQH/BAUwAwEB/zAO
BgNVHQ8BAf8EBAMCAYYwQAYDVR0fBDkwNzA1oDOgMYYvaHR0cHM6Ly9hbmRyb2lk
Lmdvb2dsZWFwaXMuY29tL2F0dGVzdGF0aW9uL2NybC8wDQYJKoZIhvcNAQELBQAD
ggIBACDIw41L3KlXG0aMiS//cqrG+EShHUGo8HNsw30W1kJtjn6UBwRM6jnmiwfB
Pb8VA91chb2vssAtX2zbTvqBJ9+LBPGCdw/E53Rbf86qhxKaiAHOjpvAy5Y3m00m
qC0w/Zwvju1twb4vhLaJ5NkUJYsUS7rmJKHHBnETLi8GFqiEsqTWpG/6ibYCv7rY
DBJDcR9W62BW9jfIoBQcxUCUJouMPH25lLNcDc1ssqvC2v7iUgI9LeoM1sNovqPm
QUiG9rHli1vXxzCyaMTjwftkJLkf6724DFhuKug2jITV0QkXvaJWF4nUaHOTNA4u
JU9WDvZLI1j83A+/xnAJUucIv/zGJ1AMH2boHqF8CY16LpsYgBt6tKxxWH00XcyD
CdW2KlBCeqbQPcsFmWyWugxdcekhYsAWyoSf818NUsZdBWBaR/OukXrNLfkQ79Iy
ZohZbvabO/X+MVT3rriAoKc8oE2Uws6DF+60PV7/WIPjNvXySdqspImSN78mflxD
qwLqRBYkA3I75qppLGG9rp7UCdRjxMl8ZDBld+7yvHVgt1cVzJx9xnyGCC23Uaic
MDSXYrB4I4WHXPGjxhZuCuPBLTdOLU8YRvMYdEvYebWHMpvwGCF6bAx3JBpIeOQ1
wDB5y0USicV3YgYGmi+NZfhA4URSh77Yd6uuJOJENRaNVTzk
-----END CERTIFICATE-----
`;
/**
 * Google Hardware Attestation Root 2
 *
 * Downloaded from https://developer.android.com/training/articles/security-key-attestation#root_certificate
 * (second entry)
 *
 * Valid until 2034-11-18 @ 12:37 PST
 *
 * SHA256 Fingerprint
 * 1E:F1:A0:4B:8B:A5:8A:B9:45:89:AC:49:8C:89:82:A7:83:F2:4E:A7:30:7E:01:59:A0:C3:A7:3B:37:7D:87:CC
 */
const Google_Hardware_Attestation_Root_2 = `-----BEGIN CERTIFICATE-----
MIIFHDCCAwSgAwIBAgIJANUP8luj8tazMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV
BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMTkxMTIyMjAzNzU4WhcNMzQxMTE4MjAz
NzU4WjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B
AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS
Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7
tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj
nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq
C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ
oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O
JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg
sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi
igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M
RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E
aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um
AGMCAwEAAaNjMGEwHQYDVR0OBBYEFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMB8GA1Ud
IwQYMBaAFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYD
VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQBOMaBc8oumXb2voc7XCWnu
XKhBBK3e2KMGz39t7lA3XXRe2ZLLAkLM5y3J7tURkf5a1SutfdOyXAmeE6SRo83U
h6WszodmMkxK5GM4JGrnt4pBisu5igXEydaW7qq2CdC6DOGjG+mEkN8/TA6p3cno
L/sPyz6evdjLlSeJ8rFBH6xWyIZCbrcpYEJzXaUOEaxxXxgYz5/cTiVKN2M1G2ok
QBUIYSY6bjEL4aUN5cfo7ogP3UvliEo3Eo0YgwuzR2v0KR6C1cZqZJSTnghIC/vA
D32KdNQ+c3N+vl2OTsUVMC1GiWkngNx1OO1+kXW+YTnnTUOtOIswUP/Vqd5SYgAI
mMAfY8U9/iIgkQj6T2W6FsScy94IN9fFhE1UtzmLoBIuUFsVXJMTz+Jucth+IqoW
Fua9v1R93/k98p41pjtFX+H8DslVgfP097vju4KDlqN64xV1grw3ZLl4CiOe/A91
oeLm2UHOq6wn3esB4r2EIQKb6jTVGu5sYCcdWpXr0AUVqcABPdgL+H7qJguBw09o
jm6xNIrw2OocrDKsudk/okr/AwqEyPKw9WnMlQgLIKw1rODG2NvU9oR3GVGdMkUB
ZutL8VuFkERQGt6vQ2OCw0sV47VMkuYbacK/xyZFiRcrPJPb41zgbQj9XAEyLKCH
ex0SdDrx+tWUDqG8At2JHA==
-----END CERTIFICATE-----
`;
/**
 * Google Hardware Attestation Root 3
 *
 * Downloaded from https://developer.android.com/training/articles/security-key-attestation#root_certificate
 * (third entry)
 *
 * Valid until 2036-11-13 @ 15:10 PST
 *
 * SHA256 Fingerprint
 * AB:66:41:17:8A:36:E1:79:AA:0C:1C:DD:DF:9A:16:EB:45:FA:20:94:3E:2B:8C:D7:C7:C0:5C:26:CF:8B:48:7A
 */
const Google_Hardware_Attestation_Root_3 = `
-----BEGIN CERTIFICATE-----
MIIFHDCCAwSgAwIBAgIJAMNrfES5rhgxMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV
BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMjExMTE3MjMxMDQyWhcNMzYxMTEzMjMx
MDQyWjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B
AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS
Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7
tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj
nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq
C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ
oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O
JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg
sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi
igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M
RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E
aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um
AGMCAwEAAaNjMGEwHQYDVR0OBBYEFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMB8GA1Ud
IwQYMBaAFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYD
VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQBTNNZe5cuf8oiq+jV0itTG
zWVhSTjOBEk2FQvh11J3o3lna0o7rd8RFHnN00q4hi6TapFhh4qaw/iG6Xg+xOan
63niLWIC5GOPFgPeYXM9+nBb3zZzC8ABypYuCusWCmt6Tn3+Pjbz3MTVhRGXuT/T
QH4KGFY4PhvzAyXwdjTOCXID+aHud4RLcSySr0Fq/L+R8TWalvM1wJJPhyRjqRCJ
erGtfBagiALzvhnmY7U1qFcS0NCnKjoO7oFedKdWlZz0YAfu3aGCJd4KHT0MsGiL
Zez9WP81xYSrKMNEsDK+zK5fVzw6jA7cxmpXcARTnmAuGUeI7VVDhDzKeVOctf3a
0qQLwC+d0+xrETZ4r2fRGNw2YEs2W8Qj6oDcfPvq9JySe7pJ6wcHnl5EZ0lwc4xH
7Y4Dx9RA1JlfooLMw3tOdJZH0enxPXaydfAD3YifeZpFaUzicHeLzVJLt9dvGB0b
HQLE4+EqKFgOZv2EoP686DQqbVS1u+9k0p2xbMA105TBIk7npraa8VM0fnrRKi7w
lZKwdH+aNAyhbXRW9xsnODJ+g8eF452zvbiKKngEKirK5LGieoXBX7tZ9D1GNBH2
Ob3bKOwwIWdEFle/YF/h6zWgdeoaNGDqVBrLr2+0DtWoiB1aDEjLWl9FmyIUyUm7
mD/vFDkzF+wm7cyWpQpCVQ==
-----END CERTIFICATE-----
`;
/**
 * Google Hardware Attestation Root 4
 *
 * Downloaded from https://developer.android.com/training/articles/security-key-attestation#root_certificate
 * (fourth entry)
 *
 * Valid until 2042-03-15 @ 11:07 PDT
 *
 * SHA256 Fingerprint
 * CE:DB:1C:B6:DC:89:6A:E5:EC:79:73:48:BC:E9:28:67:53:C2:B3:8E:E7:1C:E0:FB:E3:4A:9A:12:48:80:0D:FC
 */
const Google_Hardware_Attestation_Root_4 = `
-----BEGIN CERTIFICATE-----
MIIFHDCCAwSgAwIBAgIJAPHBcqaZ6vUdMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV
BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMjIwMzIwMTgwNzQ4WhcNNDIwMzE1MTgw
NzQ4WjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B
AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS
Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7
tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj
nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq
C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ
oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O
JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg
sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi
igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M
RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E
aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um
AGMCAwEAAaNjMGEwHQYDVR0OBBYEFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMB8GA1Ud
IwQYMBaAFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYD
VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQB8cMqTllHc8U+qCrOlg3H7
174lmaCsbo/bJ0C17JEgMLb4kvrqsXZs01U3mB/qABg/1t5Pd5AORHARs1hhqGIC
W/nKMav574f9rZN4PC2ZlufGXb7sIdJpGiO9ctRhiLuYuly10JccUZGEHpHSYM2G
tkgYbZba6lsCPYAAP83cyDV+1aOkTf1RCp/lM0PKvmxYN10RYsK631jrleGdcdkx
oSK//mSQbgcWnmAEZrzHoF1/0gso1HZgIn0YLzVhLSA/iXCX4QT2h3J5z3znluKG
1nv8NQdxei2DIIhASWfu804CA96cQKTTlaae2fweqXjdN1/v2nqOhngNyz1361mF
mr4XmaKH/ItTwOe72NI9ZcwS1lVaCvsIkTDCEXdm9rCNPAY10iTunIHFXRh+7KPz
lHGewCq/8TOohBRn0/NNfh7uRslOSZ/xKbN9tMBtw37Z8d2vvnXq/YWdsm1+JLVw
n6yYD/yacNJBlwpddla8eaVMjsF6nBnIgQOf9zKSe06nSTqvgwUHosgOECZJZ1Eu
zbH4yswbt02tKtKEFhx+v+OTge/06V+jGsqTWLsfrOCNLuA8H++z+pUENmpqnnHo
vaI47gC+TNpkgYGkkBT6B/m/U01BuOBBTzhIlMEZq9qkDWuM2cA5kW5V3FJUcfHn
w1IdYIg2Wxg7yHcQZemFQg==
-----END CERTIFICATE-----
`;

/**
 * Apple WebAuthn Root CA
 *
 * Downloaded from https://www.apple.com/certificateauthority/Apple_WebAuthn_Root_CA.pem
 *
 * Valid until 2045-03-14 @ 17:00 PST
 *
 * SHA256 Fingerprint
 * 09:15:DD:5C:07:A2:8D:B5:49:D1:F6:77:BB:5A:75:D4:BF:BE:95:61:A7:73:42:43:27:76:2E:9E:02:F9:BB:29
 */
const Apple_WebAuthn_Root_CA = `-----BEGIN CERTIFICATE-----
MIICEjCCAZmgAwIBAgIQaB0BbHo84wIlpQGUKEdXcTAKBggqhkjOPQQDAzBLMR8w
HQYDVQQDDBZBcHBsZSBXZWJBdXRobiBSb290IENBMRMwEQYDVQQKDApBcHBsZSBJ
bmMuMRMwEQYDVQQIDApDYWxpZm9ybmlhMB4XDTIwMDMxODE4MjEzMloXDTQ1MDMx
NTAwMDAwMFowSzEfMB0GA1UEAwwWQXBwbGUgV2ViQXV0aG4gUm9vdCBDQTETMBEG
A1UECgwKQXBwbGUgSW5jLjETMBEGA1UECAwKQ2FsaWZvcm5pYTB2MBAGByqGSM49
AgEGBSuBBAAiA2IABCJCQ2pTVhzjl4Wo6IhHtMSAzO2cv+H9DQKev3//fG59G11k
xu9eI0/7o6V5uShBpe1u6l6mS19S1FEh6yGljnZAJ+2GNP1mi/YK2kSXIuTHjxA/
pcoRf7XkOtO4o1qlcaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUJtdk
2cV4wlpn0afeaxLQG2PxxtcwDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2cA
MGQCMFrZ+9DsJ1PW9hfNdBywZDsWDbWFp28it1d/5w2RPkRX3Bbn/UbDTNLx7Jr3
jAGGiQIwHFj+dJZYUJR786osByBelJYsVZd2GbHQu209b5RCmGQ21gpSAk9QZW4B
1bWeT0vT
-----END CERTIFICATE-----
`;

/**
 * GlobalSign Root CA - R3
 *
 * Downloaded from https://valid.r3.roots.globalsign.com/
 *
 * Valid until 2029-03-18 @ 00:00 PST
 *
 * SHA256 Fingerprint
 * CB:B5:22:D7:B7:F1:27:AD:6A:01:13:86:5B:DF:1C:D4:10:2E:7D:07:59:AF:63:5A:7C:F4:72:0D:C9:63:C5:3B
 */
const GlobalSign_Root_CA_R3 = `-----BEGIN CERTIFICATE-----
MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4G
A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNp
Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4
MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEG
A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI
hvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWtiHL8
RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsT
gHeMCOFJ0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmm
KPZpO/bLyCiR5Z2KYVc3rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zd
QQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjlOCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZ
XriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2xmmFghcCAwEAAaNCMEAw
DgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI/wS3+o
LkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZU
RUm7lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMp
jjM5RcOO5LlXbKr8EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK
6fBdRoyV3XpYKBovHd7NADdBj+1EbddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQX
mcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18YIvDQVETI53O9zJrlAGomecs
Mx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH
WD9f
-----END CERTIFICATE-----
 `;

class BaseSettingsService {
    constructor() {
        // Certificates are stored as PEM-formatted strings
        Object.defineProperty(this, "pemCertificates", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
        this.pemCertificates = new Map();
    }
    setRootCertificates(opts) {
        const { identifier, certificates } = opts;
        const newCertificates = [];
        for (const cert of certificates) {
            if (cert instanceof Uint8Array) {
                newCertificates.push(convertCertBufferToPEM(cert));
            }
            else {
                newCertificates.push(cert);
            }
        }
        this.pemCertificates.set(identifier, newCertificates);
    }
    getRootCertificates(opts) {
        const { identifier } = opts;
        return this.pemCertificates.get(identifier) ?? [];
    }
}
/**
 * A basic service for specifying acceptable root certificates for all supported attestation
 * statement formats.
 *
 * In addition, default root certificates are included for the following statement formats:
 *
 * - `'android-key'`
 * - `'android-safetynet'`
 * - `'apple'`
 * - `'android-mds'`
 *
 * These can be overwritten as needed by setting alternative root certificates for their format
 * identifier using `setRootCertificates()`.
 */
const SettingsService = new BaseSettingsService();
// Initialize default certificates
SettingsService.setRootCertificates({
    identifier: 'android-key',
    certificates: [
        Google_Hardware_Attestation_Root_1,
        Google_Hardware_Attestation_Root_2,
        Google_Hardware_Attestation_Root_3,
        Google_Hardware_Attestation_Root_4,
    ],
});
SettingsService.setRootCertificates({
    identifier: 'android-safetynet',
    certificates: [GlobalSign_Root_CA],
});
SettingsService.setRootCertificates({
    identifier: 'apple',
    certificates: [Apple_WebAuthn_Root_CA],
});
SettingsService.setRootCertificates({
    identifier: 'mds',
    certificates: [GlobalSign_Root_CA_R3],
});

/**
 * Verify an attestation response with fmt 'fido-u2f'
 */
async function verifyAttestationFIDOU2F(options) {
    const { attStmt, clientDataHash, rpIdHash, credentialID, credentialPublicKey, aaguid, rootCertificates, } = options;
    const reservedByte = Uint8Array.from([0x00]);
    const publicKey = convertCOSEtoPKCS(credentialPublicKey);
    const signatureBase = concat([
        reservedByte,
        rpIdHash,
        clientDataHash,
        credentialID,
        publicKey,
    ]);
    const sig = attStmt.get('sig');
    const x5c = attStmt.get('x5c');
    if (!x5c) {
        throw new Error('No attestation certificate provided in attestation statement (FIDOU2F)');
    }
    if (!sig) {
        throw new Error('No attestation signature provided in attestation statement (FIDOU2F)');
    }
    // FIDO spec says that aaguid _must_ equal 0x00 here to be legit
    const aaguidToHex = Number.parseInt(toHex(aaguid), 16);
    if (aaguidToHex !== 0x00) {
        throw new Error(`AAGUID "${aaguidToHex}" was not expected value`);
    }
    try {
        // Try validating the certificate path using the root certificates set via SettingsService
        await validateCertificatePath(x5c.map(convertCertBufferToPEM), rootCertificates);
    }
    catch (err) {
        const _err = err;
        throw new Error(`${_err.message} (FIDOU2F)`);
    }
    return verifySignature({
        signature: sig,
        data: signatureBase,
        x509Certificate: x5c[0],
        hashAlgorithm: COSEALG.ES256,
    });
}

/**
 * Attestation Certificate Extension OID: `id-fido-gen-ce-aaguid`
 *
 * Sourced from https://fidoalliance.org/specs/fido-v2.0-ps-20150904/fido-key-attestation-v2.0-ps-20150904.html#verifying-an-attestation-statement
 */
const id_fido_gen_ce_aaguid = '1.3.6.1.4.1.45724.1.1.4';
/**
 * Look for the id-fido-gen-ce-aaguid certificate extension. If it's present then check it against
 * the attestation statement AAGUID.
 */
function validateExtFIDOGenCEAAGUID(certExtensions, aaguid) {
    // The certificate had no extensions so there's nothing to validate
    if (!certExtensions) {
        return true;
    }
    const extFIDOGenCEAAGUID = certExtensions.find((ext) => ext.extnID === id_fido_gen_ce_aaguid);
    // The extension isn't present so there's nothing to validate
    if (!extFIDOGenCEAAGUID) {
        return true;
    }
    // Parse the extension value
    const parsedExtFIDOGenCEAAGUID = AsnParser.parse(extFIDOGenCEAAGUID.extnValue, OctetString);
    const extValue = new Uint8Array(parsedExtFIDOGenCEAAGUID.buffer);
    // Compare the two values
    const aaguidAndExtAreEqual = areEqual(aaguid, extValue);
    if (!aaguidAndExtAreEqual) {
        const _debugExtHex = toHex(extValue);
        const _debugAAGUIDHex = toHex(aaguid);
        throw new Error(`Certificate extension id-fido-gen-ce-aaguid (${id_fido_gen_ce_aaguid}) value of "${_debugExtHex}" was present but not equal to attestation statement AAGUID value of "${_debugAAGUIDHex}"`);
    }
    return true;
}

// const defaultLogger = debug('SimpleWebAuthn');
/**
 * Generate an instance of a `debug` logger that extends off of the "simplewebauthn" namespace for
 * consistent naming.
 *
 * See https://www.npmjs.com/package/debug for information on how to control logging output when
 * using @simplewebauthn/server
 *
 * Example:
 *
 * ```
 * const log = getLogger('mds');
 * log('hello'); // simplewebauthn:mds hello +0ms
 * ```
 */
function getLogger(_name) {
    // This is a noop for now while I search for a better debug logger technique
    return (_message, ..._rest) => { };
}

/**
 * Take a certificate in PEM format and convert it to bytes
 */
function convertPEMToBytes(pem) {
    const certBase64 = pem
        .replace('-----BEGIN CERTIFICATE-----', '')
        .replace('-----END CERTIFICATE-----', '')
        .replace(/[\n ]/g, '');
    return toBuffer(certBase64, 'base64');
}

/**
 * Process a JWT into Javascript-friendly data structures
 */
function parseJWT(jwt) {
    const parts = jwt.split('.');
    return [
        JSON.parse(toUTF8String$1(parts[0])),
        JSON.parse(toUTF8String$1(parts[1])),
        parts[2],
    ];
}

/**
 * Lightweight verification for FIDO MDS JWTs. Supports use of EC2 and RSA.
 *
 * If this ever needs to support more JWS algorithms, here's the list of them:
 *
 * https://www.rfc-editor.org/rfc/rfc7518.html#section-3.1
 *
 * (Pulled from https://www.rfc-editor.org/rfc/rfc7515#section-4.1.1)
 */
function verifyJWT(jwt, leafCert) {
    const [header, payload, signature] = jwt.split('.');
    const certCOSE = convertX509PublicKeyToCOSE(leafCert);
    const data = fromUTF8String(`${header}.${payload}`);
    const signatureBytes = toBuffer(signature);
    if (isCOSEPublicKeyEC2(certCOSE)) {
        return verifyEC2({
            data,
            signature: signatureBytes,
            cosePublicKey: certCOSE,
            shaHashOverride: COSEALG.ES256,
        });
    }
    else if (isCOSEPublicKeyRSA(certCOSE)) {
        return verifyRSA({
            data,
            signature: signatureBytes,
            cosePublicKey: certCOSE,
        });
    }
    const kty = certCOSE.get(COSEKEYS.kty);
    throw new Error(`JWT verification with public key of kty ${kty} is not supported by this method`);
}

const defaultURLMDS = 'https://mds.fidoalliance.org/'; // v3
var SERVICE_STATE;
(function (SERVICE_STATE) {
    SERVICE_STATE[SERVICE_STATE["DISABLED"] = 0] = "DISABLED";
    SERVICE_STATE[SERVICE_STATE["REFRESHING"] = 1] = "REFRESHING";
    SERVICE_STATE[SERVICE_STATE["READY"] = 2] = "READY";
})(SERVICE_STATE || (SERVICE_STATE = {}));
const log = getLogger();
/**
 * An implementation of `MetadataService` that can download and parse BLOBs, and support on-demand
 * requesting and caching of individual metadata statements.
 *
 * https://fidoalliance.org/metadata/
 */
class BaseMetadataService {
    constructor() {
        Object.defineProperty(this, "mdsCache", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: {}
        });
        Object.defineProperty(this, "statementCache", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: {}
        });
        Object.defineProperty(this, "state", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: SERVICE_STATE.DISABLED
        });
        Object.defineProperty(this, "verificationMode", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: 'strict'
        });
    }
    async initialize(opts = {}) {
        const { mdsServers = [defaultURLMDS], statements, verificationMode } = opts;
        this.setState(SERVICE_STATE.REFRESHING);
        // If metadata statements are provided, load them into the cache first
        if (statements?.length) {
            let statementsAdded = 0;
            statements.forEach((statement) => {
                // Only cache statements that are for FIDO2-compatible authenticators
                if (statement.aaguid) {
                    this.statementCache[statement.aaguid] = {
                        entry: {
                            metadataStatement: statement,
                            statusReports: [],
                            timeOfLastStatusChange: '1970-01-01',
                        },
                        url: '',
                    };
                    statementsAdded += 1;
                }
            });
            log(`Cached ${statementsAdded} local statements`);
        }
        // If MDS servers are provided, then process them and add their statements to the cache
        if (mdsServers?.length) {
            // Get a current count so we know how many new statements we've added from MDS servers
            const currentCacheCount = Object.keys(this.statementCache).length;
            let numServers = mdsServers.length;
            for (const url of mdsServers) {
                try {
                    await this.downloadBlob({
                        url,
                        no: 0,
                        nextUpdate: new Date(0),
                    });
                }
                catch (err) {
                    // Notify of the error and move on
                    log(`Could not download BLOB from ${url}:`, err);
                    numServers -= 1;
                }
            }
            // Calculate the difference to get the total number of new statements we successfully added
            const newCacheCount = Object.keys(this.statementCache).length;
            const cacheDiff = newCacheCount - currentCacheCount;
            log(`Cached ${cacheDiff} statements from ${numServers} metadata server(s)`);
        }
        if (verificationMode) {
            this.verificationMode = verificationMode;
        }
        this.setState(SERVICE_STATE.READY);
    }
    async getStatement(aaguid) {
        if (this.state === SERVICE_STATE.DISABLED) {
            return;
        }
        if (!aaguid) {
            return;
        }
        if (aaguid instanceof Uint8Array) {
            aaguid = convertAAGUIDToString(aaguid);
        }
        // If a cache refresh is in progress then pause this until the service is ready
        await this.pauseUntilReady();
        // Try to grab a cached statement
        const cachedStatement = this.statementCache[aaguid];
        if (!cachedStatement) {
            if (this.verificationMode === 'strict') {
                // FIDO conformance requires RP's to only support registered AAGUID's
                throw new Error(`No metadata statement found for aaguid "${aaguid}"`);
            }
            // Allow registration verification to continue without using metadata
            return;
        }
        // If the statement points to an MDS API, check the MDS' nextUpdate to see if we need to refresh
        if (cachedStatement.url) {
            const mds = this.mdsCache[cachedStatement.url];
            const now = new Date();
            if (now > mds.nextUpdate) {
                try {
                    this.setState(SERVICE_STATE.REFRESHING);
                    await this.downloadBlob(mds);
                }
                finally {
                    this.setState(SERVICE_STATE.READY);
                }
            }
        }
        const { entry } = cachedStatement;
        // Check to see if the this aaguid has a status report with a "compromised" status
        for (const report of entry.statusReports) {
            const { status } = report;
            if (status === 'USER_VERIFICATION_BYPASS' ||
                status === 'ATTESTATION_KEY_COMPROMISE' ||
                status === 'USER_KEY_REMOTE_COMPROMISE' ||
                status === 'USER_KEY_PHYSICAL_COMPROMISE') {
                throw new Error(`Detected compromised aaguid "${aaguid}"`);
            }
        }
        return entry.metadataStatement;
    }
    /**
     * Download and process the latest BLOB from MDS
     */
    async downloadBlob(mds) {
        const { url, no } = mds;
        // Get latest "BLOB" (FIDO's terminology, not mine)
        const resp = await fetch$1(url);
        const data = await resp.text();
        // Parse the JWT
        const parsedJWT = parseJWT(data);
        const header = parsedJWT[0];
        const payload = parsedJWT[1];
        if (payload.no <= no) {
            // From FIDO MDS docs: "also ignore the file if its number (no) is less or equal to the
            // number of the last BLOB cached locally."
            throw new Error(`Latest BLOB no. "${payload.no}" is not greater than previous ${no}`);
        }
        const headerCertsPEM = header.x5c.map(convertCertBufferToPEM);
        try {
            // Validate the certificate chain
            const rootCerts = SettingsService.getRootCertificates({
                identifier: 'mds',
            });
            await validateCertificatePath(headerCertsPEM, rootCerts);
        }
        catch (error) {
            const _error = error;
            // From FIDO MDS docs: "ignore the file if the chain cannot be verified or if one of the
            // chain certificates is revoked"
            throw new Error('BLOB certificate path could not be validated', { cause: _error });
        }
        // Verify the BLOB JWT signature
        const leafCert = headerCertsPEM[0];
        const verified = await verifyJWT(data, convertPEMToBytes(leafCert));
        if (!verified) {
            // From FIDO MDS docs: "The FIDO Server SHOULD ignore the file if the signature is invalid."
            throw new Error('BLOB signature could not be verified');
        }
        // Cache statements for FIDO2 devices
        for (const entry of payload.entries) {
            // Only cache entries with an `aaguid`
            if (entry.aaguid) {
                this.statementCache[entry.aaguid] = { entry, url };
            }
        }
        // Remember info about the server so we can refresh later
        const [year, month, day] = payload.nextUpdate.split('-');
        this.mdsCache[url] = {
            ...mds,
            // Store the payload `no` to make sure we're getting the next BLOB in the sequence
            no: payload.no,
            // Convert the nextUpdate property into a Date so we can determine when to re-download
            nextUpdate: new Date(parseInt(year, 10), 
            // Months need to be zero-indexed
            parseInt(month, 10) - 1, parseInt(day, 10)),
        };
    }
    /**
     * A helper method to pause execution until the service is ready
     */
    pauseUntilReady() {
        if (this.state === SERVICE_STATE.READY) {
            return new Promise((resolve) => {
                resolve();
            });
        }
        // State isn't ready, so set up polling
        const readyPromise = new Promise((resolve, reject) => {
            const totalTimeoutMS = 70000;
            const intervalMS = 100;
            let iterations = totalTimeoutMS / intervalMS;
            // Check service state every `intervalMS` milliseconds
            const intervalID = globalThis.setInterval(() => {
                if (iterations < 1) {
                    clearInterval(intervalID);
                    reject(`State did not become ready in ${totalTimeoutMS / 1000} seconds`);
                }
                else if (this.state === SERVICE_STATE.READY) {
                    clearInterval(intervalID);
                    resolve();
                }
                iterations -= 1;
            }, intervalMS);
        });
        return readyPromise;
    }
    /**
     * Report service status on change
     */
    setState(newState) {
        this.state = newState;
        if (newState === SERVICE_STATE.DISABLED) {
            log('MetadataService is DISABLED');
        }
        else if (newState === SERVICE_STATE.REFRESHING) {
            log('MetadataService is REFRESHING');
        }
        else if (newState === SERVICE_STATE.READY) {
            log('MetadataService is READY');
        }
    }
}
/**
 * A basic service for coordinating interactions with the FIDO Metadata Service. This includes BLOB
 * download and parsing, and on-demand requesting and caching of individual metadata statements.
 *
 * https://fidoalliance.org/metadata/
 */
const MetadataService = new BaseMetadataService();

/**
 * Match properties of the authenticator's attestation statement against expected values as
 * registered with the FIDO Alliance Metadata Service
 */
async function verifyAttestationWithMetadata({ statement, credentialPublicKey, x5c, attestationStatementAlg, }) {
    const { authenticationAlgorithms, authenticatorGetInfo, attestationRootCertificates, } = statement;
    // Make sure the alg in the attestation statement matches one of the ones specified in metadata
    const keypairCOSEAlgs = new Set();
    authenticationAlgorithms.forEach((algSign) => {
        // Map algSign string to { kty, alg, crv }
        const algSignCOSEINFO = algSignToCOSEInfoMap[algSign];
        // Keeping this statement here just in case MDS returns something unexpected
        if (algSignCOSEINFO) {
            keypairCOSEAlgs.add(algSignCOSEINFO);
        }
    });
    // Extract the public key's COSE info for comparison
    const decodedPublicKey = decodeCredentialPublicKey(credentialPublicKey);
    const kty = decodedPublicKey.get(COSEKEYS.kty);
    const alg = decodedPublicKey.get(COSEKEYS.alg);
    if (!kty) {
        throw new Error('Credential public key was missing kty');
    }
    if (!alg) {
        throw new Error('Credential public key was missing alg');
    }
    if (!kty) {
        throw new Error('Credential public key was missing kty');
    }
    // Assume everything is a number because these values should be
    const publicKeyCOSEInfo = { kty, alg };
    if (isCOSEPublicKeyEC2(decodedPublicKey)) {
        const crv = decodedPublicKey.get(COSEKEYS.crv);
        publicKeyCOSEInfo.crv = crv;
    }
    /**
     * Attempt to match the credential public key's algorithm to one specified in the device's
     * metadata
     */
    let foundMatch = false;
    for (const keypairAlg of keypairCOSEAlgs) {
        // Make sure algorithm and key type match
        if (keypairAlg.alg === publicKeyCOSEInfo.alg &&
            keypairAlg.kty === publicKeyCOSEInfo.kty) {
            // If not an RSA keypair then make sure curve numbers match too
            if ((keypairAlg.kty === COSEKTY.EC2 || keypairAlg.kty === COSEKTY.OKP) &&
                keypairAlg.crv === publicKeyCOSEInfo.crv) {
                foundMatch = true;
            }
            else {
                // We've matched an RSA public key's properties
                foundMatch = true;
            }
        }
        if (foundMatch) {
            break;
        }
    }
    // Make sure the public key is one of the allowed algorithms
    if (!foundMatch) {
        /**
         * Craft some useful error output from the MDS algorithms
         *
         * Example:
         *
         * ```
         * [
         *   'rsassa_pss_sha256_raw' (COSE info: { kty: 3, alg: -37 }),
         *   'secp256k1_ecdsa_sha256_raw' (COSE info: { kty: 2, alg: -47, crv: 8 })
         * ]
         * ```
         */
        const debugMDSAlgs = authenticationAlgorithms.map((algSign) => `'${algSign}' (COSE info: ${stringifyCOSEInfo(algSignToCOSEInfoMap[algSign])})`);
        const strMDSAlgs = JSON.stringify(debugMDSAlgs, null, 2).replace(/"/g, '');
        /**
         * Construct useful error output about the public key
         */
        const strPubKeyAlg = stringifyCOSEInfo(publicKeyCOSEInfo);
        throw new Error(`Public key parameters ${strPubKeyAlg} did not match any of the following metadata algorithms:\n${strMDSAlgs}`);
    }
    /**
     * Confirm the attestation statement's algorithm is one supported according to metadata
     */
    if (attestationStatementAlg !== undefined &&
        authenticatorGetInfo?.algorithms !== undefined) {
        const getInfoAlgs = authenticatorGetInfo.algorithms.map((_alg) => _alg.alg);
        if (getInfoAlgs.indexOf(attestationStatementAlg) < 0) {
            throw new Error(`Attestation statement alg ${attestationStatementAlg} did not match one of ${getInfoAlgs}`);
        }
    }
    // Prepare to check the certificate chain
    const authenticatorCerts = x5c.map(convertCertBufferToPEM);
    const statementRootCerts = attestationRootCertificates.map(convertCertBufferToPEM);
    /**
     * If an authenticator returns exactly one certificate in its x5c, and that cert is found in the
     * metadata statement then the authenticator is "self-referencing". In this case we forego
     * certificate chain validation.
     */
    let authenticatorIsSelfReferencing = false;
    if (authenticatorCerts.length === 1 &&
        statementRootCerts.indexOf(authenticatorCerts[0]) >= 0) {
        authenticatorIsSelfReferencing = true;
    }
    if (!authenticatorIsSelfReferencing) {
        try {
            await validateCertificatePath(authenticatorCerts, statementRootCerts);
        }
        catch (err) {
            const _err = err;
            throw new Error(`Could not validate certificate path with any metadata root certificates: ${_err.message}`);
        }
    }
    return true;
}
/**
 * Convert ALG_SIGN values to COSE info
 *
 * Values pulled from `ALG_KEY_COSE` definitions in the FIDO Registry of Predefined Values
 *
 * https://fidoalliance.org/specs/common-specs/fido-registry-v2.2-ps-20220523.html#authentication-algorithms
 */
const algSignToCOSEInfoMap = {
    secp256r1_ecdsa_sha256_raw: { kty: 2, alg: -7, crv: 1 },
    secp256r1_ecdsa_sha256_der: { kty: 2, alg: -7, crv: 1 },
    rsassa_pss_sha256_raw: { kty: 3, alg: -37 },
    rsassa_pss_sha256_der: { kty: 3, alg: -37 },
    secp256k1_ecdsa_sha256_raw: { kty: 2, alg: -47, crv: 8 },
    secp256k1_ecdsa_sha256_der: { kty: 2, alg: -47, crv: 8 },
    rsassa_pss_sha384_raw: { kty: 3, alg: -38 },
    rsassa_pkcsv15_sha256_raw: { kty: 3, alg: -257 },
    rsassa_pkcsv15_sha384_raw: { kty: 3, alg: -258 },
    rsassa_pkcsv15_sha512_raw: { kty: 3, alg: -259 },
    rsassa_pkcsv15_sha1_raw: { kty: 3, alg: -65535 },
    secp384r1_ecdsa_sha384_raw: { kty: 2, alg: -35, crv: 2 },
    secp512r1_ecdsa_sha256_raw: { kty: 2, alg: -36, crv: 3 },
    ed25519_eddsa_sha512_raw: { kty: 1, alg: -8, crv: 6 },
};
/**
 * A helper to format COSEInfo a little nicer than we can achieve with JSON.stringify()
 *
 * Input: `{ "kty": 3, "alg": -257 }`
 *
 * Output: `"{ kty: 3, alg: -257 }"`
 */
function stringifyCOSEInfo(info) {
    const { kty, alg, crv } = info;
    let toReturn = '';
    if (kty !== COSEKTY.RSA) {
        toReturn = `{ kty: ${kty}, alg: ${alg}, crv: ${crv} }`;
    }
    else {
        toReturn = `{ kty: ${kty}, alg: ${alg} }`;
    }
    return toReturn;
}

/**
 * Verify an attestation response with fmt 'packed'
 */
async function verifyAttestationPacked(options) {
    const { attStmt, clientDataHash, authData, credentialPublicKey, aaguid, rootCertificates, } = options;
    const sig = attStmt.get('sig');
    const x5c = attStmt.get('x5c');
    const alg = attStmt.get('alg');
    if (!sig) {
        throw new Error('No attestation signature provided in attestation statement (Packed)');
    }
    if (!alg) {
        throw new Error('Attestation statement did not contain alg (Packed)');
    }
    if (!isCOSEAlg(alg)) {
        throw new Error(`Attestation statement contained invalid alg ${alg} (Packed)`);
    }
    const signatureBase = concat([authData, clientDataHash]);
    let verified = false;
    if (x5c) {
        const { subject, basicConstraintsCA, version, notBefore, notAfter, parsedCertificate, } = getCertificateInfo(x5c[0]);
        const { OU, CN, O, C } = subject;
        if (OU !== 'Authenticator Attestation') {
            throw new Error('Certificate OU was not "Authenticator Attestation" (Packed|Full)');
        }
        if (!CN) {
            throw new Error('Certificate CN was empty (Packed|Full)');
        }
        if (!O) {
            throw new Error('Certificate O was empty (Packed|Full)');
        }
        if (!C || C.length !== 2) {
            throw new Error('Certificate C was not two-character ISO 3166 code (Packed|Full)');
        }
        if (basicConstraintsCA) {
            throw new Error('Certificate basic constraints CA was not `false` (Packed|Full)');
        }
        if (version !== 2) {
            throw new Error('Certificate version was not `3` (ASN.1 value of 2) (Packed|Full)');
        }
        let now = new Date();
        if (notBefore > now) {
            throw new Error(`Certificate not good before "${notBefore.toString()}" (Packed|Full)`);
        }
        now = new Date();
        if (notAfter < now) {
            throw new Error(`Certificate not good after "${notAfter.toString()}" (Packed|Full)`);
        }
        // Validate attestation statement AAGUID against leaf cert AAGUID
        try {
            await validateExtFIDOGenCEAAGUID(parsedCertificate.tbsCertificate.extensions, aaguid);
        }
        catch (err) {
            const _err = err;
            throw new Error(`${_err.message} (Packed|Full)`);
        }
        // If available, validate attestation alg and x5c with info in the metadata statement
        const statement = await MetadataService.getStatement(aaguid);
        if (statement) {
            // The presence of x5c means this is a full attestation. Check to see if attestationTypes
            // includes packed attestations.
            if (statement.attestationTypes.indexOf('basic_full') < 0) {
                throw new Error('Metadata does not indicate support for full attestations (Packed|Full)');
            }
            try {
                await verifyAttestationWithMetadata({
                    statement,
                    credentialPublicKey,
                    x5c,
                    attestationStatementAlg: alg,
                });
            }
            catch (err) {
                const _err = err;
                throw new Error(`${_err.message} (Packed|Full)`);
            }
        }
        else {
            try {
                // Try validating the certificate path using the root certificates set via SettingsService
                await validateCertificatePath(x5c.map(convertCertBufferToPEM), rootCertificates);
            }
            catch (err) {
                const _err = err;
                throw new Error(`${_err.message} (Packed|Full)`);
            }
        }
        verified = await verifySignature({
            signature: sig,
            data: signatureBase,
            x509Certificate: x5c[0],
        });
    }
    else {
        verified = await verifySignature({
            signature: sig,
            data: signatureBase,
            credentialPublicKey,
            hashAlgorithm: alg,
        });
    }
    return verified;
}

/**
 * Verify an attestation response with fmt 'android-safetynet'
 */
async function verifyAttestationAndroidSafetyNet(options) {
    const { attStmt, clientDataHash, authData, aaguid, rootCertificates, verifyTimestampMS = true, credentialPublicKey, attestationSafetyNetEnforceCTSCheck, } = options;
    const alg = attStmt.get('alg');
    const response = attStmt.get('response');
    const ver = attStmt.get('ver');
    if (!ver) {
        throw new Error('No ver value in attestation (SafetyNet)');
    }
    if (!response) {
        throw new Error('No response was included in attStmt by authenticator (SafetyNet)');
    }
    // Prepare to verify a JWT
    const jwt = toUTF8String(response);
    const jwtParts = jwt.split('.');
    const HEADER = JSON.parse(toUTF8String$1(jwtParts[0]));
    const PAYLOAD = JSON.parse(toUTF8String$1(jwtParts[1]));
    const SIGNATURE = jwtParts[2];
    /**
     * START Verify PAYLOAD
     */
    const { nonce, ctsProfileMatch, timestampMs } = PAYLOAD;
    if (verifyTimestampMS) {
        // Make sure timestamp is in the past
        let now = Date.now();
        if (timestampMs > Date.now()) {
            throw new Error(`Payload timestamp "${timestampMs}" was later than "${now}" (SafetyNet)`);
        }
        // Consider a SafetyNet attestation valid within a minute of it being performed
        const timestampPlusDelay = timestampMs + 60 * 1000;
        now = Date.now();
        if (timestampPlusDelay < now) {
            throw new Error(`Payload timestamp "${timestampPlusDelay}" has expired (SafetyNet)`);
        }
    }
    const nonceBase = concat([authData, clientDataHash]);
    const nonceBuffer = await toHash(nonceBase);
    const expectedNonce = fromBuffer(nonceBuffer, 'base64');
    if (nonce !== expectedNonce) {
        throw new Error('Could not verify payload nonce (SafetyNet)');
    }
    if (attestationSafetyNetEnforceCTSCheck && !ctsProfileMatch) {
        throw new Error('Could not verify device integrity (SafetyNet)');
    }
    /**
     * END Verify PAYLOAD
     */
    /**
     * START Verify Header
     */
    // `HEADER.x5c[0]` is definitely a base64 string
    const leafCertBuffer = toBuffer(HEADER.x5c[0], 'base64');
    const leafCertInfo = getCertificateInfo(leafCertBuffer);
    const { subject } = leafCertInfo;
    // Ensure the certificate was issued to this hostname
    // See https://developer.android.com/training/safetynet/attestation#verify-attestation-response
    if (subject.CN !== 'attest.android.com') {
        throw new Error('Certificate common name was not "attest.android.com" (SafetyNet)');
    }
    const statement = await MetadataService.getStatement(aaguid);
    if (statement) {
        try {
            await verifyAttestationWithMetadata({
                statement,
                credentialPublicKey,
                x5c: HEADER.x5c,
                attestationStatementAlg: alg,
            });
        }
        catch (err) {
            const _err = err;
            throw new Error(`${_err.message} (SafetyNet)`);
        }
    }
    else {
        try {
            // Try validating the certificate path using the root certificates set via SettingsService
            await validateCertificatePath(HEADER.x5c.map(convertCertBufferToPEM), rootCertificates);
        }
        catch (err) {
            const _err = err;
            throw new Error(`${_err.message} (SafetyNet)`);
        }
    }
    /**
     * END Verify Header
     */
    /**
     * START Verify Signature
     */
    const signatureBaseBuffer = fromUTF8String(`${jwtParts[0]}.${jwtParts[1]}`);
    const signatureBuffer = toBuffer(SIGNATURE);
    const verified = await verifySignature({
        signature: signatureBuffer,
        data: signatureBaseBuffer,
        x509Certificate: leafCertBuffer,
    });
    /**
     * END Verify Signature
     */
    return verified;
}

// deno-lint-ignore-file no-dupe-keys
/**
 * A whole lotta domain knowledge is captured here, with hazy connections to source
 * documents. Good places to start searching for more info on these values are the
 * following Trusted Computing Group TPM Library docs linked in the WebAuthn API:
 *
 * - https://www.trustedcomputinggroup.org/wp-content/uploads/TPM-Rev-2.0-Part-1-Architecture-01.38.pdf
 * - https://www.trustedcomputinggroup.org/wp-content/uploads/TPM-Rev-2.0-Part-2-Structures-01.38.pdf
 * - https://www.trustedcomputinggroup.org/wp-content/uploads/TPM-Rev-2.0-Part-3-Commands-01.38.pdf
 */
/**
 * 6.9 TPM_ST (Structure Tags)
 */
const TPM_ST = {
    0x00c4: 'TPM_ST_RSP_COMMAND',
    0x8000: 'TPM_ST_NULL',
    0x8001: 'TPM_ST_NO_SESSIONS',
    0x8002: 'TPM_ST_SESSIONS',
    0x8014: 'TPM_ST_ATTEST_NV',
    0x8015: 'TPM_ST_ATTEST_COMMAND_AUDIT',
    0x8016: 'TPM_ST_ATTEST_SESSION_AUDIT',
    0x8017: 'TPM_ST_ATTEST_CERTIFY',
    0x8018: 'TPM_ST_ATTEST_QUOTE',
    0x8019: 'TPM_ST_ATTEST_TIME',
    0x801a: 'TPM_ST_ATTEST_CREATION',
    0x8021: 'TPM_ST_CREATION',
    0x8022: 'TPM_ST_VERIFIED',
    0x8023: 'TPM_ST_AUTH_SECRET',
    0x8024: 'TPM_ST_HASHCHECK',
    0x8025: 'TPM_ST_AUTH_SIGNED',
    0x8029: 'TPM_ST_FU_MANIFEST',
};
/**
 * 6.3 TPM_ALG_ID
 */
const TPM_ALG = {
    0x0000: 'TPM_ALG_ERROR',
    0x0001: 'TPM_ALG_RSA',
    0x0004: 'TPM_ALG_SHA',
    // @ts-ignore 2300
    0x0004: 'TPM_ALG_SHA1',
    0x0005: 'TPM_ALG_HMAC',
    0x0006: 'TPM_ALG_AES',
    0x0007: 'TPM_ALG_MGF1',
    0x0008: 'TPM_ALG_KEYEDHASH',
    0x000a: 'TPM_ALG_XOR',
    0x000b: 'TPM_ALG_SHA256',
    0x000c: 'TPM_ALG_SHA384',
    0x000d: 'TPM_ALG_SHA512',
    0x0010: 'TPM_ALG_NULL',
    0x0012: 'TPM_ALG_SM3_256',
    0x0013: 'TPM_ALG_SM4',
    0x0014: 'TPM_ALG_RSASSA',
    0x0015: 'TPM_ALG_RSAES',
    0x0016: 'TPM_ALG_RSAPSS',
    0x0017: 'TPM_ALG_OAEP',
    0x0018: 'TPM_ALG_ECDSA',
    0x0019: 'TPM_ALG_ECDH',
    0x001a: 'TPM_ALG_ECDAA',
    0x001b: 'TPM_ALG_SM2',
    0x001c: 'TPM_ALG_ECSCHNORR',
    0x001d: 'TPM_ALG_ECMQV',
    0x0020: 'TPM_ALG_KDF1_SP800_56A',
    0x0021: 'TPM_ALG_KDF2',
    0x0022: 'TPM_ALG_KDF1_SP800_108',
    0x0023: 'TPM_ALG_ECC',
    0x0025: 'TPM_ALG_SYMCIPHER',
    0x0026: 'TPM_ALG_CAMELLIA',
    0x0040: 'TPM_ALG_CTR',
    0x0041: 'TPM_ALG_OFB',
    0x0042: 'TPM_ALG_CBC',
    0x0043: 'TPM_ALG_CFB',
    0x0044: 'TPM_ALG_ECB',
};
/**
 * 6.4 TPM_ECC_CURVE
 */
const TPM_ECC_CURVE = {
    0x0000: 'TPM_ECC_NONE',
    0x0001: 'TPM_ECC_NIST_P192',
    0x0002: 'TPM_ECC_NIST_P224',
    0x0003: 'TPM_ECC_NIST_P256',
    0x0004: 'TPM_ECC_NIST_P384',
    0x0005: 'TPM_ECC_NIST_P521',
    0x0010: 'TPM_ECC_BN_P256',
    0x0011: 'TPM_ECC_BN_P638',
    0x0020: 'TPM_ECC_SM2_P256',
};
/**
 * Sourced from https://trustedcomputinggroup.org/resource/vendor-id-registry/
 *
 * Latest version:
 * https://trustedcomputinggroup.org/wp-content/uploads/TCG-TPM-Vendor-ID-Registry-Version-1.02-Revision-1.00.pdf
 */
const TPM_MANUFACTURERS = {
    'id:414D4400': { name: 'AMD', id: 'AMD' },
    'id:414E5400': { name: 'Ant Group', id: 'ANT' },
    'id:41544D4C': { name: 'Atmel', id: 'ATML' },
    'id:4252434D': { name: 'Broadcom', id: 'BRCM' },
    'id:4353434F': { name: 'Cisco', id: 'CSCO' },
    'id:464C5953': { name: 'Flyslice Technologies', id: 'FLYS' },
    'id:524F4343': { name: 'Fuzhou Rockchip', id: 'ROCC' },
    'id:474F4F47': { name: 'Google', id: 'GOOG' },
    'id:48504900': { name: 'HPI', id: 'HPI' },
    'id:48504500': { name: 'HPE', id: 'HPE' },
    'id:48495349': { name: 'Huawei', id: 'HISI' },
    'id:49424d00': { name: 'IBM', id: 'IBM' },
    'id:49424D00': { name: 'IBM', id: 'IBM' }, // Same ID for IBM as above, except the "D" is capitalized as per TPM spec
    'id:49465800': { name: 'Infineon', id: 'IFX' },
    'id:494E5443': { name: 'Intel', id: 'INTC' },
    'id:4C454E00': { name: 'Lenovo', id: 'LEN' },
    'id:4D534654': { name: 'Microsoft', id: 'MSFT' },
    'id:4E534D20': { name: 'National Semiconductor', id: 'NSM' },
    'id:4E545A00': { name: 'Nationz', id: 'NTZ' },
    'id:4E534700': { name: 'NSING', id: 'NSG' },
    'id:4E544300': { name: 'Nuvoton Technology', id: 'NTC' },
    'id:51434F4D': { name: 'Qualcomm', id: 'QCOM' },
    'id:534D534E': { name: 'Samsung', id: 'SMSN' },
    'id:53454345': { name: 'SecEdge', id: 'SECE' },
    'id:534E5300': { name: 'Sinosun', id: 'SNS' },
    'id:534D5343': { name: 'SMSC', id: 'SMSC' },
    'id:53544D20': { name: 'STMicroelectronics', id: 'STM' },
    'id:54584E00': { name: 'Texas Instruments', id: 'TXN' },
    'id:57454300': { name: 'Winbond', id: 'WEC' },
    'id:5345414C': { name: 'Wisekey', id: 'SEAL' },
    'id:FFFFF1D0': { name: 'FIDO Alliance', id: 'FIDO' }, // FIDO Conformance
};
/**
 * Match TPM public area curve ID's to `crv` numbers used in COSE public keys
 */
const TPM_ECC_CURVE_COSE_CRV_MAP = {
    TPM_ECC_NIST_P256: 1, // p256
    TPM_ECC_NIST_P384: 2, // p384
    TPM_ECC_NIST_P521: 3, // p521
    TPM_ECC_BN_P256: 1, // p256
    TPM_ECC_SM2_P256: 1, // p256
};

/**
 * Cut up a TPM attestation's certInfo into intelligible chunks
 */
function parseCertInfo(certInfo) {
    let pointer = 0;
    const dataView = toDataView(certInfo);
    // Get a magic constant
    const magic = dataView.getUint32(pointer);
    pointer += 4;
    // Determine the algorithm used for attestation
    const typeBuffer = dataView.getUint16(pointer);
    pointer += 2;
    const type = TPM_ST[typeBuffer];
    // The name of a parent entity, can be ignored
    const qualifiedSignerLength = dataView.getUint16(pointer);
    pointer += 2;
    const qualifiedSigner = certInfo.slice(pointer, pointer += qualifiedSignerLength);
    // Get the expected hash of `attsToBeSigned`
    const extraDataLength = dataView.getUint16(pointer);
    pointer += 2;
    const extraData = certInfo.slice(pointer, pointer += extraDataLength);
    // Information about the TPM device's internal clock, can be ignored
    const clock = certInfo.slice(pointer, pointer += 8);
    const resetCount = dataView.getUint32(pointer);
    pointer += 4;
    const restartCount = dataView.getUint32(pointer);
    pointer += 4;
    const safe = !!certInfo.slice(pointer, pointer += 1);
    const clockInfo = { clock, resetCount, restartCount, safe };
    // TPM device firmware version
    const firmwareVersion = certInfo.slice(pointer, pointer += 8);
    // Attested Name
    const attestedNameLength = dataView.getUint16(pointer);
    pointer += 2;
    const attestedName = certInfo.slice(pointer, pointer += attestedNameLength);
    const attestedNameDataView = toDataView(attestedName);
    // Attested qualified name, can be ignored
    const qualifiedNameLength = dataView.getUint16(pointer);
    pointer += 2;
    const qualifiedName = certInfo.slice(pointer, pointer += qualifiedNameLength);
    const attested = {
        nameAlg: TPM_ALG[attestedNameDataView.getUint16(0)],
        nameAlgBuffer: attestedName.slice(0, 2),
        name: attestedName,
        qualifiedName,
    };
    return {
        magic,
        type,
        qualifiedSigner,
        extraData,
        clockInfo,
        firmwareVersion,
        attested,
    };
}

/**
 * Break apart a TPM attestation's pubArea buffer
 *
 * See 12.2.4 TPMT_PUBLIC here:
 * https://trustedcomputinggroup.org/wp-content/uploads/TPM-Rev-2.0-Part-2-Structures-00.96-130315.pdf
 */
function parsePubArea(pubArea) {
    let pointer = 0;
    const dataView = toDataView(pubArea);
    const type = TPM_ALG[dataView.getUint16(pointer)];
    pointer += 2;
    const nameAlg = TPM_ALG[dataView.getUint16(pointer)];
    pointer += 2;
    // Get some authenticator attributes(?)
    // const objectAttributesInt = pubArea.slice(pointer, (pointer += 4)).readUInt32BE(0);
    const objectAttributesInt = dataView.getUint32(pointer);
    pointer += 4;
    const objectAttributes = {
        fixedTPM: !!(objectAttributesInt & 1),
        stClear: !!(objectAttributesInt & 2),
        fixedParent: !!(objectAttributesInt & 8),
        sensitiveDataOrigin: !!(objectAttributesInt & 16),
        userWithAuth: !!(objectAttributesInt & 32),
        adminWithPolicy: !!(objectAttributesInt & 64),
        noDA: !!(objectAttributesInt & 512),
        encryptedDuplication: !!(objectAttributesInt & 1024),
        restricted: !!(objectAttributesInt & 32768),
        decrypt: !!(objectAttributesInt & 65536),
        signOrEncrypt: !!(objectAttributesInt & 131072),
    };
    // Slice out the authPolicy of dynamic length
    const authPolicyLength = dataView.getUint16(pointer);
    pointer += 2;
    const authPolicy = pubArea.slice(pointer, pointer += authPolicyLength);
    // Extract additional curve params according to type
    const parameters = {};
    let unique = Uint8Array.from([]);
    if (type === 'TPM_ALG_RSA') {
        const symmetric = TPM_ALG[dataView.getUint16(pointer)];
        pointer += 2;
        const scheme = TPM_ALG[dataView.getUint16(pointer)];
        pointer += 2;
        const keyBits = dataView.getUint16(pointer);
        pointer += 2;
        const exponent = dataView.getUint32(pointer);
        pointer += 4;
        parameters.rsa = { symmetric, scheme, keyBits, exponent };
        /**
         * See 11.2.4.5 TPM2B_PUBLIC_KEY_RSA here:
         * https://trustedcomputinggroup.org/wp-content/uploads/TPM-Rev-2.0-Part-2-Structures-00.96-130315.pdf
         */
        // const uniqueLength = pubArea.slice(pointer, (pointer += 2)).readUInt16BE(0);
        const uniqueLength = dataView.getUint16(pointer);
        pointer += 2;
        unique = pubArea.slice(pointer, pointer += uniqueLength);
    }
    else if (type === 'TPM_ALG_ECC') {
        const symmetric = TPM_ALG[dataView.getUint16(pointer)];
        pointer += 2;
        const scheme = TPM_ALG[dataView.getUint16(pointer)];
        pointer += 2;
        const curveID = TPM_ECC_CURVE[dataView.getUint16(pointer)];
        pointer += 2;
        const kdf = TPM_ALG[dataView.getUint16(pointer)];
        pointer += 2;
        parameters.ecc = { symmetric, scheme, curveID, kdf };
        /**
         * See 11.2.5.1 TPM2B_ECC_PARAMETER here:
         * https://trustedcomputinggroup.org/wp-content/uploads/TPM-Rev-2.0-Part-2-Structures-00.96-130315.pdf
         */
        // Retrieve X
        const uniqueXLength = dataView.getUint16(pointer);
        pointer += 2;
        const uniqueX = pubArea.slice(pointer, pointer += uniqueXLength);
        // Retrieve Y
        const uniqueYLength = dataView.getUint16(pointer);
        pointer += 2;
        const uniqueY = pubArea.slice(pointer, pointer += uniqueYLength);
        unique = concat([uniqueX, uniqueY]);
    }
    else {
        throw new Error(`Unexpected type "${type}" (TPM)`);
    }
    return {
        type,
        nameAlg,
        objectAttributes,
        authPolicy,
        parameters,
        unique,
    };
}

async function verifyAttestationTPM(options) {
    const { aaguid, attStmt, authData, credentialPublicKey, clientDataHash, rootCertificates, } = options;
    const ver = attStmt.get('ver');
    const sig = attStmt.get('sig');
    const alg = attStmt.get('alg');
    const x5c = attStmt.get('x5c');
    const pubArea = attStmt.get('pubArea');
    const certInfo = attStmt.get('certInfo');
    /**
     * Verify structures
     */
    if (ver !== '2.0') {
        throw new Error(`Unexpected ver "${ver}", expected "2.0" (TPM)`);
    }
    if (!sig) {
        throw new Error('No attestation signature provided in attestation statement (TPM)');
    }
    if (!alg) {
        throw new Error(`Attestation statement did not contain alg (TPM)`);
    }
    if (!isCOSEAlg(alg)) {
        throw new Error(`Attestation statement contained invalid alg ${alg} (TPM)`);
    }
    if (!x5c) {
        throw new Error('No attestation certificate provided in attestation statement (TPM)');
    }
    if (!pubArea) {
        throw new Error('Attestation statement did not contain pubArea (TPM)');
    }
    if (!certInfo) {
        throw new Error('Attestation statement did not contain certInfo (TPM)');
    }
    const parsedPubArea = parsePubArea(pubArea);
    const { unique, type: pubType, parameters } = parsedPubArea;
    // Verify that the public key specified by the parameters and unique fields of pubArea is
    // identical to the credentialPublicKey in the attestedCredentialData in authenticatorData.
    const cosePublicKey = decodeCredentialPublicKey(credentialPublicKey);
    if (pubType === 'TPM_ALG_RSA') {
        if (!isCOSEPublicKeyRSA(cosePublicKey)) {
            throw new Error(`Credential public key with kty ${cosePublicKey.get(COSEKEYS.kty)} did not match ${pubType}`);
        }
        const n = cosePublicKey.get(COSEKEYS.n);
        const e = cosePublicKey.get(COSEKEYS.e);
        if (!n) {
            throw new Error('COSE public key missing n (TPM|RSA)');
        }
        if (!e) {
            throw new Error('COSE public key missing e (TPM|RSA)');
        }
        if (!areEqual(unique, n)) {
            throw new Error('PubArea unique is not same as credentialPublicKey (TPM|RSA)');
        }
        if (!parameters.rsa) {
            throw new Error(`Parsed pubArea type is RSA, but missing parameters.rsa (TPM|RSA)`);
        }
        const eBuffer = e;
        // If `exponent` is equal to 0x00, then exponent is the default RSA exponent of 2^16+1 (65537)
        const pubAreaExponent = parameters.rsa.exponent || 65537;
        // Do some bit shifting to get to an integer
        const eSum = eBuffer[0] + (eBuffer[1] << 8) + (eBuffer[2] << 16);
        if (pubAreaExponent !== eSum) {
            throw new Error(`Unexpected public key exp ${eSum}, expected ${pubAreaExponent} (TPM|RSA)`);
        }
    }
    else if (pubType === 'TPM_ALG_ECC') {
        if (!isCOSEPublicKeyEC2(cosePublicKey)) {
            throw new Error(`Credential public key with kty ${cosePublicKey.get(COSEKEYS.kty)} did not match ${pubType}`);
        }
        const crv = cosePublicKey.get(COSEKEYS.crv);
        const x = cosePublicKey.get(COSEKEYS.x);
        const y = cosePublicKey.get(COSEKEYS.y);
        if (!crv) {
            throw new Error('COSE public key missing crv (TPM|ECC)');
        }
        if (!x) {
            throw new Error('COSE public key missing x (TPM|ECC)');
        }
        if (!y) {
            throw new Error('COSE public key missing y (TPM|ECC)');
        }
        if (!areEqual(unique, concat([x, y]))) {
            throw new Error('PubArea unique is not same as public key x and y (TPM|ECC)');
        }
        if (!parameters.ecc) {
            throw new Error(`Parsed pubArea type is ECC, but missing parameters.ecc (TPM|ECC)`);
        }
        const pubAreaCurveID = parameters.ecc.curveID;
        const pubAreaCurveIDMapToCOSECRV = TPM_ECC_CURVE_COSE_CRV_MAP[pubAreaCurveID];
        if (pubAreaCurveIDMapToCOSECRV !== crv) {
            throw new Error(`Public area key curve ID "${pubAreaCurveID}" mapped to "${pubAreaCurveIDMapToCOSECRV}" which did not match public key crv of "${crv}" (TPM|ECC)`);
        }
    }
    else {
        throw new Error(`Unsupported pubArea.type "${pubType}"`);
    }
    const parsedCertInfo = parseCertInfo(certInfo);
    const { magic, type: certType, attested, extraData } = parsedCertInfo;
    if (magic !== 0xff544347) {
        throw new Error(`Unexpected magic value "${magic}", expected "0xff544347" (TPM)`);
    }
    if (certType !== 'TPM_ST_ATTEST_CERTIFY') {
        throw new Error(`Unexpected type "${certType}", expected "TPM_ST_ATTEST_CERTIFY" (TPM)`);
    }
    // Hash pubArea to create pubAreaHash using the nameAlg in attested
    const pubAreaHash = await toHash(pubArea, attestedNameAlgToCOSEAlg(attested.nameAlg));
    // Concatenate attested.nameAlg and pubAreaHash to create attestedName.
    const attestedName = concat([
        attested.nameAlgBuffer,
        pubAreaHash,
    ]);
    // Check that certInfo.attested.name is equals to attestedName.
    if (!areEqual(attested.name, attestedName)) {
        throw new Error(`Attested name comparison failed (TPM)`);
    }
    // Concatenate authData with clientDataHash to create attToBeSigned
    const attToBeSigned = concat([authData, clientDataHash]);
    // Hash attToBeSigned using the algorithm specified in attStmt.alg to create attToBeSignedHash
    const attToBeSignedHash = await toHash(attToBeSigned, alg);
    // Check that certInfo.extraData is equals to attToBeSignedHash.
    if (!areEqual(extraData, attToBeSignedHash)) {
        throw new Error('CertInfo extra data did not equal hashed attestation (TPM)');
    }
    /**
     * Verify signature
     */
    if (x5c.length < 1) {
        throw new Error('No certificates present in x5c array (TPM)');
    }
    // Pick a leaf AIK certificate of the x5c array and parse it.
    const leafCertInfo = getCertificateInfo(x5c[0]);
    const { basicConstraintsCA, version, subject, notAfter, notBefore } = leafCertInfo;
    if (basicConstraintsCA) {
        throw new Error('Certificate basic constraints CA was not `false` (TPM)');
    }
    // Check that certificate is of version 3 (value must be set to 2).
    if (version !== 2) {
        throw new Error('Certificate version was not `3` (ASN.1 value of 2) (TPM)');
    }
    // Check that Subject sequence is empty.
    if (subject.combined.length > 0) {
        throw new Error('Certificate subject was not empty (TPM)');
    }
    // Check that certificate is currently valid
    let now = new Date();
    if (notBefore > now) {
        throw new Error(`Certificate not good before "${notBefore.toString()}" (TPM)`);
    }
    // Check that certificate has not expired
    now = new Date();
    if (notAfter < now) {
        throw new Error(`Certificate not good after "${notAfter.toString()}" (TPM)`);
    }
    /**
     * Plumb the depths of the certificate's ASN.1-formatted data for some values we need to verify
     */
    const parsedCert = AsnParser.parse(x5c[0], Certificate);
    if (!parsedCert.tbsCertificate.extensions) {
        throw new Error('Certificate was missing extensions (TPM)');
    }
    let subjectAltNamePresent;
    let extKeyUsage;
    parsedCert.tbsCertificate.extensions.forEach((ext) => {
        if (ext.extnID === id_ce_subjectAltName) {
            subjectAltNamePresent = AsnParser.parse(ext.extnValue, SubjectAlternativeName);
        }
        else if (ext.extnID === id_ce_extKeyUsage) {
            extKeyUsage = AsnParser.parse(ext.extnValue, ExtendedKeyUsage$1);
        }
    });
    // Check that certificate contains subjectAltName (2.5.29.17) extension,
    if (!subjectAltNamePresent) {
        throw new Error('Certificate did not contain subjectAltName extension (TPM)');
    }
    // TPM-specific values are buried within `directoryName`, so first make sure there are values
    // there.
    if (!subjectAltNamePresent[0].directoryName?.[0].length) {
        throw new Error('Certificate subjectAltName extension directoryName was empty (TPM)');
    }
    const { tcgAtTpmManufacturer, tcgAtTpmModel, tcgAtTpmVersion } = getTcgAtTpmValues(subjectAltNamePresent[0].directoryName);
    if (!tcgAtTpmManufacturer || !tcgAtTpmModel || !tcgAtTpmVersion) {
        throw new Error('Certificate contained incomplete subjectAltName data (TPM)');
    }
    if (!extKeyUsage) {
        throw new Error('Certificate did not contain ExtendedKeyUsage extension (TPM)');
    }
    // Check that tcpaTpmManufacturer (2.23.133.2.1) field is set to a valid manufacturer ID.
    if (!TPM_MANUFACTURERS[tcgAtTpmManufacturer]) {
        throw new Error(`Could not match TPM manufacturer "${tcgAtTpmManufacturer}" (TPM)`);
    }
    // Check that certificate contains extKeyUsage (2.5.29.37) extension and it must contain
    // tcg-kp-AIKCertificate (2.23.133.8.3) OID.
    if (extKeyUsage[0] !== '2.23.133.8.3') {
        throw new Error(`Unexpected extKeyUsage "${extKeyUsage[0]}", expected "2.23.133.8.3" (TPM)`);
    }
    // Validate attestation statement AAGUID against leaf cert AAGUID
    try {
        await validateExtFIDOGenCEAAGUID(parsedCert.tbsCertificate.extensions, aaguid);
    }
    catch (err) {
        const _err = err;
        throw new Error(`${_err.message} (TPM)`);
    }
    // Run some metadata checks if a statement exists for this authenticator
    const statement = await MetadataService.getStatement(aaguid);
    if (statement) {
        try {
            await verifyAttestationWithMetadata({
                statement,
                credentialPublicKey,
                x5c,
                attestationStatementAlg: alg,
            });
        }
        catch (err) {
            const _err = err;
            throw new Error(`${_err.message} (TPM)`);
        }
    }
    else {
        try {
            // Try validating the certificate path using the root certificates set via SettingsService
            await validateCertificatePath(x5c.map(convertCertBufferToPEM), rootCertificates);
        }
        catch (err) {
            const _err = err;
            throw new Error(`${_err.message} (TPM)`);
        }
    }
    // Verify signature over certInfo with the public key extracted from AIK certificate.
    // In the wise words of Yuriy Ackermann: "Get Martini friend, you are done!"
    return verifySignature({
        signature: sig,
        data: certInfo,
        x509Certificate: x5c[0],
        hashAlgorithm: alg,
    });
}
/**
 * Contain logic for pulling TPM-specific values out of subjectAlternativeName extension
 */
function getTcgAtTpmValues(root) {
    const oidManufacturer = '2.23.133.2.1';
    const oidModel = '2.23.133.2.2';
    const oidVersion = '2.23.133.2.3';
    let tcgAtTpmManufacturer;
    let tcgAtTpmModel;
    let tcgAtTpmVersion;
    /**
     * Iterate through the following potential structures:
     *
     * (Good, follows the spec)
     * https://trustedcomputinggroup.org/wp-content/uploads/TCG_IWG_EKCredentialProfile_v2p3_r2_pub.pdf (page 33)
     * Name [
     *   RelativeDistinguishedName [
     *     AttributeTypeAndValue { type, value }
     *   ]
     *   RelativeDistinguishedName [
     *     AttributeTypeAndValue { type, value }
     *   ]
     *   RelativeDistinguishedName [
     *     AttributeTypeAndValue { type, value }
     *   ]
     * ]
     *
     * (Bad, does not follow the spec)
     * Name [
     *   RelativeDistinguishedName [
     *     AttributeTypeAndValue { type, value }
     *     AttributeTypeAndValue { type, value }
     *     AttributeTypeAndValue { type, value }
     *   ]
     * ]
     *
     * Both structures have been seen in the wild and need to be supported
     */
    root.forEach((relName) => {
        relName.forEach((attr) => {
            if (attr.type === oidManufacturer) {
                tcgAtTpmManufacturer = attr.value.toString();
            }
            else if (attr.type === oidModel) {
                tcgAtTpmModel = attr.value.toString();
            }
            else if (attr.type === oidVersion) {
                tcgAtTpmVersion = attr.value.toString();
            }
        });
    });
    return {
        tcgAtTpmManufacturer,
        tcgAtTpmModel,
        tcgAtTpmVersion,
    };
}
/**
 * Convert TPM-specific SHA algorithm ID's with COSE-specific equivalents. Note that the choice to
 * use ECDSA SHA IDs is arbitrary; any such COSEALG that would map to SHA-256 in
 * `mapCoseAlgToWebCryptoAlg()`
 *
 * SHA IDs referenced from here:
 *
 * https://trustedcomputinggroup.org/wp-content/uploads/TCG_TPM2_r1p59_Part2_Structures_pub.pdf
 */
function attestedNameAlgToCOSEAlg(alg) {
    if (alg === 'TPM_ALG_SHA256') {
        return COSEALG.ES256;
    }
    else if (alg === 'TPM_ALG_SHA384') {
        return COSEALG.ES384;
    }
    else if (alg === 'TPM_ALG_SHA512') {
        return COSEALG.ES512;
    }
    throw new Error(`Unexpected TPM attested name alg ${alg}`);
}

var IntegerSet_1;
const id_ce_keyDescription = "1.3.6.1.4.1.11129.2.1.17";
var VerifiedBootState;
(function (VerifiedBootState) {
    VerifiedBootState[VerifiedBootState["verified"] = 0] = "verified";
    VerifiedBootState[VerifiedBootState["selfSigned"] = 1] = "selfSigned";
    VerifiedBootState[VerifiedBootState["unverified"] = 2] = "unverified";
    VerifiedBootState[VerifiedBootState["failed"] = 3] = "failed";
})(VerifiedBootState || (VerifiedBootState = {}));
class RootOfTrust {
    constructor(params = {}) {
        this.verifiedBootKey = new OctetString();
        this.deviceLocked = false;
        this.verifiedBootState = VerifiedBootState.verified;
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: OctetString })
], RootOfTrust.prototype, "verifiedBootKey", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Boolean })
], RootOfTrust.prototype, "deviceLocked", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Enumerated })
], RootOfTrust.prototype, "verifiedBootState", void 0);
__decorate$1([
    AsnProp({ type: OctetString, optional: true })
], RootOfTrust.prototype, "verifiedBootHash", void 0);
let IntegerSet = IntegerSet_1 = class IntegerSet extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, IntegerSet_1.prototype);
    }
};
IntegerSet = IntegerSet_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Set, itemType: AsnPropTypes.Integer })
], IntegerSet);
class AuthorizationList {
    constructor(params = {}) {
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ context: 1, type: IntegerSet, optional: true })
], AuthorizationList.prototype, "purpose", void 0);
__decorate$1([
    AsnProp({ context: 2, type: AsnPropTypes.Integer, optional: true })
], AuthorizationList.prototype, "algorithm", void 0);
__decorate$1([
    AsnProp({ context: 3, type: AsnPropTypes.Integer, optional: true })
], AuthorizationList.prototype, "keySize", void 0);
__decorate$1([
    AsnProp({ context: 5, type: IntegerSet, optional: true })
], AuthorizationList.prototype, "digest", void 0);
__decorate$1([
    AsnProp({ context: 6, type: IntegerSet, optional: true })
], AuthorizationList.prototype, "padding", void 0);
__decorate$1([
    AsnProp({ context: 10, type: AsnPropTypes.Integer, optional: true })
], AuthorizationList.prototype, "ecCurve", void 0);
__decorate$1([
    AsnProp({ context: 200, type: AsnPropTypes.Integer, optional: true })
], AuthorizationList.prototype, "rsaPublicExponent", void 0);
__decorate$1([
    AsnProp({ context: 203, type: IntegerSet, optional: true })
], AuthorizationList.prototype, "mgfDigest", void 0);
__decorate$1([
    AsnProp({ context: 303, type: AsnPropTypes.Null, optional: true })
], AuthorizationList.prototype, "rollbackResistance", void 0);
__decorate$1([
    AsnProp({ context: 305, type: AsnPropTypes.Null, optional: true })
], AuthorizationList.prototype, "earlyBootOnly", void 0);
__decorate$1([
    AsnProp({ context: 400, type: AsnPropTypes.Integer, optional: true })
], AuthorizationList.prototype, "activeDateTime", void 0);
__decorate$1([
    AsnProp({ context: 401, type: AsnPropTypes.Integer, optional: true })
], AuthorizationList.prototype, "originationExpireDateTime", void 0);
__decorate$1([
    AsnProp({ context: 402, type: AsnPropTypes.Integer, optional: true })
], AuthorizationList.prototype, "usageExpireDateTime", void 0);
__decorate$1([
    AsnProp({ context: 405, type: AsnPropTypes.Integer, optional: true })
], AuthorizationList.prototype, "usageCountLimit", void 0);
__decorate$1([
    AsnProp({ context: 503, type: AsnPropTypes.Null, optional: true })
], AuthorizationList.prototype, "noAuthRequired", void 0);
__decorate$1([
    AsnProp({ context: 504, type: AsnPropTypes.Integer, optional: true })
], AuthorizationList.prototype, "userAuthType", void 0);
__decorate$1([
    AsnProp({ context: 505, type: AsnPropTypes.Integer, optional: true })
], AuthorizationList.prototype, "authTimeout", void 0);
__decorate$1([
    AsnProp({ context: 506, type: AsnPropTypes.Null, optional: true })
], AuthorizationList.prototype, "allowWhileOnBody", void 0);
__decorate$1([
    AsnProp({ context: 507, type: AsnPropTypes.Null, optional: true })
], AuthorizationList.prototype, "trustedUserPresenceRequired", void 0);
__decorate$1([
    AsnProp({ context: 508, type: AsnPropTypes.Null, optional: true })
], AuthorizationList.prototype, "trustedConfirmationRequired", void 0);
__decorate$1([
    AsnProp({ context: 509, type: AsnPropTypes.Null, optional: true })
], AuthorizationList.prototype, "unlockedDeviceRequired", void 0);
__decorate$1([
    AsnProp({ context: 600, type: AsnPropTypes.Null, optional: true })
], AuthorizationList.prototype, "allApplications", void 0);
__decorate$1([
    AsnProp({ context: 601, type: OctetString, optional: true })
], AuthorizationList.prototype, "applicationId", void 0);
__decorate$1([
    AsnProp({ context: 701, type: AsnPropTypes.Integer, optional: true })
], AuthorizationList.prototype, "creationDateTime", void 0);
__decorate$1([
    AsnProp({ context: 702, type: AsnPropTypes.Integer, optional: true })
], AuthorizationList.prototype, "origin", void 0);
__decorate$1([
    AsnProp({ context: 703, type: AsnPropTypes.Null, optional: true })
], AuthorizationList.prototype, "rollbackResistant", void 0);
__decorate$1([
    AsnProp({ context: 704, type: RootOfTrust, optional: true })
], AuthorizationList.prototype, "rootOfTrust", void 0);
__decorate$1([
    AsnProp({ context: 705, type: AsnPropTypes.Integer, optional: true })
], AuthorizationList.prototype, "osVersion", void 0);
__decorate$1([
    AsnProp({ context: 706, type: AsnPropTypes.Integer, optional: true })
], AuthorizationList.prototype, "osPatchLevel", void 0);
__decorate$1([
    AsnProp({ context: 709, type: OctetString, optional: true })
], AuthorizationList.prototype, "attestationApplicationId", void 0);
__decorate$1([
    AsnProp({ context: 710, type: OctetString, optional: true })
], AuthorizationList.prototype, "attestationIdBrand", void 0);
__decorate$1([
    AsnProp({ context: 711, type: OctetString, optional: true })
], AuthorizationList.prototype, "attestationIdDevice", void 0);
__decorate$1([
    AsnProp({ context: 712, type: OctetString, optional: true })
], AuthorizationList.prototype, "attestationIdProduct", void 0);
__decorate$1([
    AsnProp({ context: 713, type: OctetString, optional: true })
], AuthorizationList.prototype, "attestationIdSerial", void 0);
__decorate$1([
    AsnProp({ context: 714, type: OctetString, optional: true })
], AuthorizationList.prototype, "attestationIdImei", void 0);
__decorate$1([
    AsnProp({ context: 715, type: OctetString, optional: true })
], AuthorizationList.prototype, "attestationIdMeid", void 0);
__decorate$1([
    AsnProp({ context: 716, type: OctetString, optional: true })
], AuthorizationList.prototype, "attestationIdManufacturer", void 0);
__decorate$1([
    AsnProp({ context: 717, type: OctetString, optional: true })
], AuthorizationList.prototype, "attestationIdModel", void 0);
__decorate$1([
    AsnProp({ context: 718, type: AsnPropTypes.Integer, optional: true })
], AuthorizationList.prototype, "vendorPatchLevel", void 0);
__decorate$1([
    AsnProp({ context: 719, type: AsnPropTypes.Integer, optional: true })
], AuthorizationList.prototype, "bootPatchLevel", void 0);
__decorate$1([
    AsnProp({ context: 720, type: AsnPropTypes.Null, optional: true })
], AuthorizationList.prototype, "deviceUniqueAttestation", void 0);
__decorate$1([
    AsnProp({ context: 723, type: OctetString, optional: true })
], AuthorizationList.prototype, "attestationIdSecondImei", void 0);
__decorate$1([
    AsnProp({ context: 724, type: OctetString, optional: true })
], AuthorizationList.prototype, "moduleHash", void 0);
var SecurityLevel;
(function (SecurityLevel) {
    SecurityLevel[SecurityLevel["software"] = 0] = "software";
    SecurityLevel[SecurityLevel["trustedEnvironment"] = 1] = "trustedEnvironment";
    SecurityLevel[SecurityLevel["strongBox"] = 2] = "strongBox";
})(SecurityLevel || (SecurityLevel = {}));
var Version;
(function (Version) {
    Version[Version["KM2"] = 1] = "KM2";
    Version[Version["KM3"] = 2] = "KM3";
    Version[Version["KM4"] = 3] = "KM4";
    Version[Version["KM4_1"] = 4] = "KM4_1";
    Version[Version["keyMint1"] = 100] = "keyMint1";
    Version[Version["keyMint2"] = 200] = "keyMint2";
    Version[Version["keyMint3"] = 300] = "keyMint3";
    Version[Version["keyMint4"] = 400] = "keyMint4";
})(Version || (Version = {}));
class KeyDescription {
    constructor(params = {}) {
        this.attestationVersion = Version.KM4;
        this.attestationSecurityLevel = SecurityLevel.software;
        this.keymasterVersion = 0;
        this.keymasterSecurityLevel = SecurityLevel.software;
        this.attestationChallenge = new OctetString();
        this.uniqueId = new OctetString();
        this.softwareEnforced = new AuthorizationList();
        this.teeEnforced = new AuthorizationList();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], KeyDescription.prototype, "attestationVersion", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Enumerated })
], KeyDescription.prototype, "attestationSecurityLevel", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], KeyDescription.prototype, "keymasterVersion", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Enumerated })
], KeyDescription.prototype, "keymasterSecurityLevel", void 0);
__decorate$1([
    AsnProp({ type: OctetString })
], KeyDescription.prototype, "attestationChallenge", void 0);
__decorate$1([
    AsnProp({ type: OctetString })
], KeyDescription.prototype, "uniqueId", void 0);
__decorate$1([
    AsnProp({ type: AuthorizationList })
], KeyDescription.prototype, "softwareEnforced", void 0);
__decorate$1([
    AsnProp({ type: AuthorizationList })
], KeyDescription.prototype, "teeEnforced", void 0);
class KeyMintKeyDescription {
    constructor(params = {}) {
        this.attestationVersion = Version.keyMint4;
        this.attestationSecurityLevel = SecurityLevel.software;
        this.keyMintVersion = 0;
        this.keyMintSecurityLevel = SecurityLevel.software;
        this.attestationChallenge = new OctetString();
        this.uniqueId = new OctetString();
        this.softwareEnforced = new AuthorizationList();
        this.hardwareEnforced = new AuthorizationList();
        Object.assign(this, params);
    }
    toLegacyKeyDescription() {
        return new KeyDescription({
            attestationVersion: this.attestationVersion,
            attestationSecurityLevel: this.attestationSecurityLevel,
            keymasterVersion: this.keyMintVersion,
            keymasterSecurityLevel: this.keyMintSecurityLevel,
            attestationChallenge: this.attestationChallenge,
            uniqueId: this.uniqueId,
            softwareEnforced: this.softwareEnforced,
            teeEnforced: this.hardwareEnforced,
        });
    }
    static fromLegacyKeyDescription(keyDesc) {
        return new KeyMintKeyDescription({
            attestationVersion: keyDesc.attestationVersion,
            attestationSecurityLevel: keyDesc.attestationSecurityLevel,
            keyMintVersion: keyDesc.keymasterVersion,
            keyMintSecurityLevel: keyDesc.keymasterSecurityLevel,
            attestationChallenge: keyDesc.attestationChallenge,
            uniqueId: keyDesc.uniqueId,
            softwareEnforced: keyDesc.softwareEnforced,
            hardwareEnforced: keyDesc.teeEnforced,
        });
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], KeyMintKeyDescription.prototype, "attestationVersion", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Enumerated })
], KeyMintKeyDescription.prototype, "attestationSecurityLevel", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], KeyMintKeyDescription.prototype, "keyMintVersion", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Enumerated })
], KeyMintKeyDescription.prototype, "keyMintSecurityLevel", void 0);
__decorate$1([
    AsnProp({ type: OctetString })
], KeyMintKeyDescription.prototype, "attestationChallenge", void 0);
__decorate$1([
    AsnProp({ type: OctetString })
], KeyMintKeyDescription.prototype, "uniqueId", void 0);
__decorate$1([
    AsnProp({ type: AuthorizationList })
], KeyMintKeyDescription.prototype, "softwareEnforced", void 0);
__decorate$1([
    AsnProp({ type: AuthorizationList })
], KeyMintKeyDescription.prototype, "hardwareEnforced", void 0);

var NonStandardAuthorizationList_1;
let NonStandardAuthorization = class NonStandardAuthorization extends AuthorizationList {
};
NonStandardAuthorization = __decorate$1([
    AsnType({ type: AsnTypeTypes.Choice })
], NonStandardAuthorization);
let NonStandardAuthorizationList = NonStandardAuthorizationList_1 = class NonStandardAuthorizationList extends AsnArray {
    constructor(items) {
        super(items);
        Object.setPrototypeOf(this, NonStandardAuthorizationList_1.prototype);
    }
    findProperty(key) {
        const prop = this.find((o) => key in o);
        if (prop) {
            return prop[key];
        }
        return undefined;
    }
};
NonStandardAuthorizationList = NonStandardAuthorizationList_1 = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence, itemType: NonStandardAuthorization })
], NonStandardAuthorizationList);
class NonStandardKeyDescription {
    get keyMintVersion() {
        return this.keymasterVersion;
    }
    set keyMintVersion(value) {
        this.keymasterVersion = value;
    }
    get keyMintSecurityLevel() {
        return this.keymasterSecurityLevel;
    }
    set keyMintSecurityLevel(value) {
        this.keymasterSecurityLevel = value;
    }
    get hardwareEnforced() {
        return this.teeEnforced;
    }
    set hardwareEnforced(value) {
        this.teeEnforced = value;
    }
    constructor(params = {}) {
        this.attestationVersion = Version.KM4;
        this.attestationSecurityLevel = SecurityLevel.software;
        this.keymasterVersion = 0;
        this.keymasterSecurityLevel = SecurityLevel.software;
        this.attestationChallenge = new OctetString();
        this.uniqueId = new OctetString();
        this.softwareEnforced = new NonStandardAuthorizationList();
        this.teeEnforced = new NonStandardAuthorizationList();
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], NonStandardKeyDescription.prototype, "attestationVersion", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Enumerated })
], NonStandardKeyDescription.prototype, "attestationSecurityLevel", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], NonStandardKeyDescription.prototype, "keymasterVersion", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Enumerated })
], NonStandardKeyDescription.prototype, "keymasterSecurityLevel", void 0);
__decorate$1([
    AsnProp({ type: OctetString })
], NonStandardKeyDescription.prototype, "attestationChallenge", void 0);
__decorate$1([
    AsnProp({ type: OctetString })
], NonStandardKeyDescription.prototype, "uniqueId", void 0);
__decorate$1([
    AsnProp({ type: NonStandardAuthorizationList })
], NonStandardKeyDescription.prototype, "softwareEnforced", void 0);
__decorate$1([
    AsnProp({ type: NonStandardAuthorizationList })
], NonStandardKeyDescription.prototype, "teeEnforced", void 0);
let NonStandardKeyMintKeyDescription = class NonStandardKeyMintKeyDescription extends NonStandardKeyDescription {
    constructor(params = {}) {
        if ("keymasterVersion" in params && !("keyMintVersion" in params)) {
            params.keyMintVersion = params.keymasterVersion;
        }
        if ("keymasterSecurityLevel" in params && !("keyMintSecurityLevel" in params)) {
            params.keyMintSecurityLevel = params.keymasterSecurityLevel;
        }
        if ("teeEnforced" in params && !("hardwareEnforced" in params)) {
            params.hardwareEnforced = params.teeEnforced;
        }
        super(params);
    }
};
NonStandardKeyMintKeyDescription = __decorate$1([
    AsnType({ type: AsnTypeTypes.Sequence })
], NonStandardKeyMintKeyDescription);

class AttestationPackageInfo {
    constructor(params = {}) {
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AsnPropTypes.OctetString })
], AttestationPackageInfo.prototype, "packageName", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.Integer })
], AttestationPackageInfo.prototype, "version", void 0);
class AttestationApplicationId {
    constructor(params = {}) {
        Object.assign(this, params);
    }
}
__decorate$1([
    AsnProp({ type: AttestationPackageInfo, repeated: "set" })
], AttestationApplicationId.prototype, "packageInfos", void 0);
__decorate$1([
    AsnProp({ type: AsnPropTypes.OctetString, repeated: "set" })
], AttestationApplicationId.prototype, "signatureDigests", void 0);

/**
 * Verify an attestation response with fmt 'android-key'
 */
async function verifyAttestationAndroidKey(options) {
    const { authData, clientDataHash, attStmt, credentialPublicKey, aaguid, rootCertificates, } = options;
    const x5c = attStmt.get('x5c');
    const sig = attStmt.get('sig');
    const alg = attStmt.get('alg');
    if (!x5c) {
        throw new Error('No attestation certificate provided in attestation statement (Android Key)');
    }
    if (!sig) {
        throw new Error('No attestation signature provided in attestation statement (Android Key)');
    }
    if (!alg) {
        throw new Error(`Attestation statement did not contain alg (Android Key)`);
    }
    if (!isCOSEAlg(alg)) {
        throw new Error(`Attestation statement contained invalid alg ${alg} (Android Key)`);
    }
    /**
     * Verify that the public key in the first certificate in x5c matches the credentialPublicKey in
     * the attestedCredentialData in authenticatorData.
     */
    // Find the public cert in the certificate as PKCS
    const parsedCert = AsnParser.parse(x5c[0], Certificate);
    const parsedCertPubKey = new Uint8Array(parsedCert.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey);
    // Convert the credentialPublicKey to PKCS
    const credPubKeyPKCS = convertCOSEtoPKCS(credentialPublicKey);
    if (!areEqual(credPubKeyPKCS, parsedCertPubKey)) {
        throw new Error('Credential public key does not equal leaf cert public key (Android Key)');
    }
    /**
     * Verify that the attestationChallenge field in the attestation certificate extension data is
     * identical to clientDataHash.
     */
    // Find Android KeyStore Extension in certificate extensions
    const extKeyStore = parsedCert.tbsCertificate.extensions?.find((ext) => ext.extnID === id_ce_keyDescription);
    if (!extKeyStore) {
        throw new Error('Certificate did not contain extKeyStore (Android Key)');
    }
    const parsedExtKeyStore = AsnParser.parse(extKeyStore.extnValue, KeyDescription);
    // Verify extKeyStore values
    const { attestationChallenge, teeEnforced, softwareEnforced } = parsedExtKeyStore;
    if (!areEqual(new Uint8Array(attestationChallenge.buffer), clientDataHash)) {
        throw new Error('Attestation challenge was not equal to client data hash (Android Key)');
    }
    /**
     * The AuthorizationList.allApplications field is not present on either authorization list
     * (softwareEnforced nor teeEnforced), since PublicKeyCredential MUST be scoped to the RP ID.
     *
     * (i.e. These shouldn't contain the [600] tag)
     */
    if (teeEnforced.allApplications !== undefined) {
        throw new Error('teeEnforced contained "allApplications [600]" tag (Android Key)');
    }
    if (softwareEnforced.allApplications !== undefined) {
        throw new Error('teeEnforced contained "allApplications [600]" tag (Android Key)');
    }
    const statement = await MetadataService.getStatement(aaguid);
    if (statement) {
        try {
            await verifyAttestationWithMetadata({
                statement,
                credentialPublicKey,
                x5c,
                attestationStatementAlg: alg,
            });
        }
        catch (err) {
            const _err = err;
            throw new Error(`${_err.message} (Android Key)`, { cause: _err });
        }
    }
    else {
        /**
         * Verify that x5c contains a full certificate path.
         */
        const x5cNoRootPEM = x5c.slice(0, -1).map(convertCertBufferToPEM);
        const x5cRootPEM = x5c.slice(-1).map(convertCertBufferToPEM);
        try {
            await validateCertificatePath(x5cNoRootPEM, x5cRootPEM);
        }
        catch (err) {
            const _err = err;
            throw new Error(`${_err.message} (Android Key)`, { cause: _err });
        }
        /**
         * Make sure the root certificate is one of the Google Hardware Attestation Root certificates
         *
         * https://developer.android.com/privacy-and-security/security-key-attestation#root_certificate
         */
        if (rootCertificates.length > 0 && rootCertificates.indexOf(x5cRootPEM[0]) < 0) {
            throw new Error('x5c root certificate was not a known root certificate (Android Key)');
        }
    }
    /**
     * Verify that sig is a valid signature over the concatenation of authenticatorData and
     * clientDataHash using the public key in the first certificate in x5c with the algorithm
     * specified in alg.
     */
    const signatureBase = concat([authData, clientDataHash]);
    return verifySignature({
        signature: sig,
        data: signatureBase,
        x509Certificate: x5c[0],
        hashAlgorithm: alg,
    });
}

async function verifyAttestationApple(options) {
    const { attStmt, authData, clientDataHash, credentialPublicKey, rootCertificates, } = options;
    const x5c = attStmt.get('x5c');
    if (!x5c) {
        throw new Error('No attestation certificate provided in attestation statement (Apple)');
    }
    /**
     * Verify certificate path
     */
    try {
        await validateCertificatePath(x5c.map(convertCertBufferToPEM), rootCertificates);
    }
    catch (err) {
        const _err = err;
        throw new Error(`${_err.message} (Apple)`);
    }
    /**
     * Compare nonce in certificate extension to computed nonce
     */
    const parsedCredCert = AsnParser.parse(x5c[0], Certificate);
    const { extensions, subjectPublicKeyInfo } = parsedCredCert.tbsCertificate;
    if (!extensions) {
        throw new Error('credCert missing extensions (Apple)');
    }
    const extCertNonce = extensions.find((ext) => ext.extnID === '1.2.840.113635.100.8.2');
    if (!extCertNonce) {
        throw new Error('credCert missing "1.2.840.113635.100.8.2" extension (Apple)');
    }
    const nonceToHash = concat([authData, clientDataHash]);
    const nonce = await toHash(nonceToHash);
    /**
     * Ignore the first six ASN.1 structure bytes that define the nonce as an OCTET STRING. Should
     * trim off <Buffer 30 24 a1 22 04 20>
     *
     * TODO: Try and get @peculiar (GitHub) to add a schema for "1.2.840.113635.100.8.2" when we
     * find out where it's defined (doesn't seem to be publicly documented at the moment...)
     */
    const extNonce = new Uint8Array(extCertNonce.extnValue.buffer).slice(6);
    if (!areEqual(nonce, extNonce)) {
        throw new Error(`credCert nonce was not expected value (Apple)`);
    }
    /**
     * Verify credential public key matches the Subject Public Key of credCert
     */
    const credPubKeyPKCS = convertCOSEtoPKCS(credentialPublicKey);
    const credCertSubjectPublicKey = new Uint8Array(subjectPublicKeyInfo.subjectPublicKey);
    if (!areEqual(credPubKeyPKCS, credCertSubjectPublicKey)) {
        throw new Error('Credential public key does not equal credCert public key (Apple)');
    }
    return true;
}

/**
 * Verify that the user has legitimately completed the registration process
 *
 * **Options:**
 *
 * @param response - Response returned by **@simplewebauthn/browser**'s `startAuthentication()`
 * @param expectedChallenge - The base64url-encoded `options.challenge` returned by `generateRegistrationOptions()`
 * @param expectedOrigin - Website URL (or array of URLs) that the registration should have occurred on
 * @param expectedRPID - RP ID (or array of IDs) that was specified in the registration options
 * @param expectedType **(Optional)** - The response type expected ('webauthn.create')
 * @param requireUserPresence **(Optional)** - Enforce user presence by the authenticator (or skip it during auto registration) Defaults to `true`
 * @param requireUserVerification **(Optional)** - Enforce user verification by the authenticator (via PIN, fingerprint, etc...) Defaults to `true`
 * @param supportedAlgorithmIDs **(Optional)** - Array of numeric COSE algorithm identifiers supported for attestation by this RP. See https://www.iana.org/assignments/cose/cose.xhtml#algorithms. Defaults to all supported algorithm IDs
 * @param attestationSafetyNetEnforceCTSCheck **(Optional)** - Require that an Android device's system integrity has not been tampered with if it uses SafetyNet attestation. Defaults to `true`
 */
async function verifyRegistrationResponse(options) {
    const { response, expectedChallenge, expectedOrigin, expectedRPID, expectedType, requireUserPresence = true, requireUserVerification = true, supportedAlgorithmIDs = supportedCOSEAlgorithmIdentifiers, attestationSafetyNetEnforceCTSCheck = true, } = options;
    const { id, rawId, type: credentialType, response: attestationResponse } = response;
    // Ensure credential specified an ID
    if (!id) {
        throw new Error('Missing credential ID');
    }
    // Ensure ID is base64url-encoded
    if (id !== rawId) {
        throw new Error('Credential ID was not base64url-encoded');
    }
    // Make sure credential type is public-key
    if (credentialType !== 'public-key') {
        throw new Error(`Unexpected credential type ${credentialType}, expected "public-key"`);
    }
    const clientDataJSON = decodeClientDataJSON(attestationResponse.clientDataJSON);
    const { type, origin, challenge, tokenBinding } = clientDataJSON;
    // Make sure we're handling an registration
    if (Array.isArray(expectedType)) {
        if (!expectedType.includes(type)) {
            const joinedExpectedType = expectedType.join(', ');
            throw new Error(`Unexpected registration response type "${type}", expected one of: ${joinedExpectedType}`);
        }
    }
    else if (expectedType) {
        if (type !== expectedType) {
            throw new Error(`Unexpected registration response type "${type}", expected "${expectedType}"`);
        }
    }
    else if (type !== 'webauthn.create') {
        throw new Error(`Unexpected registration response type: ${type}`);
    }
    // Ensure the device provided the challenge we gave it
    if (typeof expectedChallenge === 'function') {
        if (!(await expectedChallenge(challenge))) {
            throw new Error(`Custom challenge verifier returned false for registration response challenge "${challenge}"`);
        }
    }
    else if (challenge !== expectedChallenge) {
        throw new Error(`Unexpected registration response challenge "${challenge}", expected "${expectedChallenge}"`);
    }
    // Check that the origin is our site
    if (Array.isArray(expectedOrigin)) {
        if (!expectedOrigin.includes(origin)) {
            throw new Error(`Unexpected registration response origin "${origin}", expected one of: ${expectedOrigin.join(', ')}`);
        }
    }
    else {
        if (origin !== expectedOrigin) {
            throw new Error(`Unexpected registration response origin "${origin}", expected "${expectedOrigin}"`);
        }
    }
    if (tokenBinding) {
        if (typeof tokenBinding !== 'object') {
            throw new Error(`Unexpected value for TokenBinding "${tokenBinding}"`);
        }
        if (['present', 'supported', 'not-supported'].indexOf(tokenBinding.status) < 0) {
            throw new Error(`Unexpected tokenBinding.status value of "${tokenBinding.status}"`);
        }
    }
    const attestationObject = toBuffer(attestationResponse.attestationObject);
    const decodedAttestationObject = decodeAttestationObject(attestationObject);
    const fmt = decodedAttestationObject.get('fmt');
    const authData = decodedAttestationObject.get('authData');
    const attStmt = decodedAttestationObject.get('attStmt');
    const parsedAuthData = parseAuthenticatorData(authData);
    const { aaguid, rpIdHash, flags, credentialID, counter, credentialPublicKey, extensionsData, } = parsedAuthData;
    // Make sure the response's RP ID is ours
    let matchedRPID;
    if (expectedRPID) {
        let expectedRPIDs = [];
        if (typeof expectedRPID === 'string') {
            expectedRPIDs = [expectedRPID];
        }
        else {
            expectedRPIDs = expectedRPID;
        }
        matchedRPID = await matchExpectedRPID(rpIdHash, expectedRPIDs);
    }
    // Make sure someone was physically present
    if (requireUserPresence && !flags.up) {
        throw new Error('User presence was required, but user was not present');
    }
    // Enforce user verification if specified
    if (requireUserVerification && !flags.uv) {
        throw new Error('User verification was required, but user could not be verified');
    }
    if (!credentialID) {
        throw new Error('No credential ID was provided by authenticator');
    }
    if (!credentialPublicKey) {
        throw new Error('No public key was provided by authenticator');
    }
    if (!aaguid) {
        throw new Error('No AAGUID was present during registration');
    }
    const decodedPublicKey = decodeCredentialPublicKey(credentialPublicKey);
    const alg = decodedPublicKey.get(COSEKEYS.alg);
    if (typeof alg !== 'number') {
        throw new Error('Credential public key was missing numeric alg');
    }
    // Make sure the key algorithm is one we specified within the registration options
    if (!supportedAlgorithmIDs.includes(alg)) {
        const supported = supportedAlgorithmIDs.join(', ');
        throw new Error(`Unexpected public key alg "${alg}", expected one of "${supported}"`);
    }
    const clientDataHash = await toHash(toBuffer(attestationResponse.clientDataJSON));
    const rootCertificates = SettingsService.getRootCertificates({
        identifier: fmt,
    });
    // Prepare arguments to pass to the relevant verification method
    const verifierOpts = {
        aaguid,
        attStmt,
        authData,
        clientDataHash,
        credentialID,
        credentialPublicKey,
        rootCertificates,
        rpIdHash,
        attestationSafetyNetEnforceCTSCheck,
    };
    /**
     * Verification can only be performed when attestation = 'direct'
     */
    let verified = false;
    if (fmt === 'fido-u2f') {
        verified = await verifyAttestationFIDOU2F(verifierOpts);
    }
    else if (fmt === 'packed') {
        verified = await verifyAttestationPacked(verifierOpts);
    }
    else if (fmt === 'android-safetynet') {
        verified = await verifyAttestationAndroidSafetyNet(verifierOpts);
    }
    else if (fmt === 'android-key') {
        verified = await verifyAttestationAndroidKey(verifierOpts);
    }
    else if (fmt === 'tpm') {
        verified = await verifyAttestationTPM(verifierOpts);
    }
    else if (fmt === 'apple') {
        verified = await verifyAttestationApple(verifierOpts);
    }
    else if (fmt === 'none') {
        if (attStmt.size > 0) {
            throw new Error('None attestation had unexpected attestation statement');
        }
        // This is the weaker of the attestations, so there's nothing else to really check
        verified = true;
    }
    else {
        throw new Error(`Unsupported Attestation Format: ${fmt}`);
    }
    if (!verified) {
        return { verified: false };
    }
    const { credentialDeviceType, credentialBackedUp } = parseBackupFlags(flags);
    return {
        verified: true,
        registrationInfo: {
            fmt,
            aaguid: convertAAGUIDToString(aaguid),
            credentialType,
            credential: {
                id: fromBuffer(credentialID),
                publicKey: credentialPublicKey,
                counter,
                transports: response.response.transports,
            },
            attestationObject,
            userVerified: flags.uv,
            credentialDeviceType,
            credentialBackedUp,
            origin: clientDataJSON.origin,
            rpID: matchedRPID,
            authenticatorExtensionResults: extensionsData,
        },
    };
}

/**
 * Prepare a value to pass into navigator.credentials.get(...) for authenticator authentication
 *
 * **Options:**
 *
 * @param rpID - Valid domain name (after `https://`)
 * @param allowCredentials **(Optional)** - Authenticators previously registered by the user, if any. If undefined the client will ask the user which credential they want to use
 * @param challenge **(Optional)** - Random value the authenticator needs to sign and pass back user for authentication. Defaults to generating a random value
 * @param timeout **(Optional)** - How long (in ms) the user can take to complete authentication. Defaults to `60000`
 * @param userVerification **(Optional)** - Set to `'discouraged'` when asserting as part of a 2FA flow, otherwise set to `'preferred'` or `'required'` as desired. Defaults to `"preferred"`
 * @param extensions **(Optional)** - Additional plugins the authenticator or browser should use during authentication
 */
async function generateAuthenticationOptions(options) {
    const { allowCredentials, challenge = await generateChallenge(), timeout = 60000, userVerification = 'preferred', extensions, rpID, } = options;
    /**
     * Preserve ability to specify `string` values for challenges
     */
    let _challenge = challenge;
    if (typeof _challenge === 'string') {
        _challenge = fromUTF8String(_challenge);
    }
    return {
        rpId: rpID,
        challenge: fromBuffer(_challenge),
        allowCredentials: allowCredentials?.map((cred) => {
            if (!isBase64URL(cred.id)) {
                throw new Error(`allowCredential id "${cred.id}" is not a valid base64url string`);
            }
            return {
                ...cred,
                id: trimPadding(cred.id),
                type: 'public-key',
            };
        }),
        timeout,
        userVerification,
        extensions,
    };
}

/**
 * Verify that the user has legitimately completed the authentication process
 *
 * **Options:**
 *
 * @param response - Response returned by **@simplewebauthn/browser**'s `startAssertion()`
 * @param expectedChallenge - The base64url-encoded `options.challenge` returned by `generateAuthenticationOptions()`
 * @param expectedOrigin - Website URL (or array of URLs) that the registration should have occurred on
 * @param expectedRPID - RP ID (or array of IDs) that was specified in the registration options
 * @param credential - An internal {@link WebAuthnCredential} corresponding to `id` in the authentication response
 * @param expectedType **(Optional)** - The response type expected ('webauthn.get')
 * @param requireUserVerification **(Optional)** - Enforce user verification by the authenticator (via PIN, fingerprint, etc...) Defaults to `true`
 * @param advancedFIDOConfig **(Optional)** - Options for satisfying more stringent FIDO RP feature requirements
 * @param advancedFIDOConfig.userVerification **(Optional)** - Enable alternative rules for evaluating the User Presence and User Verified flags in authenticator data: UV (and UP) flags are optional unless this value is `"required"`
 */
async function verifyAuthenticationResponse(options) {
    const { response, expectedChallenge, expectedOrigin, expectedRPID, expectedType, credential, requireUserVerification = true, advancedFIDOConfig, } = options;
    const { id, rawId, type: credentialType, response: assertionResponse } = response;
    // Ensure credential specified an ID
    if (!id) {
        throw new Error('Missing credential ID');
    }
    // Ensure ID is base64url-encoded
    if (id !== rawId) {
        throw new Error('Credential ID was not base64url-encoded');
    }
    // Make sure credential type is public-key
    if (credentialType !== 'public-key') {
        throw new Error(`Unexpected credential type ${credentialType}, expected "public-key"`);
    }
    if (!response) {
        throw new Error('Credential missing response');
    }
    if (typeof assertionResponse?.clientDataJSON !== 'string') {
        throw new Error('Credential response clientDataJSON was not a string');
    }
    const clientDataJSON = decodeClientDataJSON(assertionResponse.clientDataJSON);
    const { type, origin, challenge, tokenBinding } = clientDataJSON;
    // Make sure we're handling an authentication
    if (Array.isArray(expectedType)) {
        if (!expectedType.includes(type)) {
            const joinedExpectedType = expectedType.join(', ');
            throw new Error(`Unexpected authentication response type "${type}", expected one of: ${joinedExpectedType}`);
        }
    }
    else if (expectedType) {
        if (type !== expectedType) {
            throw new Error(`Unexpected authentication response type "${type}", expected "${expectedType}"`);
        }
    }
    else if (type !== 'webauthn.get') {
        throw new Error(`Unexpected authentication response type: ${type}`);
    }
    // Ensure the device provided the challenge we gave it
    if (typeof expectedChallenge === 'function') {
        if (!(await expectedChallenge(challenge))) {
            throw new Error(`Custom challenge verifier returned false for registration response challenge "${challenge}"`);
        }
    }
    else if (challenge !== expectedChallenge) {
        throw new Error(`Unexpected authentication response challenge "${challenge}", expected "${expectedChallenge}"`);
    }
    // Check that the origin is our site
    if (Array.isArray(expectedOrigin)) {
        if (!expectedOrigin.includes(origin)) {
            const joinedExpectedOrigin = expectedOrigin.join(', ');
            throw new Error(`Unexpected authentication response origin "${origin}", expected one of: ${joinedExpectedOrigin}`);
        }
    }
    else {
        if (origin !== expectedOrigin) {
            throw new Error(`Unexpected authentication response origin "${origin}", expected "${expectedOrigin}"`);
        }
    }
    if (!isBase64URL(assertionResponse.authenticatorData)) {
        throw new Error('Credential response authenticatorData was not a base64url string');
    }
    if (!isBase64URL(assertionResponse.signature)) {
        throw new Error('Credential response signature was not a base64url string');
    }
    if (assertionResponse.userHandle &&
        typeof assertionResponse.userHandle !== 'string') {
        throw new Error('Credential response userHandle was not a string');
    }
    if (tokenBinding) {
        if (typeof tokenBinding !== 'object') {
            throw new Error('ClientDataJSON tokenBinding was not an object');
        }
        if (['present', 'supported', 'notSupported'].indexOf(tokenBinding.status) < 0) {
            throw new Error(`Unexpected tokenBinding status ${tokenBinding.status}`);
        }
    }
    const authDataBuffer = toBuffer(assertionResponse.authenticatorData);
    const parsedAuthData = parseAuthenticatorData(authDataBuffer);
    const { rpIdHash, flags, counter, extensionsData } = parsedAuthData;
    // Make sure the response's RP ID is ours
    let expectedRPIDs = [];
    if (typeof expectedRPID === 'string') {
        expectedRPIDs = [expectedRPID];
    }
    else {
        expectedRPIDs = expectedRPID;
    }
    const matchedRPID = await matchExpectedRPID(rpIdHash, expectedRPIDs);
    if (advancedFIDOConfig !== undefined) {
        const { userVerification: fidoUserVerification } = advancedFIDOConfig;
        /**
         * Use FIDO Conformance-defined rules for verifying UP and UV flags
         */
        if (fidoUserVerification === 'required') {
            // Require `flags.uv` be true (implies `flags.up` is true)
            if (!flags.uv) {
                throw new Error('User verification required, but user could not be verified');
            }
        }
    }
    else {
        /**
         * Use WebAuthn spec-defined rules for verifying UP and UV flags
         */
        // WebAuthn only requires the user presence flag be true
        if (!flags.up) {
            throw new Error('User not present during authentication');
        }
        // Enforce user verification if required
        if (requireUserVerification && !flags.uv) {
            throw new Error('User verification required, but user could not be verified');
        }
    }
    const clientDataHash = await toHash(toBuffer(assertionResponse.clientDataJSON));
    const signatureBase = concat([authDataBuffer, clientDataHash]);
    const signature = toBuffer(assertionResponse.signature);
    if ((counter > 0 || credential.counter > 0) &&
        counter <= credential.counter) {
        // Error out when the counter in the DB is greater than or equal to the counter in the
        // dataStruct. It's related to how the authenticator maintains the number of times its been
        // used for this client. If this happens, then someone's somehow increased the counter
        // on the device without going through this site
        throw new Error(`Response counter value ${counter} was lower than expected ${credential.counter}`);
    }
    const { credentialDeviceType, credentialBackedUp } = parseBackupFlags(flags);
    const toReturn = {
        verified: await verifySignature({
            signature,
            data: signatureBase,
            credentialPublicKey: credential.publicKey,
        }),
        authenticationInfo: {
            newCounter: counter,
            credentialID: credential.id,
            userVerified: flags.uv,
            credentialDeviceType,
            credentialBackedUp,
            authenticatorExtensionResults: extensionsData,
            origin: clientDataJSON.origin,
            rpID: matchedRPID,
        },
    };
    return toReturn;
}

const RP_NAME = "NapCat WebUI";
class PasskeyHelper {
  static getPasskeyFilePath() {
    return path__default.join(webUiPathWrapper.configPath, "passkey.json");
  }
  // 内存中存储临时挑战数据
  static challenges = /* @__PURE__ */ new Map();
  static async ensurePasskeyFile() {
    try {
      const passkeyFile = this.getPasskeyFilePath();
      await promises.mkdir(path__default.dirname(passkeyFile), { recursive: true });
      try {
        await promises.access(passkeyFile);
      } catch {
        await promises.writeFile(passkeyFile, JSON.stringify({}, null, 2));
      }
    } catch (error) {
    }
  }
  static async getAllPasskeys() {
    await this.ensurePasskeyFile();
    try {
      const passkeyFile = this.getPasskeyFilePath();
      const data = await promises.readFile(passkeyFile, "utf-8");
      const passkeys = JSON.parse(data);
      return typeof passkeys === "object" && passkeys !== null ? passkeys : {};
    } catch (error) {
      return {};
    }
  }
  static async saveAllPasskeys(allPasskeys) {
    await this.ensurePasskeyFile();
    const passkeyFile = this.getPasskeyFilePath();
    await promises.writeFile(passkeyFile, JSON.stringify(allPasskeys, null, 2));
  }
  static async getUserPasskeys(userId) {
    const allPasskeys = await this.getAllPasskeys();
    return allPasskeys[userId] || [];
  }
  // 持久性存储用户的passkey到统一配置文件
  static async setUserPasskeys(userId, passkeys) {
    const allPasskeys = await this.getAllPasskeys();
    if (passkeys.length > 0) {
      allPasskeys[userId] = passkeys;
    } else {
      delete allPasskeys[userId];
    }
    await this.saveAllPasskeys(allPasskeys);
  }
  static async generateRegistrationOptions(userId, userName, rpId) {
    const userPasskeys = await this.getUserPasskeys(userId);
    const options = await generateRegistrationOptions({
      rpName: RP_NAME,
      rpID: rpId,
      userID: new TextEncoder().encode(userId),
      userName,
      attestationType: "none",
      excludeCredentials: userPasskeys.map((passkey) => ({
        id: passkey.id,
        type: "public-key",
        transports: passkey.transports
      })),
      // Temporarily simplify authenticatorSelection - remove residentKey to avoid conflicts
      authenticatorSelection: {
        userVerification: "preferred"
      }
    });
    this.challenges.set(`reg_${userId}`, options.challenge);
    setTimeout(() => {
      this.challenges.delete(`reg_${userId}`);
    }, 3e5);
    return options;
  }
  static async verifyRegistration(userId, response, origin, rpId) {
    const expectedChallenge = this.challenges.get(`reg_${userId}`);
    if (!expectedChallenge) {
      throw new Error("Challenge not found or expired");
    }
    const verification = await verifyRegistrationResponse({
      response,
      expectedChallenge,
      expectedOrigin: origin,
      expectedRPID: rpId
    });
    if (verification.verified && verification.registrationInfo) {
      const { registrationInfo } = verification;
      const newPasskey = {
        id: registrationInfo.credential.id,
        publicKey: fromBuffer(registrationInfo.credential.publicKey),
        counter: registrationInfo.credential.counter || 0,
        transports: response.response.transports
      };
      const userPasskeys = await this.getUserPasskeys(userId);
      userPasskeys.push(newPasskey);
      await this.setUserPasskeys(userId, userPasskeys);
      this.challenges.delete(`reg_${userId}`);
    }
    return verification;
  }
  static async generateAuthenticationOptions(userId, rpId) {
    const userPasskeys = await this.getUserPasskeys(userId);
    const options = await generateAuthenticationOptions({
      rpID: rpId,
      allowCredentials: userPasskeys.map((passkey) => ({
        id: passkey.id,
        type: "public-key",
        transports: passkey.transports
      })),
      userVerification: "preferred"
    });
    this.challenges.set(`auth_${userId}`, options.challenge);
    setTimeout(() => {
      this.challenges.delete(`auth_${userId}`);
    }, 3e5);
    return options;
  }
  static async verifyAuthentication(userId, response, origin, rpId) {
    const expectedChallenge = this.challenges.get(`auth_${userId}`);
    if (!expectedChallenge) {
      throw new Error("Challenge not found or expired");
    }
    const userPasskeys = await this.getUserPasskeys(userId);
    const passkey = userPasskeys.find((p) => p.id === response.id);
    if (!passkey) {
      throw new Error("Passkey not found");
    }
    const verification = await verifyAuthenticationResponse({
      response,
      expectedChallenge,
      expectedOrigin: origin,
      expectedRPID: rpId,
      credential: {
        id: passkey.id,
        publicKey: toBuffer(passkey.publicKey),
        counter: passkey.counter
      }
    });
    if (verification.verified && verification.authenticationInfo) {
      passkey.counter = verification.authenticationInfo.newCounter;
      await this.setUserPasskeys(userId, userPasskeys);
      this.challenges.delete(`auth_${userId}`);
    }
    return verification;
  }
  static async hasPasskeys(userId) {
    const userPasskeys = await this.getUserPasskeys(userId);
    return userPasskeys.length > 0;
  }
}

const LoginHandler = async (req, res) => {
  const WebUiConfigData = await WebUiConfig.GetWebUIConfig();
  const { hash } = req.body;
  const clientIP = req.ip || req.socket.remoteAddress || "";
  if (isEmpty(hash)) {
    return sendError(res, "token is empty");
  }
  if (!WebUiDataRuntime.checkLoginRate(clientIP, WebUiConfigData.loginRate)) {
    return sendError(res, "login rate limit");
  }
  const initialToken = getInitialWebUiToken();
  if (!initialToken) {
    return sendError(res, "Server token not initialized");
  }
  if (!AuthHelper.comparePasswordHash(initialToken, hash)) {
    return sendError(res, "token is invalid");
  }
  const signCredential = Buffer.from(JSON.stringify(AuthHelper.signCredential(hash))).toString(
    "base64"
  );
  return sendSuccess(res, {
    Credential: signCredential
  });
};
const LogoutHandler = async (req, res) => {
  const authorization = req.headers.authorization;
  try {
    const CredentialBase64 = authorization?.split(" ")[1];
    const Credential = JSON.parse(Buffer.from(CredentialBase64, "base64").toString());
    AuthHelper.revokeCredential(Credential);
    return sendSuccess(res, "Logged out successfully");
  } catch (_e) {
    return sendError(res, "Logout failed");
  }
};
const checkHandler = async (req, res) => {
  const authorization = req.headers.authorization;
  try {
    const CredentialBase64 = authorization?.split(" ")[1];
    const Credential = JSON.parse(Buffer.from(CredentialBase64, "base64").toString());
    if (AuthHelper.isCredentialRevoked(Credential)) {
      return sendError(res, "Token has been revoked");
    }
    const initialToken = getInitialWebUiToken();
    if (!initialToken) {
      return sendError(res, "Server token not initialized");
    }
    const valid = AuthHelper.validateCredentialWithinOneHour(initialToken, Credential);
    if (valid) return sendSuccess(res, null);
    return sendError(res, "Authorization Failed");
  } catch (_e) {
    return sendError(res, "Authorization Failed");
  }
};
const UpdateTokenHandler = async (req, res) => {
  const { oldToken, newToken } = req.body;
  const authorization = req.headers.authorization;
  if (isEmpty(newToken)) {
    return sendError(res, "newToken is empty");
  }
  if (isEmpty(oldToken)) {
    return sendError(res, "oldToken is required");
  }
  if (oldToken === newToken) {
    return sendError(res, "新密码不能与旧密码相同");
  }
  if (newToken.length < 6) {
    return sendError(res, "新密码至少需要6个字符");
  }
  if (!/[a-zA-Z]/.test(newToken)) {
    return sendError(res, "新密码必须包含字母");
  }
  if (!/[0-9]/.test(newToken)) {
    return sendError(res, "新密码必须包含数字");
  }
  try {
    if (authorization) {
      const CredentialBase64 = authorization.split(" ")[1];
      const Credential = JSON.parse(Buffer.from(CredentialBase64, "base64").toString());
      AuthHelper.revokeCredential(Credential);
    }
    const initialToken = getInitialWebUiToken();
    if (!initialToken) {
      return sendError(res, "Server token not initialized");
    }
    if (initialToken !== oldToken) {
      return sendError(res, "旧 token 不匹配");
    }
    await WebUiConfig.UpdateWebUIConfig({ token: newToken });
    setInitialWebUiToken(newToken);
    return sendSuccess(res, "Token updated successfully");
  } catch (e) {
    return sendError(res, `Failed to update token: ${e.message}`);
  }
};
const GeneratePasskeyRegistrationOptionsHandler = async (_req, res) => {
  try {
    const userId = "napcat-user";
    const userName = "NapCat User";
    const host = _req.get("host") || "localhost";
    const hostname = host.split(":")[0] || "localhost";
    const rpId = hostname === "127.0.0.1" || hostname === "localhost" ? "localhost" : hostname;
    const options = await PasskeyHelper.generateRegistrationOptions(userId, userName, rpId);
    return sendSuccess(res, options);
  } catch (error) {
    return sendError(res, `Failed to generate registration options: ${error.message}`);
  }
};
const VerifyPasskeyRegistrationHandler = async (req, res) => {
  try {
    const { response } = req.body;
    if (!response) {
      return sendError(res, "Response is required");
    }
    const origin = req.get("origin") || req.protocol + "://" + req.get("host");
    const host = req.get("host") || "localhost";
    const hostname = host.split(":")[0] || "localhost";
    const rpId = hostname === "127.0.0.1" || hostname === "localhost" ? "localhost" : hostname;
    const userId = "napcat-user";
    const verification = await PasskeyHelper.verifyRegistration(userId, response, origin, rpId);
    if (verification.verified) {
      return sendSuccess(res, { verified: true });
    } else {
      return sendError(res, "Registration failed");
    }
  } catch (error) {
    return sendError(res, `Registration verification failed: ${error.message}`);
  }
};
const GeneratePasskeyAuthenticationOptionsHandler = async (_req, res) => {
  try {
    const userId = "napcat-user";
    if (!await PasskeyHelper.hasPasskeys(userId)) {
      return sendError(res, "No passkeys registered");
    }
    const host = _req.get("host") || "localhost";
    const hostname = host.split(":")[0] || "localhost";
    const rpId = hostname === "127.0.0.1" || hostname === "localhost" ? "localhost" : hostname;
    const options = await PasskeyHelper.generateAuthenticationOptions(userId, rpId);
    return sendSuccess(res, options);
  } catch (error) {
    return sendError(res, `Failed to generate authentication options: ${error.message}`);
  }
};
const VerifyPasskeyAuthenticationHandler = async (req, res) => {
  try {
    const { response } = req.body;
    if (!response) {
      return sendError(res, "Response is required");
    }
    const WebUiConfigData = await WebUiConfig.GetWebUIConfig();
    const clientIP = req.ip || req.socket.remoteAddress || "";
    if (!WebUiDataRuntime.checkLoginRate(clientIP, WebUiConfigData.loginRate)) {
      return sendError(res, "login rate limit");
    }
    const origin = req.get("origin") || req.protocol + "://" + req.get("host");
    const host = req.get("host") || "localhost";
    const hostname = host.split(":")[0] || "localhost";
    const rpId = hostname === "127.0.0.1" || hostname === "localhost" ? "localhost" : hostname;
    const userId = "napcat-user";
    const verification = await PasskeyHelper.verifyAuthentication(userId, response, origin, rpId);
    if (verification.verified) {
      const initialToken = getInitialWebUiToken();
      if (!initialToken) {
        return sendError(res, "Server token not initialized");
      }
      const signCredential = Buffer.from(JSON.stringify(AuthHelper.signCredential(AuthHelper.generatePasswordHash(initialToken)))).toString("base64");
      return sendSuccess(res, {
        Credential: signCredential
      });
    } else {
      return sendError(res, "Authentication failed");
    }
  } catch (error) {
    return sendError(res, `Authentication verification failed: ${error.message}`);
  }
};

const router$7 = Router();
router$7.post("/login", LoginHandler);
router$7.post("/check", checkHandler);
router$7.post("/logout", LogoutHandler);
router$7.post("/update_token", UpdateTokenHandler);
router$7.post("/passkey/generate-registration-options", GeneratePasskeyRegistrationOptionsHandler);
router$7.post("/passkey/verify-registration", VerifyPasskeyRegistrationHandler);
router$7.post("/passkey/generate-authentication-options", GeneratePasskeyAuthenticationOptionsHandler);
router$7.post("/passkey/verify-authentication", VerifyPasskeyAuthenticationHandler);

class EventEmitter2 {
  _listeners = [];
  _event;
  get event() {
    if (!this._event) {
      this._event = (listener) => {
        this._listeners.push(listener);
        const disposable = {
          dispose: () => {
            for (let i = 0; i < this._listeners.length; i++) {
              if (this._listeners[i] === listener) {
                this._listeners.splice(i, 1);
                return;
              }
            }
          }
        };
        return disposable;
      };
    }
    return this._event;
  }
  fire(data) {
    const queue = [];
    for (let i = 0; i < this._listeners.length; i++) {
      queue.push(this._listeners[i]);
    }
    for (let i = 0; i < queue.length; i++) {
      queue[i].call(void 0, data);
    }
  }
}

const DEFAULT_COLS = 80;
const DEFAULT_ROWS = 24;
const FLOW_CONTROL_PAUSE = "";
const FLOW_CONTROL_RESUME = "";
class Terminal {
  _socket;
  // HACK: This is unsafe
  _pid = 0;
  _fd = 0;
  _pty;
  _file;
  // HACK: This is unsafe
  _name;
  // HACK: This is unsafe
  _cols = 0;
  _rows = 0;
  _readable = false;
  _writable = false;
  _internalee;
  _flowControlPause;
  _flowControlResume;
  handleFlowControl;
  _onData = new EventEmitter2();
  get onData() {
    return this._onData.event;
  }
  _onExit = new EventEmitter2();
  get onExit() {
    return this._onExit.event;
  }
  get pid() {
    return this._pid;
  }
  get cols() {
    return this._cols;
  }
  get rows() {
    return this._rows;
  }
  constructor(opt) {
    this._internalee = new EventEmitter$2();
    this.handleFlowControl = !!opt?.handleFlowControl;
    this._flowControlPause = opt?.flowControlPause || FLOW_CONTROL_PAUSE;
    this._flowControlResume = opt?.flowControlResume || FLOW_CONTROL_RESUME;
    if (!opt) {
      return;
    }
    this._checkType("name", opt.name ? opt.name : void 0, "string");
    this._checkType("cols", opt.cols ? opt.cols : void 0, "number");
    this._checkType("rows", opt.rows ? opt.rows : void 0, "number");
    this._checkType("cwd", opt.cwd ? opt.cwd : void 0, "string");
    this._checkType("env", opt.env ? opt.env : void 0, "object");
    this._checkType("uid", opt.uid ? opt.uid : void 0, "number");
    this._checkType("gid", opt.gid ? opt.gid : void 0, "number");
    this._checkType("encoding", opt.encoding ? opt.encoding : void 0, "string");
  }
  write(data) {
    if (this.handleFlowControl) {
      if (data === this._flowControlPause) {
        this.pause();
        return;
      }
      if (data === this._flowControlResume) {
        this.resume();
        return;
      }
    }
    this._write(data);
  }
  _forwardEvents() {
    this.on("data", (e) => this._onData.fire(e));
    this.on("exit", (exitCode, signal) => this._onExit.fire({ exitCode, signal }));
  }
  _checkType(name, value, type, allowArray = false) {
    if (value === void 0) {
      return;
    }
    if (allowArray) {
      if (Array.isArray(value)) {
        value.forEach((v, i) => {
          if (typeof v !== type) {
            throw new Error(`${name}[${i}] must be a ${type} (not a ${typeof v[i]})`);
          }
        });
        return;
      }
    }
    if (typeof value !== type) {
      throw new Error(`${name} must be a ${type} (not a ${typeof value})`);
    }
  }
  /** See net.Socket.end */
  end(data) {
    this._socket.end(data);
  }
  /** See stream.Readable.pipe */
  pipe(dest, options) {
    return this._socket.pipe(dest, options);
  }
  /** See net.Socket.pause */
  pause() {
    return this._socket.pause();
  }
  /** See net.Socket.resume */
  resume() {
    return this._socket.resume();
  }
  /** See net.Socket.setEncoding */
  setEncoding(encoding) {
    if (this._socket._decoder) {
      delete this._socket._decoder;
    }
    if (encoding) {
      this._socket.setEncoding(encoding);
    }
  }
  addListener(eventName, listener) {
    this.on(eventName, listener);
  }
  on(eventName, listener) {
    if (eventName === "close") {
      this._internalee.on("close", listener);
      return;
    }
    this._socket.on(eventName, listener);
  }
  emit(eventName, ...args) {
    if (eventName === "close") {
      return this._internalee.emit.apply(this._internalee, arguments);
    }
    return this._socket.emit.apply(this._socket, arguments);
  }
  listeners(eventName) {
    return this._socket.listeners(eventName);
  }
  removeListener(eventName, listener) {
    this._socket.removeListener(eventName, listener);
  }
  removeAllListeners(eventName) {
    this._socket.removeAllListeners(eventName);
  }
  once(eventName, listener) {
    this._socket.once(eventName, listener);
  }
  _close() {
    this._socket.readable = false;
    this.write = () => {
    };
    this.end = () => {
    };
    this._writable = false;
    this._readable = false;
  }
  _parseEnv(env) {
    const keys = Object.keys(env || {});
    const pairs = [];
    for (let i = 0; i < keys.length; i++) {
      if (keys[i] === void 0) {
        continue;
      }
      pairs.push(keys[i] + "=" + env[keys[i]]);
    }
    return pairs;
  }
}

const FLUSH_DATA_INTERVAL$1 = 1e3;
class ConoutConnection {
  constructor(_conoutPipeName) {
    this._conoutPipeName = _conoutPipeName;
    const workerData = { conoutPipeName: _conoutPipeName };
    const scriptPath = dirname(fileURLToPath$1(import.meta.url));
    this._worker = new Worker$1(join(scriptPath, "worker/conoutSocketWorker.mjs"), { workerData });
    this._worker.on("message", (message) => {
      switch (message) {
        case ConoutWorkerMessage.READY:
          this._onReady.fire();
          return;
        default:
          console.warn("Unexpected ConoutWorkerMessage", message);
      }
    });
  }
  _worker;
  _drainTimeout;
  _isDisposed = false;
  _onReady = new EventEmitter2();
  get onReady() {
    return this._onReady.event;
  }
  dispose() {
    if (this._isDisposed) {
      return;
    }
    this._isDisposed = true;
    this._drainDataAndClose();
  }
  connectSocket(socket) {
    socket.connect(getWorkerPipeName(this._conoutPipeName));
  }
  _drainDataAndClose() {
    if (this._drainTimeout) {
      clearTimeout(this._drainTimeout);
    }
    this._drainTimeout = setTimeout(() => this._destroySocket(), FLUSH_DATA_INTERVAL$1);
  }
  async _destroySocket() {
    await this._worker.terminate();
  }
}

let conptyNative;
let winptyNative;
const FLUSH_DATA_INTERVAL = 1e3;
class WindowsPtyAgent {
  constructor(file, args, env, cwd, cols, rows, debug, _useConpty, _useConptyDll = false, conptyInheritCursor = false) {
    this._useConpty = _useConpty;
    this._useConptyDll = _useConptyDll;
    if (this._useConpty === void 0 || this._useConpty === true) {
      this._useConpty = this._getWindowsBuildNumber() >= 18309;
    }
    if (this._useConpty) {
      if (!conptyNative) {
        conptyNative = require_dlopen("./native/pty/" + process.platform + "." + process.arch + "/conpty.node");
      }
    } else {
      if (!winptyNative) {
        winptyNative = require_dlopen("./native/pty/" + process.platform + "." + process.arch + "/pty.node");
      }
    }
    this._ptyNative = this._useConpty ? conptyNative : winptyNative;
    cwd = path.resolve(cwd);
    const commandLine = argsToCommandLine(file, args);
    let term;
    if (this._useConpty) {
      term = this._ptyNative.startProcess(file, cols, rows, debug, this._generatePipeName(), conptyInheritCursor, this._useConptyDll);
    } else {
      term = this._ptyNative.startProcess(file, commandLine, env, cwd, cols, rows, debug);
      this._pid = term.pid;
      this._innerPid = term.innerPid;
    }
    this._fd = term.fd;
    this._pty = term.pty;
    this._outSocket = new Socket();
    this._outSocket.setEncoding("utf8");
    this._conoutSocketWorker = new ConoutConnection(term.conout);
    this._conoutSocketWorker.onReady(() => {
      this._conoutSocketWorker.connectSocket(this._outSocket);
    });
    this._outSocket.on("connect", () => {
      this._outSocket.emit("ready_datapipe");
    });
    const inSocketFD = fs.openSync(term.conin, "w");
    this._inSocket = new Socket({
      fd: inSocketFD,
      readable: false,
      writable: true
    });
    this._inSocket.setEncoding("utf8");
    if (this._useConpty) {
      const connect = this._ptyNative.connect(this._pty, commandLine, cwd, env, (c) => this._$onProcessExit(c));
      this._innerPid = connect.pid;
    }
  }
  _inSocket;
  _outSocket;
  _pid = 0;
  _innerPid = 0;
  _closeTimeout;
  _exitCode;
  _conoutSocketWorker;
  _fd;
  _pty;
  _ptyNative;
  get inSocket() {
    return this._inSocket;
  }
  get outSocket() {
    return this._outSocket;
  }
  get fd() {
    return this._fd;
  }
  get innerPid() {
    return this._innerPid;
  }
  get pty() {
    return this._pty;
  }
  resize(cols, rows) {
    if (this._useConpty) {
      if (this._exitCode !== void 0) {
        throw new Error("Cannot resize a pty that has already exited");
      }
      this._ptyNative.resize(this._pty, cols, rows, this._useConptyDll);
      return;
    }
    this._ptyNative.resize(this._pid, cols, rows);
  }
  clear() {
    if (this._useConpty) {
      this._ptyNative.clear(this._pty, this._useConptyDll);
    }
  }
  kill() {
    this._inSocket.readable = false;
    this._outSocket.readable = false;
    if (this._useConpty) {
      this._getConsoleProcessList().then((consoleProcessList) => {
        consoleProcessList.forEach((pid) => {
          try {
            process.kill(pid);
          } catch {
          }
        });
        this._ptyNative.kill(this._pty, this._useConptyDll);
      });
    } else {
      const processList = this._ptyNative.getProcessList(this._pid);
      this._ptyNative.kill(this._pid, this._innerPid);
      processList.forEach((pid) => {
        try {
          process.kill(pid);
        } catch {
        }
      });
    }
    this._conoutSocketWorker.dispose();
  }
  _getConsoleProcessList() {
    const import__dirname = dirname(fileURLToPath(import.meta.url));
    return new Promise((resolve) => {
      const agent = fork(path.join(import__dirname, "conpty_console_list_agent"), [this._innerPid.toString()]);
      agent.on("message", (message) => {
        clearTimeout(timeout);
        resolve(message.consoleProcessList);
      });
      const timeout = setTimeout(() => {
        agent.kill();
        resolve([this._innerPid]);
      }, 5e3);
    });
  }
  get exitCode() {
    if (this._useConpty) {
      return this._exitCode;
    }
    const winptyExitCode = this._ptyNative.getExitCode(this._innerPid);
    return winptyExitCode === -1 ? void 0 : winptyExitCode;
  }
  _getWindowsBuildNumber() {
    const release = os.release();
    if (release.length > 50) {
      return 0;
    }
    const osVersion = /^(\d{1,5})\.(\d{1,5})\.(\d{1,10})/.exec(release);
    let buildNumber = 0;
    if (osVersion && osVersion.length === 4) {
      buildNumber = parseInt(osVersion[3]);
    }
    return buildNumber;
  }
  _generatePipeName() {
    return `conpty-${Math.random() * 1e7}`;
  }
  /**
   * Triggered from the native side when a contpy process exits.
   */
  _$onProcessExit(exitCode) {
    this._exitCode = exitCode;
    this._flushDataAndCleanUp();
    this._outSocket.on("data", () => this._flushDataAndCleanUp());
  }
  _flushDataAndCleanUp() {
    if (this._closeTimeout) {
      clearTimeout(this._closeTimeout);
    }
    this._closeTimeout = setTimeout(() => this._cleanUpProcess(), FLUSH_DATA_INTERVAL);
  }
  _cleanUpProcess() {
    this._inSocket.readable = false;
    this._outSocket.readable = false;
    this._outSocket.destroy();
  }
}
function argsToCommandLine(file, args) {
  if (isCommandLine(args)) {
    if (args.length === 0) {
      return file;
    }
    return `${argsToCommandLine(file, [])} ${args}`;
  }
  const argv = [file];
  Array.prototype.push.apply(argv, args);
  let result = "";
  for (let argIndex = 0; argIndex < argv.length; argIndex++) {
    if (argIndex > 0) {
      result += " ";
    }
    const arg = argv[argIndex];
    const hasLopsidedEnclosingQuote = xOr(arg[0] !== '"', arg[arg.length - 1] !== '"');
    const hasNoEnclosingQuotes = arg[0] !== '"' && arg[arg.length - 1] !== '"';
    const quote = arg === "" || (arg.indexOf(" ") !== -1 || arg.indexOf("	") !== -1) && (arg.length > 1 && (hasLopsidedEnclosingQuote || hasNoEnclosingQuotes));
    if (quote) {
      result += '"';
    }
    let bsCount = 0;
    for (let i = 0; i < arg.length; i++) {
      const p = arg[i];
      if (p === "\\") {
        bsCount++;
      } else if (p === '"') {
        result += repeatText("\\", bsCount * 2 + 1);
        result += '"';
        bsCount = 0;
      } else {
        result += repeatText("\\", bsCount);
        bsCount = 0;
        result += p;
      }
    }
    if (quote) {
      result += repeatText("\\", bsCount * 2);
      result += '"';
    } else {
      result += repeatText("\\", bsCount);
    }
  }
  return result;
}
function isCommandLine(args) {
  return typeof args === "string";
}
function repeatText(text, count) {
  let result = "";
  for (let i = 0; i < count; i++) {
    result += text;
  }
  return result;
}
function xOr(arg1, arg2) {
  return arg1 && !arg2 || !arg1 && arg2;
}

function assign(target, ...sources) {
  sources.forEach((source) => Object.keys(source).forEach((key) => target[key] = source[key]));
  return target;
}

const DEFAULT_FILE$1 = "cmd.exe";
const DEFAULT_NAME$1 = "Windows Shell";
class WindowsTerminal extends Terminal {
  _isReady;
  _deferreds;
  _agent;
  constructor(file, args, opt) {
    super(opt);
    this._checkType("args", args, "string", true);
    args = args || [];
    file = file || DEFAULT_FILE$1;
    opt = opt || {};
    opt.env = opt.env || process.env;
    if (opt.encoding) {
      console.warn("Setting encoding on Windows is not supported");
    }
    const env = assign({}, opt.env);
    this._cols = opt.cols || DEFAULT_COLS;
    this._rows = opt.rows || DEFAULT_ROWS;
    const cwd = opt.cwd || process.cwd();
    const name = opt.name || env.TERM || DEFAULT_NAME$1;
    const parsedEnv = this._parseEnv(env);
    this._isReady = false;
    this._deferreds = [];
    this._agent = new WindowsPtyAgent(file, args, parsedEnv, cwd, this._cols, this._rows, false, opt.useConpty, opt.useConptyDll, opt.conptyInheritCursor);
    this._socket = this._agent.outSocket;
    this._pid = this._agent.innerPid;
    this._fd = this._agent.fd;
    this._pty = this._agent.pty;
    this._socket.on("ready_datapipe", () => {
      ["connect", "data", "end", "timeout", "drain"].forEach((event) => {
        this._socket.on(event, () => {
          if (!this._isReady && event === "data") {
            this._isReady = true;
            this._deferreds.forEach((fn) => {
              fn.run();
            });
            this._deferreds = [];
          }
        });
      });
      this._socket.on("error", (err) => {
        this._close();
        if (err.code) {
          if (~err.code.indexOf("errno 5") || ~err.code.indexOf("EIO")) return;
        }
        if (this.listeners("error").length < 2) {
          throw err;
        }
      });
      this._socket.on("close", () => {
        this.emit("exit", this._agent.exitCode);
        this._close();
      });
    });
    this._file = file;
    this._name = name;
    this._readable = true;
    this._writable = true;
    this._forwardEvents();
  }
  _write(data) {
    this._defer(this._doWrite, data);
  }
  _doWrite(data) {
    this._agent.inSocket.write(data);
  }
  /**
   * openpty
   */
  static open(_options) {
    throw new Error("open() not supported on windows, use Fork() instead.");
  }
  /**
   * TTY
   */
  resize(cols, rows) {
    if (cols <= 0 || rows <= 0 || isNaN(cols) || isNaN(rows) || cols === Infinity || rows === Infinity) {
      throw new Error("resizing must be done using positive cols and rows");
    }
    this._deferNoArgs(() => {
      this._agent.resize(cols, rows);
      this._cols = cols;
      this._rows = rows;
    });
  }
  clear() {
    this._deferNoArgs(() => {
      this._agent.clear();
    });
  }
  destroy() {
    this._deferNoArgs(() => {
      this.kill();
    });
  }
  kill(signal) {
    this._deferNoArgs(() => {
      if (signal) {
        throw new Error("Signals not supported on windows.");
      }
      this._close();
      this._agent.kill();
    });
  }
  // @ts-expect-error - This is a private method that is not part of the public API.
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  _deferNoArgs(deferredFn) {
    if (this._isReady) {
      deferredFn.call(this);
      return;
    }
    this._deferreds.push({
      run: () => deferredFn.call(this)
    });
  }
  _defer(deferredFn, arg) {
    if (this._isReady) {
      deferredFn.call(this, arg);
      return;
    }
    this._deferreds.push({
      run: () => deferredFn.call(this, arg)
    });
  }
  get process() {
    return this._name;
  }
  get master() {
    throw new Error("master is not supported on Windows");
  }
  get slave() {
    throw new Error("slave is not supported on Windows");
  }
}

function pty_loader() {
  let pty;
  try {
    pty = require_dlopen("./native/pty/" + process.platform + "." + process.arch + "/pty.node");
  } catch {
    pty = void 0;
  }
  return pty;
}

let _pty;
const pty = new Proxy({}, {
  get(_target, prop) {
    if (!_pty) {
      _pty = pty_loader();
    }
    return _pty[prop];
  }
});
let helperPath;
helperPath = "../build/Release/spawn-helper";
const import__dirname = path.dirname(fileURLToPath(import.meta.url));
helperPath = path.resolve(import__dirname, helperPath);
helperPath = helperPath.replace("app.asar", "app.asar.unpacked");
helperPath = helperPath.replace("node_modules.asar", "node_modules.asar.unpacked");
const DEFAULT_FILE = "sh";
const DEFAULT_NAME = "xterm";
const DESTROY_SOCKET_TIMEOUT_MS = 200;
class UnixTerminal extends Terminal {
  _fd;
  _pty;
  _file;
  _name;
  _readable;
  _writable;
  _boundClose = false;
  _emittedClose = false;
  _master;
  _slave;
  get master() {
    return this._master;
  }
  get slave() {
    return this._slave;
  }
  constructor(file, args, opt) {
    super(opt);
    if (typeof args === "string") {
      throw new Error("args as a string is not supported on unix.");
    }
    args = args || [];
    file = file || DEFAULT_FILE;
    opt = opt || {};
    opt.env = opt.env || process.env;
    this._cols = opt.cols || DEFAULT_COLS;
    this._rows = opt.rows || DEFAULT_ROWS;
    const uid = opt.uid ?? -1;
    const gid = opt.gid ?? -1;
    const env = assign({}, opt.env);
    if (opt.env === process.env) {
      this._sanitizeEnv(env);
    }
    const cwd = opt.cwd || process.cwd();
    env["PWD"] = cwd;
    const name = opt.name || env["TERM"] || DEFAULT_NAME;
    env["TERM"] = name;
    const parsedEnv = this._parseEnv(env);
    const encoding = opt.encoding === void 0 ? "utf8" : opt.encoding;
    const onexit = (code, signal) => {
      if (!this._emittedClose) {
        if (this._boundClose) {
          return;
        }
        this._boundClose = true;
        let timeout = setTimeout(() => {
          timeout = null;
          this._socket.destroy();
        }, DESTROY_SOCKET_TIMEOUT_MS);
        this.once("close", () => {
          if (timeout !== null) {
            clearTimeout(timeout);
          }
          this.emit("exit", code, signal);
        });
        return;
      }
      this.emit("exit", code, signal);
    };
    const term = pty.fork(file, args, parsedEnv, cwd, this._cols, this._rows, uid, gid, encoding === "utf8", helperPath, onexit);
    this._socket = new tty.ReadStream(term.fd);
    if (encoding !== null) {
      this._socket.setEncoding(encoding);
    }
    this._socket.on("error", (err) => {
      if (err.code) {
        if (~err.code.indexOf("EAGAIN")) {
          return;
        }
      }
      this._close();
      if (!this._emittedClose) {
        this._emittedClose = true;
        this.emit("close");
      }
      if (err.code) {
        if (~err.code.indexOf("errno 5") || ~err.code.indexOf("EIO")) {
          return;
        }
      }
      if (this.listeners("error").length < 2) {
        throw err;
      }
    });
    this._pid = term.pid;
    this._fd = term.fd;
    this._pty = term.pty;
    this._file = file;
    this._name = name;
    this._readable = true;
    this._writable = true;
    this._socket.on("close", () => {
      if (this._emittedClose) {
        return;
      }
      this._emittedClose = true;
      this._close();
      this.emit("close");
    });
    this._forwardEvents();
  }
  _write(data) {
    this._socket.write(data);
  }
  /* Accessors */
  get fd() {
    return this._fd;
  }
  get ptsName() {
    return this._pty;
  }
  /**
  * openpty
  */
  static open(opt) {
    const self = Object.create(UnixTerminal.prototype);
    opt = opt || {};
    if (arguments.length > 1) {
      opt = {
        cols: arguments[1],
        rows: arguments[2]
      };
    }
    const cols = opt.cols || DEFAULT_COLS;
    const rows = opt.rows || DEFAULT_ROWS;
    const encoding = opt.encoding === void 0 ? "utf8" : opt.encoding;
    const term = pty.open(cols, rows);
    self._master = new tty.ReadStream(term.master);
    if (encoding !== null) {
      self._master.setEncoding(encoding);
    }
    self._master.resume();
    self._slave = new tty.ReadStream(term.slave);
    if (encoding !== null) {
      self._slave.setEncoding(encoding);
    }
    self._slave.resume();
    self._socket = self._master;
    self._pid = -1;
    self._fd = term.master;
    self._pty = term.pty;
    self._file = process.argv[0] || "node";
    self._name = process.env["TERM"] || "";
    self._readable = true;
    self._writable = true;
    self._socket.on("error", (err) => {
      self._close();
      if (self.listeners("error").length < 2) {
        throw err;
      }
    });
    self._socket.on("close", () => {
      self._close();
    });
    return self;
  }
  destroy() {
    this._close();
    this._socket.once("close", () => {
      this.kill("SIGHUP");
    });
    this._socket.destroy();
  }
  kill(signal) {
    try {
      process.kill(this.pid, signal || "SIGHUP");
    } catch {
    }
  }
  /**
  * Gets the name of the process.
  */
  get process() {
    if (process.platform === "darwin") {
      const title = pty.process(this._fd);
      return title !== "kernel_task" ? title : this._file;
    }
    return pty.process(this._fd, this._pty) || this._file;
  }
  /**
  * TTY
  */
  resize(cols, rows) {
    if (cols <= 0 || rows <= 0 || isNaN(cols) || isNaN(rows) || cols === Infinity || rows === Infinity) {
      throw new Error("resizing must be done using positive cols and rows");
    }
    pty.resize(this._fd, cols, rows);
    this._cols = cols;
    this._rows = rows;
  }
  clear() {
  }
  _sanitizeEnv(env) {
    delete env["TMUX"];
    delete env["TMUX_PANE"];
    delete env["STY"];
    delete env["WINDOW"];
    delete env["WINDOWID"];
    delete env["TERMCAP"];
    delete env["COLUMNS"];
    delete env["LINES"];
  }
}

let terminalCtor;
if (process.platform === "win32") {
  terminalCtor = WindowsTerminal;
} else {
  terminalCtor = UnixTerminal;
}
function spawn(file, args, opt) {
  return new terminalCtor(file, args, opt);
}
function require_dlopen(modulename) {
  const module = { exports: {} };
  const import__dirname = dirname$1(fileURLToPath$1(import.meta.url));
  process.dlopen(module, path$1.join(import__dirname, modulename));
  return module.exports;
}

class TerminalManager {
  terminals = /* @__PURE__ */ new Map();
  wss = null;
  initialize(req, socket, head, logger) {
    logger?.log("[NapCat] [WebUi] terminal websocket initialized");
    this.wss = new WebSocketServer({
      noServer: true,
      verifyClient: async (info, cb) => {
        const url = new URL(info.req.url || "", "ws://localhost");
        const token = url.searchParams.get("token");
        const terminalId = url.searchParams.get("id");
        if (!token || !terminalId) {
          cb(false, 401, "Unauthorized");
          return;
        }
        let Credential;
        try {
          Credential = JSON.parse(Buffer.from(token, "base64").toString("utf-8"));
        } catch (_e) {
          cb(false, 401, "Unauthorized");
          return;
        }
        const config = await WebUiConfig.GetWebUIConfig();
        const validate = AuthHelper.validateCredentialWithinOneHour(config.token, Credential);
        if (!validate) {
          cb(false, 401, "Unauthorized");
          return;
        }
        cb(true);
      }
    });
    this.wss.handleUpgrade(req, socket, head, (ws) => {
      this.wss?.emit("connection", ws, req);
    });
    this.wss.on("connection", async (ws, req2) => {
      logger?.log("建立终端连接");
      try {
        const url = new URL(req2.url || "", "ws://localhost");
        const terminalId = url.searchParams.get("id");
        const instance = this.terminals.get(terminalId);
        if (!instance) {
          ws.close();
          return;
        }
        instance.sockets.add(ws);
        instance.lastAccess = Date.now();
        if (ws.readyState === WebSocket.OPEN) {
          ws.send(JSON.stringify({ type: "output", data: instance.buffer }));
        }
        ws.on("message", (data) => {
          if (instance) {
            const result = JSON.parse(data.toString());
            if (result.type === "input") {
              instance.pty.write(result.data);
            }
            if (result.type === "resize") {
              instance.pty.resize(result.cols, result.rows);
            }
          }
        });
        ws.on("close", () => {
          instance.sockets.delete(ws);
          if (instance.sockets.size === 0 && !instance.isClosing) {
            instance.isClosing = true;
            if (os__default.platform() === "win32") {
              process.kill(instance.pty.pid);
            } else {
              instance.pty.kill();
            }
          }
        });
      } catch (err) {
        console.error("WebSocket authentication failed:", err);
        ws.close();
      }
    });
  }
  // 修改：新增 cols 和 rows 参数，同步 xterm 尺寸，防止错位
  createTerminal(cols, rows) {
    const id = randomUUID();
    const shell = os__default.platform() === "win32" ? "powershell.exe" : "bash";
    const pty = spawn(shell, [], {
      name: "xterm-256color",
      cols,
      // 使用客户端传入的 cols
      rows,
      // 使用客户端传入的 rows
      cwd: process.cwd(),
      env: {
        ...process.env,
        LANG: os__default.platform() === "win32" ? "chcp 65001" : "zh_CN.UTF-8",
        TERM: "xterm-256color"
      }
    });
    const instance = {
      pty,
      lastAccess: Date.now(),
      sockets: /* @__PURE__ */ new Set(),
      isClosing: false,
      buffer: ""
      // 初始化终端内容缓存
    };
    pty.onData((data) => {
      instance.buffer += data;
      instance.sockets.forEach((ws) => {
        if (ws.readyState === WebSocket.OPEN) {
          ws.send(JSON.stringify({ type: "output", data }));
        }
      });
    });
    pty.onExit(() => {
      this.closeTerminal(id);
    });
    this.terminals.set(id, instance);
    return { id, instance };
  }
  closeTerminal(id) {
    const instance = this.terminals.get(id);
    if (instance) {
      if (!instance.isClosing) {
        instance.isClosing = true;
        if (os__default.platform() === "win32") {
          process.kill(instance.pty.pid);
        } else {
          instance.pty.kill();
        }
      }
      instance.sockets.forEach((ws) => ws.close());
      this.terminals.delete(id);
    }
  }
  getTerminal(id) {
    return this.terminals.get(id);
  }
  getTerminalList() {
    return Array.from(this.terminals.keys()).map((id) => ({
      id,
      lastAccess: this.terminals.get(id).lastAccess
    }));
  }
}
const terminalManager = new TerminalManager();

const isMacOS = process.platform === "darwin";
const sanitizeLog = (log) => {
  return log.replace(/token=[\w\d]+/gi, "token=***");
};
const LogHandler = async (req, res) => {
  const filename = req.query["id"];
  if (!filename || typeof filename !== "string") {
    return sendError(res, "ID不能为空");
  }
  if (filename.includes("..")) {
    return sendError(res, "ID不合法");
  }
  const logContent = await WebUiConfig.GetLogContent(filename);
  const sanitizedLogContent = sanitizeLog(logContent);
  return sendSuccess(res, sanitizedLogContent);
};
const LogListHandler = async (_, res) => {
  const logList = await WebUiConfig.GetLogsList();
  return sendSuccess(res, logList);
};
const LogRealTimeHandler = async (req, res) => {
  res.setHeader("Content-Type", "text/event-stream");
  res.setHeader("Connection", "keep-alive");
  const listener = (log) => {
    try {
      const sanitizedLog = sanitizeLog(log);
      res.write(`data: ${sanitizedLog}

`);
    } catch (error) {
      console.error("向客户端写入日志数据时出错:", error);
    }
  };
  logSubscription.subscribe(listener);
  req.on("close", () => {
    logSubscription.unsubscribe(listener);
  });
};
const CreateTerminalHandler = async (req, res) => {
  if (isMacOS) {
    return sendError(res, "MacOS不支持终端");
  }
  try {
    const { cols, rows } = req.body;
    const { id } = terminalManager.createTerminal(cols, rows);
    return sendSuccess(res, { id });
  } catch (error) {
    console.error("Failed to create terminal:", error);
    return sendError(res, "创建终端失败");
  }
};
const GetTerminalListHandler = (_, res) => {
  const list = terminalManager.getTerminalList();
  return sendSuccess(res, list);
};
const CloseTerminalHandler = (req, res) => {
  const id = req.params["id"];
  if (!id) {
    return sendError(res, "ID不能为空");
  }
  terminalManager.closeTerminal(id);
  return sendSuccess(res, {});
};

const router$6 = Router();
router$6.get("/GetLog", LogHandler);
router$6.get("/GetLogList", LogListHandler);
router$6.get("/GetLogRealTime", LogRealTimeHandler);
router$6.get("/terminal/list", GetTerminalListHandler);
router$6.post("/terminal/create", CreateTerminalHandler);
router$6.post("/terminal/:id/close", CloseTerminalHandler);

const GetNapCatVersion = (_, res) => {
  const data = WebUiDataRuntime.GetNapCatVersion();
  sendSuccess(res, { version: data });
};
const getLatestTagHandler = async (_, res) => {
  try {
    const latestTag = await getLatestTag();
    sendSuccess(res, latestTag);
  } catch (error) {
    res.status(500).json({ error: "Failed to fetch latest tag" });
  }
};
const QQVersionHandler = (_, res) => {
  const data = WebUiDataRuntime.getQQVersion();
  sendSuccess(res, data);
};
const GetThemeConfigHandler = async (_, res) => {
  const data = await WebUiConfig.GetTheme();
  sendSuccess(res, data);
};
const SetThemeConfigHandler = async (req, res) => {
  const { theme } = req.body;
  await WebUiConfig.UpdateTheme(theme);
  sendSuccess(res, { message: "更新成功" });
};

const StatusRealTimeHandler = async (req, res) => {
  res.setHeader("Content-Type", "text/event-stream");
  res.setHeader("Connection", "keep-alive");
  const sendStatus = (status) => {
    try {
      res.write(`data: ${JSON.stringify(status)}

`);
    } catch (e) {
      console.error(`An error occurred when writing sendStatus data to client: ${e}`);
    }
  };
  statusHelperSubscription$1.on("statusUpdate", sendStatus);
  req.on("close", () => {
    statusHelperSubscription$1.off("statusUpdate", sendStatus);
    res.end();
  });
};

const GetProxyHandler = async (req, res) => {
  let { url } = req.query;
  if (url && typeof url === "string") {
    url = decodeURIComponent(url);
    const responseText = await RequestUtil.HttpGetText(url);
    return sendSuccess(res, responseText);
  } else {
    return sendError(res, "url参数不合法");
  }
};

const router$5 = Router();
router$5.get("/QQVersion", QQVersionHandler);
router$5.get("/GetNapCatVersion", GetNapCatVersion);
router$5.get("/getLatestTag", getLatestTagHandler);
router$5.get("/GetSysStatusRealTime", StatusRealTimeHandler);
router$5.get("/proxy", GetProxyHandler);
router$5.get("/Theme", GetThemeConfigHandler);
router$5.post("/SetTheme", SetThemeConfigHandler);

// source/headers.ts
var SUPPORTED_DRAFT_VERSIONS = [
  "draft-6",
  "draft-7",
  "draft-8"
];
var getResetSeconds = (resetTime, windowMs) => {
  let resetSeconds = void 0;
  if (resetTime) {
    const deltaSeconds = Math.ceil((resetTime.getTime() - Date.now()) / 1e3);
    resetSeconds = Math.max(0, deltaSeconds);
  } else if (windowMs) {
    resetSeconds = Math.ceil(windowMs / 1e3);
  }
  return resetSeconds;
};
var getPartitionKey = (key) => {
  const hash = createHash("sha256");
  hash.update(key);
  const partitionKey = hash.digest("hex").slice(0, 12);
  return Buffer$1.from(partitionKey).toString("base64");
};
var setLegacyHeaders = (response, info) => {
  if (response.headersSent) return;
  response.setHeader("X-RateLimit-Limit", info.limit.toString());
  response.setHeader("X-RateLimit-Remaining", info.remaining.toString());
  if (info.resetTime instanceof Date) {
    response.setHeader("Date", (/* @__PURE__ */ new Date()).toUTCString());
    response.setHeader(
      "X-RateLimit-Reset",
      Math.ceil(info.resetTime.getTime() / 1e3).toString()
    );
  }
};
var setDraft6Headers = (response, info, windowMs) => {
  if (response.headersSent) return;
  const windowSeconds = Math.ceil(windowMs / 1e3);
  const resetSeconds = getResetSeconds(info.resetTime);
  response.setHeader("RateLimit-Policy", `${info.limit};w=${windowSeconds}`);
  response.setHeader("RateLimit-Limit", info.limit.toString());
  response.setHeader("RateLimit-Remaining", info.remaining.toString());
  if (resetSeconds)
    response.setHeader("RateLimit-Reset", resetSeconds.toString());
};
var setDraft7Headers = (response, info, windowMs) => {
  if (response.headersSent) return;
  const windowSeconds = Math.ceil(windowMs / 1e3);
  const resetSeconds = getResetSeconds(info.resetTime, windowMs);
  response.setHeader("RateLimit-Policy", `${info.limit};w=${windowSeconds}`);
  response.setHeader(
    "RateLimit",
    `limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}`
  );
};
var setDraft8Headers = (response, info, windowMs, name, key) => {
  if (response.headersSent) return;
  const windowSeconds = Math.ceil(windowMs / 1e3);
  const resetSeconds = getResetSeconds(info.resetTime, windowMs);
  const partitionKey = getPartitionKey(key);
  const policy = `q=${info.limit}; w=${windowSeconds}; pk=:${partitionKey}:`;
  const header = `r=${info.remaining}; t=${resetSeconds}`;
  response.append("RateLimit-Policy", `"${name}"; ${policy}`);
  response.append("RateLimit", `"${name}"; ${header}`);
};
var setRetryAfterHeader = (response, info, windowMs) => {
  if (response.headersSent) return;
  const resetSeconds = getResetSeconds(info.resetTime, windowMs);
  response.setHeader("Retry-After", resetSeconds.toString());
};
var ValidationError = class extends Error {
  /**
   * The code must be a string, in snake case and all capital, that starts with
   * the substring `ERR_ERL_`.
   *
   * The message must be a string, starting with an uppercase character,
   * describing the issue in detail.
   */
  constructor(code, message) {
    const url = `https://express-rate-limit.github.io/${code}/`;
    super(`${message} See ${url} for more information.`);
    this.name = this.constructor.name;
    this.code = code;
    this.help = url;
  }
};
var ChangeWarning = class extends ValidationError {
};
var usedStores = /* @__PURE__ */ new Set();
var singleCountKeys = /* @__PURE__ */ new WeakMap();
var validations = {
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
  enabled: {
    default: true
  },
  // Should be EnabledValidations type, but that's a circular reference
  disable() {
    for (const k of Object.keys(this.enabled)) this.enabled[k] = false;
  },
  /**
   * Checks whether the IP address is valid, and that it does not have a port
   * number in it.
   *
   * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_invalid_ip_address.
   *
   * @param ip {string | undefined} - The IP address provided by Express as request.ip.
   *
   * @returns {void}
   */
  ip(ip) {
    if (ip === void 0) {
      throw new ValidationError(
        "ERR_ERL_UNDEFINED_IP_ADDRESS",
        `An undefined 'request.ip' was detected. This might indicate a misconfiguration or the connection being destroyed prematurely.`
      );
    }
    if (!isIP(ip)) {
      throw new ValidationError(
        "ERR_ERL_INVALID_IP_ADDRESS",
        `An invalid 'request.ip' (${ip}) was detected. Consider passing a custom 'keyGenerator' function to the rate limiter.`
      );
    }
  },
  /**
   * Makes sure the trust proxy setting is not set to `true`.
   *
   * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_permissive_trust_proxy.
   *
   * @param request {Request} - The Express request object.
   *
   * @returns {void}
   */
  trustProxy(request) {
    if (request.app.get("trust proxy") === true) {
      throw new ValidationError(
        "ERR_ERL_PERMISSIVE_TRUST_PROXY",
        `The Express 'trust proxy' setting is true, which allows anyone to trivially bypass IP-based rate limiting.`
      );
    }
  },
  /**
   * Makes sure the trust proxy setting is set in case the `X-Forwarded-For`
   * header is present.
   *
   * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_unset_trust_proxy.
   *
   * @param request {Request} - The Express request object.
   *
   * @returns {void}
   */
  xForwardedForHeader(request) {
    if (request.headers["x-forwarded-for"] && request.app.get("trust proxy") === false) {
      throw new ValidationError(
        "ERR_ERL_UNEXPECTED_X_FORWARDED_FOR",
        `The 'X-Forwarded-For' header is set but the Express 'trust proxy' setting is false (default). This could indicate a misconfiguration which would prevent express-rate-limit from accurately identifying users.`
      );
    }
  },
  /**
   * Ensures totalHits value from store is a positive integer.
   *
   * @param hits {any} - The `totalHits` returned by the store.
   */
  positiveHits(hits) {
    if (typeof hits !== "number" || hits < 1 || hits !== Math.round(hits)) {
      throw new ValidationError(
        "ERR_ERL_INVALID_HITS",
        `The totalHits value returned from the store must be a positive integer, got ${hits}`
      );
    }
  },
  /**
   * Ensures a single store instance is not used with multiple express-rate-limit instances
   */
  unsharedStore(store) {
    if (usedStores.has(store)) {
      const maybeUniquePrefix = store?.localKeys ? "" : " (with a unique prefix)";
      throw new ValidationError(
        "ERR_ERL_STORE_REUSE",
        `A Store instance must not be shared across multiple rate limiters. Create a new instance of ${store.constructor.name}${maybeUniquePrefix} for each limiter instead.`
      );
    }
    usedStores.add(store);
  },
  /**
   * Ensures a given key is incremented only once per request.
   *
   * @param request {Request} - The Express request object.
   * @param store {Store} - The store class.
   * @param key {string} - The key used to store the client's hit count.
   *
   * @returns {void}
   */
  singleCount(request, store, key) {
    let storeKeys = singleCountKeys.get(request);
    if (!storeKeys) {
      storeKeys = /* @__PURE__ */ new Map();
      singleCountKeys.set(request, storeKeys);
    }
    const storeKey = store.localKeys ? store : store.constructor.name;
    let keys = storeKeys.get(storeKey);
    if (!keys) {
      keys = [];
      storeKeys.set(storeKey, keys);
    }
    const prefixedKey = `${store.prefix ?? ""}${key}`;
    if (keys.includes(prefixedKey)) {
      throw new ValidationError(
        "ERR_ERL_DOUBLE_COUNT",
        `The hit count for ${key} was incremented more than once for a single request.`
      );
    }
    keys.push(prefixedKey);
  },
  /**
   * Warns the user that the behaviour for `max: 0` / `limit: 0` is
   * changing in the next major release.
   *
   * @param limit {number} - The maximum number of hits per client.
   *
   * @returns {void}
   */
  limit(limit) {
    if (limit === 0) {
      throw new ChangeWarning(
        "WRN_ERL_MAX_ZERO",
        `Setting limit or max to 0 disables rate limiting in express-rate-limit v6 and older, but will cause all requests to be blocked in v7`
      );
    }
  },
  /**
   * Warns the user that the `draft_polli_ratelimit_headers` option is deprecated
   * and will be removed in the next major release.
   *
   * @param draft_polli_ratelimit_headers {any | undefined} - The now-deprecated setting that was used to enable standard headers.
   *
   * @returns {void}
   */
  draftPolliHeaders(draft_polli_ratelimit_headers) {
    if (draft_polli_ratelimit_headers) {
      throw new ChangeWarning(
        "WRN_ERL_DEPRECATED_DRAFT_POLLI_HEADERS",
        `The draft_polli_ratelimit_headers configuration option is deprecated and has been removed in express-rate-limit v7, please set standardHeaders: 'draft-6' instead.`
      );
    }
  },
  /**
   * Warns the user that the `onLimitReached` option is deprecated and
   * will be removed in the next major release.
   *
   * @param onLimitReached {any | undefined} - The maximum number of hits per client.
   *
   * @returns {void}
   */
  onLimitReached(onLimitReached) {
    if (onLimitReached) {
      throw new ChangeWarning(
        "WRN_ERL_DEPRECATED_ON_LIMIT_REACHED",
        `The onLimitReached configuration option is deprecated and has been removed in express-rate-limit v7.`
      );
    }
  },
  /**
   * Warns the user when an invalid/unsupported version of the draft spec is passed.
   *
   * @param version {any | undefined} - The version passed by the user.
   *
   * @returns {void}
   */
  headersDraftVersion(version) {
    if (typeof version !== "string" || // @ts-expect-error This is fine. If version is not in the array, it will just return false.
    !SUPPORTED_DRAFT_VERSIONS.includes(version)) {
      const versionString = SUPPORTED_DRAFT_VERSIONS.join(", ");
      throw new ValidationError(
        "ERR_ERL_HEADERS_UNSUPPORTED_DRAFT_VERSION",
        `standardHeaders: only the following versions of the IETF draft specification are supported: ${versionString}.`
      );
    }
  },
  /**
   * Warns the user when the selected headers option requires a reset time but
   * the store does not provide one.
   *
   * @param resetTime {Date | undefined} - The timestamp when the client's hit count will be reset.
   *
   * @returns {void}
   */
  headersResetTime(resetTime) {
    if (!resetTime) {
      throw new ValidationError(
        "ERR_ERL_HEADERS_NO_RESET",
        `standardHeaders:  'draft-7' requires a 'resetTime', but the store did not provide one. The 'windowMs' value will be used instead, which may cause clients to wait longer than necessary.`
      );
    }
  },
  /**
   * Checks the options.validate setting to ensure that only recognized
   * validations are enabled or disabled.
   *
   * If any unrecognized values are found, an error is logged that
   * includes the list of supported vaidations.
   */
  validationsConfig() {
    const supportedValidations = Object.keys(this).filter(
      (k) => !["enabled", "disable"].includes(k)
    );
    supportedValidations.push("default");
    for (const key of Object.keys(this.enabled)) {
      if (!supportedValidations.includes(key)) {
        throw new ValidationError(
          "ERR_ERL_UNKNOWN_VALIDATION",
          `options.validate.${key} is not recognized. Supported validate options are: ${supportedValidations.join(
            ", "
          )}.`
        );
      }
    }
  },
  /**
   * Checks to see if the instance was created inside of a request handler,
   * which would prevent it from working correctly, with the default memory
   * store (or any other store with localKeys.)
   */
  creationStack(store) {
    const { stack } = new Error(
      "express-rate-limit validation check (set options.validate.creationStack=false to disable)"
    );
    if (stack?.includes("Layer.handle [as handle_request]")) {
      if (!store.localKeys) {
        throw new ValidationError(
          "ERR_ERL_CREATED_IN_REQUEST_HANDLER",
          "express-rate-limit instance should *usually* be created at app initialization, not when responding to a request."
        );
      }
      throw new ValidationError(
        "ERR_ERL_CREATED_IN_REQUEST_HANDLER",
        `express-rate-limit instance should be created at app initialization, not when responding to a request.`
      );
    }
  }
};
var getValidations = (_enabled) => {
  let enabled;
  if (typeof _enabled === "boolean") {
    enabled = {
      default: _enabled
    };
  } else {
    enabled = {
      default: true,
      ..._enabled
    };
  }
  const wrappedValidations = {
    enabled
  };
  for (const [name, validation] of Object.entries(validations)) {
    if (typeof validation === "function")
      wrappedValidations[name] = (...args) => {
        if (!(enabled[name] ?? enabled.default)) {
          return;
        }
        try {
          ;
          validation.apply(
            wrappedValidations,
            args
          );
        } catch (error) {
          if (error instanceof ChangeWarning) console.warn(error);
          else console.error(error);
        }
      };
  }
  return wrappedValidations;
};

// source/memory-store.ts
var MemoryStore = class {
  constructor() {
    /**
     * These two maps store usage (requests) and reset time by key (for example, IP
     * addresses or API keys).
     *
     * They are split into two to avoid having to iterate through the entire set to
     * determine which ones need reset. Instead, `Client`s are moved from `previous`
     * to `current` as they hit the endpoint. Once `windowMs` has elapsed, all clients
     * left in `previous`, i.e., those that have not made any recent requests, are
     * known to be expired and can be deleted in bulk.
     */
    this.previous = /* @__PURE__ */ new Map();
    this.current = /* @__PURE__ */ new Map();
    /**
     * Confirmation that the keys incremented in once instance of MemoryStore
     * cannot affect other instances.
     */
    this.localKeys = true;
  }
  /**
   * Method that initializes the store.
   *
   * @param options {Options} - The options used to setup the middleware.
   */
  init(options) {
    this.windowMs = options.windowMs;
    if (this.interval) clearInterval(this.interval);
    this.interval = setInterval(() => {
      this.clearExpired();
    }, this.windowMs);
    if (this.interval.unref) this.interval.unref();
  }
  /**
   * Method to fetch a client's hit count and reset time.
   *
   * @param key {string} - The identifier for a client.
   *
   * @returns {ClientRateLimitInfo | undefined} - The number of hits and reset time for that client.
   *
   * @public
   */
  async get(key) {
    return this.current.get(key) ?? this.previous.get(key);
  }
  /**
   * Method to increment a client's hit counter.
   *
   * @param key {string} - The identifier for a client.
   *
   * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
   *
   * @public
   */
  async increment(key) {
    const client = this.getClient(key);
    const now = Date.now();
    if (client.resetTime.getTime() <= now) {
      this.resetClient(client, now);
    }
    client.totalHits++;
    return client;
  }
  /**
   * Method to decrement a client's hit counter.
   *
   * @param key {string} - The identifier for a client.
   *
   * @public
   */
  async decrement(key) {
    const client = this.getClient(key);
    if (client.totalHits > 0) client.totalHits--;
  }
  /**
   * Method to reset a client's hit counter.
   *
   * @param key {string} - The identifier for a client.
   *
   * @public
   */
  async resetKey(key) {
    this.current.delete(key);
    this.previous.delete(key);
  }
  /**
   * Method to reset everyone's hit counter.
   *
   * @public
   */
  async resetAll() {
    this.current.clear();
    this.previous.clear();
  }
  /**
   * Method to stop the timer (if currently running) and prevent any memory
   * leaks.
   *
   * @public
   */
  shutdown() {
    clearInterval(this.interval);
    void this.resetAll();
  }
  /**
   * Recycles a client by setting its hit count to zero, and reset time to
   * `windowMs` milliseconds from now.
   *
   * NOT to be confused with `#resetKey()`, which removes a client from both the
   * `current` and `previous` maps.
   *
   * @param client {Client} - The client to recycle.
   * @param now {number} - The current time, to which the `windowMs` is added to get the `resetTime` for the client.
   *
   * @return {Client} - The modified client that was passed in, to allow for chaining.
   */
  resetClient(client, now = Date.now()) {
    client.totalHits = 0;
    client.resetTime.setTime(now + this.windowMs);
    return client;
  }
  /**
   * Retrieves or creates a client, given a key. Also ensures that the client being
   * returned is in the `current` map.
   *
   * @param key {string} - The key under which the client is (or is to be) stored.
   *
   * @returns {Client} - The requested client.
   */
  getClient(key) {
    if (this.current.has(key)) return this.current.get(key);
    let client;
    if (this.previous.has(key)) {
      client = this.previous.get(key);
      this.previous.delete(key);
    } else {
      client = { totalHits: 0, resetTime: /* @__PURE__ */ new Date() };
      this.resetClient(client);
    }
    this.current.set(key, client);
    return client;
  }
  /**
   * Move current clients to previous, create a new map for current.
   *
   * This function is called every `windowMs`.
   */
  clearExpired() {
    this.previous = this.current;
    this.current = /* @__PURE__ */ new Map();
  }
};

// source/lib.ts
var isLegacyStore = (store) => (
  // Check that `incr` exists but `increment` does not - store authors might want
  // to keep both around for backwards compatibility.
  typeof store.incr === "function" && typeof store.increment !== "function"
);
var promisifyStore = (passedStore) => {
  if (!isLegacyStore(passedStore)) {
    return passedStore;
  }
  const legacyStore = passedStore;
  class PromisifiedStore {
    async increment(key) {
      return new Promise((resolve, reject) => {
        legacyStore.incr(
          key,
          (error, totalHits, resetTime) => {
            if (error) reject(error);
            resolve({ totalHits, resetTime });
          }
        );
      });
    }
    async decrement(key) {
      return legacyStore.decrement(key);
    }
    async resetKey(key) {
      return legacyStore.resetKey(key);
    }
    /* istanbul ignore next */
    async resetAll() {
      if (typeof legacyStore.resetAll === "function")
        return legacyStore.resetAll();
    }
  }
  return new PromisifiedStore();
};
var getOptionsFromConfig = (config) => {
  const { validations: validations2, ...directlyPassableEntries } = config;
  return {
    ...directlyPassableEntries,
    validate: validations2.enabled
  };
};
var omitUndefinedOptions = (passedOptions) => {
  const omittedOptions = {};
  for (const k of Object.keys(passedOptions)) {
    const key = k;
    if (passedOptions[key] !== void 0) {
      omittedOptions[key] = passedOptions[key];
    }
  }
  return omittedOptions;
};
var parseOptions = (passedOptions) => {
  const notUndefinedOptions = omitUndefinedOptions(passedOptions);
  const validations2 = getValidations(notUndefinedOptions?.validate ?? true);
  validations2.validationsConfig();
  validations2.draftPolliHeaders(
    // @ts-expect-error see the note above.
    notUndefinedOptions.draft_polli_ratelimit_headers
  );
  validations2.onLimitReached(notUndefinedOptions.onLimitReached);
  let standardHeaders = notUndefinedOptions.standardHeaders ?? false;
  if (standardHeaders === true) standardHeaders = "draft-6";
  const config = {
    windowMs: 60 * 1e3,
    limit: passedOptions.max ?? 5,
    // `max` is deprecated, but support it anyways.
    message: "Too many requests, please try again later.",
    statusCode: 429,
    legacyHeaders: passedOptions.headers ?? true,
    identifier(request, _response) {
      let duration = "";
      const property = config.requestPropertyName;
      const { limit } = request[property];
      const seconds = config.windowMs / 1e3;
      const minutes = config.windowMs / (1e3 * 60);
      const hours = config.windowMs / (1e3 * 60 * 60);
      const days = config.windowMs / (1e3 * 60 * 60 * 24);
      if (seconds < 60) duration = `${seconds}sec`;
      else if (minutes < 60) duration = `${minutes}min`;
      else if (hours < 24) duration = `${hours}hr${hours > 1 ? "s" : ""}`;
      else duration = `${days}day${days > 1 ? "s" : ""}`;
      return `${limit}-in-${duration}`;
    },
    requestPropertyName: "rateLimit",
    skipFailedRequests: false,
    skipSuccessfulRequests: false,
    requestWasSuccessful: (_request, response) => response.statusCode < 400,
    skip: (_request, _response) => false,
    keyGenerator(request, _response) {
      validations2.ip(request.ip);
      validations2.trustProxy(request);
      validations2.xForwardedForHeader(request);
      return request.ip;
    },
    async handler(request, response, _next, _optionsUsed) {
      response.status(config.statusCode);
      const message = typeof config.message === "function" ? await config.message(
        request,
        response
      ) : config.message;
      if (!response.writableEnded) {
        response.send(message);
      }
    },
    passOnStoreError: false,
    // Allow the default options to be overridden by the passed options.
    ...notUndefinedOptions,
    // `standardHeaders` is resolved into a draft version above, use that.
    standardHeaders,
    // Note that this field is declared after the user's options are spread in,
    // so that this field doesn't get overridden with an un-promisified store!
    store: promisifyStore(notUndefinedOptions.store ?? new MemoryStore()),
    // Print an error to the console if a few known misconfigurations are detected.
    validations: validations2
  };
  if (typeof config.store.increment !== "function" || typeof config.store.decrement !== "function" || typeof config.store.resetKey !== "function" || config.store.resetAll !== void 0 && typeof config.store.resetAll !== "function" || config.store.init !== void 0 && typeof config.store.init !== "function") {
    throw new TypeError(
      "An invalid store was passed. Please ensure that the store is a class that implements the `Store` interface."
    );
  }
  return config;
};
var handleAsyncErrors = (fn) => async (request, response, next) => {
  try {
    await Promise.resolve(fn(request, response, next)).catch(next);
  } catch (error) {
    next(error);
  }
};
var rateLimit = (passedOptions) => {
  const config = parseOptions(passedOptions ?? {});
  const options = getOptionsFromConfig(config);
  config.validations.creationStack(config.store);
  config.validations.unsharedStore(config.store);
  if (typeof config.store.init === "function") config.store.init(options);
  const middleware = handleAsyncErrors(
    async (request, response, next) => {
      const skip = await config.skip(request, response);
      if (skip) {
        next();
        return;
      }
      const augmentedRequest = request;
      const key = await config.keyGenerator(request, response);
      let totalHits = 0;
      let resetTime;
      try {
        const incrementResult = await config.store.increment(key);
        totalHits = incrementResult.totalHits;
        resetTime = incrementResult.resetTime;
      } catch (error) {
        if (config.passOnStoreError) {
          console.error(
            "express-rate-limit: error from store, allowing request without rate-limiting.",
            error
          );
          next();
          return;
        }
        throw error;
      }
      config.validations.positiveHits(totalHits);
      config.validations.singleCount(request, config.store, key);
      const retrieveLimit = typeof config.limit === "function" ? config.limit(request, response) : config.limit;
      const limit = await retrieveLimit;
      config.validations.limit(limit);
      const info = {
        limit,
        used: totalHits,
        remaining: Math.max(limit - totalHits, 0),
        resetTime
      };
      Object.defineProperty(info, "current", {
        configurable: false,
        enumerable: false,
        value: totalHits
      });
      augmentedRequest[config.requestPropertyName] = info;
      if (config.legacyHeaders && !response.headersSent) {
        setLegacyHeaders(response, info);
      }
      if (config.standardHeaders && !response.headersSent) {
        switch (config.standardHeaders) {
          case "draft-6": {
            setDraft6Headers(response, info, config.windowMs);
            break;
          }
          case "draft-7": {
            config.validations.headersResetTime(info.resetTime);
            setDraft7Headers(response, info, config.windowMs);
            break;
          }
          case "draft-8": {
            const retrieveName = typeof config.identifier === "function" ? config.identifier(request, response) : config.identifier;
            const name = await retrieveName;
            config.validations.headersResetTime(info.resetTime);
            setDraft8Headers(response, info, config.windowMs, name, key);
            break;
          }
          default: {
            config.validations.headersDraftVersion(config.standardHeaders);
            break;
          }
        }
      }
      if (config.skipFailedRequests || config.skipSuccessfulRequests) {
        let decremented = false;
        const decrementKey = async () => {
          if (!decremented) {
            await config.store.decrement(key);
            decremented = true;
          }
        };
        if (config.skipFailedRequests) {
          response.on("finish", async () => {
            if (!await config.requestWasSuccessful(request, response))
              await decrementKey();
          });
          response.on("close", async () => {
            if (!response.writableEnded) await decrementKey();
          });
          response.on("error", async () => {
            await decrementKey();
          });
        }
        if (config.skipSuccessfulRequests) {
          response.on("finish", async () => {
            if (await config.requestWasSuccessful(request, response))
              await decrementKey();
          });
        }
      }
      config.validations.disable();
      if (totalHits > limit) {
        if (config.legacyHeaders || config.standardHeaders) {
          setRetryAfterHeader(response, info, config.windowMs);
        }
        config.handler(request, response, next, options);
        return;
      }
      next();
    }
  );
  const getThrowFn = () => {
    throw new Error("The current store does not support the get/getKey method");
  };
  middleware.resetKey = config.store.resetKey.bind(config.store);
  middleware.getKey = typeof config.store.get === "function" ? config.store.get.bind(config.store) : getThrowFn;
  return middleware;
};
var lib_default = rateLimit;

var multer$1 = {exports: {}};

var typeIs = {exports: {}};

var mediaTyper = {};

/*!
 * media-typer
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */

var hasRequiredMediaTyper;

function requireMediaTyper () {
	if (hasRequiredMediaTyper) return mediaTyper;
	hasRequiredMediaTyper = 1;
	/**
	 * RegExp to match *( ";" parameter ) in RFC 2616 sec 3.7
	 *
	 * parameter     = token "=" ( token | quoted-string )
	 * token         = 1*<any CHAR except CTLs or separators>
	 * separators    = "(" | ")" | "<" | ">" | "@"
	 *               | "," | ";" | ":" | "\" | <">
	 *               | "/" | "[" | "]" | "?" | "="
	 *               | "{" | "}" | SP | HT
	 * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
	 * qdtext        = <any TEXT except <">>
	 * quoted-pair   = "\" CHAR
	 * CHAR          = <any US-ASCII character (octets 0 - 127)>
	 * TEXT          = <any OCTET except CTLs, but including LWS>
	 * LWS           = [CRLF] 1*( SP | HT )
	 * CRLF          = CR LF
	 * CR            = <US-ASCII CR, carriage return (13)>
	 * LF            = <US-ASCII LF, linefeed (10)>
	 * SP            = <US-ASCII SP, space (32)>
	 * SHT           = <US-ASCII HT, horizontal-tab (9)>
	 * CTL           = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
	 * OCTET         = <any 8-bit sequence of data>
	 */
	var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u0020-\u007e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g;
	var textRegExp = /^[\u0020-\u007e\u0080-\u00ff]+$/;
	var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/;

	/**
	 * RegExp to match quoted-pair in RFC 2616
	 *
	 * quoted-pair = "\" CHAR
	 * CHAR        = <any US-ASCII character (octets 0 - 127)>
	 */
	var qescRegExp = /\\([\u0000-\u007f])/g;

	/**
	 * RegExp to match chars that must be quoted-pair in RFC 2616
	 */
	var quoteRegExp = /([\\"])/g;

	/**
	 * RegExp to match type in RFC 6838
	 *
	 * type-name = restricted-name
	 * subtype-name = restricted-name
	 * restricted-name = restricted-name-first *126restricted-name-chars
	 * restricted-name-first  = ALPHA / DIGIT
	 * restricted-name-chars  = ALPHA / DIGIT / "!" / "#" /
	 *                          "$" / "&" / "-" / "^" / "_"
	 * restricted-name-chars =/ "." ; Characters before first dot always
	 *                              ; specify a facet name
	 * restricted-name-chars =/ "+" ; Characters after last plus always
	 *                              ; specify a structured syntax suffix
	 * ALPHA =  %x41-5A / %x61-7A   ; A-Z / a-z
	 * DIGIT =  %x30-39             ; 0-9
	 */
	var subtypeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/;
	var typeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/;
	var typeRegExp = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/;

	/**
	 * Module exports.
	 */

	mediaTyper.format = format;
	mediaTyper.parse = parse;

	/**
	 * Format object to media type.
	 *
	 * @param {object} obj
	 * @return {string}
	 * @api public
	 */

	function format(obj) {
	  if (!obj || typeof obj !== 'object') {
	    throw new TypeError('argument obj is required')
	  }

	  var parameters = obj.parameters;
	  var subtype = obj.subtype;
	  var suffix = obj.suffix;
	  var type = obj.type;

	  if (!type || !typeNameRegExp.test(type)) {
	    throw new TypeError('invalid type')
	  }

	  if (!subtype || !subtypeNameRegExp.test(subtype)) {
	    throw new TypeError('invalid subtype')
	  }

	  // format as type/subtype
	  var string = type + '/' + subtype;

	  // append +suffix
	  if (suffix) {
	    if (!typeNameRegExp.test(suffix)) {
	      throw new TypeError('invalid suffix')
	    }

	    string += '+' + suffix;
	  }

	  // append parameters
	  if (parameters && typeof parameters === 'object') {
	    var param;
	    var params = Object.keys(parameters).sort();

	    for (var i = 0; i < params.length; i++) {
	      param = params[i];

	      if (!tokenRegExp.test(param)) {
	        throw new TypeError('invalid parameter name')
	      }

	      string += '; ' + param + '=' + qstring(parameters[param]);
	    }
	  }

	  return string
	}

	/**
	 * Parse media type to object.
	 *
	 * @param {string|object} string
	 * @return {Object}
	 * @api public
	 */

	function parse(string) {
	  if (!string) {
	    throw new TypeError('argument string is required')
	  }

	  // support req/res-like objects as argument
	  if (typeof string === 'object') {
	    string = getcontenttype(string);
	  }

	  if (typeof string !== 'string') {
	    throw new TypeError('argument string is required to be a string')
	  }

	  var index = string.indexOf(';');
	  var type = index !== -1
	    ? string.substr(0, index)
	    : string;

	  var key;
	  var match;
	  var obj = splitType(type);
	  var params = {};
	  var value;

	  paramRegExp.lastIndex = index;

	  while (match = paramRegExp.exec(string)) {
	    if (match.index !== index) {
	      throw new TypeError('invalid parameter format')
	    }

	    index += match[0].length;
	    key = match[1].toLowerCase();
	    value = match[2];

	    if (value[0] === '"') {
	      // remove quotes and escapes
	      value = value
	        .substr(1, value.length - 2)
	        .replace(qescRegExp, '$1');
	    }

	    params[key] = value;
	  }

	  if (index !== -1 && index !== string.length) {
	    throw new TypeError('invalid parameter format')
	  }

	  obj.parameters = params;

	  return obj
	}

	/**
	 * Get content-type from req/res objects.
	 *
	 * @param {object}
	 * @return {Object}
	 * @api private
	 */

	function getcontenttype(obj) {
	  if (typeof obj.getHeader === 'function') {
	    // res-like
	    return obj.getHeader('content-type')
	  }

	  if (typeof obj.headers === 'object') {
	    // req-like
	    return obj.headers && obj.headers['content-type']
	  }
	}

	/**
	 * Quote a string if necessary.
	 *
	 * @param {string} val
	 * @return {string}
	 * @api private
	 */

	function qstring(val) {
	  var str = String(val);

	  // no need to quote tokens
	  if (tokenRegExp.test(str)) {
	    return str
	  }

	  if (str.length > 0 && !textRegExp.test(str)) {
	    throw new TypeError('invalid parameter value')
	  }

	  return '"' + str.replace(quoteRegExp, '\\$1') + '"'
	}

	/**
	 * Simply "type/subtype+siffx" into parts.
	 *
	 * @param {string} string
	 * @return {Object}
	 * @api private
	 */

	function splitType(string) {
	  var match = typeRegExp.exec(string.toLowerCase());

	  if (!match) {
	    throw new TypeError('invalid media type')
	  }

	  var type = match[1];
	  var subtype = match[2];
	  var suffix;

	  // suffix after last +
	  var index = subtype.lastIndexOf('+');
	  if (index !== -1) {
	    suffix = subtype.substr(index + 1);
	    subtype = subtype.substr(0, index);
	  }

	  var obj = {
	    type: type,
	    subtype: subtype,
	    suffix: suffix
	  };

	  return obj
	}
	return mediaTyper;
}

var mimeTypes = {};

const require$$0$1 = {
  "application/1d-interleaved-parityfec": {"source":"iana"},
  "application/3gpdash-qoe-report+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/3gpp-ims+xml": {"source":"iana","compressible":true},
  "application/3gpphal+json": {"source":"iana","compressible":true},
  "application/3gpphalforms+json": {"source":"iana","compressible":true},
  "application/a2l": {"source":"iana"},
  "application/ace+cbor": {"source":"iana"},
  "application/activemessage": {"source":"iana"},
  "application/activity+json": {"source":"iana","compressible":true},
  "application/alto-costmap+json": {"source":"iana","compressible":true},
  "application/alto-costmapfilter+json": {"source":"iana","compressible":true},
  "application/alto-directory+json": {"source":"iana","compressible":true},
  "application/alto-endpointcost+json": {"source":"iana","compressible":true},
  "application/alto-endpointcostparams+json": {"source":"iana","compressible":true},
  "application/alto-endpointprop+json": {"source":"iana","compressible":true},
  "application/alto-endpointpropparams+json": {"source":"iana","compressible":true},
  "application/alto-error+json": {"source":"iana","compressible":true},
  "application/alto-networkmap+json": {"source":"iana","compressible":true},
  "application/alto-networkmapfilter+json": {"source":"iana","compressible":true},
  "application/alto-updatestreamcontrol+json": {"source":"iana","compressible":true},
  "application/alto-updatestreamparams+json": {"source":"iana","compressible":true},
  "application/aml": {"source":"iana"},
  "application/andrew-inset": {"source":"iana","extensions":["ez"]},
  "application/applefile": {"source":"iana"},
  "application/applixware": {"source":"apache","extensions":["aw"]},
  "application/at+jwt": {"source":"iana"},
  "application/atf": {"source":"iana"},
  "application/atfx": {"source":"iana"},
  "application/atom+xml": {"source":"iana","compressible":true,"extensions":["atom"]},
  "application/atomcat+xml": {"source":"iana","compressible":true,"extensions":["atomcat"]},
  "application/atomdeleted+xml": {"source":"iana","compressible":true,"extensions":["atomdeleted"]},
  "application/atomicmail": {"source":"iana"},
  "application/atomsvc+xml": {"source":"iana","compressible":true,"extensions":["atomsvc"]},
  "application/atsc-dwd+xml": {"source":"iana","compressible":true,"extensions":["dwd"]},
  "application/atsc-dynamic-event-message": {"source":"iana"},
  "application/atsc-held+xml": {"source":"iana","compressible":true,"extensions":["held"]},
  "application/atsc-rdt+json": {"source":"iana","compressible":true},
  "application/atsc-rsat+xml": {"source":"iana","compressible":true,"extensions":["rsat"]},
  "application/atxml": {"source":"iana"},
  "application/auth-policy+xml": {"source":"iana","compressible":true},
  "application/bacnet-xdd+zip": {"source":"iana","compressible":false},
  "application/batch-smtp": {"source":"iana"},
  "application/bdoc": {"compressible":false,"extensions":["bdoc"]},
  "application/beep+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/calendar+json": {"source":"iana","compressible":true},
  "application/calendar+xml": {"source":"iana","compressible":true,"extensions":["xcs"]},
  "application/call-completion": {"source":"iana"},
  "application/cals-1840": {"source":"iana"},
  "application/captive+json": {"source":"iana","compressible":true},
  "application/cbor": {"source":"iana"},
  "application/cbor-seq": {"source":"iana"},
  "application/cccex": {"source":"iana"},
  "application/ccmp+xml": {"source":"iana","compressible":true},
  "application/ccxml+xml": {"source":"iana","compressible":true,"extensions":["ccxml"]},
  "application/cdfx+xml": {"source":"iana","compressible":true,"extensions":["cdfx"]},
  "application/cdmi-capability": {"source":"iana","extensions":["cdmia"]},
  "application/cdmi-container": {"source":"iana","extensions":["cdmic"]},
  "application/cdmi-domain": {"source":"iana","extensions":["cdmid"]},
  "application/cdmi-object": {"source":"iana","extensions":["cdmio"]},
  "application/cdmi-queue": {"source":"iana","extensions":["cdmiq"]},
  "application/cdni": {"source":"iana"},
  "application/cea": {"source":"iana"},
  "application/cea-2018+xml": {"source":"iana","compressible":true},
  "application/cellml+xml": {"source":"iana","compressible":true},
  "application/cfw": {"source":"iana"},
  "application/city+json": {"source":"iana","compressible":true},
  "application/clr": {"source":"iana"},
  "application/clue+xml": {"source":"iana","compressible":true},
  "application/clue_info+xml": {"source":"iana","compressible":true},
  "application/cms": {"source":"iana"},
  "application/cnrp+xml": {"source":"iana","compressible":true},
  "application/coap-group+json": {"source":"iana","compressible":true},
  "application/coap-payload": {"source":"iana"},
  "application/commonground": {"source":"iana"},
  "application/conference-info+xml": {"source":"iana","compressible":true},
  "application/cose": {"source":"iana"},
  "application/cose-key": {"source":"iana"},
  "application/cose-key-set": {"source":"iana"},
  "application/cpl+xml": {"source":"iana","compressible":true,"extensions":["cpl"]},
  "application/csrattrs": {"source":"iana"},
  "application/csta+xml": {"source":"iana","compressible":true},
  "application/cstadata+xml": {"source":"iana","compressible":true},
  "application/csvm+json": {"source":"iana","compressible":true},
  "application/cu-seeme": {"source":"apache","extensions":["cu"]},
  "application/cwt": {"source":"iana"},
  "application/cybercash": {"source":"iana"},
  "application/dart": {"compressible":true},
  "application/dash+xml": {"source":"iana","compressible":true,"extensions":["mpd"]},
  "application/dash-patch+xml": {"source":"iana","compressible":true,"extensions":["mpp"]},
  "application/dashdelta": {"source":"iana"},
  "application/davmount+xml": {"source":"iana","compressible":true,"extensions":["davmount"]},
  "application/dca-rft": {"source":"iana"},
  "application/dcd": {"source":"iana"},
  "application/dec-dx": {"source":"iana"},
  "application/dialog-info+xml": {"source":"iana","compressible":true},
  "application/dicom": {"source":"iana"},
  "application/dicom+json": {"source":"iana","compressible":true},
  "application/dicom+xml": {"source":"iana","compressible":true},
  "application/dii": {"source":"iana"},
  "application/dit": {"source":"iana"},
  "application/dns": {"source":"iana"},
  "application/dns+json": {"source":"iana","compressible":true},
  "application/dns-message": {"source":"iana"},
  "application/docbook+xml": {"source":"apache","compressible":true,"extensions":["dbk"]},
  "application/dots+cbor": {"source":"iana"},
  "application/dskpp+xml": {"source":"iana","compressible":true},
  "application/dssc+der": {"source":"iana","extensions":["dssc"]},
  "application/dssc+xml": {"source":"iana","compressible":true,"extensions":["xdssc"]},
  "application/dvcs": {"source":"iana"},
  "application/ecmascript": {"source":"iana","compressible":true,"extensions":["es","ecma"]},
  "application/edi-consent": {"source":"iana"},
  "application/edi-x12": {"source":"iana","compressible":false},
  "application/edifact": {"source":"iana","compressible":false},
  "application/efi": {"source":"iana"},
  "application/elm+json": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/elm+xml": {"source":"iana","compressible":true},
  "application/emergencycalldata.cap+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/emergencycalldata.comment+xml": {"source":"iana","compressible":true},
  "application/emergencycalldata.control+xml": {"source":"iana","compressible":true},
  "application/emergencycalldata.deviceinfo+xml": {"source":"iana","compressible":true},
  "application/emergencycalldata.ecall.msd": {"source":"iana"},
  "application/emergencycalldata.providerinfo+xml": {"source":"iana","compressible":true},
  "application/emergencycalldata.serviceinfo+xml": {"source":"iana","compressible":true},
  "application/emergencycalldata.subscriberinfo+xml": {"source":"iana","compressible":true},
  "application/emergencycalldata.veds+xml": {"source":"iana","compressible":true},
  "application/emma+xml": {"source":"iana","compressible":true,"extensions":["emma"]},
  "application/emotionml+xml": {"source":"iana","compressible":true,"extensions":["emotionml"]},
  "application/encaprtp": {"source":"iana"},
  "application/epp+xml": {"source":"iana","compressible":true},
  "application/epub+zip": {"source":"iana","compressible":false,"extensions":["epub"]},
  "application/eshop": {"source":"iana"},
  "application/exi": {"source":"iana","extensions":["exi"]},
  "application/expect-ct-report+json": {"source":"iana","compressible":true},
  "application/express": {"source":"iana","extensions":["exp"]},
  "application/fastinfoset": {"source":"iana"},
  "application/fastsoap": {"source":"iana"},
  "application/fdt+xml": {"source":"iana","compressible":true,"extensions":["fdt"]},
  "application/fhir+json": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/fhir+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/fido.trusted-apps+json": {"compressible":true},
  "application/fits": {"source":"iana"},
  "application/flexfec": {"source":"iana"},
  "application/font-sfnt": {"source":"iana"},
  "application/font-tdpfr": {"source":"iana","extensions":["pfr"]},
  "application/font-woff": {"source":"iana","compressible":false},
  "application/framework-attributes+xml": {"source":"iana","compressible":true},
  "application/geo+json": {"source":"iana","compressible":true,"extensions":["geojson"]},
  "application/geo+json-seq": {"source":"iana"},
  "application/geopackage+sqlite3": {"source":"iana"},
  "application/geoxacml+xml": {"source":"iana","compressible":true},
  "application/gltf-buffer": {"source":"iana"},
  "application/gml+xml": {"source":"iana","compressible":true,"extensions":["gml"]},
  "application/gpx+xml": {"source":"apache","compressible":true,"extensions":["gpx"]},
  "application/gxf": {"source":"apache","extensions":["gxf"]},
  "application/gzip": {"source":"iana","compressible":false,"extensions":["gz"]},
  "application/h224": {"source":"iana"},
  "application/held+xml": {"source":"iana","compressible":true},
  "application/hjson": {"extensions":["hjson"]},
  "application/http": {"source":"iana"},
  "application/hyperstudio": {"source":"iana","extensions":["stk"]},
  "application/ibe-key-request+xml": {"source":"iana","compressible":true},
  "application/ibe-pkg-reply+xml": {"source":"iana","compressible":true},
  "application/ibe-pp-data": {"source":"iana"},
  "application/iges": {"source":"iana"},
  "application/im-iscomposing+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/index": {"source":"iana"},
  "application/index.cmd": {"source":"iana"},
  "application/index.obj": {"source":"iana"},
  "application/index.response": {"source":"iana"},
  "application/index.vnd": {"source":"iana"},
  "application/inkml+xml": {"source":"iana","compressible":true,"extensions":["ink","inkml"]},
  "application/iotp": {"source":"iana"},
  "application/ipfix": {"source":"iana","extensions":["ipfix"]},
  "application/ipp": {"source":"iana"},
  "application/isup": {"source":"iana"},
  "application/its+xml": {"source":"iana","compressible":true,"extensions":["its"]},
  "application/java-archive": {"source":"apache","compressible":false,"extensions":["jar","war","ear"]},
  "application/java-serialized-object": {"source":"apache","compressible":false,"extensions":["ser"]},
  "application/java-vm": {"source":"apache","compressible":false,"extensions":["class"]},
  "application/javascript": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["js","mjs"]},
  "application/jf2feed+json": {"source":"iana","compressible":true},
  "application/jose": {"source":"iana"},
  "application/jose+json": {"source":"iana","compressible":true},
  "application/jrd+json": {"source":"iana","compressible":true},
  "application/jscalendar+json": {"source":"iana","compressible":true},
  "application/json": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["json","map"]},
  "application/json-patch+json": {"source":"iana","compressible":true},
  "application/json-seq": {"source":"iana"},
  "application/json5": {"extensions":["json5"]},
  "application/jsonml+json": {"source":"apache","compressible":true,"extensions":["jsonml"]},
  "application/jwk+json": {"source":"iana","compressible":true},
  "application/jwk-set+json": {"source":"iana","compressible":true},
  "application/jwt": {"source":"iana"},
  "application/kpml-request+xml": {"source":"iana","compressible":true},
  "application/kpml-response+xml": {"source":"iana","compressible":true},
  "application/ld+json": {"source":"iana","compressible":true,"extensions":["jsonld"]},
  "application/lgr+xml": {"source":"iana","compressible":true,"extensions":["lgr"]},
  "application/link-format": {"source":"iana"},
  "application/load-control+xml": {"source":"iana","compressible":true},
  "application/lost+xml": {"source":"iana","compressible":true,"extensions":["lostxml"]},
  "application/lostsync+xml": {"source":"iana","compressible":true},
  "application/lpf+zip": {"source":"iana","compressible":false},
  "application/lxf": {"source":"iana"},
  "application/mac-binhex40": {"source":"iana","extensions":["hqx"]},
  "application/mac-compactpro": {"source":"apache","extensions":["cpt"]},
  "application/macwriteii": {"source":"iana"},
  "application/mads+xml": {"source":"iana","compressible":true,"extensions":["mads"]},
  "application/manifest+json": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["webmanifest"]},
  "application/marc": {"source":"iana","extensions":["mrc"]},
  "application/marcxml+xml": {"source":"iana","compressible":true,"extensions":["mrcx"]},
  "application/mathematica": {"source":"iana","extensions":["ma","nb","mb"]},
  "application/mathml+xml": {"source":"iana","compressible":true,"extensions":["mathml"]},
  "application/mathml-content+xml": {"source":"iana","compressible":true},
  "application/mathml-presentation+xml": {"source":"iana","compressible":true},
  "application/mbms-associated-procedure-description+xml": {"source":"iana","compressible":true},
  "application/mbms-deregister+xml": {"source":"iana","compressible":true},
  "application/mbms-envelope+xml": {"source":"iana","compressible":true},
  "application/mbms-msk+xml": {"source":"iana","compressible":true},
  "application/mbms-msk-response+xml": {"source":"iana","compressible":true},
  "application/mbms-protection-description+xml": {"source":"iana","compressible":true},
  "application/mbms-reception-report+xml": {"source":"iana","compressible":true},
  "application/mbms-register+xml": {"source":"iana","compressible":true},
  "application/mbms-register-response+xml": {"source":"iana","compressible":true},
  "application/mbms-schedule+xml": {"source":"iana","compressible":true},
  "application/mbms-user-service-description+xml": {"source":"iana","compressible":true},
  "application/mbox": {"source":"iana","extensions":["mbox"]},
  "application/media-policy-dataset+xml": {"source":"iana","compressible":true,"extensions":["mpf"]},
  "application/media_control+xml": {"source":"iana","compressible":true},
  "application/mediaservercontrol+xml": {"source":"iana","compressible":true,"extensions":["mscml"]},
  "application/merge-patch+json": {"source":"iana","compressible":true},
  "application/metalink+xml": {"source":"apache","compressible":true,"extensions":["metalink"]},
  "application/metalink4+xml": {"source":"iana","compressible":true,"extensions":["meta4"]},
  "application/mets+xml": {"source":"iana","compressible":true,"extensions":["mets"]},
  "application/mf4": {"source":"iana"},
  "application/mikey": {"source":"iana"},
  "application/mipc": {"source":"iana"},
  "application/missing-blocks+cbor-seq": {"source":"iana"},
  "application/mmt-aei+xml": {"source":"iana","compressible":true,"extensions":["maei"]},
  "application/mmt-usd+xml": {"source":"iana","compressible":true,"extensions":["musd"]},
  "application/mods+xml": {"source":"iana","compressible":true,"extensions":["mods"]},
  "application/moss-keys": {"source":"iana"},
  "application/moss-signature": {"source":"iana"},
  "application/mosskey-data": {"source":"iana"},
  "application/mosskey-request": {"source":"iana"},
  "application/mp21": {"source":"iana","extensions":["m21","mp21"]},
  "application/mp4": {"source":"iana","extensions":["mp4s","m4p"]},
  "application/mpeg4-generic": {"source":"iana"},
  "application/mpeg4-iod": {"source":"iana"},
  "application/mpeg4-iod-xmt": {"source":"iana"},
  "application/mrb-consumer+xml": {"source":"iana","compressible":true},
  "application/mrb-publish+xml": {"source":"iana","compressible":true},
  "application/msc-ivr+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/msc-mixer+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/msword": {"source":"iana","compressible":false,"extensions":["doc","dot"]},
  "application/mud+json": {"source":"iana","compressible":true},
  "application/multipart-core": {"source":"iana"},
  "application/mxf": {"source":"iana","extensions":["mxf"]},
  "application/n-quads": {"source":"iana","extensions":["nq"]},
  "application/n-triples": {"source":"iana","extensions":["nt"]},
  "application/nasdata": {"source":"iana"},
  "application/news-checkgroups": {"source":"iana","charset":"US-ASCII"},
  "application/news-groupinfo": {"source":"iana","charset":"US-ASCII"},
  "application/news-transmission": {"source":"iana"},
  "application/nlsml+xml": {"source":"iana","compressible":true},
  "application/node": {"source":"iana","extensions":["cjs"]},
  "application/nss": {"source":"iana"},
  "application/oauth-authz-req+jwt": {"source":"iana"},
  "application/oblivious-dns-message": {"source":"iana"},
  "application/ocsp-request": {"source":"iana"},
  "application/ocsp-response": {"source":"iana"},
  "application/octet-stream": {"source":"iana","compressible":false,"extensions":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]},
  "application/oda": {"source":"iana","extensions":["oda"]},
  "application/odm+xml": {"source":"iana","compressible":true},
  "application/odx": {"source":"iana"},
  "application/oebps-package+xml": {"source":"iana","compressible":true,"extensions":["opf"]},
  "application/ogg": {"source":"iana","compressible":false,"extensions":["ogx"]},
  "application/omdoc+xml": {"source":"apache","compressible":true,"extensions":["omdoc"]},
  "application/onenote": {"source":"apache","extensions":["onetoc","onetoc2","onetmp","onepkg"]},
  "application/opc-nodeset+xml": {"source":"iana","compressible":true},
  "application/oscore": {"source":"iana"},
  "application/oxps": {"source":"iana","extensions":["oxps"]},
  "application/p21": {"source":"iana"},
  "application/p21+zip": {"source":"iana","compressible":false},
  "application/p2p-overlay+xml": {"source":"iana","compressible":true,"extensions":["relo"]},
  "application/parityfec": {"source":"iana"},
  "application/passport": {"source":"iana"},
  "application/patch-ops-error+xml": {"source":"iana","compressible":true,"extensions":["xer"]},
  "application/pdf": {"source":"iana","compressible":false,"extensions":["pdf"]},
  "application/pdx": {"source":"iana"},
  "application/pem-certificate-chain": {"source":"iana"},
  "application/pgp-encrypted": {"source":"iana","compressible":false,"extensions":["pgp"]},
  "application/pgp-keys": {"source":"iana","extensions":["asc"]},
  "application/pgp-signature": {"source":"iana","extensions":["asc","sig"]},
  "application/pics-rules": {"source":"apache","extensions":["prf"]},
  "application/pidf+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/pidf-diff+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/pkcs10": {"source":"iana","extensions":["p10"]},
  "application/pkcs12": {"source":"iana"},
  "application/pkcs7-mime": {"source":"iana","extensions":["p7m","p7c"]},
  "application/pkcs7-signature": {"source":"iana","extensions":["p7s"]},
  "application/pkcs8": {"source":"iana","extensions":["p8"]},
  "application/pkcs8-encrypted": {"source":"iana"},
  "application/pkix-attr-cert": {"source":"iana","extensions":["ac"]},
  "application/pkix-cert": {"source":"iana","extensions":["cer"]},
  "application/pkix-crl": {"source":"iana","extensions":["crl"]},
  "application/pkix-pkipath": {"source":"iana","extensions":["pkipath"]},
  "application/pkixcmp": {"source":"iana","extensions":["pki"]},
  "application/pls+xml": {"source":"iana","compressible":true,"extensions":["pls"]},
  "application/poc-settings+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/postscript": {"source":"iana","compressible":true,"extensions":["ai","eps","ps"]},
  "application/ppsp-tracker+json": {"source":"iana","compressible":true},
  "application/problem+json": {"source":"iana","compressible":true},
  "application/problem+xml": {"source":"iana","compressible":true},
  "application/provenance+xml": {"source":"iana","compressible":true,"extensions":["provx"]},
  "application/prs.alvestrand.titrax-sheet": {"source":"iana"},
  "application/prs.cww": {"source":"iana","extensions":["cww"]},
  "application/prs.cyn": {"source":"iana","charset":"7-BIT"},
  "application/prs.hpub+zip": {"source":"iana","compressible":false},
  "application/prs.nprend": {"source":"iana"},
  "application/prs.plucker": {"source":"iana"},
  "application/prs.rdf-xml-crypt": {"source":"iana"},
  "application/prs.xsf+xml": {"source":"iana","compressible":true},
  "application/pskc+xml": {"source":"iana","compressible":true,"extensions":["pskcxml"]},
  "application/pvd+json": {"source":"iana","compressible":true},
  "application/qsig": {"source":"iana"},
  "application/raml+yaml": {"compressible":true,"extensions":["raml"]},
  "application/raptorfec": {"source":"iana"},
  "application/rdap+json": {"source":"iana","compressible":true},
  "application/rdf+xml": {"source":"iana","compressible":true,"extensions":["rdf","owl"]},
  "application/reginfo+xml": {"source":"iana","compressible":true,"extensions":["rif"]},
  "application/relax-ng-compact-syntax": {"source":"iana","extensions":["rnc"]},
  "application/remote-printing": {"source":"iana"},
  "application/reputon+json": {"source":"iana","compressible":true},
  "application/resource-lists+xml": {"source":"iana","compressible":true,"extensions":["rl"]},
  "application/resource-lists-diff+xml": {"source":"iana","compressible":true,"extensions":["rld"]},
  "application/rfc+xml": {"source":"iana","compressible":true},
  "application/riscos": {"source":"iana"},
  "application/rlmi+xml": {"source":"iana","compressible":true},
  "application/rls-services+xml": {"source":"iana","compressible":true,"extensions":["rs"]},
  "application/route-apd+xml": {"source":"iana","compressible":true,"extensions":["rapd"]},
  "application/route-s-tsid+xml": {"source":"iana","compressible":true,"extensions":["sls"]},
  "application/route-usd+xml": {"source":"iana","compressible":true,"extensions":["rusd"]},
  "application/rpki-ghostbusters": {"source":"iana","extensions":["gbr"]},
  "application/rpki-manifest": {"source":"iana","extensions":["mft"]},
  "application/rpki-publication": {"source":"iana"},
  "application/rpki-roa": {"source":"iana","extensions":["roa"]},
  "application/rpki-updown": {"source":"iana"},
  "application/rsd+xml": {"source":"apache","compressible":true,"extensions":["rsd"]},
  "application/rss+xml": {"source":"apache","compressible":true,"extensions":["rss"]},
  "application/rtf": {"source":"iana","compressible":true,"extensions":["rtf"]},
  "application/rtploopback": {"source":"iana"},
  "application/rtx": {"source":"iana"},
  "application/samlassertion+xml": {"source":"iana","compressible":true},
  "application/samlmetadata+xml": {"source":"iana","compressible":true},
  "application/sarif+json": {"source":"iana","compressible":true},
  "application/sarif-external-properties+json": {"source":"iana","compressible":true},
  "application/sbe": {"source":"iana"},
  "application/sbml+xml": {"source":"iana","compressible":true,"extensions":["sbml"]},
  "application/scaip+xml": {"source":"iana","compressible":true},
  "application/scim+json": {"source":"iana","compressible":true},
  "application/scvp-cv-request": {"source":"iana","extensions":["scq"]},
  "application/scvp-cv-response": {"source":"iana","extensions":["scs"]},
  "application/scvp-vp-request": {"source":"iana","extensions":["spq"]},
  "application/scvp-vp-response": {"source":"iana","extensions":["spp"]},
  "application/sdp": {"source":"iana","extensions":["sdp"]},
  "application/secevent+jwt": {"source":"iana"},
  "application/senml+cbor": {"source":"iana"},
  "application/senml+json": {"source":"iana","compressible":true},
  "application/senml+xml": {"source":"iana","compressible":true,"extensions":["senmlx"]},
  "application/senml-etch+cbor": {"source":"iana"},
  "application/senml-etch+json": {"source":"iana","compressible":true},
  "application/senml-exi": {"source":"iana"},
  "application/sensml+cbor": {"source":"iana"},
  "application/sensml+json": {"source":"iana","compressible":true},
  "application/sensml+xml": {"source":"iana","compressible":true,"extensions":["sensmlx"]},
  "application/sensml-exi": {"source":"iana"},
  "application/sep+xml": {"source":"iana","compressible":true},
  "application/sep-exi": {"source":"iana"},
  "application/session-info": {"source":"iana"},
  "application/set-payment": {"source":"iana"},
  "application/set-payment-initiation": {"source":"iana","extensions":["setpay"]},
  "application/set-registration": {"source":"iana"},
  "application/set-registration-initiation": {"source":"iana","extensions":["setreg"]},
  "application/sgml": {"source":"iana"},
  "application/sgml-open-catalog": {"source":"iana"},
  "application/shf+xml": {"source":"iana","compressible":true,"extensions":["shf"]},
  "application/sieve": {"source":"iana","extensions":["siv","sieve"]},
  "application/simple-filter+xml": {"source":"iana","compressible":true},
  "application/simple-message-summary": {"source":"iana"},
  "application/simplesymbolcontainer": {"source":"iana"},
  "application/sipc": {"source":"iana"},
  "application/slate": {"source":"iana"},
  "application/smil": {"source":"iana"},
  "application/smil+xml": {"source":"iana","compressible":true,"extensions":["smi","smil"]},
  "application/smpte336m": {"source":"iana"},
  "application/soap+fastinfoset": {"source":"iana"},
  "application/soap+xml": {"source":"iana","compressible":true},
  "application/sparql-query": {"source":"iana","extensions":["rq"]},
  "application/sparql-results+xml": {"source":"iana","compressible":true,"extensions":["srx"]},
  "application/spdx+json": {"source":"iana","compressible":true},
  "application/spirits-event+xml": {"source":"iana","compressible":true},
  "application/sql": {"source":"iana"},
  "application/srgs": {"source":"iana","extensions":["gram"]},
  "application/srgs+xml": {"source":"iana","compressible":true,"extensions":["grxml"]},
  "application/sru+xml": {"source":"iana","compressible":true,"extensions":["sru"]},
  "application/ssdl+xml": {"source":"apache","compressible":true,"extensions":["ssdl"]},
  "application/ssml+xml": {"source":"iana","compressible":true,"extensions":["ssml"]},
  "application/stix+json": {"source":"iana","compressible":true},
  "application/swid+xml": {"source":"iana","compressible":true,"extensions":["swidtag"]},
  "application/tamp-apex-update": {"source":"iana"},
  "application/tamp-apex-update-confirm": {"source":"iana"},
  "application/tamp-community-update": {"source":"iana"},
  "application/tamp-community-update-confirm": {"source":"iana"},
  "application/tamp-error": {"source":"iana"},
  "application/tamp-sequence-adjust": {"source":"iana"},
  "application/tamp-sequence-adjust-confirm": {"source":"iana"},
  "application/tamp-status-query": {"source":"iana"},
  "application/tamp-status-response": {"source":"iana"},
  "application/tamp-update": {"source":"iana"},
  "application/tamp-update-confirm": {"source":"iana"},
  "application/tar": {"compressible":true},
  "application/taxii+json": {"source":"iana","compressible":true},
  "application/td+json": {"source":"iana","compressible":true},
  "application/tei+xml": {"source":"iana","compressible":true,"extensions":["tei","teicorpus"]},
  "application/tetra_isi": {"source":"iana"},
  "application/thraud+xml": {"source":"iana","compressible":true,"extensions":["tfi"]},
  "application/timestamp-query": {"source":"iana"},
  "application/timestamp-reply": {"source":"iana"},
  "application/timestamped-data": {"source":"iana","extensions":["tsd"]},
  "application/tlsrpt+gzip": {"source":"iana"},
  "application/tlsrpt+json": {"source":"iana","compressible":true},
  "application/tnauthlist": {"source":"iana"},
  "application/token-introspection+jwt": {"source":"iana"},
  "application/toml": {"compressible":true,"extensions":["toml"]},
  "application/trickle-ice-sdpfrag": {"source":"iana"},
  "application/trig": {"source":"iana","extensions":["trig"]},
  "application/ttml+xml": {"source":"iana","compressible":true,"extensions":["ttml"]},
  "application/tve-trigger": {"source":"iana"},
  "application/tzif": {"source":"iana"},
  "application/tzif-leap": {"source":"iana"},
  "application/ubjson": {"compressible":false,"extensions":["ubj"]},
  "application/ulpfec": {"source":"iana"},
  "application/urc-grpsheet+xml": {"source":"iana","compressible":true},
  "application/urc-ressheet+xml": {"source":"iana","compressible":true,"extensions":["rsheet"]},
  "application/urc-targetdesc+xml": {"source":"iana","compressible":true,"extensions":["td"]},
  "application/urc-uisocketdesc+xml": {"source":"iana","compressible":true},
  "application/vcard+json": {"source":"iana","compressible":true},
  "application/vcard+xml": {"source":"iana","compressible":true},
  "application/vemmi": {"source":"iana"},
  "application/vividence.scriptfile": {"source":"apache"},
  "application/vnd.1000minds.decision-model+xml": {"source":"iana","compressible":true,"extensions":["1km"]},
  "application/vnd.3gpp-prose+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp-prose-pc3ch+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp-v2x-local-service-information": {"source":"iana"},
  "application/vnd.3gpp.5gnas": {"source":"iana"},
  "application/vnd.3gpp.access-transfer-events+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.bsf+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.gmop+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.gtpc": {"source":"iana"},
  "application/vnd.3gpp.interworking-data": {"source":"iana"},
  "application/vnd.3gpp.lpp": {"source":"iana"},
  "application/vnd.3gpp.mc-signalling-ear": {"source":"iana"},
  "application/vnd.3gpp.mcdata-affiliation-command+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcdata-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcdata-payload": {"source":"iana"},
  "application/vnd.3gpp.mcdata-service-config+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcdata-signalling": {"source":"iana"},
  "application/vnd.3gpp.mcdata-ue-config+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcdata-user-profile+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-affiliation-command+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-floor-request+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-location-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-mbms-usage-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-service-config+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-signed+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-ue-config+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-ue-init-config+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-user-profile+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-affiliation-command+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-affiliation-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-location-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-service-config+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-transmission-request+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-ue-config+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-user-profile+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mid-call+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.ngap": {"source":"iana"},
  "application/vnd.3gpp.pfcp": {"source":"iana"},
  "application/vnd.3gpp.pic-bw-large": {"source":"iana","extensions":["plb"]},
  "application/vnd.3gpp.pic-bw-small": {"source":"iana","extensions":["psb"]},
  "application/vnd.3gpp.pic-bw-var": {"source":"iana","extensions":["pvb"]},
  "application/vnd.3gpp.s1ap": {"source":"iana"},
  "application/vnd.3gpp.sms": {"source":"iana"},
  "application/vnd.3gpp.sms+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.srvcc-ext+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.srvcc-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.state-and-event-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.ussd+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp2.bcmcsinfo+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp2.sms": {"source":"iana"},
  "application/vnd.3gpp2.tcap": {"source":"iana","extensions":["tcap"]},
  "application/vnd.3lightssoftware.imagescal": {"source":"iana"},
  "application/vnd.3m.post-it-notes": {"source":"iana","extensions":["pwn"]},
  "application/vnd.accpac.simply.aso": {"source":"iana","extensions":["aso"]},
  "application/vnd.accpac.simply.imp": {"source":"iana","extensions":["imp"]},
  "application/vnd.acucobol": {"source":"iana","extensions":["acu"]},
  "application/vnd.acucorp": {"source":"iana","extensions":["atc","acutc"]},
  "application/vnd.adobe.air-application-installer-package+zip": {"source":"apache","compressible":false,"extensions":["air"]},
  "application/vnd.adobe.flash.movie": {"source":"iana"},
  "application/vnd.adobe.formscentral.fcdt": {"source":"iana","extensions":["fcdt"]},
  "application/vnd.adobe.fxp": {"source":"iana","extensions":["fxp","fxpl"]},
  "application/vnd.adobe.partial-upload": {"source":"iana"},
  "application/vnd.adobe.xdp+xml": {"source":"iana","compressible":true,"extensions":["xdp"]},
  "application/vnd.adobe.xfdf": {"source":"iana","extensions":["xfdf"]},
  "application/vnd.aether.imp": {"source":"iana"},
  "application/vnd.afpc.afplinedata": {"source":"iana"},
  "application/vnd.afpc.afplinedata-pagedef": {"source":"iana"},
  "application/vnd.afpc.cmoca-cmresource": {"source":"iana"},
  "application/vnd.afpc.foca-charset": {"source":"iana"},
  "application/vnd.afpc.foca-codedfont": {"source":"iana"},
  "application/vnd.afpc.foca-codepage": {"source":"iana"},
  "application/vnd.afpc.modca": {"source":"iana"},
  "application/vnd.afpc.modca-cmtable": {"source":"iana"},
  "application/vnd.afpc.modca-formdef": {"source":"iana"},
  "application/vnd.afpc.modca-mediummap": {"source":"iana"},
  "application/vnd.afpc.modca-objectcontainer": {"source":"iana"},
  "application/vnd.afpc.modca-overlay": {"source":"iana"},
  "application/vnd.afpc.modca-pagesegment": {"source":"iana"},
  "application/vnd.age": {"source":"iana","extensions":["age"]},
  "application/vnd.ah-barcode": {"source":"iana"},
  "application/vnd.ahead.space": {"source":"iana","extensions":["ahead"]},
  "application/vnd.airzip.filesecure.azf": {"source":"iana","extensions":["azf"]},
  "application/vnd.airzip.filesecure.azs": {"source":"iana","extensions":["azs"]},
  "application/vnd.amadeus+json": {"source":"iana","compressible":true},
  "application/vnd.amazon.ebook": {"source":"apache","extensions":["azw"]},
  "application/vnd.amazon.mobi8-ebook": {"source":"iana"},
  "application/vnd.americandynamics.acc": {"source":"iana","extensions":["acc"]},
  "application/vnd.amiga.ami": {"source":"iana","extensions":["ami"]},
  "application/vnd.amundsen.maze+xml": {"source":"iana","compressible":true},
  "application/vnd.android.ota": {"source":"iana"},
  "application/vnd.android.package-archive": {"source":"apache","compressible":false,"extensions":["apk"]},
  "application/vnd.anki": {"source":"iana"},
  "application/vnd.anser-web-certificate-issue-initiation": {"source":"iana","extensions":["cii"]},
  "application/vnd.anser-web-funds-transfer-initiation": {"source":"apache","extensions":["fti"]},
  "application/vnd.antix.game-component": {"source":"iana","extensions":["atx"]},
  "application/vnd.apache.arrow.file": {"source":"iana"},
  "application/vnd.apache.arrow.stream": {"source":"iana"},
  "application/vnd.apache.thrift.binary": {"source":"iana"},
  "application/vnd.apache.thrift.compact": {"source":"iana"},
  "application/vnd.apache.thrift.json": {"source":"iana"},
  "application/vnd.api+json": {"source":"iana","compressible":true},
  "application/vnd.aplextor.warrp+json": {"source":"iana","compressible":true},
  "application/vnd.apothekende.reservation+json": {"source":"iana","compressible":true},
  "application/vnd.apple.installer+xml": {"source":"iana","compressible":true,"extensions":["mpkg"]},
  "application/vnd.apple.keynote": {"source":"iana","extensions":["key"]},
  "application/vnd.apple.mpegurl": {"source":"iana","extensions":["m3u8"]},
  "application/vnd.apple.numbers": {"source":"iana","extensions":["numbers"]},
  "application/vnd.apple.pages": {"source":"iana","extensions":["pages"]},
  "application/vnd.apple.pkpass": {"compressible":false,"extensions":["pkpass"]},
  "application/vnd.arastra.swi": {"source":"iana"},
  "application/vnd.aristanetworks.swi": {"source":"iana","extensions":["swi"]},
  "application/vnd.artisan+json": {"source":"iana","compressible":true},
  "application/vnd.artsquare": {"source":"iana"},
  "application/vnd.astraea-software.iota": {"source":"iana","extensions":["iota"]},
  "application/vnd.audiograph": {"source":"iana","extensions":["aep"]},
  "application/vnd.autopackage": {"source":"iana"},
  "application/vnd.avalon+json": {"source":"iana","compressible":true},
  "application/vnd.avistar+xml": {"source":"iana","compressible":true},
  "application/vnd.balsamiq.bmml+xml": {"source":"iana","compressible":true,"extensions":["bmml"]},
  "application/vnd.balsamiq.bmpr": {"source":"iana"},
  "application/vnd.banana-accounting": {"source":"iana"},
  "application/vnd.bbf.usp.error": {"source":"iana"},
  "application/vnd.bbf.usp.msg": {"source":"iana"},
  "application/vnd.bbf.usp.msg+json": {"source":"iana","compressible":true},
  "application/vnd.bekitzur-stech+json": {"source":"iana","compressible":true},
  "application/vnd.bint.med-content": {"source":"iana"},
  "application/vnd.biopax.rdf+xml": {"source":"iana","compressible":true},
  "application/vnd.blink-idb-value-wrapper": {"source":"iana"},
  "application/vnd.blueice.multipass": {"source":"iana","extensions":["mpm"]},
  "application/vnd.bluetooth.ep.oob": {"source":"iana"},
  "application/vnd.bluetooth.le.oob": {"source":"iana"},
  "application/vnd.bmi": {"source":"iana","extensions":["bmi"]},
  "application/vnd.bpf": {"source":"iana"},
  "application/vnd.bpf3": {"source":"iana"},
  "application/vnd.businessobjects": {"source":"iana","extensions":["rep"]},
  "application/vnd.byu.uapi+json": {"source":"iana","compressible":true},
  "application/vnd.cab-jscript": {"source":"iana"},
  "application/vnd.canon-cpdl": {"source":"iana"},
  "application/vnd.canon-lips": {"source":"iana"},
  "application/vnd.capasystems-pg+json": {"source":"iana","compressible":true},
  "application/vnd.cendio.thinlinc.clientconf": {"source":"iana"},
  "application/vnd.century-systems.tcp_stream": {"source":"iana"},
  "application/vnd.chemdraw+xml": {"source":"iana","compressible":true,"extensions":["cdxml"]},
  "application/vnd.chess-pgn": {"source":"iana"},
  "application/vnd.chipnuts.karaoke-mmd": {"source":"iana","extensions":["mmd"]},
  "application/vnd.ciedi": {"source":"iana"},
  "application/vnd.cinderella": {"source":"iana","extensions":["cdy"]},
  "application/vnd.cirpack.isdn-ext": {"source":"iana"},
  "application/vnd.citationstyles.style+xml": {"source":"iana","compressible":true,"extensions":["csl"]},
  "application/vnd.claymore": {"source":"iana","extensions":["cla"]},
  "application/vnd.cloanto.rp9": {"source":"iana","extensions":["rp9"]},
  "application/vnd.clonk.c4group": {"source":"iana","extensions":["c4g","c4d","c4f","c4p","c4u"]},
  "application/vnd.cluetrust.cartomobile-config": {"source":"iana","extensions":["c11amc"]},
  "application/vnd.cluetrust.cartomobile-config-pkg": {"source":"iana","extensions":["c11amz"]},
  "application/vnd.coffeescript": {"source":"iana"},
  "application/vnd.collabio.xodocuments.document": {"source":"iana"},
  "application/vnd.collabio.xodocuments.document-template": {"source":"iana"},
  "application/vnd.collabio.xodocuments.presentation": {"source":"iana"},
  "application/vnd.collabio.xodocuments.presentation-template": {"source":"iana"},
  "application/vnd.collabio.xodocuments.spreadsheet": {"source":"iana"},
  "application/vnd.collabio.xodocuments.spreadsheet-template": {"source":"iana"},
  "application/vnd.collection+json": {"source":"iana","compressible":true},
  "application/vnd.collection.doc+json": {"source":"iana","compressible":true},
  "application/vnd.collection.next+json": {"source":"iana","compressible":true},
  "application/vnd.comicbook+zip": {"source":"iana","compressible":false},
  "application/vnd.comicbook-rar": {"source":"iana"},
  "application/vnd.commerce-battelle": {"source":"iana"},
  "application/vnd.commonspace": {"source":"iana","extensions":["csp"]},
  "application/vnd.contact.cmsg": {"source":"iana","extensions":["cdbcmsg"]},
  "application/vnd.coreos.ignition+json": {"source":"iana","compressible":true},
  "application/vnd.cosmocaller": {"source":"iana","extensions":["cmc"]},
  "application/vnd.crick.clicker": {"source":"iana","extensions":["clkx"]},
  "application/vnd.crick.clicker.keyboard": {"source":"iana","extensions":["clkk"]},
  "application/vnd.crick.clicker.palette": {"source":"iana","extensions":["clkp"]},
  "application/vnd.crick.clicker.template": {"source":"iana","extensions":["clkt"]},
  "application/vnd.crick.clicker.wordbank": {"source":"iana","extensions":["clkw"]},
  "application/vnd.criticaltools.wbs+xml": {"source":"iana","compressible":true,"extensions":["wbs"]},
  "application/vnd.cryptii.pipe+json": {"source":"iana","compressible":true},
  "application/vnd.crypto-shade-file": {"source":"iana"},
  "application/vnd.cryptomator.encrypted": {"source":"iana"},
  "application/vnd.cryptomator.vault": {"source":"iana"},
  "application/vnd.ctc-posml": {"source":"iana","extensions":["pml"]},
  "application/vnd.ctct.ws+xml": {"source":"iana","compressible":true},
  "application/vnd.cups-pdf": {"source":"iana"},
  "application/vnd.cups-postscript": {"source":"iana"},
  "application/vnd.cups-ppd": {"source":"iana","extensions":["ppd"]},
  "application/vnd.cups-raster": {"source":"iana"},
  "application/vnd.cups-raw": {"source":"iana"},
  "application/vnd.curl": {"source":"iana"},
  "application/vnd.curl.car": {"source":"apache","extensions":["car"]},
  "application/vnd.curl.pcurl": {"source":"apache","extensions":["pcurl"]},
  "application/vnd.cyan.dean.root+xml": {"source":"iana","compressible":true},
  "application/vnd.cybank": {"source":"iana"},
  "application/vnd.cyclonedx+json": {"source":"iana","compressible":true},
  "application/vnd.cyclonedx+xml": {"source":"iana","compressible":true},
  "application/vnd.d2l.coursepackage1p0+zip": {"source":"iana","compressible":false},
  "application/vnd.d3m-dataset": {"source":"iana"},
  "application/vnd.d3m-problem": {"source":"iana"},
  "application/vnd.dart": {"source":"iana","compressible":true,"extensions":["dart"]},
  "application/vnd.data-vision.rdz": {"source":"iana","extensions":["rdz"]},
  "application/vnd.datapackage+json": {"source":"iana","compressible":true},
  "application/vnd.dataresource+json": {"source":"iana","compressible":true},
  "application/vnd.dbf": {"source":"iana","extensions":["dbf"]},
  "application/vnd.debian.binary-package": {"source":"iana"},
  "application/vnd.dece.data": {"source":"iana","extensions":["uvf","uvvf","uvd","uvvd"]},
  "application/vnd.dece.ttml+xml": {"source":"iana","compressible":true,"extensions":["uvt","uvvt"]},
  "application/vnd.dece.unspecified": {"source":"iana","extensions":["uvx","uvvx"]},
  "application/vnd.dece.zip": {"source":"iana","extensions":["uvz","uvvz"]},
  "application/vnd.denovo.fcselayout-link": {"source":"iana","extensions":["fe_launch"]},
  "application/vnd.desmume.movie": {"source":"iana"},
  "application/vnd.dir-bi.plate-dl-nosuffix": {"source":"iana"},
  "application/vnd.dm.delegation+xml": {"source":"iana","compressible":true},
  "application/vnd.dna": {"source":"iana","extensions":["dna"]},
  "application/vnd.document+json": {"source":"iana","compressible":true},
  "application/vnd.dolby.mlp": {"source":"apache","extensions":["mlp"]},
  "application/vnd.dolby.mobile.1": {"source":"iana"},
  "application/vnd.dolby.mobile.2": {"source":"iana"},
  "application/vnd.doremir.scorecloud-binary-document": {"source":"iana"},
  "application/vnd.dpgraph": {"source":"iana","extensions":["dpg"]},
  "application/vnd.dreamfactory": {"source":"iana","extensions":["dfac"]},
  "application/vnd.drive+json": {"source":"iana","compressible":true},
  "application/vnd.ds-keypoint": {"source":"apache","extensions":["kpxx"]},
  "application/vnd.dtg.local": {"source":"iana"},
  "application/vnd.dtg.local.flash": {"source":"iana"},
  "application/vnd.dtg.local.html": {"source":"iana"},
  "application/vnd.dvb.ait": {"source":"iana","extensions":["ait"]},
  "application/vnd.dvb.dvbisl+xml": {"source":"iana","compressible":true},
  "application/vnd.dvb.dvbj": {"source":"iana"},
  "application/vnd.dvb.esgcontainer": {"source":"iana"},
  "application/vnd.dvb.ipdcdftnotifaccess": {"source":"iana"},
  "application/vnd.dvb.ipdcesgaccess": {"source":"iana"},
  "application/vnd.dvb.ipdcesgaccess2": {"source":"iana"},
  "application/vnd.dvb.ipdcesgpdd": {"source":"iana"},
  "application/vnd.dvb.ipdcroaming": {"source":"iana"},
  "application/vnd.dvb.iptv.alfec-base": {"source":"iana"},
  "application/vnd.dvb.iptv.alfec-enhancement": {"source":"iana"},
  "application/vnd.dvb.notif-aggregate-root+xml": {"source":"iana","compressible":true},
  "application/vnd.dvb.notif-container+xml": {"source":"iana","compressible":true},
  "application/vnd.dvb.notif-generic+xml": {"source":"iana","compressible":true},
  "application/vnd.dvb.notif-ia-msglist+xml": {"source":"iana","compressible":true},
  "application/vnd.dvb.notif-ia-registration-request+xml": {"source":"iana","compressible":true},
  "application/vnd.dvb.notif-ia-registration-response+xml": {"source":"iana","compressible":true},
  "application/vnd.dvb.notif-init+xml": {"source":"iana","compressible":true},
  "application/vnd.dvb.pfr": {"source":"iana"},
  "application/vnd.dvb.service": {"source":"iana","extensions":["svc"]},
  "application/vnd.dxr": {"source":"iana"},
  "application/vnd.dynageo": {"source":"iana","extensions":["geo"]},
  "application/vnd.dzr": {"source":"iana"},
  "application/vnd.easykaraoke.cdgdownload": {"source":"iana"},
  "application/vnd.ecdis-update": {"source":"iana"},
  "application/vnd.ecip.rlp": {"source":"iana"},
  "application/vnd.eclipse.ditto+json": {"source":"iana","compressible":true},
  "application/vnd.ecowin.chart": {"source":"iana","extensions":["mag"]},
  "application/vnd.ecowin.filerequest": {"source":"iana"},
  "application/vnd.ecowin.fileupdate": {"source":"iana"},
  "application/vnd.ecowin.series": {"source":"iana"},
  "application/vnd.ecowin.seriesrequest": {"source":"iana"},
  "application/vnd.ecowin.seriesupdate": {"source":"iana"},
  "application/vnd.efi.img": {"source":"iana"},
  "application/vnd.efi.iso": {"source":"iana"},
  "application/vnd.emclient.accessrequest+xml": {"source":"iana","compressible":true},
  "application/vnd.enliven": {"source":"iana","extensions":["nml"]},
  "application/vnd.enphase.envoy": {"source":"iana"},
  "application/vnd.eprints.data+xml": {"source":"iana","compressible":true},
  "application/vnd.epson.esf": {"source":"iana","extensions":["esf"]},
  "application/vnd.epson.msf": {"source":"iana","extensions":["msf"]},
  "application/vnd.epson.quickanime": {"source":"iana","extensions":["qam"]},
  "application/vnd.epson.salt": {"source":"iana","extensions":["slt"]},
  "application/vnd.epson.ssf": {"source":"iana","extensions":["ssf"]},
  "application/vnd.ericsson.quickcall": {"source":"iana"},
  "application/vnd.espass-espass+zip": {"source":"iana","compressible":false},
  "application/vnd.eszigno3+xml": {"source":"iana","compressible":true,"extensions":["es3","et3"]},
  "application/vnd.etsi.aoc+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.asic-e+zip": {"source":"iana","compressible":false},
  "application/vnd.etsi.asic-s+zip": {"source":"iana","compressible":false},
  "application/vnd.etsi.cug+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvcommand+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvdiscovery+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvprofile+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvsad-bc+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvsad-cod+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvsad-npvr+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvservice+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvsync+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvueprofile+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.mcid+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.mheg5": {"source":"iana"},
  "application/vnd.etsi.overload-control-policy-dataset+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.pstn+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.sci+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.simservs+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.timestamp-token": {"source":"iana"},
  "application/vnd.etsi.tsl+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.tsl.der": {"source":"iana"},
  "application/vnd.eu.kasparian.car+json": {"source":"iana","compressible":true},
  "application/vnd.eudora.data": {"source":"iana"},
  "application/vnd.evolv.ecig.profile": {"source":"iana"},
  "application/vnd.evolv.ecig.settings": {"source":"iana"},
  "application/vnd.evolv.ecig.theme": {"source":"iana"},
  "application/vnd.exstream-empower+zip": {"source":"iana","compressible":false},
  "application/vnd.exstream-package": {"source":"iana"},
  "application/vnd.ezpix-album": {"source":"iana","extensions":["ez2"]},
  "application/vnd.ezpix-package": {"source":"iana","extensions":["ez3"]},
  "application/vnd.f-secure.mobile": {"source":"iana"},
  "application/vnd.familysearch.gedcom+zip": {"source":"iana","compressible":false},
  "application/vnd.fastcopy-disk-image": {"source":"iana"},
  "application/vnd.fdf": {"source":"iana","extensions":["fdf"]},
  "application/vnd.fdsn.mseed": {"source":"iana","extensions":["mseed"]},
  "application/vnd.fdsn.seed": {"source":"iana","extensions":["seed","dataless"]},
  "application/vnd.ffsns": {"source":"iana"},
  "application/vnd.ficlab.flb+zip": {"source":"iana","compressible":false},
  "application/vnd.filmit.zfc": {"source":"iana"},
  "application/vnd.fints": {"source":"iana"},
  "application/vnd.firemonkeys.cloudcell": {"source":"iana"},
  "application/vnd.flographit": {"source":"iana","extensions":["gph"]},
  "application/vnd.fluxtime.clip": {"source":"iana","extensions":["ftc"]},
  "application/vnd.font-fontforge-sfd": {"source":"iana"},
  "application/vnd.framemaker": {"source":"iana","extensions":["fm","frame","maker","book"]},
  "application/vnd.frogans.fnc": {"source":"iana","extensions":["fnc"]},
  "application/vnd.frogans.ltf": {"source":"iana","extensions":["ltf"]},
  "application/vnd.fsc.weblaunch": {"source":"iana","extensions":["fsc"]},
  "application/vnd.fujifilm.fb.docuworks": {"source":"iana"},
  "application/vnd.fujifilm.fb.docuworks.binder": {"source":"iana"},
  "application/vnd.fujifilm.fb.docuworks.container": {"source":"iana"},
  "application/vnd.fujifilm.fb.jfi+xml": {"source":"iana","compressible":true},
  "application/vnd.fujitsu.oasys": {"source":"iana","extensions":["oas"]},
  "application/vnd.fujitsu.oasys2": {"source":"iana","extensions":["oa2"]},
  "application/vnd.fujitsu.oasys3": {"source":"iana","extensions":["oa3"]},
  "application/vnd.fujitsu.oasysgp": {"source":"iana","extensions":["fg5"]},
  "application/vnd.fujitsu.oasysprs": {"source":"iana","extensions":["bh2"]},
  "application/vnd.fujixerox.art-ex": {"source":"iana"},
  "application/vnd.fujixerox.art4": {"source":"iana"},
  "application/vnd.fujixerox.ddd": {"source":"iana","extensions":["ddd"]},
  "application/vnd.fujixerox.docuworks": {"source":"iana","extensions":["xdw"]},
  "application/vnd.fujixerox.docuworks.binder": {"source":"iana","extensions":["xbd"]},
  "application/vnd.fujixerox.docuworks.container": {"source":"iana"},
  "application/vnd.fujixerox.hbpl": {"source":"iana"},
  "application/vnd.fut-misnet": {"source":"iana"},
  "application/vnd.futoin+cbor": {"source":"iana"},
  "application/vnd.futoin+json": {"source":"iana","compressible":true},
  "application/vnd.fuzzysheet": {"source":"iana","extensions":["fzs"]},
  "application/vnd.genomatix.tuxedo": {"source":"iana","extensions":["txd"]},
  "application/vnd.gentics.grd+json": {"source":"iana","compressible":true},
  "application/vnd.geo+json": {"source":"iana","compressible":true},
  "application/vnd.geocube+xml": {"source":"iana","compressible":true},
  "application/vnd.geogebra.file": {"source":"iana","extensions":["ggb"]},
  "application/vnd.geogebra.slides": {"source":"iana"},
  "application/vnd.geogebra.tool": {"source":"iana","extensions":["ggt"]},
  "application/vnd.geometry-explorer": {"source":"iana","extensions":["gex","gre"]},
  "application/vnd.geonext": {"source":"iana","extensions":["gxt"]},
  "application/vnd.geoplan": {"source":"iana","extensions":["g2w"]},
  "application/vnd.geospace": {"source":"iana","extensions":["g3w"]},
  "application/vnd.gerber": {"source":"iana"},
  "application/vnd.globalplatform.card-content-mgt": {"source":"iana"},
  "application/vnd.globalplatform.card-content-mgt-response": {"source":"iana"},
  "application/vnd.gmx": {"source":"iana","extensions":["gmx"]},
  "application/vnd.google-apps.document": {"compressible":false,"extensions":["gdoc"]},
  "application/vnd.google-apps.presentation": {"compressible":false,"extensions":["gslides"]},
  "application/vnd.google-apps.spreadsheet": {"compressible":false,"extensions":["gsheet"]},
  "application/vnd.google-earth.kml+xml": {"source":"iana","compressible":true,"extensions":["kml"]},
  "application/vnd.google-earth.kmz": {"source":"iana","compressible":false,"extensions":["kmz"]},
  "application/vnd.gov.sk.e-form+xml": {"source":"iana","compressible":true},
  "application/vnd.gov.sk.e-form+zip": {"source":"iana","compressible":false},
  "application/vnd.gov.sk.xmldatacontainer+xml": {"source":"iana","compressible":true},
  "application/vnd.grafeq": {"source":"iana","extensions":["gqf","gqs"]},
  "application/vnd.gridmp": {"source":"iana"},
  "application/vnd.groove-account": {"source":"iana","extensions":["gac"]},
  "application/vnd.groove-help": {"source":"iana","extensions":["ghf"]},
  "application/vnd.groove-identity-message": {"source":"iana","extensions":["gim"]},
  "application/vnd.groove-injector": {"source":"iana","extensions":["grv"]},
  "application/vnd.groove-tool-message": {"source":"iana","extensions":["gtm"]},
  "application/vnd.groove-tool-template": {"source":"iana","extensions":["tpl"]},
  "application/vnd.groove-vcard": {"source":"iana","extensions":["vcg"]},
  "application/vnd.hal+json": {"source":"iana","compressible":true},
  "application/vnd.hal+xml": {"source":"iana","compressible":true,"extensions":["hal"]},
  "application/vnd.handheld-entertainment+xml": {"source":"iana","compressible":true,"extensions":["zmm"]},
  "application/vnd.hbci": {"source":"iana","extensions":["hbci"]},
  "application/vnd.hc+json": {"source":"iana","compressible":true},
  "application/vnd.hcl-bireports": {"source":"iana"},
  "application/vnd.hdt": {"source":"iana"},
  "application/vnd.heroku+json": {"source":"iana","compressible":true},
  "application/vnd.hhe.lesson-player": {"source":"iana","extensions":["les"]},
  "application/vnd.hl7cda+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/vnd.hl7v2+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/vnd.hp-hpgl": {"source":"iana","extensions":["hpgl"]},
  "application/vnd.hp-hpid": {"source":"iana","extensions":["hpid"]},
  "application/vnd.hp-hps": {"source":"iana","extensions":["hps"]},
  "application/vnd.hp-jlyt": {"source":"iana","extensions":["jlt"]},
  "application/vnd.hp-pcl": {"source":"iana","extensions":["pcl"]},
  "application/vnd.hp-pclxl": {"source":"iana","extensions":["pclxl"]},
  "application/vnd.httphone": {"source":"iana"},
  "application/vnd.hydrostatix.sof-data": {"source":"iana","extensions":["sfd-hdstx"]},
  "application/vnd.hyper+json": {"source":"iana","compressible":true},
  "application/vnd.hyper-item+json": {"source":"iana","compressible":true},
  "application/vnd.hyperdrive+json": {"source":"iana","compressible":true},
  "application/vnd.hzn-3d-crossword": {"source":"iana"},
  "application/vnd.ibm.afplinedata": {"source":"iana"},
  "application/vnd.ibm.electronic-media": {"source":"iana"},
  "application/vnd.ibm.minipay": {"source":"iana","extensions":["mpy"]},
  "application/vnd.ibm.modcap": {"source":"iana","extensions":["afp","listafp","list3820"]},
  "application/vnd.ibm.rights-management": {"source":"iana","extensions":["irm"]},
  "application/vnd.ibm.secure-container": {"source":"iana","extensions":["sc"]},
  "application/vnd.iccprofile": {"source":"iana","extensions":["icc","icm"]},
  "application/vnd.ieee.1905": {"source":"iana"},
  "application/vnd.igloader": {"source":"iana","extensions":["igl"]},
  "application/vnd.imagemeter.folder+zip": {"source":"iana","compressible":false},
  "application/vnd.imagemeter.image+zip": {"source":"iana","compressible":false},
  "application/vnd.immervision-ivp": {"source":"iana","extensions":["ivp"]},
  "application/vnd.immervision-ivu": {"source":"iana","extensions":["ivu"]},
  "application/vnd.ims.imsccv1p1": {"source":"iana"},
  "application/vnd.ims.imsccv1p2": {"source":"iana"},
  "application/vnd.ims.imsccv1p3": {"source":"iana"},
  "application/vnd.ims.lis.v2.result+json": {"source":"iana","compressible":true},
  "application/vnd.ims.lti.v2.toolconsumerprofile+json": {"source":"iana","compressible":true},
  "application/vnd.ims.lti.v2.toolproxy+json": {"source":"iana","compressible":true},
  "application/vnd.ims.lti.v2.toolproxy.id+json": {"source":"iana","compressible":true},
  "application/vnd.ims.lti.v2.toolsettings+json": {"source":"iana","compressible":true},
  "application/vnd.ims.lti.v2.toolsettings.simple+json": {"source":"iana","compressible":true},
  "application/vnd.informedcontrol.rms+xml": {"source":"iana","compressible":true},
  "application/vnd.informix-visionary": {"source":"iana"},
  "application/vnd.infotech.project": {"source":"iana"},
  "application/vnd.infotech.project+xml": {"source":"iana","compressible":true},
  "application/vnd.innopath.wamp.notification": {"source":"iana"},
  "application/vnd.insors.igm": {"source":"iana","extensions":["igm"]},
  "application/vnd.intercon.formnet": {"source":"iana","extensions":["xpw","xpx"]},
  "application/vnd.intergeo": {"source":"iana","extensions":["i2g"]},
  "application/vnd.intertrust.digibox": {"source":"iana"},
  "application/vnd.intertrust.nncp": {"source":"iana"},
  "application/vnd.intu.qbo": {"source":"iana","extensions":["qbo"]},
  "application/vnd.intu.qfx": {"source":"iana","extensions":["qfx"]},
  "application/vnd.iptc.g2.catalogitem+xml": {"source":"iana","compressible":true},
  "application/vnd.iptc.g2.conceptitem+xml": {"source":"iana","compressible":true},
  "application/vnd.iptc.g2.knowledgeitem+xml": {"source":"iana","compressible":true},
  "application/vnd.iptc.g2.newsitem+xml": {"source":"iana","compressible":true},
  "application/vnd.iptc.g2.newsmessage+xml": {"source":"iana","compressible":true},
  "application/vnd.iptc.g2.packageitem+xml": {"source":"iana","compressible":true},
  "application/vnd.iptc.g2.planningitem+xml": {"source":"iana","compressible":true},
  "application/vnd.ipunplugged.rcprofile": {"source":"iana","extensions":["rcprofile"]},
  "application/vnd.irepository.package+xml": {"source":"iana","compressible":true,"extensions":["irp"]},
  "application/vnd.is-xpr": {"source":"iana","extensions":["xpr"]},
  "application/vnd.isac.fcs": {"source":"iana","extensions":["fcs"]},
  "application/vnd.iso11783-10+zip": {"source":"iana","compressible":false},
  "application/vnd.jam": {"source":"iana","extensions":["jam"]},
  "application/vnd.japannet-directory-service": {"source":"iana"},
  "application/vnd.japannet-jpnstore-wakeup": {"source":"iana"},
  "application/vnd.japannet-payment-wakeup": {"source":"iana"},
  "application/vnd.japannet-registration": {"source":"iana"},
  "application/vnd.japannet-registration-wakeup": {"source":"iana"},
  "application/vnd.japannet-setstore-wakeup": {"source":"iana"},
  "application/vnd.japannet-verification": {"source":"iana"},
  "application/vnd.japannet-verification-wakeup": {"source":"iana"},
  "application/vnd.jcp.javame.midlet-rms": {"source":"iana","extensions":["rms"]},
  "application/vnd.jisp": {"source":"iana","extensions":["jisp"]},
  "application/vnd.joost.joda-archive": {"source":"iana","extensions":["joda"]},
  "application/vnd.jsk.isdn-ngn": {"source":"iana"},
  "application/vnd.kahootz": {"source":"iana","extensions":["ktz","ktr"]},
  "application/vnd.kde.karbon": {"source":"iana","extensions":["karbon"]},
  "application/vnd.kde.kchart": {"source":"iana","extensions":["chrt"]},
  "application/vnd.kde.kformula": {"source":"iana","extensions":["kfo"]},
  "application/vnd.kde.kivio": {"source":"iana","extensions":["flw"]},
  "application/vnd.kde.kontour": {"source":"iana","extensions":["kon"]},
  "application/vnd.kde.kpresenter": {"source":"iana","extensions":["kpr","kpt"]},
  "application/vnd.kde.kspread": {"source":"iana","extensions":["ksp"]},
  "application/vnd.kde.kword": {"source":"iana","extensions":["kwd","kwt"]},
  "application/vnd.kenameaapp": {"source":"iana","extensions":["htke"]},
  "application/vnd.kidspiration": {"source":"iana","extensions":["kia"]},
  "application/vnd.kinar": {"source":"iana","extensions":["kne","knp"]},
  "application/vnd.koan": {"source":"iana","extensions":["skp","skd","skt","skm"]},
  "application/vnd.kodak-descriptor": {"source":"iana","extensions":["sse"]},
  "application/vnd.las": {"source":"iana"},
  "application/vnd.las.las+json": {"source":"iana","compressible":true},
  "application/vnd.las.las+xml": {"source":"iana","compressible":true,"extensions":["lasxml"]},
  "application/vnd.laszip": {"source":"iana"},
  "application/vnd.leap+json": {"source":"iana","compressible":true},
  "application/vnd.liberty-request+xml": {"source":"iana","compressible":true},
  "application/vnd.llamagraphics.life-balance.desktop": {"source":"iana","extensions":["lbd"]},
  "application/vnd.llamagraphics.life-balance.exchange+xml": {"source":"iana","compressible":true,"extensions":["lbe"]},
  "application/vnd.logipipe.circuit+zip": {"source":"iana","compressible":false},
  "application/vnd.loom": {"source":"iana"},
  "application/vnd.lotus-1-2-3": {"source":"iana","extensions":["123"]},
  "application/vnd.lotus-approach": {"source":"iana","extensions":["apr"]},
  "application/vnd.lotus-freelance": {"source":"iana","extensions":["pre"]},
  "application/vnd.lotus-notes": {"source":"iana","extensions":["nsf"]},
  "application/vnd.lotus-organizer": {"source":"iana","extensions":["org"]},
  "application/vnd.lotus-screencam": {"source":"iana","extensions":["scm"]},
  "application/vnd.lotus-wordpro": {"source":"iana","extensions":["lwp"]},
  "application/vnd.macports.portpkg": {"source":"iana","extensions":["portpkg"]},
  "application/vnd.mapbox-vector-tile": {"source":"iana","extensions":["mvt"]},
  "application/vnd.marlin.drm.actiontoken+xml": {"source":"iana","compressible":true},
  "application/vnd.marlin.drm.conftoken+xml": {"source":"iana","compressible":true},
  "application/vnd.marlin.drm.license+xml": {"source":"iana","compressible":true},
  "application/vnd.marlin.drm.mdcf": {"source":"iana"},
  "application/vnd.mason+json": {"source":"iana","compressible":true},
  "application/vnd.maxar.archive.3tz+zip": {"source":"iana","compressible":false},
  "application/vnd.maxmind.maxmind-db": {"source":"iana"},
  "application/vnd.mcd": {"source":"iana","extensions":["mcd"]},
  "application/vnd.medcalcdata": {"source":"iana","extensions":["mc1"]},
  "application/vnd.mediastation.cdkey": {"source":"iana","extensions":["cdkey"]},
  "application/vnd.meridian-slingshot": {"source":"iana"},
  "application/vnd.mfer": {"source":"iana","extensions":["mwf"]},
  "application/vnd.mfmp": {"source":"iana","extensions":["mfm"]},
  "application/vnd.micro+json": {"source":"iana","compressible":true},
  "application/vnd.micrografx.flo": {"source":"iana","extensions":["flo"]},
  "application/vnd.micrografx.igx": {"source":"iana","extensions":["igx"]},
  "application/vnd.microsoft.portable-executable": {"source":"iana"},
  "application/vnd.microsoft.windows.thumbnail-cache": {"source":"iana"},
  "application/vnd.miele+json": {"source":"iana","compressible":true},
  "application/vnd.mif": {"source":"iana","extensions":["mif"]},
  "application/vnd.minisoft-hp3000-save": {"source":"iana"},
  "application/vnd.mitsubishi.misty-guard.trustweb": {"source":"iana"},
  "application/vnd.mobius.daf": {"source":"iana","extensions":["daf"]},
  "application/vnd.mobius.dis": {"source":"iana","extensions":["dis"]},
  "application/vnd.mobius.mbk": {"source":"iana","extensions":["mbk"]},
  "application/vnd.mobius.mqy": {"source":"iana","extensions":["mqy"]},
  "application/vnd.mobius.msl": {"source":"iana","extensions":["msl"]},
  "application/vnd.mobius.plc": {"source":"iana","extensions":["plc"]},
  "application/vnd.mobius.txf": {"source":"iana","extensions":["txf"]},
  "application/vnd.mophun.application": {"source":"iana","extensions":["mpn"]},
  "application/vnd.mophun.certificate": {"source":"iana","extensions":["mpc"]},
  "application/vnd.motorola.flexsuite": {"source":"iana"},
  "application/vnd.motorola.flexsuite.adsi": {"source":"iana"},
  "application/vnd.motorola.flexsuite.fis": {"source":"iana"},
  "application/vnd.motorola.flexsuite.gotap": {"source":"iana"},
  "application/vnd.motorola.flexsuite.kmr": {"source":"iana"},
  "application/vnd.motorola.flexsuite.ttc": {"source":"iana"},
  "application/vnd.motorola.flexsuite.wem": {"source":"iana"},
  "application/vnd.motorola.iprm": {"source":"iana"},
  "application/vnd.mozilla.xul+xml": {"source":"iana","compressible":true,"extensions":["xul"]},
  "application/vnd.ms-3mfdocument": {"source":"iana"},
  "application/vnd.ms-artgalry": {"source":"iana","extensions":["cil"]},
  "application/vnd.ms-asf": {"source":"iana"},
  "application/vnd.ms-cab-compressed": {"source":"iana","extensions":["cab"]},
  "application/vnd.ms-color.iccprofile": {"source":"apache"},
  "application/vnd.ms-excel": {"source":"iana","compressible":false,"extensions":["xls","xlm","xla","xlc","xlt","xlw"]},
  "application/vnd.ms-excel.addin.macroenabled.12": {"source":"iana","extensions":["xlam"]},
  "application/vnd.ms-excel.sheet.binary.macroenabled.12": {"source":"iana","extensions":["xlsb"]},
  "application/vnd.ms-excel.sheet.macroenabled.12": {"source":"iana","extensions":["xlsm"]},
  "application/vnd.ms-excel.template.macroenabled.12": {"source":"iana","extensions":["xltm"]},
  "application/vnd.ms-fontobject": {"source":"iana","compressible":true,"extensions":["eot"]},
  "application/vnd.ms-htmlhelp": {"source":"iana","extensions":["chm"]},
  "application/vnd.ms-ims": {"source":"iana","extensions":["ims"]},
  "application/vnd.ms-lrm": {"source":"iana","extensions":["lrm"]},
  "application/vnd.ms-office.activex+xml": {"source":"iana","compressible":true},
  "application/vnd.ms-officetheme": {"source":"iana","extensions":["thmx"]},
  "application/vnd.ms-opentype": {"source":"apache","compressible":true},
  "application/vnd.ms-outlook": {"compressible":false,"extensions":["msg"]},
  "application/vnd.ms-package.obfuscated-opentype": {"source":"apache"},
  "application/vnd.ms-pki.seccat": {"source":"apache","extensions":["cat"]},
  "application/vnd.ms-pki.stl": {"source":"apache","extensions":["stl"]},
  "application/vnd.ms-playready.initiator+xml": {"source":"iana","compressible":true},
  "application/vnd.ms-powerpoint": {"source":"iana","compressible":false,"extensions":["ppt","pps","pot"]},
  "application/vnd.ms-powerpoint.addin.macroenabled.12": {"source":"iana","extensions":["ppam"]},
  "application/vnd.ms-powerpoint.presentation.macroenabled.12": {"source":"iana","extensions":["pptm"]},
  "application/vnd.ms-powerpoint.slide.macroenabled.12": {"source":"iana","extensions":["sldm"]},
  "application/vnd.ms-powerpoint.slideshow.macroenabled.12": {"source":"iana","extensions":["ppsm"]},
  "application/vnd.ms-powerpoint.template.macroenabled.12": {"source":"iana","extensions":["potm"]},
  "application/vnd.ms-printdevicecapabilities+xml": {"source":"iana","compressible":true},
  "application/vnd.ms-printing.printticket+xml": {"source":"apache","compressible":true},
  "application/vnd.ms-printschematicket+xml": {"source":"iana","compressible":true},
  "application/vnd.ms-project": {"source":"iana","extensions":["mpp","mpt"]},
  "application/vnd.ms-tnef": {"source":"iana"},
  "application/vnd.ms-windows.devicepairing": {"source":"iana"},
  "application/vnd.ms-windows.nwprinting.oob": {"source":"iana"},
  "application/vnd.ms-windows.printerpairing": {"source":"iana"},
  "application/vnd.ms-windows.wsd.oob": {"source":"iana"},
  "application/vnd.ms-wmdrm.lic-chlg-req": {"source":"iana"},
  "application/vnd.ms-wmdrm.lic-resp": {"source":"iana"},
  "application/vnd.ms-wmdrm.meter-chlg-req": {"source":"iana"},
  "application/vnd.ms-wmdrm.meter-resp": {"source":"iana"},
  "application/vnd.ms-word.document.macroenabled.12": {"source":"iana","extensions":["docm"]},
  "application/vnd.ms-word.template.macroenabled.12": {"source":"iana","extensions":["dotm"]},
  "application/vnd.ms-works": {"source":"iana","extensions":["wps","wks","wcm","wdb"]},
  "application/vnd.ms-wpl": {"source":"iana","extensions":["wpl"]},
  "application/vnd.ms-xpsdocument": {"source":"iana","compressible":false,"extensions":["xps"]},
  "application/vnd.msa-disk-image": {"source":"iana"},
  "application/vnd.mseq": {"source":"iana","extensions":["mseq"]},
  "application/vnd.msign": {"source":"iana"},
  "application/vnd.multiad.creator": {"source":"iana"},
  "application/vnd.multiad.creator.cif": {"source":"iana"},
  "application/vnd.music-niff": {"source":"iana"},
  "application/vnd.musician": {"source":"iana","extensions":["mus"]},
  "application/vnd.muvee.style": {"source":"iana","extensions":["msty"]},
  "application/vnd.mynfc": {"source":"iana","extensions":["taglet"]},
  "application/vnd.nacamar.ybrid+json": {"source":"iana","compressible":true},
  "application/vnd.ncd.control": {"source":"iana"},
  "application/vnd.ncd.reference": {"source":"iana"},
  "application/vnd.nearst.inv+json": {"source":"iana","compressible":true},
  "application/vnd.nebumind.line": {"source":"iana"},
  "application/vnd.nervana": {"source":"iana"},
  "application/vnd.netfpx": {"source":"iana"},
  "application/vnd.neurolanguage.nlu": {"source":"iana","extensions":["nlu"]},
  "application/vnd.nimn": {"source":"iana"},
  "application/vnd.nintendo.nitro.rom": {"source":"iana"},
  "application/vnd.nintendo.snes.rom": {"source":"iana"},
  "application/vnd.nitf": {"source":"iana","extensions":["ntf","nitf"]},
  "application/vnd.noblenet-directory": {"source":"iana","extensions":["nnd"]},
  "application/vnd.noblenet-sealer": {"source":"iana","extensions":["nns"]},
  "application/vnd.noblenet-web": {"source":"iana","extensions":["nnw"]},
  "application/vnd.nokia.catalogs": {"source":"iana"},
  "application/vnd.nokia.conml+wbxml": {"source":"iana"},
  "application/vnd.nokia.conml+xml": {"source":"iana","compressible":true},
  "application/vnd.nokia.iptv.config+xml": {"source":"iana","compressible":true},
  "application/vnd.nokia.isds-radio-presets": {"source":"iana"},
  "application/vnd.nokia.landmark+wbxml": {"source":"iana"},
  "application/vnd.nokia.landmark+xml": {"source":"iana","compressible":true},
  "application/vnd.nokia.landmarkcollection+xml": {"source":"iana","compressible":true},
  "application/vnd.nokia.n-gage.ac+xml": {"source":"iana","compressible":true,"extensions":["ac"]},
  "application/vnd.nokia.n-gage.data": {"source":"iana","extensions":["ngdat"]},
  "application/vnd.nokia.n-gage.symbian.install": {"source":"iana","extensions":["n-gage"]},
  "application/vnd.nokia.ncd": {"source":"iana"},
  "application/vnd.nokia.pcd+wbxml": {"source":"iana"},
  "application/vnd.nokia.pcd+xml": {"source":"iana","compressible":true},
  "application/vnd.nokia.radio-preset": {"source":"iana","extensions":["rpst"]},
  "application/vnd.nokia.radio-presets": {"source":"iana","extensions":["rpss"]},
  "application/vnd.novadigm.edm": {"source":"iana","extensions":["edm"]},
  "application/vnd.novadigm.edx": {"source":"iana","extensions":["edx"]},
  "application/vnd.novadigm.ext": {"source":"iana","extensions":["ext"]},
  "application/vnd.ntt-local.content-share": {"source":"iana"},
  "application/vnd.ntt-local.file-transfer": {"source":"iana"},
  "application/vnd.ntt-local.ogw_remote-access": {"source":"iana"},
  "application/vnd.ntt-local.sip-ta_remote": {"source":"iana"},
  "application/vnd.ntt-local.sip-ta_tcp_stream": {"source":"iana"},
  "application/vnd.oasis.opendocument.chart": {"source":"iana","extensions":["odc"]},
  "application/vnd.oasis.opendocument.chart-template": {"source":"iana","extensions":["otc"]},
  "application/vnd.oasis.opendocument.database": {"source":"iana","extensions":["odb"]},
  "application/vnd.oasis.opendocument.formula": {"source":"iana","extensions":["odf"]},
  "application/vnd.oasis.opendocument.formula-template": {"source":"iana","extensions":["odft"]},
  "application/vnd.oasis.opendocument.graphics": {"source":"iana","compressible":false,"extensions":["odg"]},
  "application/vnd.oasis.opendocument.graphics-template": {"source":"iana","extensions":["otg"]},
  "application/vnd.oasis.opendocument.image": {"source":"iana","extensions":["odi"]},
  "application/vnd.oasis.opendocument.image-template": {"source":"iana","extensions":["oti"]},
  "application/vnd.oasis.opendocument.presentation": {"source":"iana","compressible":false,"extensions":["odp"]},
  "application/vnd.oasis.opendocument.presentation-template": {"source":"iana","extensions":["otp"]},
  "application/vnd.oasis.opendocument.spreadsheet": {"source":"iana","compressible":false,"extensions":["ods"]},
  "application/vnd.oasis.opendocument.spreadsheet-template": {"source":"iana","extensions":["ots"]},
  "application/vnd.oasis.opendocument.text": {"source":"iana","compressible":false,"extensions":["odt"]},
  "application/vnd.oasis.opendocument.text-master": {"source":"iana","extensions":["odm"]},
  "application/vnd.oasis.opendocument.text-template": {"source":"iana","extensions":["ott"]},
  "application/vnd.oasis.opendocument.text-web": {"source":"iana","extensions":["oth"]},
  "application/vnd.obn": {"source":"iana"},
  "application/vnd.ocf+cbor": {"source":"iana"},
  "application/vnd.oci.image.manifest.v1+json": {"source":"iana","compressible":true},
  "application/vnd.oftn.l10n+json": {"source":"iana","compressible":true},
  "application/vnd.oipf.contentaccessdownload+xml": {"source":"iana","compressible":true},
  "application/vnd.oipf.contentaccessstreaming+xml": {"source":"iana","compressible":true},
  "application/vnd.oipf.cspg-hexbinary": {"source":"iana"},
  "application/vnd.oipf.dae.svg+xml": {"source":"iana","compressible":true},
  "application/vnd.oipf.dae.xhtml+xml": {"source":"iana","compressible":true},
  "application/vnd.oipf.mippvcontrolmessage+xml": {"source":"iana","compressible":true},
  "application/vnd.oipf.pae.gem": {"source":"iana"},
  "application/vnd.oipf.spdiscovery+xml": {"source":"iana","compressible":true},
  "application/vnd.oipf.spdlist+xml": {"source":"iana","compressible":true},
  "application/vnd.oipf.ueprofile+xml": {"source":"iana","compressible":true},
  "application/vnd.oipf.userprofile+xml": {"source":"iana","compressible":true},
  "application/vnd.olpc-sugar": {"source":"iana","extensions":["xo"]},
  "application/vnd.oma-scws-config": {"source":"iana"},
  "application/vnd.oma-scws-http-request": {"source":"iana"},
  "application/vnd.oma-scws-http-response": {"source":"iana"},
  "application/vnd.oma.bcast.associated-procedure-parameter+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.bcast.drm-trigger+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.bcast.imd+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.bcast.ltkm": {"source":"iana"},
  "application/vnd.oma.bcast.notification+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.bcast.provisioningtrigger": {"source":"iana"},
  "application/vnd.oma.bcast.sgboot": {"source":"iana"},
  "application/vnd.oma.bcast.sgdd+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.bcast.sgdu": {"source":"iana"},
  "application/vnd.oma.bcast.simple-symbol-container": {"source":"iana"},
  "application/vnd.oma.bcast.smartcard-trigger+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.bcast.sprov+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.bcast.stkm": {"source":"iana"},
  "application/vnd.oma.cab-address-book+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.cab-feature-handler+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.cab-pcc+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.cab-subs-invite+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.cab-user-prefs+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.dcd": {"source":"iana"},
  "application/vnd.oma.dcdc": {"source":"iana"},
  "application/vnd.oma.dd2+xml": {"source":"iana","compressible":true,"extensions":["dd2"]},
  "application/vnd.oma.drm.risd+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.group-usage-list+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.lwm2m+cbor": {"source":"iana"},
  "application/vnd.oma.lwm2m+json": {"source":"iana","compressible":true},
  "application/vnd.oma.lwm2m+tlv": {"source":"iana"},
  "application/vnd.oma.pal+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.poc.detailed-progress-report+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.poc.final-report+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.poc.groups+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.poc.invocation-descriptor+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.poc.optimized-progress-report+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.push": {"source":"iana"},
  "application/vnd.oma.scidm.messages+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.xcap-directory+xml": {"source":"iana","compressible":true},
  "application/vnd.omads-email+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/vnd.omads-file+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/vnd.omads-folder+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/vnd.omaloc-supl-init": {"source":"iana"},
  "application/vnd.onepager": {"source":"iana"},
  "application/vnd.onepagertamp": {"source":"iana"},
  "application/vnd.onepagertamx": {"source":"iana"},
  "application/vnd.onepagertat": {"source":"iana"},
  "application/vnd.onepagertatp": {"source":"iana"},
  "application/vnd.onepagertatx": {"source":"iana"},
  "application/vnd.openblox.game+xml": {"source":"iana","compressible":true,"extensions":["obgx"]},
  "application/vnd.openblox.game-binary": {"source":"iana"},
  "application/vnd.openeye.oeb": {"source":"iana"},
  "application/vnd.openofficeorg.extension": {"source":"apache","extensions":["oxt"]},
  "application/vnd.openstreetmap.data+xml": {"source":"iana","compressible":true,"extensions":["osm"]},
  "application/vnd.opentimestamps.ots": {"source":"iana"},
  "application/vnd.openxmlformats-officedocument.custom-properties+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.drawing+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.extended-properties+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.presentation": {"source":"iana","compressible":false,"extensions":["pptx"]},
  "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.slide": {"source":"iana","extensions":["sldx"]},
  "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.slideshow": {"source":"iana","extensions":["ppsx"]},
  "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.template": {"source":"iana","extensions":["potx"]},
  "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {"source":"iana","compressible":false,"extensions":["xlsx"]},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.template": {"source":"iana","extensions":["xltx"]},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.theme+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.themeoverride+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.vmldrawing": {"source":"iana"},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document": {"source":"iana","compressible":false,"extensions":["docx"]},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.template": {"source":"iana","extensions":["dotx"]},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-package.core-properties+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-package.relationships+xml": {"source":"iana","compressible":true},
  "application/vnd.oracle.resource+json": {"source":"iana","compressible":true},
  "application/vnd.orange.indata": {"source":"iana"},
  "application/vnd.osa.netdeploy": {"source":"iana"},
  "application/vnd.osgeo.mapguide.package": {"source":"iana","extensions":["mgp"]},
  "application/vnd.osgi.bundle": {"source":"iana"},
  "application/vnd.osgi.dp": {"source":"iana","extensions":["dp"]},
  "application/vnd.osgi.subsystem": {"source":"iana","extensions":["esa"]},
  "application/vnd.otps.ct-kip+xml": {"source":"iana","compressible":true},
  "application/vnd.oxli.countgraph": {"source":"iana"},
  "application/vnd.pagerduty+json": {"source":"iana","compressible":true},
  "application/vnd.palm": {"source":"iana","extensions":["pdb","pqa","oprc"]},
  "application/vnd.panoply": {"source":"iana"},
  "application/vnd.paos.xml": {"source":"iana"},
  "application/vnd.patentdive": {"source":"iana"},
  "application/vnd.patientecommsdoc": {"source":"iana"},
  "application/vnd.pawaafile": {"source":"iana","extensions":["paw"]},
  "application/vnd.pcos": {"source":"iana"},
  "application/vnd.pg.format": {"source":"iana","extensions":["str"]},
  "application/vnd.pg.osasli": {"source":"iana","extensions":["ei6"]},
  "application/vnd.piaccess.application-licence": {"source":"iana"},
  "application/vnd.picsel": {"source":"iana","extensions":["efif"]},
  "application/vnd.pmi.widget": {"source":"iana","extensions":["wg"]},
  "application/vnd.poc.group-advertisement+xml": {"source":"iana","compressible":true},
  "application/vnd.pocketlearn": {"source":"iana","extensions":["plf"]},
  "application/vnd.powerbuilder6": {"source":"iana","extensions":["pbd"]},
  "application/vnd.powerbuilder6-s": {"source":"iana"},
  "application/vnd.powerbuilder7": {"source":"iana"},
  "application/vnd.powerbuilder7-s": {"source":"iana"},
  "application/vnd.powerbuilder75": {"source":"iana"},
  "application/vnd.powerbuilder75-s": {"source":"iana"},
  "application/vnd.preminet": {"source":"iana"},
  "application/vnd.previewsystems.box": {"source":"iana","extensions":["box"]},
  "application/vnd.proteus.magazine": {"source":"iana","extensions":["mgz"]},
  "application/vnd.psfs": {"source":"iana"},
  "application/vnd.publishare-delta-tree": {"source":"iana","extensions":["qps"]},
  "application/vnd.pvi.ptid1": {"source":"iana","extensions":["ptid"]},
  "application/vnd.pwg-multiplexed": {"source":"iana"},
  "application/vnd.pwg-xhtml-print+xml": {"source":"iana","compressible":true},
  "application/vnd.qualcomm.brew-app-res": {"source":"iana"},
  "application/vnd.quarantainenet": {"source":"iana"},
  "application/vnd.quark.quarkxpress": {"source":"iana","extensions":["qxd","qxt","qwd","qwt","qxl","qxb"]},
  "application/vnd.quobject-quoxdocument": {"source":"iana"},
  "application/vnd.radisys.moml+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-audit+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-audit-conf+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-audit-conn+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-audit-dialog+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-audit-stream+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-conf+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-dialog+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-dialog-base+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-dialog-fax-detect+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-dialog-group+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-dialog-speech+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-dialog-transform+xml": {"source":"iana","compressible":true},
  "application/vnd.rainstor.data": {"source":"iana"},
  "application/vnd.rapid": {"source":"iana"},
  "application/vnd.rar": {"source":"iana","extensions":["rar"]},
  "application/vnd.realvnc.bed": {"source":"iana","extensions":["bed"]},
  "application/vnd.recordare.musicxml": {"source":"iana","extensions":["mxl"]},
  "application/vnd.recordare.musicxml+xml": {"source":"iana","compressible":true,"extensions":["musicxml"]},
  "application/vnd.renlearn.rlprint": {"source":"iana"},
  "application/vnd.resilient.logic": {"source":"iana"},
  "application/vnd.restful+json": {"source":"iana","compressible":true},
  "application/vnd.rig.cryptonote": {"source":"iana","extensions":["cryptonote"]},
  "application/vnd.rim.cod": {"source":"apache","extensions":["cod"]},
  "application/vnd.rn-realmedia": {"source":"apache","extensions":["rm"]},
  "application/vnd.rn-realmedia-vbr": {"source":"apache","extensions":["rmvb"]},
  "application/vnd.route66.link66+xml": {"source":"iana","compressible":true,"extensions":["link66"]},
  "application/vnd.rs-274x": {"source":"iana"},
  "application/vnd.ruckus.download": {"source":"iana"},
  "application/vnd.s3sms": {"source":"iana"},
  "application/vnd.sailingtracker.track": {"source":"iana","extensions":["st"]},
  "application/vnd.sar": {"source":"iana"},
  "application/vnd.sbm.cid": {"source":"iana"},
  "application/vnd.sbm.mid2": {"source":"iana"},
  "application/vnd.scribus": {"source":"iana"},
  "application/vnd.sealed.3df": {"source":"iana"},
  "application/vnd.sealed.csf": {"source":"iana"},
  "application/vnd.sealed.doc": {"source":"iana"},
  "application/vnd.sealed.eml": {"source":"iana"},
  "application/vnd.sealed.mht": {"source":"iana"},
  "application/vnd.sealed.net": {"source":"iana"},
  "application/vnd.sealed.ppt": {"source":"iana"},
  "application/vnd.sealed.tiff": {"source":"iana"},
  "application/vnd.sealed.xls": {"source":"iana"},
  "application/vnd.sealedmedia.softseal.html": {"source":"iana"},
  "application/vnd.sealedmedia.softseal.pdf": {"source":"iana"},
  "application/vnd.seemail": {"source":"iana","extensions":["see"]},
  "application/vnd.seis+json": {"source":"iana","compressible":true},
  "application/vnd.sema": {"source":"iana","extensions":["sema"]},
  "application/vnd.semd": {"source":"iana","extensions":["semd"]},
  "application/vnd.semf": {"source":"iana","extensions":["semf"]},
  "application/vnd.shade-save-file": {"source":"iana"},
  "application/vnd.shana.informed.formdata": {"source":"iana","extensions":["ifm"]},
  "application/vnd.shana.informed.formtemplate": {"source":"iana","extensions":["itp"]},
  "application/vnd.shana.informed.interchange": {"source":"iana","extensions":["iif"]},
  "application/vnd.shana.informed.package": {"source":"iana","extensions":["ipk"]},
  "application/vnd.shootproof+json": {"source":"iana","compressible":true},
  "application/vnd.shopkick+json": {"source":"iana","compressible":true},
  "application/vnd.shp": {"source":"iana"},
  "application/vnd.shx": {"source":"iana"},
  "application/vnd.sigrok.session": {"source":"iana"},
  "application/vnd.simtech-mindmapper": {"source":"iana","extensions":["twd","twds"]},
  "application/vnd.siren+json": {"source":"iana","compressible":true},
  "application/vnd.smaf": {"source":"iana","extensions":["mmf"]},
  "application/vnd.smart.notebook": {"source":"iana"},
  "application/vnd.smart.teacher": {"source":"iana","extensions":["teacher"]},
  "application/vnd.snesdev-page-table": {"source":"iana"},
  "application/vnd.software602.filler.form+xml": {"source":"iana","compressible":true,"extensions":["fo"]},
  "application/vnd.software602.filler.form-xml-zip": {"source":"iana"},
  "application/vnd.solent.sdkm+xml": {"source":"iana","compressible":true,"extensions":["sdkm","sdkd"]},
  "application/vnd.spotfire.dxp": {"source":"iana","extensions":["dxp"]},
  "application/vnd.spotfire.sfs": {"source":"iana","extensions":["sfs"]},
  "application/vnd.sqlite3": {"source":"iana"},
  "application/vnd.sss-cod": {"source":"iana"},
  "application/vnd.sss-dtf": {"source":"iana"},
  "application/vnd.sss-ntf": {"source":"iana"},
  "application/vnd.stardivision.calc": {"source":"apache","extensions":["sdc"]},
  "application/vnd.stardivision.draw": {"source":"apache","extensions":["sda"]},
  "application/vnd.stardivision.impress": {"source":"apache","extensions":["sdd"]},
  "application/vnd.stardivision.math": {"source":"apache","extensions":["smf"]},
  "application/vnd.stardivision.writer": {"source":"apache","extensions":["sdw","vor"]},
  "application/vnd.stardivision.writer-global": {"source":"apache","extensions":["sgl"]},
  "application/vnd.stepmania.package": {"source":"iana","extensions":["smzip"]},
  "application/vnd.stepmania.stepchart": {"source":"iana","extensions":["sm"]},
  "application/vnd.street-stream": {"source":"iana"},
  "application/vnd.sun.wadl+xml": {"source":"iana","compressible":true,"extensions":["wadl"]},
  "application/vnd.sun.xml.calc": {"source":"apache","extensions":["sxc"]},
  "application/vnd.sun.xml.calc.template": {"source":"apache","extensions":["stc"]},
  "application/vnd.sun.xml.draw": {"source":"apache","extensions":["sxd"]},
  "application/vnd.sun.xml.draw.template": {"source":"apache","extensions":["std"]},
  "application/vnd.sun.xml.impress": {"source":"apache","extensions":["sxi"]},
  "application/vnd.sun.xml.impress.template": {"source":"apache","extensions":["sti"]},
  "application/vnd.sun.xml.math": {"source":"apache","extensions":["sxm"]},
  "application/vnd.sun.xml.writer": {"source":"apache","extensions":["sxw"]},
  "application/vnd.sun.xml.writer.global": {"source":"apache","extensions":["sxg"]},
  "application/vnd.sun.xml.writer.template": {"source":"apache","extensions":["stw"]},
  "application/vnd.sus-calendar": {"source":"iana","extensions":["sus","susp"]},
  "application/vnd.svd": {"source":"iana","extensions":["svd"]},
  "application/vnd.swiftview-ics": {"source":"iana"},
  "application/vnd.sycle+xml": {"source":"iana","compressible":true},
  "application/vnd.syft+json": {"source":"iana","compressible":true},
  "application/vnd.symbian.install": {"source":"apache","extensions":["sis","sisx"]},
  "application/vnd.syncml+xml": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["xsm"]},
  "application/vnd.syncml.dm+wbxml": {"source":"iana","charset":"UTF-8","extensions":["bdm"]},
  "application/vnd.syncml.dm+xml": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["xdm"]},
  "application/vnd.syncml.dm.notification": {"source":"iana"},
  "application/vnd.syncml.dmddf+wbxml": {"source":"iana"},
  "application/vnd.syncml.dmddf+xml": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["ddf"]},
  "application/vnd.syncml.dmtnds+wbxml": {"source":"iana"},
  "application/vnd.syncml.dmtnds+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/vnd.syncml.ds.notification": {"source":"iana"},
  "application/vnd.tableschema+json": {"source":"iana","compressible":true},
  "application/vnd.tao.intent-module-archive": {"source":"iana","extensions":["tao"]},
  "application/vnd.tcpdump.pcap": {"source":"iana","extensions":["pcap","cap","dmp"]},
  "application/vnd.think-cell.ppttc+json": {"source":"iana","compressible":true},
  "application/vnd.tmd.mediaflex.api+xml": {"source":"iana","compressible":true},
  "application/vnd.tml": {"source":"iana"},
  "application/vnd.tmobile-livetv": {"source":"iana","extensions":["tmo"]},
  "application/vnd.tri.onesource": {"source":"iana"},
  "application/vnd.trid.tpt": {"source":"iana","extensions":["tpt"]},
  "application/vnd.triscape.mxs": {"source":"iana","extensions":["mxs"]},
  "application/vnd.trueapp": {"source":"iana","extensions":["tra"]},
  "application/vnd.truedoc": {"source":"iana"},
  "application/vnd.ubisoft.webplayer": {"source":"iana"},
  "application/vnd.ufdl": {"source":"iana","extensions":["ufd","ufdl"]},
  "application/vnd.uiq.theme": {"source":"iana","extensions":["utz"]},
  "application/vnd.umajin": {"source":"iana","extensions":["umj"]},
  "application/vnd.unity": {"source":"iana","extensions":["unityweb"]},
  "application/vnd.uoml+xml": {"source":"iana","compressible":true,"extensions":["uoml"]},
  "application/vnd.uplanet.alert": {"source":"iana"},
  "application/vnd.uplanet.alert-wbxml": {"source":"iana"},
  "application/vnd.uplanet.bearer-choice": {"source":"iana"},
  "application/vnd.uplanet.bearer-choice-wbxml": {"source":"iana"},
  "application/vnd.uplanet.cacheop": {"source":"iana"},
  "application/vnd.uplanet.cacheop-wbxml": {"source":"iana"},
  "application/vnd.uplanet.channel": {"source":"iana"},
  "application/vnd.uplanet.channel-wbxml": {"source":"iana"},
  "application/vnd.uplanet.list": {"source":"iana"},
  "application/vnd.uplanet.list-wbxml": {"source":"iana"},
  "application/vnd.uplanet.listcmd": {"source":"iana"},
  "application/vnd.uplanet.listcmd-wbxml": {"source":"iana"},
  "application/vnd.uplanet.signal": {"source":"iana"},
  "application/vnd.uri-map": {"source":"iana"},
  "application/vnd.valve.source.material": {"source":"iana"},
  "application/vnd.vcx": {"source":"iana","extensions":["vcx"]},
  "application/vnd.vd-study": {"source":"iana"},
  "application/vnd.vectorworks": {"source":"iana"},
  "application/vnd.vel+json": {"source":"iana","compressible":true},
  "application/vnd.verimatrix.vcas": {"source":"iana"},
  "application/vnd.veritone.aion+json": {"source":"iana","compressible":true},
  "application/vnd.veryant.thin": {"source":"iana"},
  "application/vnd.ves.encrypted": {"source":"iana"},
  "application/vnd.vidsoft.vidconference": {"source":"iana"},
  "application/vnd.visio": {"source":"iana","extensions":["vsd","vst","vss","vsw"]},
  "application/vnd.visionary": {"source":"iana","extensions":["vis"]},
  "application/vnd.vividence.scriptfile": {"source":"iana"},
  "application/vnd.vsf": {"source":"iana","extensions":["vsf"]},
  "application/vnd.wap.sic": {"source":"iana"},
  "application/vnd.wap.slc": {"source":"iana"},
  "application/vnd.wap.wbxml": {"source":"iana","charset":"UTF-8","extensions":["wbxml"]},
  "application/vnd.wap.wmlc": {"source":"iana","extensions":["wmlc"]},
  "application/vnd.wap.wmlscriptc": {"source":"iana","extensions":["wmlsc"]},
  "application/vnd.webturbo": {"source":"iana","extensions":["wtb"]},
  "application/vnd.wfa.dpp": {"source":"iana"},
  "application/vnd.wfa.p2p": {"source":"iana"},
  "application/vnd.wfa.wsc": {"source":"iana"},
  "application/vnd.windows.devicepairing": {"source":"iana"},
  "application/vnd.wmc": {"source":"iana"},
  "application/vnd.wmf.bootstrap": {"source":"iana"},
  "application/vnd.wolfram.mathematica": {"source":"iana"},
  "application/vnd.wolfram.mathematica.package": {"source":"iana"},
  "application/vnd.wolfram.player": {"source":"iana","extensions":["nbp"]},
  "application/vnd.wordperfect": {"source":"iana","extensions":["wpd"]},
  "application/vnd.wqd": {"source":"iana","extensions":["wqd"]},
  "application/vnd.wrq-hp3000-labelled": {"source":"iana"},
  "application/vnd.wt.stf": {"source":"iana","extensions":["stf"]},
  "application/vnd.wv.csp+wbxml": {"source":"iana"},
  "application/vnd.wv.csp+xml": {"source":"iana","compressible":true},
  "application/vnd.wv.ssp+xml": {"source":"iana","compressible":true},
  "application/vnd.xacml+json": {"source":"iana","compressible":true},
  "application/vnd.xara": {"source":"iana","extensions":["xar"]},
  "application/vnd.xfdl": {"source":"iana","extensions":["xfdl"]},
  "application/vnd.xfdl.webform": {"source":"iana"},
  "application/vnd.xmi+xml": {"source":"iana","compressible":true},
  "application/vnd.xmpie.cpkg": {"source":"iana"},
  "application/vnd.xmpie.dpkg": {"source":"iana"},
  "application/vnd.xmpie.plan": {"source":"iana"},
  "application/vnd.xmpie.ppkg": {"source":"iana"},
  "application/vnd.xmpie.xlim": {"source":"iana"},
  "application/vnd.yamaha.hv-dic": {"source":"iana","extensions":["hvd"]},
  "application/vnd.yamaha.hv-script": {"source":"iana","extensions":["hvs"]},
  "application/vnd.yamaha.hv-voice": {"source":"iana","extensions":["hvp"]},
  "application/vnd.yamaha.openscoreformat": {"source":"iana","extensions":["osf"]},
  "application/vnd.yamaha.openscoreformat.osfpvg+xml": {"source":"iana","compressible":true,"extensions":["osfpvg"]},
  "application/vnd.yamaha.remote-setup": {"source":"iana"},
  "application/vnd.yamaha.smaf-audio": {"source":"iana","extensions":["saf"]},
  "application/vnd.yamaha.smaf-phrase": {"source":"iana","extensions":["spf"]},
  "application/vnd.yamaha.through-ngn": {"source":"iana"},
  "application/vnd.yamaha.tunnel-udpencap": {"source":"iana"},
  "application/vnd.yaoweme": {"source":"iana"},
  "application/vnd.yellowriver-custom-menu": {"source":"iana","extensions":["cmp"]},
  "application/vnd.youtube.yt": {"source":"iana"},
  "application/vnd.zul": {"source":"iana","extensions":["zir","zirz"]},
  "application/vnd.zzazz.deck+xml": {"source":"iana","compressible":true,"extensions":["zaz"]},
  "application/voicexml+xml": {"source":"iana","compressible":true,"extensions":["vxml"]},
  "application/voucher-cms+json": {"source":"iana","compressible":true},
  "application/vq-rtcpxr": {"source":"iana"},
  "application/wasm": {"source":"iana","compressible":true,"extensions":["wasm"]},
  "application/watcherinfo+xml": {"source":"iana","compressible":true,"extensions":["wif"]},
  "application/webpush-options+json": {"source":"iana","compressible":true},
  "application/whoispp-query": {"source":"iana"},
  "application/whoispp-response": {"source":"iana"},
  "application/widget": {"source":"iana","extensions":["wgt"]},
  "application/winhlp": {"source":"apache","extensions":["hlp"]},
  "application/wita": {"source":"iana"},
  "application/wordperfect5.1": {"source":"iana"},
  "application/wsdl+xml": {"source":"iana","compressible":true,"extensions":["wsdl"]},
  "application/wspolicy+xml": {"source":"iana","compressible":true,"extensions":["wspolicy"]},
  "application/x-7z-compressed": {"source":"apache","compressible":false,"extensions":["7z"]},
  "application/x-abiword": {"source":"apache","extensions":["abw"]},
  "application/x-ace-compressed": {"source":"apache","extensions":["ace"]},
  "application/x-amf": {"source":"apache"},
  "application/x-apple-diskimage": {"source":"apache","extensions":["dmg"]},
  "application/x-arj": {"compressible":false,"extensions":["arj"]},
  "application/x-authorware-bin": {"source":"apache","extensions":["aab","x32","u32","vox"]},
  "application/x-authorware-map": {"source":"apache","extensions":["aam"]},
  "application/x-authorware-seg": {"source":"apache","extensions":["aas"]},
  "application/x-bcpio": {"source":"apache","extensions":["bcpio"]},
  "application/x-bdoc": {"compressible":false,"extensions":["bdoc"]},
  "application/x-bittorrent": {"source":"apache","extensions":["torrent"]},
  "application/x-blorb": {"source":"apache","extensions":["blb","blorb"]},
  "application/x-bzip": {"source":"apache","compressible":false,"extensions":["bz"]},
  "application/x-bzip2": {"source":"apache","compressible":false,"extensions":["bz2","boz"]},
  "application/x-cbr": {"source":"apache","extensions":["cbr","cba","cbt","cbz","cb7"]},
  "application/x-cdlink": {"source":"apache","extensions":["vcd"]},
  "application/x-cfs-compressed": {"source":"apache","extensions":["cfs"]},
  "application/x-chat": {"source":"apache","extensions":["chat"]},
  "application/x-chess-pgn": {"source":"apache","extensions":["pgn"]},
  "application/x-chrome-extension": {"extensions":["crx"]},
  "application/x-cocoa": {"source":"nginx","extensions":["cco"]},
  "application/x-compress": {"source":"apache"},
  "application/x-conference": {"source":"apache","extensions":["nsc"]},
  "application/x-cpio": {"source":"apache","extensions":["cpio"]},
  "application/x-csh": {"source":"apache","extensions":["csh"]},
  "application/x-deb": {"compressible":false},
  "application/x-debian-package": {"source":"apache","extensions":["deb","udeb"]},
  "application/x-dgc-compressed": {"source":"apache","extensions":["dgc"]},
  "application/x-director": {"source":"apache","extensions":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]},
  "application/x-doom": {"source":"apache","extensions":["wad"]},
  "application/x-dtbncx+xml": {"source":"apache","compressible":true,"extensions":["ncx"]},
  "application/x-dtbook+xml": {"source":"apache","compressible":true,"extensions":["dtb"]},
  "application/x-dtbresource+xml": {"source":"apache","compressible":true,"extensions":["res"]},
  "application/x-dvi": {"source":"apache","compressible":false,"extensions":["dvi"]},
  "application/x-envoy": {"source":"apache","extensions":["evy"]},
  "application/x-eva": {"source":"apache","extensions":["eva"]},
  "application/x-font-bdf": {"source":"apache","extensions":["bdf"]},
  "application/x-font-dos": {"source":"apache"},
  "application/x-font-framemaker": {"source":"apache"},
  "application/x-font-ghostscript": {"source":"apache","extensions":["gsf"]},
  "application/x-font-libgrx": {"source":"apache"},
  "application/x-font-linux-psf": {"source":"apache","extensions":["psf"]},
  "application/x-font-pcf": {"source":"apache","extensions":["pcf"]},
  "application/x-font-snf": {"source":"apache","extensions":["snf"]},
  "application/x-font-speedo": {"source":"apache"},
  "application/x-font-sunos-news": {"source":"apache"},
  "application/x-font-type1": {"source":"apache","extensions":["pfa","pfb","pfm","afm"]},
  "application/x-font-vfont": {"source":"apache"},
  "application/x-freearc": {"source":"apache","extensions":["arc"]},
  "application/x-futuresplash": {"source":"apache","extensions":["spl"]},
  "application/x-gca-compressed": {"source":"apache","extensions":["gca"]},
  "application/x-glulx": {"source":"apache","extensions":["ulx"]},
  "application/x-gnumeric": {"source":"apache","extensions":["gnumeric"]},
  "application/x-gramps-xml": {"source":"apache","extensions":["gramps"]},
  "application/x-gtar": {"source":"apache","extensions":["gtar"]},
  "application/x-gzip": {"source":"apache"},
  "application/x-hdf": {"source":"apache","extensions":["hdf"]},
  "application/x-httpd-php": {"compressible":true,"extensions":["php"]},
  "application/x-install-instructions": {"source":"apache","extensions":["install"]},
  "application/x-iso9660-image": {"source":"apache","extensions":["iso"]},
  "application/x-iwork-keynote-sffkey": {"extensions":["key"]},
  "application/x-iwork-numbers-sffnumbers": {"extensions":["numbers"]},
  "application/x-iwork-pages-sffpages": {"extensions":["pages"]},
  "application/x-java-archive-diff": {"source":"nginx","extensions":["jardiff"]},
  "application/x-java-jnlp-file": {"source":"apache","compressible":false,"extensions":["jnlp"]},
  "application/x-javascript": {"compressible":true},
  "application/x-keepass2": {"extensions":["kdbx"]},
  "application/x-latex": {"source":"apache","compressible":false,"extensions":["latex"]},
  "application/x-lua-bytecode": {"extensions":["luac"]},
  "application/x-lzh-compressed": {"source":"apache","extensions":["lzh","lha"]},
  "application/x-makeself": {"source":"nginx","extensions":["run"]},
  "application/x-mie": {"source":"apache","extensions":["mie"]},
  "application/x-mobipocket-ebook": {"source":"apache","extensions":["prc","mobi"]},
  "application/x-mpegurl": {"compressible":false},
  "application/x-ms-application": {"source":"apache","extensions":["application"]},
  "application/x-ms-shortcut": {"source":"apache","extensions":["lnk"]},
  "application/x-ms-wmd": {"source":"apache","extensions":["wmd"]},
  "application/x-ms-wmz": {"source":"apache","extensions":["wmz"]},
  "application/x-ms-xbap": {"source":"apache","extensions":["xbap"]},
  "application/x-msaccess": {"source":"apache","extensions":["mdb"]},
  "application/x-msbinder": {"source":"apache","extensions":["obd"]},
  "application/x-mscardfile": {"source":"apache","extensions":["crd"]},
  "application/x-msclip": {"source":"apache","extensions":["clp"]},
  "application/x-msdos-program": {"extensions":["exe"]},
  "application/x-msdownload": {"source":"apache","extensions":["exe","dll","com","bat","msi"]},
  "application/x-msmediaview": {"source":"apache","extensions":["mvb","m13","m14"]},
  "application/x-msmetafile": {"source":"apache","extensions":["wmf","wmz","emf","emz"]},
  "application/x-msmoney": {"source":"apache","extensions":["mny"]},
  "application/x-mspublisher": {"source":"apache","extensions":["pub"]},
  "application/x-msschedule": {"source":"apache","extensions":["scd"]},
  "application/x-msterminal": {"source":"apache","extensions":["trm"]},
  "application/x-mswrite": {"source":"apache","extensions":["wri"]},
  "application/x-netcdf": {"source":"apache","extensions":["nc","cdf"]},
  "application/x-ns-proxy-autoconfig": {"compressible":true,"extensions":["pac"]},
  "application/x-nzb": {"source":"apache","extensions":["nzb"]},
  "application/x-perl": {"source":"nginx","extensions":["pl","pm"]},
  "application/x-pilot": {"source":"nginx","extensions":["prc","pdb"]},
  "application/x-pkcs12": {"source":"apache","compressible":false,"extensions":["p12","pfx"]},
  "application/x-pkcs7-certificates": {"source":"apache","extensions":["p7b","spc"]},
  "application/x-pkcs7-certreqresp": {"source":"apache","extensions":["p7r"]},
  "application/x-pki-message": {"source":"iana"},
  "application/x-rar-compressed": {"source":"apache","compressible":false,"extensions":["rar"]},
  "application/x-redhat-package-manager": {"source":"nginx","extensions":["rpm"]},
  "application/x-research-info-systems": {"source":"apache","extensions":["ris"]},
  "application/x-sea": {"source":"nginx","extensions":["sea"]},
  "application/x-sh": {"source":"apache","compressible":true,"extensions":["sh"]},
  "application/x-shar": {"source":"apache","extensions":["shar"]},
  "application/x-shockwave-flash": {"source":"apache","compressible":false,"extensions":["swf"]},
  "application/x-silverlight-app": {"source":"apache","extensions":["xap"]},
  "application/x-sql": {"source":"apache","extensions":["sql"]},
  "application/x-stuffit": {"source":"apache","compressible":false,"extensions":["sit"]},
  "application/x-stuffitx": {"source":"apache","extensions":["sitx"]},
  "application/x-subrip": {"source":"apache","extensions":["srt"]},
  "application/x-sv4cpio": {"source":"apache","extensions":["sv4cpio"]},
  "application/x-sv4crc": {"source":"apache","extensions":["sv4crc"]},
  "application/x-t3vm-image": {"source":"apache","extensions":["t3"]},
  "application/x-tads": {"source":"apache","extensions":["gam"]},
  "application/x-tar": {"source":"apache","compressible":true,"extensions":["tar"]},
  "application/x-tcl": {"source":"apache","extensions":["tcl","tk"]},
  "application/x-tex": {"source":"apache","extensions":["tex"]},
  "application/x-tex-tfm": {"source":"apache","extensions":["tfm"]},
  "application/x-texinfo": {"source":"apache","extensions":["texinfo","texi"]},
  "application/x-tgif": {"source":"apache","extensions":["obj"]},
  "application/x-ustar": {"source":"apache","extensions":["ustar"]},
  "application/x-virtualbox-hdd": {"compressible":true,"extensions":["hdd"]},
  "application/x-virtualbox-ova": {"compressible":true,"extensions":["ova"]},
  "application/x-virtualbox-ovf": {"compressible":true,"extensions":["ovf"]},
  "application/x-virtualbox-vbox": {"compressible":true,"extensions":["vbox"]},
  "application/x-virtualbox-vbox-extpack": {"compressible":false,"extensions":["vbox-extpack"]},
  "application/x-virtualbox-vdi": {"compressible":true,"extensions":["vdi"]},
  "application/x-virtualbox-vhd": {"compressible":true,"extensions":["vhd"]},
  "application/x-virtualbox-vmdk": {"compressible":true,"extensions":["vmdk"]},
  "application/x-wais-source": {"source":"apache","extensions":["src"]},
  "application/x-web-app-manifest+json": {"compressible":true,"extensions":["webapp"]},
  "application/x-www-form-urlencoded": {"source":"iana","compressible":true},
  "application/x-x509-ca-cert": {"source":"iana","extensions":["der","crt","pem"]},
  "application/x-x509-ca-ra-cert": {"source":"iana"},
  "application/x-x509-next-ca-cert": {"source":"iana"},
  "application/x-xfig": {"source":"apache","extensions":["fig"]},
  "application/x-xliff+xml": {"source":"apache","compressible":true,"extensions":["xlf"]},
  "application/x-xpinstall": {"source":"apache","compressible":false,"extensions":["xpi"]},
  "application/x-xz": {"source":"apache","extensions":["xz"]},
  "application/x-zmachine": {"source":"apache","extensions":["z1","z2","z3","z4","z5","z6","z7","z8"]},
  "application/x400-bp": {"source":"iana"},
  "application/xacml+xml": {"source":"iana","compressible":true},
  "application/xaml+xml": {"source":"apache","compressible":true,"extensions":["xaml"]},
  "application/xcap-att+xml": {"source":"iana","compressible":true,"extensions":["xav"]},
  "application/xcap-caps+xml": {"source":"iana","compressible":true,"extensions":["xca"]},
  "application/xcap-diff+xml": {"source":"iana","compressible":true,"extensions":["xdf"]},
  "application/xcap-el+xml": {"source":"iana","compressible":true,"extensions":["xel"]},
  "application/xcap-error+xml": {"source":"iana","compressible":true},
  "application/xcap-ns+xml": {"source":"iana","compressible":true,"extensions":["xns"]},
  "application/xcon-conference-info+xml": {"source":"iana","compressible":true},
  "application/xcon-conference-info-diff+xml": {"source":"iana","compressible":true},
  "application/xenc+xml": {"source":"iana","compressible":true,"extensions":["xenc"]},
  "application/xhtml+xml": {"source":"iana","compressible":true,"extensions":["xhtml","xht"]},
  "application/xhtml-voice+xml": {"source":"apache","compressible":true},
  "application/xliff+xml": {"source":"iana","compressible":true,"extensions":["xlf"]},
  "application/xml": {"source":"iana","compressible":true,"extensions":["xml","xsl","xsd","rng"]},
  "application/xml-dtd": {"source":"iana","compressible":true,"extensions":["dtd"]},
  "application/xml-external-parsed-entity": {"source":"iana"},
  "application/xml-patch+xml": {"source":"iana","compressible":true},
  "application/xmpp+xml": {"source":"iana","compressible":true},
  "application/xop+xml": {"source":"iana","compressible":true,"extensions":["xop"]},
  "application/xproc+xml": {"source":"apache","compressible":true,"extensions":["xpl"]},
  "application/xslt+xml": {"source":"iana","compressible":true,"extensions":["xsl","xslt"]},
  "application/xspf+xml": {"source":"apache","compressible":true,"extensions":["xspf"]},
  "application/xv+xml": {"source":"iana","compressible":true,"extensions":["mxml","xhvml","xvml","xvm"]},
  "application/yang": {"source":"iana","extensions":["yang"]},
  "application/yang-data+json": {"source":"iana","compressible":true},
  "application/yang-data+xml": {"source":"iana","compressible":true},
  "application/yang-patch+json": {"source":"iana","compressible":true},
  "application/yang-patch+xml": {"source":"iana","compressible":true},
  "application/yin+xml": {"source":"iana","compressible":true,"extensions":["yin"]},
  "application/zip": {"source":"iana","compressible":false,"extensions":["zip"]},
  "application/zlib": {"source":"iana"},
  "application/zstd": {"source":"iana"},
  "audio/1d-interleaved-parityfec": {"source":"iana"},
  "audio/32kadpcm": {"source":"iana"},
  "audio/3gpp": {"source":"iana","compressible":false,"extensions":["3gpp"]},
  "audio/3gpp2": {"source":"iana"},
  "audio/aac": {"source":"iana"},
  "audio/ac3": {"source":"iana"},
  "audio/adpcm": {"source":"apache","extensions":["adp"]},
  "audio/amr": {"source":"iana","extensions":["amr"]},
  "audio/amr-wb": {"source":"iana"},
  "audio/amr-wb+": {"source":"iana"},
  "audio/aptx": {"source":"iana"},
  "audio/asc": {"source":"iana"},
  "audio/atrac-advanced-lossless": {"source":"iana"},
  "audio/atrac-x": {"source":"iana"},
  "audio/atrac3": {"source":"iana"},
  "audio/basic": {"source":"iana","compressible":false,"extensions":["au","snd"]},
  "audio/bv16": {"source":"iana"},
  "audio/bv32": {"source":"iana"},
  "audio/clearmode": {"source":"iana"},
  "audio/cn": {"source":"iana"},
  "audio/dat12": {"source":"iana"},
  "audio/dls": {"source":"iana"},
  "audio/dsr-es201108": {"source":"iana"},
  "audio/dsr-es202050": {"source":"iana"},
  "audio/dsr-es202211": {"source":"iana"},
  "audio/dsr-es202212": {"source":"iana"},
  "audio/dv": {"source":"iana"},
  "audio/dvi4": {"source":"iana"},
  "audio/eac3": {"source":"iana"},
  "audio/encaprtp": {"source":"iana"},
  "audio/evrc": {"source":"iana"},
  "audio/evrc-qcp": {"source":"iana"},
  "audio/evrc0": {"source":"iana"},
  "audio/evrc1": {"source":"iana"},
  "audio/evrcb": {"source":"iana"},
  "audio/evrcb0": {"source":"iana"},
  "audio/evrcb1": {"source":"iana"},
  "audio/evrcnw": {"source":"iana"},
  "audio/evrcnw0": {"source":"iana"},
  "audio/evrcnw1": {"source":"iana"},
  "audio/evrcwb": {"source":"iana"},
  "audio/evrcwb0": {"source":"iana"},
  "audio/evrcwb1": {"source":"iana"},
  "audio/evs": {"source":"iana"},
  "audio/flexfec": {"source":"iana"},
  "audio/fwdred": {"source":"iana"},
  "audio/g711-0": {"source":"iana"},
  "audio/g719": {"source":"iana"},
  "audio/g722": {"source":"iana"},
  "audio/g7221": {"source":"iana"},
  "audio/g723": {"source":"iana"},
  "audio/g726-16": {"source":"iana"},
  "audio/g726-24": {"source":"iana"},
  "audio/g726-32": {"source":"iana"},
  "audio/g726-40": {"source":"iana"},
  "audio/g728": {"source":"iana"},
  "audio/g729": {"source":"iana"},
  "audio/g7291": {"source":"iana"},
  "audio/g729d": {"source":"iana"},
  "audio/g729e": {"source":"iana"},
  "audio/gsm": {"source":"iana"},
  "audio/gsm-efr": {"source":"iana"},
  "audio/gsm-hr-08": {"source":"iana"},
  "audio/ilbc": {"source":"iana"},
  "audio/ip-mr_v2.5": {"source":"iana"},
  "audio/isac": {"source":"apache"},
  "audio/l16": {"source":"iana"},
  "audio/l20": {"source":"iana"},
  "audio/l24": {"source":"iana","compressible":false},
  "audio/l8": {"source":"iana"},
  "audio/lpc": {"source":"iana"},
  "audio/melp": {"source":"iana"},
  "audio/melp1200": {"source":"iana"},
  "audio/melp2400": {"source":"iana"},
  "audio/melp600": {"source":"iana"},
  "audio/mhas": {"source":"iana"},
  "audio/midi": {"source":"apache","extensions":["mid","midi","kar","rmi"]},
  "audio/mobile-xmf": {"source":"iana","extensions":["mxmf"]},
  "audio/mp3": {"compressible":false,"extensions":["mp3"]},
  "audio/mp4": {"source":"iana","compressible":false,"extensions":["m4a","mp4a"]},
  "audio/mp4a-latm": {"source":"iana"},
  "audio/mpa": {"source":"iana"},
  "audio/mpa-robust": {"source":"iana"},
  "audio/mpeg": {"source":"iana","compressible":false,"extensions":["mpga","mp2","mp2a","mp3","m2a","m3a"]},
  "audio/mpeg4-generic": {"source":"iana"},
  "audio/musepack": {"source":"apache"},
  "audio/ogg": {"source":"iana","compressible":false,"extensions":["oga","ogg","spx","opus"]},
  "audio/opus": {"source":"iana"},
  "audio/parityfec": {"source":"iana"},
  "audio/pcma": {"source":"iana"},
  "audio/pcma-wb": {"source":"iana"},
  "audio/pcmu": {"source":"iana"},
  "audio/pcmu-wb": {"source":"iana"},
  "audio/prs.sid": {"source":"iana"},
  "audio/qcelp": {"source":"iana"},
  "audio/raptorfec": {"source":"iana"},
  "audio/red": {"source":"iana"},
  "audio/rtp-enc-aescm128": {"source":"iana"},
  "audio/rtp-midi": {"source":"iana"},
  "audio/rtploopback": {"source":"iana"},
  "audio/rtx": {"source":"iana"},
  "audio/s3m": {"source":"apache","extensions":["s3m"]},
  "audio/scip": {"source":"iana"},
  "audio/silk": {"source":"apache","extensions":["sil"]},
  "audio/smv": {"source":"iana"},
  "audio/smv-qcp": {"source":"iana"},
  "audio/smv0": {"source":"iana"},
  "audio/sofa": {"source":"iana"},
  "audio/sp-midi": {"source":"iana"},
  "audio/speex": {"source":"iana"},
  "audio/t140c": {"source":"iana"},
  "audio/t38": {"source":"iana"},
  "audio/telephone-event": {"source":"iana"},
  "audio/tetra_acelp": {"source":"iana"},
  "audio/tetra_acelp_bb": {"source":"iana"},
  "audio/tone": {"source":"iana"},
  "audio/tsvcis": {"source":"iana"},
  "audio/uemclip": {"source":"iana"},
  "audio/ulpfec": {"source":"iana"},
  "audio/usac": {"source":"iana"},
  "audio/vdvi": {"source":"iana"},
  "audio/vmr-wb": {"source":"iana"},
  "audio/vnd.3gpp.iufp": {"source":"iana"},
  "audio/vnd.4sb": {"source":"iana"},
  "audio/vnd.audiokoz": {"source":"iana"},
  "audio/vnd.celp": {"source":"iana"},
  "audio/vnd.cisco.nse": {"source":"iana"},
  "audio/vnd.cmles.radio-events": {"source":"iana"},
  "audio/vnd.cns.anp1": {"source":"iana"},
  "audio/vnd.cns.inf1": {"source":"iana"},
  "audio/vnd.dece.audio": {"source":"iana","extensions":["uva","uvva"]},
  "audio/vnd.digital-winds": {"source":"iana","extensions":["eol"]},
  "audio/vnd.dlna.adts": {"source":"iana"},
  "audio/vnd.dolby.heaac.1": {"source":"iana"},
  "audio/vnd.dolby.heaac.2": {"source":"iana"},
  "audio/vnd.dolby.mlp": {"source":"iana"},
  "audio/vnd.dolby.mps": {"source":"iana"},
  "audio/vnd.dolby.pl2": {"source":"iana"},
  "audio/vnd.dolby.pl2x": {"source":"iana"},
  "audio/vnd.dolby.pl2z": {"source":"iana"},
  "audio/vnd.dolby.pulse.1": {"source":"iana"},
  "audio/vnd.dra": {"source":"iana","extensions":["dra"]},
  "audio/vnd.dts": {"source":"iana","extensions":["dts"]},
  "audio/vnd.dts.hd": {"source":"iana","extensions":["dtshd"]},
  "audio/vnd.dts.uhd": {"source":"iana"},
  "audio/vnd.dvb.file": {"source":"iana"},
  "audio/vnd.everad.plj": {"source":"iana"},
  "audio/vnd.hns.audio": {"source":"iana"},
  "audio/vnd.lucent.voice": {"source":"iana","extensions":["lvp"]},
  "audio/vnd.ms-playready.media.pya": {"source":"iana","extensions":["pya"]},
  "audio/vnd.nokia.mobile-xmf": {"source":"iana"},
  "audio/vnd.nortel.vbk": {"source":"iana"},
  "audio/vnd.nuera.ecelp4800": {"source":"iana","extensions":["ecelp4800"]},
  "audio/vnd.nuera.ecelp7470": {"source":"iana","extensions":["ecelp7470"]},
  "audio/vnd.nuera.ecelp9600": {"source":"iana","extensions":["ecelp9600"]},
  "audio/vnd.octel.sbc": {"source":"iana"},
  "audio/vnd.presonus.multitrack": {"source":"iana"},
  "audio/vnd.qcelp": {"source":"iana"},
  "audio/vnd.rhetorex.32kadpcm": {"source":"iana"},
  "audio/vnd.rip": {"source":"iana","extensions":["rip"]},
  "audio/vnd.rn-realaudio": {"compressible":false},
  "audio/vnd.sealedmedia.softseal.mpeg": {"source":"iana"},
  "audio/vnd.vmx.cvsd": {"source":"iana"},
  "audio/vnd.wave": {"compressible":false},
  "audio/vorbis": {"source":"iana","compressible":false},
  "audio/vorbis-config": {"source":"iana"},
  "audio/wav": {"compressible":false,"extensions":["wav"]},
  "audio/wave": {"compressible":false,"extensions":["wav"]},
  "audio/webm": {"source":"apache","compressible":false,"extensions":["weba"]},
  "audio/x-aac": {"source":"apache","compressible":false,"extensions":["aac"]},
  "audio/x-aiff": {"source":"apache","extensions":["aif","aiff","aifc"]},
  "audio/x-caf": {"source":"apache","compressible":false,"extensions":["caf"]},
  "audio/x-flac": {"source":"apache","extensions":["flac"]},
  "audio/x-m4a": {"source":"nginx","extensions":["m4a"]},
  "audio/x-matroska": {"source":"apache","extensions":["mka"]},
  "audio/x-mpegurl": {"source":"apache","extensions":["m3u"]},
  "audio/x-ms-wax": {"source":"apache","extensions":["wax"]},
  "audio/x-ms-wma": {"source":"apache","extensions":["wma"]},
  "audio/x-pn-realaudio": {"source":"apache","extensions":["ram","ra"]},
  "audio/x-pn-realaudio-plugin": {"source":"apache","extensions":["rmp"]},
  "audio/x-realaudio": {"source":"nginx","extensions":["ra"]},
  "audio/x-tta": {"source":"apache"},
  "audio/x-wav": {"source":"apache","extensions":["wav"]},
  "audio/xm": {"source":"apache","extensions":["xm"]},
  "chemical/x-cdx": {"source":"apache","extensions":["cdx"]},
  "chemical/x-cif": {"source":"apache","extensions":["cif"]},
  "chemical/x-cmdf": {"source":"apache","extensions":["cmdf"]},
  "chemical/x-cml": {"source":"apache","extensions":["cml"]},
  "chemical/x-csml": {"source":"apache","extensions":["csml"]},
  "chemical/x-pdb": {"source":"apache"},
  "chemical/x-xyz": {"source":"apache","extensions":["xyz"]},
  "font/collection": {"source":"iana","extensions":["ttc"]},
  "font/otf": {"source":"iana","compressible":true,"extensions":["otf"]},
  "font/sfnt": {"source":"iana"},
  "font/ttf": {"source":"iana","compressible":true,"extensions":["ttf"]},
  "font/woff": {"source":"iana","extensions":["woff"]},
  "font/woff2": {"source":"iana","extensions":["woff2"]},
  "image/aces": {"source":"iana","extensions":["exr"]},
  "image/apng": {"compressible":false,"extensions":["apng"]},
  "image/avci": {"source":"iana","extensions":["avci"]},
  "image/avcs": {"source":"iana","extensions":["avcs"]},
  "image/avif": {"source":"iana","compressible":false,"extensions":["avif"]},
  "image/bmp": {"source":"iana","compressible":true,"extensions":["bmp"]},
  "image/cgm": {"source":"iana","extensions":["cgm"]},
  "image/dicom-rle": {"source":"iana","extensions":["drle"]},
  "image/emf": {"source":"iana","extensions":["emf"]},
  "image/fits": {"source":"iana","extensions":["fits"]},
  "image/g3fax": {"source":"iana","extensions":["g3"]},
  "image/gif": {"source":"iana","compressible":false,"extensions":["gif"]},
  "image/heic": {"source":"iana","extensions":["heic"]},
  "image/heic-sequence": {"source":"iana","extensions":["heics"]},
  "image/heif": {"source":"iana","extensions":["heif"]},
  "image/heif-sequence": {"source":"iana","extensions":["heifs"]},
  "image/hej2k": {"source":"iana","extensions":["hej2"]},
  "image/hsj2": {"source":"iana","extensions":["hsj2"]},
  "image/ief": {"source":"iana","extensions":["ief"]},
  "image/jls": {"source":"iana","extensions":["jls"]},
  "image/jp2": {"source":"iana","compressible":false,"extensions":["jp2","jpg2"]},
  "image/jpeg": {"source":"iana","compressible":false,"extensions":["jpeg","jpg","jpe"]},
  "image/jph": {"source":"iana","extensions":["jph"]},
  "image/jphc": {"source":"iana","extensions":["jhc"]},
  "image/jpm": {"source":"iana","compressible":false,"extensions":["jpm"]},
  "image/jpx": {"source":"iana","compressible":false,"extensions":["jpx","jpf"]},
  "image/jxr": {"source":"iana","extensions":["jxr"]},
  "image/jxra": {"source":"iana","extensions":["jxra"]},
  "image/jxrs": {"source":"iana","extensions":["jxrs"]},
  "image/jxs": {"source":"iana","extensions":["jxs"]},
  "image/jxsc": {"source":"iana","extensions":["jxsc"]},
  "image/jxsi": {"source":"iana","extensions":["jxsi"]},
  "image/jxss": {"source":"iana","extensions":["jxss"]},
  "image/ktx": {"source":"iana","extensions":["ktx"]},
  "image/ktx2": {"source":"iana","extensions":["ktx2"]},
  "image/naplps": {"source":"iana"},
  "image/pjpeg": {"compressible":false},
  "image/png": {"source":"iana","compressible":false,"extensions":["png"]},
  "image/prs.btif": {"source":"iana","extensions":["btif"]},
  "image/prs.pti": {"source":"iana","extensions":["pti"]},
  "image/pwg-raster": {"source":"iana"},
  "image/sgi": {"source":"apache","extensions":["sgi"]},
  "image/svg+xml": {"source":"iana","compressible":true,"extensions":["svg","svgz"]},
  "image/t38": {"source":"iana","extensions":["t38"]},
  "image/tiff": {"source":"iana","compressible":false,"extensions":["tif","tiff"]},
  "image/tiff-fx": {"source":"iana","extensions":["tfx"]},
  "image/vnd.adobe.photoshop": {"source":"iana","compressible":true,"extensions":["psd"]},
  "image/vnd.airzip.accelerator.azv": {"source":"iana","extensions":["azv"]},
  "image/vnd.cns.inf2": {"source":"iana"},
  "image/vnd.dece.graphic": {"source":"iana","extensions":["uvi","uvvi","uvg","uvvg"]},
  "image/vnd.djvu": {"source":"iana","extensions":["djvu","djv"]},
  "image/vnd.dvb.subtitle": {"source":"iana","extensions":["sub"]},
  "image/vnd.dwg": {"source":"iana","extensions":["dwg"]},
  "image/vnd.dxf": {"source":"iana","extensions":["dxf"]},
  "image/vnd.fastbidsheet": {"source":"iana","extensions":["fbs"]},
  "image/vnd.fpx": {"source":"iana","extensions":["fpx"]},
  "image/vnd.fst": {"source":"iana","extensions":["fst"]},
  "image/vnd.fujixerox.edmics-mmr": {"source":"iana","extensions":["mmr"]},
  "image/vnd.fujixerox.edmics-rlc": {"source":"iana","extensions":["rlc"]},
  "image/vnd.globalgraphics.pgb": {"source":"iana"},
  "image/vnd.microsoft.icon": {"source":"iana","compressible":true,"extensions":["ico"]},
  "image/vnd.mix": {"source":"iana"},
  "image/vnd.mozilla.apng": {"source":"iana"},
  "image/vnd.ms-dds": {"compressible":true,"extensions":["dds"]},
  "image/vnd.ms-modi": {"source":"iana","extensions":["mdi"]},
  "image/vnd.ms-photo": {"source":"apache","extensions":["wdp"]},
  "image/vnd.net-fpx": {"source":"iana","extensions":["npx"]},
  "image/vnd.pco.b16": {"source":"iana","extensions":["b16"]},
  "image/vnd.radiance": {"source":"iana"},
  "image/vnd.sealed.png": {"source":"iana"},
  "image/vnd.sealedmedia.softseal.gif": {"source":"iana"},
  "image/vnd.sealedmedia.softseal.jpg": {"source":"iana"},
  "image/vnd.svf": {"source":"iana"},
  "image/vnd.tencent.tap": {"source":"iana","extensions":["tap"]},
  "image/vnd.valve.source.texture": {"source":"iana","extensions":["vtf"]},
  "image/vnd.wap.wbmp": {"source":"iana","extensions":["wbmp"]},
  "image/vnd.xiff": {"source":"iana","extensions":["xif"]},
  "image/vnd.zbrush.pcx": {"source":"iana","extensions":["pcx"]},
  "image/webp": {"source":"apache","extensions":["webp"]},
  "image/wmf": {"source":"iana","extensions":["wmf"]},
  "image/x-3ds": {"source":"apache","extensions":["3ds"]},
  "image/x-cmu-raster": {"source":"apache","extensions":["ras"]},
  "image/x-cmx": {"source":"apache","extensions":["cmx"]},
  "image/x-freehand": {"source":"apache","extensions":["fh","fhc","fh4","fh5","fh7"]},
  "image/x-icon": {"source":"apache","compressible":true,"extensions":["ico"]},
  "image/x-jng": {"source":"nginx","extensions":["jng"]},
  "image/x-mrsid-image": {"source":"apache","extensions":["sid"]},
  "image/x-ms-bmp": {"source":"nginx","compressible":true,"extensions":["bmp"]},
  "image/x-pcx": {"source":"apache","extensions":["pcx"]},
  "image/x-pict": {"source":"apache","extensions":["pic","pct"]},
  "image/x-portable-anymap": {"source":"apache","extensions":["pnm"]},
  "image/x-portable-bitmap": {"source":"apache","extensions":["pbm"]},
  "image/x-portable-graymap": {"source":"apache","extensions":["pgm"]},
  "image/x-portable-pixmap": {"source":"apache","extensions":["ppm"]},
  "image/x-rgb": {"source":"apache","extensions":["rgb"]},
  "image/x-tga": {"source":"apache","extensions":["tga"]},
  "image/x-xbitmap": {"source":"apache","extensions":["xbm"]},
  "image/x-xcf": {"compressible":false},
  "image/x-xpixmap": {"source":"apache","extensions":["xpm"]},
  "image/x-xwindowdump": {"source":"apache","extensions":["xwd"]},
  "message/cpim": {"source":"iana"},
  "message/delivery-status": {"source":"iana"},
  "message/disposition-notification": {"source":"iana","extensions":["disposition-notification"]},
  "message/external-body": {"source":"iana"},
  "message/feedback-report": {"source":"iana"},
  "message/global": {"source":"iana","extensions":["u8msg"]},
  "message/global-delivery-status": {"source":"iana","extensions":["u8dsn"]},
  "message/global-disposition-notification": {"source":"iana","extensions":["u8mdn"]},
  "message/global-headers": {"source":"iana","extensions":["u8hdr"]},
  "message/http": {"source":"iana","compressible":false},
  "message/imdn+xml": {"source":"iana","compressible":true},
  "message/news": {"source":"iana"},
  "message/partial": {"source":"iana","compressible":false},
  "message/rfc822": {"source":"iana","compressible":true,"extensions":["eml","mime"]},
  "message/s-http": {"source":"iana"},
  "message/sip": {"source":"iana"},
  "message/sipfrag": {"source":"iana"},
  "message/tracking-status": {"source":"iana"},
  "message/vnd.si.simp": {"source":"iana"},
  "message/vnd.wfa.wsc": {"source":"iana","extensions":["wsc"]},
  "model/3mf": {"source":"iana","extensions":["3mf"]},
  "model/e57": {"source":"iana"},
  "model/gltf+json": {"source":"iana","compressible":true,"extensions":["gltf"]},
  "model/gltf-binary": {"source":"iana","compressible":true,"extensions":["glb"]},
  "model/iges": {"source":"iana","compressible":false,"extensions":["igs","iges"]},
  "model/mesh": {"source":"iana","compressible":false,"extensions":["msh","mesh","silo"]},
  "model/mtl": {"source":"iana","extensions":["mtl"]},
  "model/obj": {"source":"iana","extensions":["obj"]},
  "model/step": {"source":"iana"},
  "model/step+xml": {"source":"iana","compressible":true,"extensions":["stpx"]},
  "model/step+zip": {"source":"iana","compressible":false,"extensions":["stpz"]},
  "model/step-xml+zip": {"source":"iana","compressible":false,"extensions":["stpxz"]},
  "model/stl": {"source":"iana","extensions":["stl"]},
  "model/vnd.collada+xml": {"source":"iana","compressible":true,"extensions":["dae"]},
  "model/vnd.dwf": {"source":"iana","extensions":["dwf"]},
  "model/vnd.flatland.3dml": {"source":"iana"},
  "model/vnd.gdl": {"source":"iana","extensions":["gdl"]},
  "model/vnd.gs-gdl": {"source":"apache"},
  "model/vnd.gs.gdl": {"source":"iana"},
  "model/vnd.gtw": {"source":"iana","extensions":["gtw"]},
  "model/vnd.moml+xml": {"source":"iana","compressible":true},
  "model/vnd.mts": {"source":"iana","extensions":["mts"]},
  "model/vnd.opengex": {"source":"iana","extensions":["ogex"]},
  "model/vnd.parasolid.transmit.binary": {"source":"iana","extensions":["x_b"]},
  "model/vnd.parasolid.transmit.text": {"source":"iana","extensions":["x_t"]},
  "model/vnd.pytha.pyox": {"source":"iana"},
  "model/vnd.rosette.annotated-data-model": {"source":"iana"},
  "model/vnd.sap.vds": {"source":"iana","extensions":["vds"]},
  "model/vnd.usdz+zip": {"source":"iana","compressible":false,"extensions":["usdz"]},
  "model/vnd.valve.source.compiled-map": {"source":"iana","extensions":["bsp"]},
  "model/vnd.vtu": {"source":"iana","extensions":["vtu"]},
  "model/vrml": {"source":"iana","compressible":false,"extensions":["wrl","vrml"]},
  "model/x3d+binary": {"source":"apache","compressible":false,"extensions":["x3db","x3dbz"]},
  "model/x3d+fastinfoset": {"source":"iana","extensions":["x3db"]},
  "model/x3d+vrml": {"source":"apache","compressible":false,"extensions":["x3dv","x3dvz"]},
  "model/x3d+xml": {"source":"iana","compressible":true,"extensions":["x3d","x3dz"]},
  "model/x3d-vrml": {"source":"iana","extensions":["x3dv"]},
  "multipart/alternative": {"source":"iana","compressible":false},
  "multipart/appledouble": {"source":"iana"},
  "multipart/byteranges": {"source":"iana"},
  "multipart/digest": {"source":"iana"},
  "multipart/encrypted": {"source":"iana","compressible":false},
  "multipart/form-data": {"source":"iana","compressible":false},
  "multipart/header-set": {"source":"iana"},
  "multipart/mixed": {"source":"iana"},
  "multipart/multilingual": {"source":"iana"},
  "multipart/parallel": {"source":"iana"},
  "multipart/related": {"source":"iana","compressible":false},
  "multipart/report": {"source":"iana"},
  "multipart/signed": {"source":"iana","compressible":false},
  "multipart/vnd.bint.med-plus": {"source":"iana"},
  "multipart/voice-message": {"source":"iana"},
  "multipart/x-mixed-replace": {"source":"iana"},
  "text/1d-interleaved-parityfec": {"source":"iana"},
  "text/cache-manifest": {"source":"iana","compressible":true,"extensions":["appcache","manifest"]},
  "text/calendar": {"source":"iana","extensions":["ics","ifb"]},
  "text/calender": {"compressible":true},
  "text/cmd": {"compressible":true},
  "text/coffeescript": {"extensions":["coffee","litcoffee"]},
  "text/cql": {"source":"iana"},
  "text/cql-expression": {"source":"iana"},
  "text/cql-identifier": {"source":"iana"},
  "text/css": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["css"]},
  "text/csv": {"source":"iana","compressible":true,"extensions":["csv"]},
  "text/csv-schema": {"source":"iana"},
  "text/directory": {"source":"iana"},
  "text/dns": {"source":"iana"},
  "text/ecmascript": {"source":"iana"},
  "text/encaprtp": {"source":"iana"},
  "text/enriched": {"source":"iana"},
  "text/fhirpath": {"source":"iana"},
  "text/flexfec": {"source":"iana"},
  "text/fwdred": {"source":"iana"},
  "text/gff3": {"source":"iana"},
  "text/grammar-ref-list": {"source":"iana"},
  "text/html": {"source":"iana","compressible":true,"extensions":["html","htm","shtml"]},
  "text/jade": {"extensions":["jade"]},
  "text/javascript": {"source":"iana","compressible":true},
  "text/jcr-cnd": {"source":"iana"},
  "text/jsx": {"compressible":true,"extensions":["jsx"]},
  "text/less": {"compressible":true,"extensions":["less"]},
  "text/markdown": {"source":"iana","compressible":true,"extensions":["markdown","md"]},
  "text/mathml": {"source":"nginx","extensions":["mml"]},
  "text/mdx": {"compressible":true,"extensions":["mdx"]},
  "text/mizar": {"source":"iana"},
  "text/n3": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["n3"]},
  "text/parameters": {"source":"iana","charset":"UTF-8"},
  "text/parityfec": {"source":"iana"},
  "text/plain": {"source":"iana","compressible":true,"extensions":["txt","text","conf","def","list","log","in","ini"]},
  "text/provenance-notation": {"source":"iana","charset":"UTF-8"},
  "text/prs.fallenstein.rst": {"source":"iana"},
  "text/prs.lines.tag": {"source":"iana","extensions":["dsc"]},
  "text/prs.prop.logic": {"source":"iana"},
  "text/raptorfec": {"source":"iana"},
  "text/red": {"source":"iana"},
  "text/rfc822-headers": {"source":"iana"},
  "text/richtext": {"source":"iana","compressible":true,"extensions":["rtx"]},
  "text/rtf": {"source":"iana","compressible":true,"extensions":["rtf"]},
  "text/rtp-enc-aescm128": {"source":"iana"},
  "text/rtploopback": {"source":"iana"},
  "text/rtx": {"source":"iana"},
  "text/sgml": {"source":"iana","extensions":["sgml","sgm"]},
  "text/shaclc": {"source":"iana"},
  "text/shex": {"source":"iana","extensions":["shex"]},
  "text/slim": {"extensions":["slim","slm"]},
  "text/spdx": {"source":"iana","extensions":["spdx"]},
  "text/strings": {"source":"iana"},
  "text/stylus": {"extensions":["stylus","styl"]},
  "text/t140": {"source":"iana"},
  "text/tab-separated-values": {"source":"iana","compressible":true,"extensions":["tsv"]},
  "text/troff": {"source":"iana","extensions":["t","tr","roff","man","me","ms"]},
  "text/turtle": {"source":"iana","charset":"UTF-8","extensions":["ttl"]},
  "text/ulpfec": {"source":"iana"},
  "text/uri-list": {"source":"iana","compressible":true,"extensions":["uri","uris","urls"]},
  "text/vcard": {"source":"iana","compressible":true,"extensions":["vcard"]},
  "text/vnd.a": {"source":"iana"},
  "text/vnd.abc": {"source":"iana"},
  "text/vnd.ascii-art": {"source":"iana"},
  "text/vnd.curl": {"source":"iana","extensions":["curl"]},
  "text/vnd.curl.dcurl": {"source":"apache","extensions":["dcurl"]},
  "text/vnd.curl.mcurl": {"source":"apache","extensions":["mcurl"]},
  "text/vnd.curl.scurl": {"source":"apache","extensions":["scurl"]},
  "text/vnd.debian.copyright": {"source":"iana","charset":"UTF-8"},
  "text/vnd.dmclientscript": {"source":"iana"},
  "text/vnd.dvb.subtitle": {"source":"iana","extensions":["sub"]},
  "text/vnd.esmertec.theme-descriptor": {"source":"iana","charset":"UTF-8"},
  "text/vnd.familysearch.gedcom": {"source":"iana","extensions":["ged"]},
  "text/vnd.ficlab.flt": {"source":"iana"},
  "text/vnd.fly": {"source":"iana","extensions":["fly"]},
  "text/vnd.fmi.flexstor": {"source":"iana","extensions":["flx"]},
  "text/vnd.gml": {"source":"iana"},
  "text/vnd.graphviz": {"source":"iana","extensions":["gv"]},
  "text/vnd.hans": {"source":"iana"},
  "text/vnd.hgl": {"source":"iana"},
  "text/vnd.in3d.3dml": {"source":"iana","extensions":["3dml"]},
  "text/vnd.in3d.spot": {"source":"iana","extensions":["spot"]},
  "text/vnd.iptc.newsml": {"source":"iana"},
  "text/vnd.iptc.nitf": {"source":"iana"},
  "text/vnd.latex-z": {"source":"iana"},
  "text/vnd.motorola.reflex": {"source":"iana"},
  "text/vnd.ms-mediapackage": {"source":"iana"},
  "text/vnd.net2phone.commcenter.command": {"source":"iana"},
  "text/vnd.radisys.msml-basic-layout": {"source":"iana"},
  "text/vnd.senx.warpscript": {"source":"iana"},
  "text/vnd.si.uricatalogue": {"source":"iana"},
  "text/vnd.sosi": {"source":"iana"},
  "text/vnd.sun.j2me.app-descriptor": {"source":"iana","charset":"UTF-8","extensions":["jad"]},
  "text/vnd.trolltech.linguist": {"source":"iana","charset":"UTF-8"},
  "text/vnd.wap.si": {"source":"iana"},
  "text/vnd.wap.sl": {"source":"iana"},
  "text/vnd.wap.wml": {"source":"iana","extensions":["wml"]},
  "text/vnd.wap.wmlscript": {"source":"iana","extensions":["wmls"]},
  "text/vtt": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["vtt"]},
  "text/x-asm": {"source":"apache","extensions":["s","asm"]},
  "text/x-c": {"source":"apache","extensions":["c","cc","cxx","cpp","h","hh","dic"]},
  "text/x-component": {"source":"nginx","extensions":["htc"]},
  "text/x-fortran": {"source":"apache","extensions":["f","for","f77","f90"]},
  "text/x-gwt-rpc": {"compressible":true},
  "text/x-handlebars-template": {"extensions":["hbs"]},
  "text/x-java-source": {"source":"apache","extensions":["java"]},
  "text/x-jquery-tmpl": {"compressible":true},
  "text/x-lua": {"extensions":["lua"]},
  "text/x-markdown": {"compressible":true,"extensions":["mkd"]},
  "text/x-nfo": {"source":"apache","extensions":["nfo"]},
  "text/x-opml": {"source":"apache","extensions":["opml"]},
  "text/x-org": {"compressible":true,"extensions":["org"]},
  "text/x-pascal": {"source":"apache","extensions":["p","pas"]},
  "text/x-processing": {"compressible":true,"extensions":["pde"]},
  "text/x-sass": {"extensions":["sass"]},
  "text/x-scss": {"extensions":["scss"]},
  "text/x-setext": {"source":"apache","extensions":["etx"]},
  "text/x-sfv": {"source":"apache","extensions":["sfv"]},
  "text/x-suse-ymp": {"compressible":true,"extensions":["ymp"]},
  "text/x-uuencode": {"source":"apache","extensions":["uu"]},
  "text/x-vcalendar": {"source":"apache","extensions":["vcs"]},
  "text/x-vcard": {"source":"apache","extensions":["vcf"]},
  "text/xml": {"source":"iana","compressible":true,"extensions":["xml"]},
  "text/xml-external-parsed-entity": {"source":"iana"},
  "text/yaml": {"compressible":true,"extensions":["yaml","yml"]},
  "video/1d-interleaved-parityfec": {"source":"iana"},
  "video/3gpp": {"source":"iana","extensions":["3gp","3gpp"]},
  "video/3gpp-tt": {"source":"iana"},
  "video/3gpp2": {"source":"iana","extensions":["3g2"]},
  "video/av1": {"source":"iana"},
  "video/bmpeg": {"source":"iana"},
  "video/bt656": {"source":"iana"},
  "video/celb": {"source":"iana"},
  "video/dv": {"source":"iana"},
  "video/encaprtp": {"source":"iana"},
  "video/ffv1": {"source":"iana"},
  "video/flexfec": {"source":"iana"},
  "video/h261": {"source":"iana","extensions":["h261"]},
  "video/h263": {"source":"iana","extensions":["h263"]},
  "video/h263-1998": {"source":"iana"},
  "video/h263-2000": {"source":"iana"},
  "video/h264": {"source":"iana","extensions":["h264"]},
  "video/h264-rcdo": {"source":"iana"},
  "video/h264-svc": {"source":"iana"},
  "video/h265": {"source":"iana"},
  "video/iso.segment": {"source":"iana","extensions":["m4s"]},
  "video/jpeg": {"source":"iana","extensions":["jpgv"]},
  "video/jpeg2000": {"source":"iana"},
  "video/jpm": {"source":"apache","extensions":["jpm","jpgm"]},
  "video/jxsv": {"source":"iana"},
  "video/mj2": {"source":"iana","extensions":["mj2","mjp2"]},
  "video/mp1s": {"source":"iana"},
  "video/mp2p": {"source":"iana"},
  "video/mp2t": {"source":"iana","extensions":["ts"]},
  "video/mp4": {"source":"iana","compressible":false,"extensions":["mp4","mp4v","mpg4"]},
  "video/mp4v-es": {"source":"iana"},
  "video/mpeg": {"source":"iana","compressible":false,"extensions":["mpeg","mpg","mpe","m1v","m2v"]},
  "video/mpeg4-generic": {"source":"iana"},
  "video/mpv": {"source":"iana"},
  "video/nv": {"source":"iana"},
  "video/ogg": {"source":"iana","compressible":false,"extensions":["ogv"]},
  "video/parityfec": {"source":"iana"},
  "video/pointer": {"source":"iana"},
  "video/quicktime": {"source":"iana","compressible":false,"extensions":["qt","mov"]},
  "video/raptorfec": {"source":"iana"},
  "video/raw": {"source":"iana"},
  "video/rtp-enc-aescm128": {"source":"iana"},
  "video/rtploopback": {"source":"iana"},
  "video/rtx": {"source":"iana"},
  "video/scip": {"source":"iana"},
  "video/smpte291": {"source":"iana"},
  "video/smpte292m": {"source":"iana"},
  "video/ulpfec": {"source":"iana"},
  "video/vc1": {"source":"iana"},
  "video/vc2": {"source":"iana"},
  "video/vnd.cctv": {"source":"iana"},
  "video/vnd.dece.hd": {"source":"iana","extensions":["uvh","uvvh"]},
  "video/vnd.dece.mobile": {"source":"iana","extensions":["uvm","uvvm"]},
  "video/vnd.dece.mp4": {"source":"iana"},
  "video/vnd.dece.pd": {"source":"iana","extensions":["uvp","uvvp"]},
  "video/vnd.dece.sd": {"source":"iana","extensions":["uvs","uvvs"]},
  "video/vnd.dece.video": {"source":"iana","extensions":["uvv","uvvv"]},
  "video/vnd.directv.mpeg": {"source":"iana"},
  "video/vnd.directv.mpeg-tts": {"source":"iana"},
  "video/vnd.dlna.mpeg-tts": {"source":"iana"},
  "video/vnd.dvb.file": {"source":"iana","extensions":["dvb"]},
  "video/vnd.fvt": {"source":"iana","extensions":["fvt"]},
  "video/vnd.hns.video": {"source":"iana"},
  "video/vnd.iptvforum.1dparityfec-1010": {"source":"iana"},
  "video/vnd.iptvforum.1dparityfec-2005": {"source":"iana"},
  "video/vnd.iptvforum.2dparityfec-1010": {"source":"iana"},
  "video/vnd.iptvforum.2dparityfec-2005": {"source":"iana"},
  "video/vnd.iptvforum.ttsavc": {"source":"iana"},
  "video/vnd.iptvforum.ttsmpeg2": {"source":"iana"},
  "video/vnd.motorola.video": {"source":"iana"},
  "video/vnd.motorola.videop": {"source":"iana"},
  "video/vnd.mpegurl": {"source":"iana","extensions":["mxu","m4u"]},
  "video/vnd.ms-playready.media.pyv": {"source":"iana","extensions":["pyv"]},
  "video/vnd.nokia.interleaved-multimedia": {"source":"iana"},
  "video/vnd.nokia.mp4vr": {"source":"iana"},
  "video/vnd.nokia.videovoip": {"source":"iana"},
  "video/vnd.objectvideo": {"source":"iana"},
  "video/vnd.radgamettools.bink": {"source":"iana"},
  "video/vnd.radgamettools.smacker": {"source":"iana"},
  "video/vnd.sealed.mpeg1": {"source":"iana"},
  "video/vnd.sealed.mpeg4": {"source":"iana"},
  "video/vnd.sealed.swf": {"source":"iana"},
  "video/vnd.sealedmedia.softseal.mov": {"source":"iana"},
  "video/vnd.uvvu.mp4": {"source":"iana","extensions":["uvu","uvvu"]},
  "video/vnd.vivo": {"source":"iana","extensions":["viv"]},
  "video/vnd.youtube.yt": {"source":"iana"},
  "video/vp8": {"source":"iana"},
  "video/vp9": {"source":"iana"},
  "video/webm": {"source":"apache","compressible":false,"extensions":["webm"]},
  "video/x-f4v": {"source":"apache","extensions":["f4v"]},
  "video/x-fli": {"source":"apache","extensions":["fli"]},
  "video/x-flv": {"source":"apache","compressible":false,"extensions":["flv"]},
  "video/x-m4v": {"source":"apache","extensions":["m4v"]},
  "video/x-matroska": {"source":"apache","compressible":false,"extensions":["mkv","mk3d","mks"]},
  "video/x-mng": {"source":"apache","extensions":["mng"]},
  "video/x-ms-asf": {"source":"apache","extensions":["asf","asx"]},
  "video/x-ms-vob": {"source":"apache","extensions":["vob"]},
  "video/x-ms-wm": {"source":"apache","extensions":["wm"]},
  "video/x-ms-wmv": {"source":"apache","compressible":false,"extensions":["wmv"]},
  "video/x-ms-wmx": {"source":"apache","extensions":["wmx"]},
  "video/x-ms-wvx": {"source":"apache","extensions":["wvx"]},
  "video/x-msvideo": {"source":"apache","extensions":["avi"]},
  "video/x-sgi-movie": {"source":"apache","extensions":["movie"]},
  "video/x-smv": {"source":"apache","extensions":["smv"]},
  "x-conference/x-cooltalk": {"source":"apache","extensions":["ice"]},
  "x-shader/x-fragment": {"compressible":true},
  "x-shader/x-vertex": {"compressible":true},
};

/*!
 * mime-db
 * Copyright(c) 2014 Jonathan Ong
 * Copyright(c) 2015-2022 Douglas Christopher Wilson
 * MIT Licensed
 */

var mimeDb$1;
var hasRequiredMimeDb$1;

function requireMimeDb$1 () {
	if (hasRequiredMimeDb$1) return mimeDb$1;
	hasRequiredMimeDb$1 = 1;
	/**
	 * Module exports.
	 */

	mimeDb$1 = require$$0$1;
	return mimeDb$1;
}

/*!
 * mime-types
 * Copyright(c) 2014 Jonathan Ong
 * Copyright(c) 2015 Douglas Christopher Wilson
 * MIT Licensed
 */

var hasRequiredMimeTypes;

function requireMimeTypes () {
	if (hasRequiredMimeTypes) return mimeTypes;
	hasRequiredMimeTypes = 1;
	(function (exports$1) {

		/**
		 * Module dependencies.
		 * @private
		 */

		var db = requireMimeDb$1();
		var extname = path__default.extname;

		/**
		 * Module variables.
		 * @private
		 */

		var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/;
		var TEXT_TYPE_REGEXP = /^text\//i;

		/**
		 * Module exports.
		 * @public
		 */

		exports$1.charset = charset;
		exports$1.charsets = { lookup: charset };
		exports$1.contentType = contentType;
		exports$1.extension = extension;
		exports$1.extensions = Object.create(null);
		exports$1.lookup = lookup;
		exports$1.types = Object.create(null);

		// Populate the extensions/types maps
		populateMaps(exports$1.extensions, exports$1.types);

		/**
		 * Get the default charset for a MIME type.
		 *
		 * @param {string} type
		 * @return {boolean|string}
		 */

		function charset (type) {
		  if (!type || typeof type !== 'string') {
		    return false
		  }

		  // TODO: use media-typer
		  var match = EXTRACT_TYPE_REGEXP.exec(type);
		  var mime = match && db[match[1].toLowerCase()];

		  if (mime && mime.charset) {
		    return mime.charset
		  }

		  // default text/* to utf-8
		  if (match && TEXT_TYPE_REGEXP.test(match[1])) {
		    return 'UTF-8'
		  }

		  return false
		}

		/**
		 * Create a full Content-Type header given a MIME type or extension.
		 *
		 * @param {string} str
		 * @return {boolean|string}
		 */

		function contentType (str) {
		  // TODO: should this even be in this module?
		  if (!str || typeof str !== 'string') {
		    return false
		  }

		  var mime = str.indexOf('/') === -1
		    ? exports$1.lookup(str)
		    : str;

		  if (!mime) {
		    return false
		  }

		  // TODO: use content-type or other module
		  if (mime.indexOf('charset') === -1) {
		    var charset = exports$1.charset(mime);
		    if (charset) mime += '; charset=' + charset.toLowerCase();
		  }

		  return mime
		}

		/**
		 * Get the default extension for a MIME type.
		 *
		 * @param {string} type
		 * @return {boolean|string}
		 */

		function extension (type) {
		  if (!type || typeof type !== 'string') {
		    return false
		  }

		  // TODO: use media-typer
		  var match = EXTRACT_TYPE_REGEXP.exec(type);

		  // get extensions
		  var exts = match && exports$1.extensions[match[1].toLowerCase()];

		  if (!exts || !exts.length) {
		    return false
		  }

		  return exts[0]
		}

		/**
		 * Lookup the MIME type for a file path/extension.
		 *
		 * @param {string} path
		 * @return {boolean|string}
		 */

		function lookup (path) {
		  if (!path || typeof path !== 'string') {
		    return false
		  }

		  // get the extension ("ext" or ".ext" or full path)
		  var extension = extname('x.' + path)
		    .toLowerCase()
		    .substr(1);

		  if (!extension) {
		    return false
		  }

		  return exports$1.types[extension] || false
		}

		/**
		 * Populate the extensions and types maps.
		 * @private
		 */

		function populateMaps (extensions, types) {
		  // source preference (least -> most)
		  var preference = ['nginx', 'apache', undefined, 'iana'];

		  Object.keys(db).forEach(function forEachMimeType (type) {
		    var mime = db[type];
		    var exts = mime.extensions;

		    if (!exts || !exts.length) {
		      return
		    }

		    // mime -> extensions
		    extensions[type] = exts;

		    // extension -> mime
		    for (var i = 0; i < exts.length; i++) {
		      var extension = exts[i];

		      if (types[extension]) {
		        var from = preference.indexOf(db[types[extension]].source);
		        var to = preference.indexOf(mime.source);

		        if (types[extension] !== 'application/octet-stream' &&
		          (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) {
		          // skip the remapping
		          continue
		        }
		      }

		      // set the extension -> mime
		      types[extension] = type;
		    }
		  });
		} 
	} (mimeTypes));
	return mimeTypes;
}

/*!
 * type-is
 * Copyright(c) 2014 Jonathan Ong
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
 * MIT Licensed
 */

var hasRequiredTypeIs;

function requireTypeIs () {
	if (hasRequiredTypeIs) return typeIs.exports;
	hasRequiredTypeIs = 1;

	/**
	 * Module dependencies.
	 * @private
	 */

	var typer = requireMediaTyper();
	var mime = requireMimeTypes();

	/**
	 * Module exports.
	 * @public
	 */

	typeIs.exports = typeofrequest;
	typeIs.exports.is = typeis;
	typeIs.exports.hasBody = hasbody;
	typeIs.exports.normalize = normalize;
	typeIs.exports.match = mimeMatch;

	/**
	 * Compare a `value` content-type with `types`.
	 * Each `type` can be an extension like `html`,
	 * a special shortcut like `multipart` or `urlencoded`,
	 * or a mime type.
	 *
	 * If no types match, `false` is returned.
	 * Otherwise, the first `type` that matches is returned.
	 *
	 * @param {String} value
	 * @param {Array} types
	 * @public
	 */

	function typeis (value, types_) {
	  var i;
	  var types = types_;

	  // remove parameters and normalize
	  var val = tryNormalizeType(value);

	  // no type or invalid
	  if (!val) {
	    return false
	  }

	  // support flattened arguments
	  if (types && !Array.isArray(types)) {
	    types = new Array(arguments.length - 1);
	    for (i = 0; i < types.length; i++) {
	      types[i] = arguments[i + 1];
	    }
	  }

	  // no types, return the content type
	  if (!types || !types.length) {
	    return val
	  }

	  var type;
	  for (i = 0; i < types.length; i++) {
	    if (mimeMatch(normalize(type = types[i]), val)) {
	      return type[0] === '+' || type.indexOf('*') !== -1
	        ? val
	        : type
	    }
	  }

	  // no matches
	  return false
	}

	/**
	 * Check if a request has a request body.
	 * A request with a body __must__ either have `transfer-encoding`
	 * or `content-length` headers set.
	 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3
	 *
	 * @param {Object} request
	 * @return {Boolean}
	 * @public
	 */

	function hasbody (req) {
	  return req.headers['transfer-encoding'] !== undefined ||
	    !isNaN(req.headers['content-length'])
	}

	/**
	 * Check if the incoming request contains the "Content-Type"
	 * header field, and it contains any of the give mime `type`s.
	 * If there is no request body, `null` is returned.
	 * If there is no content type, `false` is returned.
	 * Otherwise, it returns the first `type` that matches.
	 *
	 * Examples:
	 *
	 *     // With Content-Type: text/html; charset=utf-8
	 *     this.is('html'); // => 'html'
	 *     this.is('text/html'); // => 'text/html'
	 *     this.is('text/*', 'application/json'); // => 'text/html'
	 *
	 *     // When Content-Type is application/json
	 *     this.is('json', 'urlencoded'); // => 'json'
	 *     this.is('application/json'); // => 'application/json'
	 *     this.is('html', 'application/*'); // => 'application/json'
	 *
	 *     this.is('html'); // => false
	 *
	 * @param {String|Array} types...
	 * @return {String|false|null}
	 * @public
	 */

	function typeofrequest (req, types_) {
	  var types = types_;

	  // no body
	  if (!hasbody(req)) {
	    return null
	  }

	  // support flattened arguments
	  if (arguments.length > 2) {
	    types = new Array(arguments.length - 1);
	    for (var i = 0; i < types.length; i++) {
	      types[i] = arguments[i + 1];
	    }
	  }

	  // request content type
	  var value = req.headers['content-type'];

	  return typeis(value, types)
	}

	/**
	 * Normalize a mime type.
	 * If it's a shorthand, expand it to a valid mime type.
	 *
	 * In general, you probably want:
	 *
	 *   var type = is(req, ['urlencoded', 'json', 'multipart']);
	 *
	 * Then use the appropriate body parsers.
	 * These three are the most common request body types
	 * and are thus ensured to work.
	 *
	 * @param {String} type
	 * @private
	 */

	function normalize (type) {
	  if (typeof type !== 'string') {
	    // invalid type
	    return false
	  }

	  switch (type) {
	    case 'urlencoded':
	      return 'application/x-www-form-urlencoded'
	    case 'multipart':
	      return 'multipart/*'
	  }

	  if (type[0] === '+') {
	    // "+json" -> "*/*+json" expando
	    return '*/*' + type
	  }

	  return type.indexOf('/') === -1
	    ? mime.lookup(type)
	    : type
	}

	/**
	 * Check if `expected` mime type
	 * matches `actual` mime type with
	 * wildcard and +suffix support.
	 *
	 * @param {String} expected
	 * @param {String} actual
	 * @return {Boolean}
	 * @private
	 */

	function mimeMatch (expected, actual) {
	  // invalid type
	  if (expected === false) {
	    return false
	  }

	  // split types
	  var actualParts = actual.split('/');
	  var expectedParts = expected.split('/');

	  // invalid format
	  if (actualParts.length !== 2 || expectedParts.length !== 2) {
	    return false
	  }

	  // validate type
	  if (expectedParts[0] !== '*' && expectedParts[0] !== actualParts[0]) {
	    return false
	  }

	  // validate suffix wildcard
	  if (expectedParts[1].substr(0, 2) === '*+') {
	    return expectedParts[1].length <= actualParts[1].length + 1 &&
	      expectedParts[1].substr(1) === actualParts[1].substr(1 - expectedParts[1].length)
	  }

	  // validate subtype
	  if (expectedParts[1] !== '*' && expectedParts[1] !== actualParts[1]) {
	    return false
	  }

	  return true
	}

	/**
	 * Normalize a type and remove parameters.
	 *
	 * @param {string} value
	 * @return {string}
	 * @private
	 */

	function normalizeType (value) {
	  // parse the type
	  var type = typer.parse(value);

	  // remove the parameters
	  type.parameters = undefined;

	  // reformat it
	  return typer.format(type)
	}

	/**
	 * Try to normalize a type and remove parameters.
	 *
	 * @param {string} value
	 * @return {string}
	 * @private
	 */

	function tryNormalizeType (value) {
	  if (!value) {
	    return null
	  }

	  try {
	    return normalizeType(value)
	  } catch (err) {
	    return null
	  }
	}
	return typeIs.exports;
}

var utils;
var hasRequiredUtils;

function requireUtils () {
	if (hasRequiredUtils) return utils;
	hasRequiredUtils = 1;

	function parseContentType(str) {
	  if (str.length === 0)
	    return;

	  const params = Object.create(null);
	  let i = 0;

	  // Parse type
	  for (; i < str.length; ++i) {
	    const code = str.charCodeAt(i);
	    if (TOKEN[code] !== 1) {
	      if (code !== 47/* '/' */ || i === 0)
	        return;
	      break;
	    }
	  }
	  // Check for type without subtype
	  if (i === str.length)
	    return;

	  const type = str.slice(0, i).toLowerCase();

	  // Parse subtype
	  const subtypeStart = ++i;
	  for (; i < str.length; ++i) {
	    const code = str.charCodeAt(i);
	    if (TOKEN[code] !== 1) {
	      // Make sure we have a subtype
	      if (i === subtypeStart)
	        return;

	      if (parseContentTypeParams(str, i, params) === undefined)
	        return;
	      break;
	    }
	  }
	  // Make sure we have a subtype
	  if (i === subtypeStart)
	    return;

	  const subtype = str.slice(subtypeStart, i).toLowerCase();

	  return { type, subtype, params };
	}

	function parseContentTypeParams(str, i, params) {
	  while (i < str.length) {
	    // Consume whitespace
	    for (; i < str.length; ++i) {
	      const code = str.charCodeAt(i);
	      if (code !== 32/* ' ' */ && code !== 9/* '\t' */)
	        break;
	    }

	    // Ended on whitespace
	    if (i === str.length)
	      break;

	    // Check for malformed parameter
	    if (str.charCodeAt(i++) !== 59/* ';' */)
	      return;

	    // Consume whitespace
	    for (; i < str.length; ++i) {
	      const code = str.charCodeAt(i);
	      if (code !== 32/* ' ' */ && code !== 9/* '\t' */)
	        break;
	    }

	    // Ended on whitespace (malformed)
	    if (i === str.length)
	      return;

	    let name;
	    const nameStart = i;
	    // Parse parameter name
	    for (; i < str.length; ++i) {
	      const code = str.charCodeAt(i);
	      if (TOKEN[code] !== 1) {
	        if (code !== 61/* '=' */)
	          return;
	        break;
	      }
	    }

	    // No value (malformed)
	    if (i === str.length)
	      return;

	    name = str.slice(nameStart, i);
	    ++i; // Skip over '='

	    // No value (malformed)
	    if (i === str.length)
	      return;

	    let value = '';
	    let valueStart;
	    if (str.charCodeAt(i) === 34/* '"' */) {
	      valueStart = ++i;
	      let escaping = false;
	      // Parse quoted value
	      for (; i < str.length; ++i) {
	        const code = str.charCodeAt(i);
	        if (code === 92/* '\\' */) {
	          if (escaping) {
	            valueStart = i;
	            escaping = false;
	          } else {
	            value += str.slice(valueStart, i);
	            escaping = true;
	          }
	          continue;
	        }
	        if (code === 34/* '"' */) {
	          if (escaping) {
	            valueStart = i;
	            escaping = false;
	            continue;
	          }
	          value += str.slice(valueStart, i);
	          break;
	        }
	        if (escaping) {
	          valueStart = i - 1;
	          escaping = false;
	        }
	        // Invalid unescaped quoted character (malformed)
	        if (QDTEXT[code] !== 1)
	          return;
	      }

	      // No end quote (malformed)
	      if (i === str.length)
	        return;

	      ++i; // Skip over double quote
	    } else {
	      valueStart = i;
	      // Parse unquoted value
	      for (; i < str.length; ++i) {
	        const code = str.charCodeAt(i);
	        if (TOKEN[code] !== 1) {
	          // No value (malformed)
	          if (i === valueStart)
	            return;
	          break;
	        }
	      }
	      value = str.slice(valueStart, i);
	    }

	    name = name.toLowerCase();
	    if (params[name] === undefined)
	      params[name] = value;
	  }

	  return params;
	}

	function parseDisposition(str, defDecoder) {
	  if (str.length === 0)
	    return;

	  const params = Object.create(null);
	  let i = 0;

	  for (; i < str.length; ++i) {
	    const code = str.charCodeAt(i);
	    if (TOKEN[code] !== 1) {
	      if (parseDispositionParams(str, i, params, defDecoder) === undefined)
	        return;
	      break;
	    }
	  }

	  const type = str.slice(0, i).toLowerCase();

	  return { type, params };
	}

	function parseDispositionParams(str, i, params, defDecoder) {
	  while (i < str.length) {
	    // Consume whitespace
	    for (; i < str.length; ++i) {
	      const code = str.charCodeAt(i);
	      if (code !== 32/* ' ' */ && code !== 9/* '\t' */)
	        break;
	    }

	    // Ended on whitespace
	    if (i === str.length)
	      break;

	    // Check for malformed parameter
	    if (str.charCodeAt(i++) !== 59/* ';' */)
	      return;

	    // Consume whitespace
	    for (; i < str.length; ++i) {
	      const code = str.charCodeAt(i);
	      if (code !== 32/* ' ' */ && code !== 9/* '\t' */)
	        break;
	    }

	    // Ended on whitespace (malformed)
	    if (i === str.length)
	      return;

	    let name;
	    const nameStart = i;
	    // Parse parameter name
	    for (; i < str.length; ++i) {
	      const code = str.charCodeAt(i);
	      if (TOKEN[code] !== 1) {
	        if (code === 61/* '=' */)
	          break;
	        return;
	      }
	    }

	    // No value (malformed)
	    if (i === str.length)
	      return;

	    let value = '';
	    let valueStart;
	    let charset;
	    //~ let lang;
	    name = str.slice(nameStart, i);
	    if (name.charCodeAt(name.length - 1) === 42/* '*' */) {
	      // Extended value

	      const charsetStart = ++i;
	      // Parse charset name
	      for (; i < str.length; ++i) {
	        const code = str.charCodeAt(i);
	        if (CHARSET[code] !== 1) {
	          if (code !== 39/* '\'' */)
	            return;
	          break;
	        }
	      }

	      // Incomplete charset (malformed)
	      if (i === str.length)
	        return;

	      charset = str.slice(charsetStart, i);
	      ++i; // Skip over the '\''

	      //~ const langStart = ++i;
	      // Parse language name
	      for (; i < str.length; ++i) {
	        const code = str.charCodeAt(i);
	        if (code === 39/* '\'' */)
	          break;
	      }

	      // Incomplete language (malformed)
	      if (i === str.length)
	        return;

	      //~ lang = str.slice(langStart, i);
	      ++i; // Skip over the '\''

	      // No value (malformed)
	      if (i === str.length)
	        return;

	      valueStart = i;

	      let encode = 0;
	      // Parse value
	      for (; i < str.length; ++i) {
	        const code = str.charCodeAt(i);
	        if (EXTENDED_VALUE[code] !== 1) {
	          if (code === 37/* '%' */) {
	            let hexUpper;
	            let hexLower;
	            if (i + 2 < str.length
	                && (hexUpper = HEX_VALUES[str.charCodeAt(i + 1)]) !== -1
	                && (hexLower = HEX_VALUES[str.charCodeAt(i + 2)]) !== -1) {
	              const byteVal = (hexUpper << 4) + hexLower;
	              value += str.slice(valueStart, i);
	              value += String.fromCharCode(byteVal);
	              i += 2;
	              valueStart = i + 1;
	              if (byteVal >= 128)
	                encode = 2;
	              else if (encode === 0)
	                encode = 1;
	              continue;
	            }
	            // '%' disallowed in non-percent encoded contexts (malformed)
	            return;
	          }
	          break;
	        }
	      }

	      value += str.slice(valueStart, i);
	      value = convertToUTF8(value, charset, encode);
	      if (value === undefined)
	        return;
	    } else {
	      // Non-extended value

	      ++i; // Skip over '='

	      // No value (malformed)
	      if (i === str.length)
	        return;

	      if (str.charCodeAt(i) === 34/* '"' */) {
	        valueStart = ++i;
	        let escaping = false;
	        // Parse quoted value
	        for (; i < str.length; ++i) {
	          const code = str.charCodeAt(i);
	          if (code === 92/* '\\' */) {
	            if (escaping) {
	              valueStart = i;
	              escaping = false;
	            } else {
	              value += str.slice(valueStart, i);
	              escaping = true;
	            }
	            continue;
	          }
	          if (code === 34/* '"' */) {
	            if (escaping) {
	              valueStart = i;
	              escaping = false;
	              continue;
	            }
	            value += str.slice(valueStart, i);
	            break;
	          }
	          if (escaping) {
	            valueStart = i - 1;
	            escaping = false;
	          }
	          // Invalid unescaped quoted character (malformed)
	          if (QDTEXT[code] !== 1)
	            return;
	        }

	        // No end quote (malformed)
	        if (i === str.length)
	          return;

	        ++i; // Skip over double quote
	      } else {
	        valueStart = i;
	        // Parse unquoted value
	        for (; i < str.length; ++i) {
	          const code = str.charCodeAt(i);
	          if (TOKEN[code] !== 1) {
	            // No value (malformed)
	            if (i === valueStart)
	              return;
	            break;
	          }
	        }
	        value = str.slice(valueStart, i);
	      }

	      value = defDecoder(value, 2);
	      if (value === undefined)
	        return;
	    }

	    name = name.toLowerCase();
	    if (params[name] === undefined)
	      params[name] = value;
	  }

	  return params;
	}

	function getDecoder(charset) {
	  let lc;
	  while (true) {
	    switch (charset) {
	      case 'utf-8':
	      case 'utf8':
	        return decoders.utf8;
	      case 'latin1':
	      case 'ascii': // TODO: Make these a separate, strict decoder?
	      case 'us-ascii':
	      case 'iso-8859-1':
	      case 'iso8859-1':
	      case 'iso88591':
	      case 'iso_8859-1':
	      case 'windows-1252':
	      case 'iso_8859-1:1987':
	      case 'cp1252':
	      case 'x-cp1252':
	        return decoders.latin1;
	      case 'utf16le':
	      case 'utf-16le':
	      case 'ucs2':
	      case 'ucs-2':
	        return decoders.utf16le;
	      case 'base64':
	        return decoders.base64;
	      default:
	        if (lc === undefined) {
	          lc = true;
	          charset = charset.toLowerCase();
	          continue;
	        }
	        return decoders.other.bind(charset);
	    }
	  }
	}

	const decoders = {
	  utf8: (data, hint) => {
	    if (data.length === 0)
	      return '';
	    if (typeof data === 'string') {
	      // If `data` never had any percent-encoded bytes or never had any that
	      // were outside of the ASCII range, then we can safely just return the
	      // input since UTF-8 is ASCII compatible
	      if (hint < 2)
	        return data;

	      data = Buffer.from(data, 'latin1');
	    }
	    return data.utf8Slice(0, data.length);
	  },

	  latin1: (data, hint) => {
	    if (data.length === 0)
	      return '';
	    if (typeof data === 'string')
	      return data;
	    return data.latin1Slice(0, data.length);
	  },

	  utf16le: (data, hint) => {
	    if (data.length === 0)
	      return '';
	    if (typeof data === 'string')
	      data = Buffer.from(data, 'latin1');
	    return data.ucs2Slice(0, data.length);
	  },

	  base64: (data, hint) => {
	    if (data.length === 0)
	      return '';
	    if (typeof data === 'string')
	      data = Buffer.from(data, 'latin1');
	    return data.base64Slice(0, data.length);
	  },

	  other: (data, hint) => {
	    if (data.length === 0)
	      return '';
	    if (typeof data === 'string')
	      data = Buffer.from(data, 'latin1');
	    try {
	      const decoder = new TextDecoder(this);
	      return decoder.decode(data);
	    } catch {}
	  },
	};

	function convertToUTF8(data, charset, hint) {
	  const decode = getDecoder(charset);
	  if (decode)
	    return decode(data, hint);
	}

	function basename(path) {
	  if (typeof path !== 'string')
	    return '';
	  for (let i = path.length - 1; i >= 0; --i) {
	    switch (path.charCodeAt(i)) {
	      case 0x2F: // '/'
	      case 0x5C: // '\'
	        path = path.slice(i + 1);
	        return (path === '..' || path === '.' ? '' : path);
	    }
	  }
	  return (path === '..' || path === '.' ? '' : path);
	}

	const TOKEN = [
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
	  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	];

	const QDTEXT = [
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	];

	const CHARSET = [
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
	  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	];

	const EXTENDED_VALUE = [
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
	  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	];

	/* eslint-disable no-multi-spaces */
	const HEX_VALUES = [
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	   0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
	  -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	];
	/* eslint-enable no-multi-spaces */

	utils = {
	  basename,
	  convertToUTF8,
	  getDecoder,
	  parseContentType,
	  parseDisposition,
	};
	return utils;
}

var sbmh;
var hasRequiredSbmh;

function requireSbmh () {
	if (hasRequiredSbmh) return sbmh;
	hasRequiredSbmh = 1;
	/*
	  Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation
	  by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool
	*/
	function memcmp(buf1, pos1, buf2, pos2, num) {
	  for (let i = 0; i < num; ++i) {
	    if (buf1[pos1 + i] !== buf2[pos2 + i])
	      return false;
	  }
	  return true;
	}

	class SBMH {
	  constructor(needle, cb) {
	    if (typeof cb !== 'function')
	      throw new Error('Missing match callback');

	    if (typeof needle === 'string')
	      needle = Buffer.from(needle);
	    else if (!Buffer.isBuffer(needle))
	      throw new Error(`Expected Buffer for needle, got ${typeof needle}`);

	    const needleLen = needle.length;

	    this.maxMatches = Infinity;
	    this.matches = 0;

	    this._cb = cb;
	    this._lookbehindSize = 0;
	    this._needle = needle;
	    this._bufPos = 0;

	    this._lookbehind = Buffer.allocUnsafe(needleLen);

	    // Initialize occurrence table.
	    this._occ = [
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen, needleLen, needleLen,
	      needleLen, needleLen, needleLen, needleLen
	    ];

	    // Populate occurrence table with analysis of the needle, ignoring the last
	    // letter.
	    if (needleLen > 1) {
	      for (let i = 0; i < needleLen - 1; ++i)
	        this._occ[needle[i]] = needleLen - 1 - i;
	    }
	  }

	  reset() {
	    this.matches = 0;
	    this._lookbehindSize = 0;
	    this._bufPos = 0;
	  }

	  push(chunk, pos) {
	    let result;
	    if (!Buffer.isBuffer(chunk))
	      chunk = Buffer.from(chunk, 'latin1');
	    const chunkLen = chunk.length;
	    this._bufPos = pos || 0;
	    while (result !== chunkLen && this.matches < this.maxMatches)
	      result = feed(this, chunk);
	    return result;
	  }

	  destroy() {
	    const lbSize = this._lookbehindSize;
	    if (lbSize)
	      this._cb(false, this._lookbehind, 0, lbSize, false);
	    this.reset();
	  }
	}

	function feed(self, data) {
	  const len = data.length;
	  const needle = self._needle;
	  const needleLen = needle.length;

	  // Positive: points to a position in `data`
	  //           pos == 3 points to data[3]
	  // Negative: points to a position in the lookbehind buffer
	  //           pos == -2 points to lookbehind[lookbehindSize - 2]
	  let pos = -self._lookbehindSize;
	  const lastNeedleCharPos = needleLen - 1;
	  const lastNeedleChar = needle[lastNeedleCharPos];
	  const end = len - needleLen;
	  const occ = self._occ;
	  const lookbehind = self._lookbehind;

	  if (pos < 0) {
	    // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool
	    // search with character lookup code that considers both the
	    // lookbehind buffer and the current round's haystack data.
	    //
	    // Loop until
	    //   there is a match.
	    // or until
	    //   we've moved past the position that requires the
	    //   lookbehind buffer. In this case we switch to the
	    //   optimized loop.
	    // or until
	    //   the character to look at lies outside the haystack.
	    while (pos < 0 && pos <= end) {
	      const nextPos = pos + lastNeedleCharPos;
	      const ch = (nextPos < 0
	                  ? lookbehind[self._lookbehindSize + nextPos]
	                  : data[nextPos]);

	      if (ch === lastNeedleChar
	          && matchNeedle(self, data, pos, lastNeedleCharPos)) {
	        self._lookbehindSize = 0;
	        ++self.matches;
	        if (pos > -self._lookbehindSize)
	          self._cb(true, lookbehind, 0, self._lookbehindSize + pos, false);
	        else
	          self._cb(true, undefined, 0, 0, true);

	        return (self._bufPos = pos + needleLen);
	      }

	      pos += occ[ch];
	    }

	    // No match.

	    // There's too few data for Boyer-Moore-Horspool to run,
	    // so let's use a different algorithm to skip as much as
	    // we can.
	    // Forward pos until
	    //   the trailing part of lookbehind + data
	    //   looks like the beginning of the needle
	    // or until
	    //   pos == 0
	    while (pos < 0 && !matchNeedle(self, data, pos, len - pos))
	      ++pos;

	    if (pos < 0) {
	      // Cut off part of the lookbehind buffer that has
	      // been processed and append the entire haystack
	      // into it.
	      const bytesToCutOff = self._lookbehindSize + pos;

	      if (bytesToCutOff > 0) {
	        // The cut off data is guaranteed not to contain the needle.
	        self._cb(false, lookbehind, 0, bytesToCutOff, false);
	      }

	      self._lookbehindSize -= bytesToCutOff;
	      lookbehind.copy(lookbehind, 0, bytesToCutOff, self._lookbehindSize);
	      lookbehind.set(data, self._lookbehindSize);
	      self._lookbehindSize += len;

	      self._bufPos = len;
	      return len;
	    }

	    // Discard lookbehind buffer.
	    self._cb(false, lookbehind, 0, self._lookbehindSize, false);
	    self._lookbehindSize = 0;
	  }

	  pos += self._bufPos;

	  const firstNeedleChar = needle[0];

	  // Lookbehind buffer is now empty. Perform Boyer-Moore-Horspool
	  // search with optimized character lookup code that only considers
	  // the current round's haystack data.
	  while (pos <= end) {
	    const ch = data[pos + lastNeedleCharPos];

	    if (ch === lastNeedleChar
	        && data[pos] === firstNeedleChar
	        && memcmp(needle, 0, data, pos, lastNeedleCharPos)) {
	      ++self.matches;
	      if (pos > 0)
	        self._cb(true, data, self._bufPos, pos, true);
	      else
	        self._cb(true, undefined, 0, 0, true);

	      return (self._bufPos = pos + needleLen);
	    }

	    pos += occ[ch];
	  }

	  // There was no match. If there's trailing haystack data that we cannot
	  // match yet using the Boyer-Moore-Horspool algorithm (because the trailing
	  // data is less than the needle size) then match using a modified
	  // algorithm that starts matching from the beginning instead of the end.
	  // Whatever trailing data is left after running this algorithm is added to
	  // the lookbehind buffer.
	  while (pos < len) {
	    if (data[pos] !== firstNeedleChar
	        || !memcmp(data, pos, needle, 0, len - pos)) {
	      ++pos;
	      continue;
	    }
	    data.copy(lookbehind, 0, pos, len);
	    self._lookbehindSize = len - pos;
	    break;
	  }

	  // Everything until `pos` is guaranteed not to contain needle data.
	  if (pos > 0)
	    self._cb(false, data, self._bufPos, pos < len ? pos : len, true);

	  self._bufPos = len;
	  return len;
	}

	function matchNeedle(self, data, pos, len) {
	  const lb = self._lookbehind;
	  const lbSize = self._lookbehindSize;
	  const needle = self._needle;

	  for (let i = 0; i < len; ++i, ++pos) {
	    const ch = (pos < 0 ? lb[lbSize + pos] : data[pos]);
	    if (ch !== needle[i])
	      return false;
	  }
	  return true;
	}

	sbmh = SBMH;
	return sbmh;
}

var multipart;
var hasRequiredMultipart;

function requireMultipart () {
	if (hasRequiredMultipart) return multipart;
	hasRequiredMultipart = 1;

	const { Readable, Writable } = require$$1$1;

	const StreamSearch = requireSbmh();

	const {
	  basename,
	  convertToUTF8,
	  getDecoder,
	  parseContentType,
	  parseDisposition,
	} = requireUtils();

	const BUF_CRLF = Buffer.from('\r\n');
	const BUF_CR = Buffer.from('\r');
	const BUF_DASH = Buffer.from('-');

	function noop() {}

	const MAX_HEADER_PAIRS = 2000; // From node
	const MAX_HEADER_SIZE = 16 * 1024; // From node (its default value)

	const HPARSER_NAME = 0;
	const HPARSER_PRE_OWS = 1;
	const HPARSER_VALUE = 2;
	class HeaderParser {
	  constructor(cb) {
	    this.header = Object.create(null);
	    this.pairCount = 0;
	    this.byteCount = 0;
	    this.state = HPARSER_NAME;
	    this.name = '';
	    this.value = '';
	    this.crlf = 0;
	    this.cb = cb;
	  }

	  reset() {
	    this.header = Object.create(null);
	    this.pairCount = 0;
	    this.byteCount = 0;
	    this.state = HPARSER_NAME;
	    this.name = '';
	    this.value = '';
	    this.crlf = 0;
	  }

	  push(chunk, pos, end) {
	    let start = pos;
	    while (pos < end) {
	      switch (this.state) {
	        case HPARSER_NAME: {
	          let done = false;
	          for (; pos < end; ++pos) {
	            if (this.byteCount === MAX_HEADER_SIZE)
	              return -1;
	            ++this.byteCount;
	            const code = chunk[pos];
	            if (TOKEN[code] !== 1) {
	              if (code !== 58/* ':' */)
	                return -1;
	              this.name += chunk.latin1Slice(start, pos);
	              if (this.name.length === 0)
	                return -1;
	              ++pos;
	              done = true;
	              this.state = HPARSER_PRE_OWS;
	              break;
	            }
	          }
	          if (!done) {
	            this.name += chunk.latin1Slice(start, pos);
	            break;
	          }
	          // FALLTHROUGH
	        }
	        case HPARSER_PRE_OWS: {
	          // Skip optional whitespace
	          let done = false;
	          for (; pos < end; ++pos) {
	            if (this.byteCount === MAX_HEADER_SIZE)
	              return -1;
	            ++this.byteCount;
	            const code = chunk[pos];
	            if (code !== 32/* ' ' */ && code !== 9/* '\t' */) {
	              start = pos;
	              done = true;
	              this.state = HPARSER_VALUE;
	              break;
	            }
	          }
	          if (!done)
	            break;
	          // FALLTHROUGH
	        }
	        case HPARSER_VALUE:
	          switch (this.crlf) {
	            case 0: // Nothing yet
	              for (; pos < end; ++pos) {
	                if (this.byteCount === MAX_HEADER_SIZE)
	                  return -1;
	                ++this.byteCount;
	                const code = chunk[pos];
	                if (FIELD_VCHAR[code] !== 1) {
	                  if (code !== 13/* '\r' */)
	                    return -1;
	                  ++this.crlf;
	                  break;
	                }
	              }
	              this.value += chunk.latin1Slice(start, pos++);
	              break;
	            case 1: // Received CR
	              if (this.byteCount === MAX_HEADER_SIZE)
	                return -1;
	              ++this.byteCount;
	              if (chunk[pos++] !== 10/* '\n' */)
	                return -1;
	              ++this.crlf;
	              break;
	            case 2: { // Received CR LF
	              if (this.byteCount === MAX_HEADER_SIZE)
	                return -1;
	              ++this.byteCount;
	              const code = chunk[pos];
	              if (code === 32/* ' ' */ || code === 9/* '\t' */) {
	                // Folded value
	                start = pos;
	                this.crlf = 0;
	              } else {
	                if (++this.pairCount < MAX_HEADER_PAIRS) {
	                  this.name = this.name.toLowerCase();
	                  if (this.header[this.name] === undefined)
	                    this.header[this.name] = [this.value];
	                  else
	                    this.header[this.name].push(this.value);
	                }
	                if (code === 13/* '\r' */) {
	                  ++this.crlf;
	                  ++pos;
	                } else {
	                  // Assume start of next header field name
	                  start = pos;
	                  this.crlf = 0;
	                  this.state = HPARSER_NAME;
	                  this.name = '';
	                  this.value = '';
	                }
	              }
	              break;
	            }
	            case 3: { // Received CR LF CR
	              if (this.byteCount === MAX_HEADER_SIZE)
	                return -1;
	              ++this.byteCount;
	              if (chunk[pos++] !== 10/* '\n' */)
	                return -1;
	              // End of header
	              const header = this.header;
	              this.reset();
	              this.cb(header);
	              return pos;
	            }
	          }
	          break;
	      }
	    }

	    return pos;
	  }
	}

	class FileStream extends Readable {
	  constructor(opts, owner) {
	    super(opts);
	    this.truncated = false;
	    this._readcb = null;
	    this.once('end', () => {
	      // We need to make sure that we call any outstanding _writecb() that is
	      // associated with this file so that processing of the rest of the form
	      // can continue. This may not happen if the file stream ends right after
	      // backpressure kicks in, so we force it here.
	      this._read();
	      if (--owner._fileEndsLeft === 0 && owner._finalcb) {
	        const cb = owner._finalcb;
	        owner._finalcb = null;
	        // Make sure other 'end' event handlers get a chance to be executed
	        // before busboy's 'finish' event is emitted
	        process.nextTick(cb);
	      }
	    });
	  }
	  _read(n) {
	    const cb = this._readcb;
	    if (cb) {
	      this._readcb = null;
	      cb();
	    }
	  }
	}

	const ignoreData = {
	  push: (chunk, pos) => {},
	  destroy: () => {},
	};

	function callAndUnsetCb(self, err) {
	  const cb = self._writecb;
	  self._writecb = null;
	  if (cb)
	    cb();
	}

	function nullDecoder(val, hint) {
	  return val;
	}

	class Multipart extends Writable {
	  constructor(cfg) {
	    const streamOpts = {
	      autoDestroy: true,
	      emitClose: true,
	      highWaterMark: (typeof cfg.highWaterMark === 'number'
	                      ? cfg.highWaterMark
	                      : undefined),
	    };
	    super(streamOpts);

	    if (!cfg.conType.params || typeof cfg.conType.params.boundary !== 'string')
	      throw new Error('Multipart: Boundary not found');

	    const boundary = cfg.conType.params.boundary;
	    const paramDecoder = (typeof cfg.defParamCharset === 'string'
	                            && cfg.defParamCharset
	                          ? getDecoder(cfg.defParamCharset)
	                          : nullDecoder);
	    const defCharset = (cfg.defCharset || 'utf8');
	    const preservePath = cfg.preservePath;
	    const fileOpts = {
	      autoDestroy: true,
	      emitClose: true,
	      highWaterMark: (typeof cfg.fileHwm === 'number'
	                      ? cfg.fileHwm
	                      : undefined),
	    };

	    const limits = cfg.limits;
	    const fieldSizeLimit = (limits && typeof limits.fieldSize === 'number'
	                            ? limits.fieldSize
	                            : 1 * 1024 * 1024);
	    const fileSizeLimit = (limits && typeof limits.fileSize === 'number'
	                           ? limits.fileSize
	                           : Infinity);
	    const filesLimit = (limits && typeof limits.files === 'number'
	                        ? limits.files
	                        : Infinity);
	    const fieldsLimit = (limits && typeof limits.fields === 'number'
	                         ? limits.fields
	                         : Infinity);
	    const partsLimit = (limits && typeof limits.parts === 'number'
	                        ? limits.parts
	                        : Infinity);

	    let parts = -1; // Account for initial boundary
	    let fields = 0;
	    let files = 0;
	    let skipPart = false;

	    this._fileEndsLeft = 0;
	    this._fileStream = undefined;
	    this._complete = false;
	    let fileSize = 0;

	    let field;
	    let fieldSize = 0;
	    let partCharset;
	    let partEncoding;
	    let partType;
	    let partName;
	    let partTruncated = false;

	    let hitFilesLimit = false;
	    let hitFieldsLimit = false;

	    this._hparser = null;
	    const hparser = new HeaderParser((header) => {
	      this._hparser = null;
	      skipPart = false;

	      partType = 'text/plain';
	      partCharset = defCharset;
	      partEncoding = '7bit';
	      partName = undefined;
	      partTruncated = false;

	      let filename;
	      if (!header['content-disposition']) {
	        skipPart = true;
	        return;
	      }

	      const disp = parseDisposition(header['content-disposition'][0],
	                                    paramDecoder);
	      if (!disp || disp.type !== 'form-data') {
	        skipPart = true;
	        return;
	      }

	      if (disp.params) {
	        if (disp.params.name)
	          partName = disp.params.name;

	        if (disp.params['filename*'])
	          filename = disp.params['filename*'];
	        else if (disp.params.filename)
	          filename = disp.params.filename;

	        if (filename !== undefined && !preservePath)
	          filename = basename(filename);
	      }

	      if (header['content-type']) {
	        const conType = parseContentType(header['content-type'][0]);
	        if (conType) {
	          partType = `${conType.type}/${conType.subtype}`;
	          if (conType.params && typeof conType.params.charset === 'string')
	            partCharset = conType.params.charset.toLowerCase();
	        }
	      }

	      if (header['content-transfer-encoding'])
	        partEncoding = header['content-transfer-encoding'][0].toLowerCase();

	      if (partType === 'application/octet-stream' || filename !== undefined) {
	        // File

	        if (files === filesLimit) {
	          if (!hitFilesLimit) {
	            hitFilesLimit = true;
	            this.emit('filesLimit');
	          }
	          skipPart = true;
	          return;
	        }
	        ++files;

	        if (this.listenerCount('file') === 0) {
	          skipPart = true;
	          return;
	        }

	        fileSize = 0;
	        this._fileStream = new FileStream(fileOpts, this);
	        ++this._fileEndsLeft;
	        this.emit(
	          'file',
	          partName,
	          this._fileStream,
	          { filename,
	            encoding: partEncoding,
	            mimeType: partType }
	        );
	      } else {
	        // Non-file

	        if (fields === fieldsLimit) {
	          if (!hitFieldsLimit) {
	            hitFieldsLimit = true;
	            this.emit('fieldsLimit');
	          }
	          skipPart = true;
	          return;
	        }
	        ++fields;

	        if (this.listenerCount('field') === 0) {
	          skipPart = true;
	          return;
	        }

	        field = [];
	        fieldSize = 0;
	      }
	    });

	    let matchPostBoundary = 0;
	    const ssCb = (isMatch, data, start, end, isDataSafe) => {
	retrydata:
	      while (data) {
	        if (this._hparser !== null) {
	          const ret = this._hparser.push(data, start, end);
	          if (ret === -1) {
	            this._hparser = null;
	            hparser.reset();
	            this.emit('error', new Error('Malformed part header'));
	            break;
	          }
	          start = ret;
	        }

	        if (start === end)
	          break;

	        if (matchPostBoundary !== 0) {
	          if (matchPostBoundary === 1) {
	            switch (data[start]) {
	              case 45: // '-'
	                // Try matching '--' after boundary
	                matchPostBoundary = 2;
	                ++start;
	                break;
	              case 13: // '\r'
	                // Try matching CR LF before header
	                matchPostBoundary = 3;
	                ++start;
	                break;
	              default:
	                matchPostBoundary = 0;
	            }
	            if (start === end)
	              return;
	          }

	          if (matchPostBoundary === 2) {
	            matchPostBoundary = 0;
	            if (data[start] === 45/* '-' */) {
	              // End of multipart data
	              this._complete = true;
	              this._bparser = ignoreData;
	              return;
	            }
	            // We saw something other than '-', so put the dash we consumed
	            // "back"
	            const writecb = this._writecb;
	            this._writecb = noop;
	            ssCb(false, BUF_DASH, 0, 1, false);
	            this._writecb = writecb;
	          } else if (matchPostBoundary === 3) {
	            matchPostBoundary = 0;
	            if (data[start] === 10/* '\n' */) {
	              ++start;
	              if (parts >= partsLimit)
	                break;
	              // Prepare the header parser
	              this._hparser = hparser;
	              if (start === end)
	                break;
	              // Process the remaining data as a header
	              continue retrydata;
	            } else {
	              // We saw something other than LF, so put the CR we consumed
	              // "back"
	              const writecb = this._writecb;
	              this._writecb = noop;
	              ssCb(false, BUF_CR, 0, 1, false);
	              this._writecb = writecb;
	            }
	          }
	        }

	        if (!skipPart) {
	          if (this._fileStream) {
	            let chunk;
	            const actualLen = Math.min(end - start, fileSizeLimit - fileSize);
	            if (!isDataSafe) {
	              chunk = Buffer.allocUnsafe(actualLen);
	              data.copy(chunk, 0, start, start + actualLen);
	            } else {
	              chunk = data.slice(start, start + actualLen);
	            }

	            fileSize += chunk.length;
	            if (fileSize === fileSizeLimit) {
	              if (chunk.length > 0)
	                this._fileStream.push(chunk);
	              this._fileStream.emit('limit');
	              this._fileStream.truncated = true;
	              skipPart = true;
	            } else if (!this._fileStream.push(chunk)) {
	              if (this._writecb)
	                this._fileStream._readcb = this._writecb;
	              this._writecb = null;
	            }
	          } else if (field !== undefined) {
	            let chunk;
	            const actualLen = Math.min(
	              end - start,
	              fieldSizeLimit - fieldSize
	            );
	            if (!isDataSafe) {
	              chunk = Buffer.allocUnsafe(actualLen);
	              data.copy(chunk, 0, start, start + actualLen);
	            } else {
	              chunk = data.slice(start, start + actualLen);
	            }

	            fieldSize += actualLen;
	            field.push(chunk);
	            if (fieldSize === fieldSizeLimit) {
	              skipPart = true;
	              partTruncated = true;
	            }
	          }
	        }

	        break;
	      }

	      if (isMatch) {
	        matchPostBoundary = 1;

	        if (this._fileStream) {
	          // End the active file stream if the previous part was a file
	          this._fileStream.push(null);
	          this._fileStream = null;
	        } else if (field !== undefined) {
	          let data;
	          switch (field.length) {
	            case 0:
	              data = '';
	              break;
	            case 1:
	              data = convertToUTF8(field[0], partCharset, 0);
	              break;
	            default:
	              data = convertToUTF8(
	                Buffer.concat(field, fieldSize),
	                partCharset,
	                0
	              );
	          }
	          field = undefined;
	          fieldSize = 0;
	          this.emit(
	            'field',
	            partName,
	            data,
	            { nameTruncated: false,
	              valueTruncated: partTruncated,
	              encoding: partEncoding,
	              mimeType: partType }
	          );
	        }

	        if (++parts === partsLimit)
	          this.emit('partsLimit');
	      }
	    };
	    this._bparser = new StreamSearch(`\r\n--${boundary}`, ssCb);

	    this._writecb = null;
	    this._finalcb = null;

	    // Just in case there is no preamble
	    this.write(BUF_CRLF);
	  }

	  static detect(conType) {
	    return (conType.type === 'multipart' && conType.subtype === 'form-data');
	  }

	  _write(chunk, enc, cb) {
	    this._writecb = cb;
	    this._bparser.push(chunk, 0);
	    if (this._writecb)
	      callAndUnsetCb(this);
	  }

	  _destroy(err, cb) {
	    this._hparser = null;
	    this._bparser = ignoreData;
	    if (!err)
	      err = checkEndState(this);
	    const fileStream = this._fileStream;
	    if (fileStream) {
	      this._fileStream = null;
	      fileStream.destroy(err);
	    }
	    cb(err);
	  }

	  _final(cb) {
	    this._bparser.destroy();
	    if (!this._complete)
	      return cb(new Error('Unexpected end of form'));
	    if (this._fileEndsLeft)
	      this._finalcb = finalcb.bind(null, this, cb);
	    else
	      finalcb(this, cb);
	  }
	}

	function finalcb(self, cb, err) {
	  if (err)
	    return cb(err);
	  err = checkEndState(self);
	  cb(err);
	}

	function checkEndState(self) {
	  if (self._hparser)
	    return new Error('Malformed part header');
	  const fileStream = self._fileStream;
	  if (fileStream) {
	    self._fileStream = null;
	    fileStream.destroy(new Error('Unexpected end of file'));
	  }
	  if (!self._complete)
	    return new Error('Unexpected end of form');
	}

	const TOKEN = [
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
	  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	];

	const FIELD_VCHAR = [
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	];

	multipart = Multipart;
	return multipart;
}

var urlencoded;
var hasRequiredUrlencoded;

function requireUrlencoded () {
	if (hasRequiredUrlencoded) return urlencoded;
	hasRequiredUrlencoded = 1;

	const { Writable } = require$$1$1;

	const { getDecoder } = requireUtils();

	class URLEncoded extends Writable {
	  constructor(cfg) {
	    const streamOpts = {
	      autoDestroy: true,
	      emitClose: true,
	      highWaterMark: (typeof cfg.highWaterMark === 'number'
	                      ? cfg.highWaterMark
	                      : undefined),
	    };
	    super(streamOpts);

	    let charset = (cfg.defCharset || 'utf8');
	    if (cfg.conType.params && typeof cfg.conType.params.charset === 'string')
	      charset = cfg.conType.params.charset;

	    this.charset = charset;

	    const limits = cfg.limits;
	    this.fieldSizeLimit = (limits && typeof limits.fieldSize === 'number'
	                           ? limits.fieldSize
	                           : 1 * 1024 * 1024);
	    this.fieldsLimit = (limits && typeof limits.fields === 'number'
	                        ? limits.fields
	                        : Infinity);
	    this.fieldNameSizeLimit = (
	      limits && typeof limits.fieldNameSize === 'number'
	      ? limits.fieldNameSize
	      : 100
	    );

	    this._inKey = true;
	    this._keyTrunc = false;
	    this._valTrunc = false;
	    this._bytesKey = 0;
	    this._bytesVal = 0;
	    this._fields = 0;
	    this._key = '';
	    this._val = '';
	    this._byte = -2;
	    this._lastPos = 0;
	    this._encode = 0;
	    this._decoder = getDecoder(charset);
	  }

	  static detect(conType) {
	    return (conType.type === 'application'
	            && conType.subtype === 'x-www-form-urlencoded');
	  }

	  _write(chunk, enc, cb) {
	    if (this._fields >= this.fieldsLimit)
	      return cb();

	    let i = 0;
	    const len = chunk.length;
	    this._lastPos = 0;

	    // Check if we last ended mid-percent-encoded byte
	    if (this._byte !== -2) {
	      i = readPctEnc(this, chunk, i, len);
	      if (i === -1)
	        return cb(new Error('Malformed urlencoded form'));
	      if (i >= len)
	        return cb();
	      if (this._inKey)
	        ++this._bytesKey;
	      else
	        ++this._bytesVal;
	    }

	main:
	    while (i < len) {
	      if (this._inKey) {
	        // Parsing key

	        i = skipKeyBytes(this, chunk, i, len);

	        while (i < len) {
	          switch (chunk[i]) {
	            case 61: // '='
	              if (this._lastPos < i)
	                this._key += chunk.latin1Slice(this._lastPos, i);
	              this._lastPos = ++i;
	              this._key = this._decoder(this._key, this._encode);
	              this._encode = 0;
	              this._inKey = false;
	              continue main;
	            case 38: // '&'
	              if (this._lastPos < i)
	                this._key += chunk.latin1Slice(this._lastPos, i);
	              this._lastPos = ++i;
	              this._key = this._decoder(this._key, this._encode);
	              this._encode = 0;
	              if (this._bytesKey > 0) {
	                this.emit(
	                  'field',
	                  this._key,
	                  '',
	                  { nameTruncated: this._keyTrunc,
	                    valueTruncated: false,
	                    encoding: this.charset,
	                    mimeType: 'text/plain' }
	                );
	              }
	              this._key = '';
	              this._val = '';
	              this._keyTrunc = false;
	              this._valTrunc = false;
	              this._bytesKey = 0;
	              this._bytesVal = 0;
	              if (++this._fields >= this.fieldsLimit) {
	                this.emit('fieldsLimit');
	                return cb();
	              }
	              continue;
	            case 43: // '+'
	              if (this._lastPos < i)
	                this._key += chunk.latin1Slice(this._lastPos, i);
	              this._key += ' ';
	              this._lastPos = i + 1;
	              break;
	            case 37: // '%'
	              if (this._encode === 0)
	                this._encode = 1;
	              if (this._lastPos < i)
	                this._key += chunk.latin1Slice(this._lastPos, i);
	              this._lastPos = i + 1;
	              this._byte = -1;
	              i = readPctEnc(this, chunk, i + 1, len);
	              if (i === -1)
	                return cb(new Error('Malformed urlencoded form'));
	              if (i >= len)
	                return cb();
	              ++this._bytesKey;
	              i = skipKeyBytes(this, chunk, i, len);
	              continue;
	          }
	          ++i;
	          ++this._bytesKey;
	          i = skipKeyBytes(this, chunk, i, len);
	        }
	        if (this._lastPos < i)
	          this._key += chunk.latin1Slice(this._lastPos, i);
	      } else {
	        // Parsing value

	        i = skipValBytes(this, chunk, i, len);

	        while (i < len) {
	          switch (chunk[i]) {
	            case 38: // '&'
	              if (this._lastPos < i)
	                this._val += chunk.latin1Slice(this._lastPos, i);
	              this._lastPos = ++i;
	              this._inKey = true;
	              this._val = this._decoder(this._val, this._encode);
	              this._encode = 0;
	              if (this._bytesKey > 0 || this._bytesVal > 0) {
	                this.emit(
	                  'field',
	                  this._key,
	                  this._val,
	                  { nameTruncated: this._keyTrunc,
	                    valueTruncated: this._valTrunc,
	                    encoding: this.charset,
	                    mimeType: 'text/plain' }
	                );
	              }
	              this._key = '';
	              this._val = '';
	              this._keyTrunc = false;
	              this._valTrunc = false;
	              this._bytesKey = 0;
	              this._bytesVal = 0;
	              if (++this._fields >= this.fieldsLimit) {
	                this.emit('fieldsLimit');
	                return cb();
	              }
	              continue main;
	            case 43: // '+'
	              if (this._lastPos < i)
	                this._val += chunk.latin1Slice(this._lastPos, i);
	              this._val += ' ';
	              this._lastPos = i + 1;
	              break;
	            case 37: // '%'
	              if (this._encode === 0)
	                this._encode = 1;
	              if (this._lastPos < i)
	                this._val += chunk.latin1Slice(this._lastPos, i);
	              this._lastPos = i + 1;
	              this._byte = -1;
	              i = readPctEnc(this, chunk, i + 1, len);
	              if (i === -1)
	                return cb(new Error('Malformed urlencoded form'));
	              if (i >= len)
	                return cb();
	              ++this._bytesVal;
	              i = skipValBytes(this, chunk, i, len);
	              continue;
	          }
	          ++i;
	          ++this._bytesVal;
	          i = skipValBytes(this, chunk, i, len);
	        }
	        if (this._lastPos < i)
	          this._val += chunk.latin1Slice(this._lastPos, i);
	      }
	    }

	    cb();
	  }

	  _final(cb) {
	    if (this._byte !== -2)
	      return cb(new Error('Malformed urlencoded form'));
	    if (!this._inKey || this._bytesKey > 0 || this._bytesVal > 0) {
	      if (this._inKey)
	        this._key = this._decoder(this._key, this._encode);
	      else
	        this._val = this._decoder(this._val, this._encode);
	      this.emit(
	        'field',
	        this._key,
	        this._val,
	        { nameTruncated: this._keyTrunc,
	          valueTruncated: this._valTrunc,
	          encoding: this.charset,
	          mimeType: 'text/plain' }
	      );
	    }
	    cb();
	  }
	}

	function readPctEnc(self, chunk, pos, len) {
	  if (pos >= len)
	    return len;

	  if (self._byte === -1) {
	    // We saw a '%' but no hex characters yet
	    const hexUpper = HEX_VALUES[chunk[pos++]];
	    if (hexUpper === -1)
	      return -1;

	    if (hexUpper >= 8)
	      self._encode = 2; // Indicate high bits detected

	    if (pos < len) {
	      // Both hex characters are in this chunk
	      const hexLower = HEX_VALUES[chunk[pos++]];
	      if (hexLower === -1)
	        return -1;

	      if (self._inKey)
	        self._key += String.fromCharCode((hexUpper << 4) + hexLower);
	      else
	        self._val += String.fromCharCode((hexUpper << 4) + hexLower);

	      self._byte = -2;
	      self._lastPos = pos;
	    } else {
	      // Only one hex character was available in this chunk
	      self._byte = hexUpper;
	    }
	  } else {
	    // We saw only one hex character so far
	    const hexLower = HEX_VALUES[chunk[pos++]];
	    if (hexLower === -1)
	      return -1;

	    if (self._inKey)
	      self._key += String.fromCharCode((self._byte << 4) + hexLower);
	    else
	      self._val += String.fromCharCode((self._byte << 4) + hexLower);

	    self._byte = -2;
	    self._lastPos = pos;
	  }

	  return pos;
	}

	function skipKeyBytes(self, chunk, pos, len) {
	  // Skip bytes if we've truncated
	  if (self._bytesKey > self.fieldNameSizeLimit) {
	    if (!self._keyTrunc) {
	      if (self._lastPos < pos)
	        self._key += chunk.latin1Slice(self._lastPos, pos - 1);
	    }
	    self._keyTrunc = true;
	    for (; pos < len; ++pos) {
	      const code = chunk[pos];
	      if (code === 61/* '=' */ || code === 38/* '&' */)
	        break;
	      ++self._bytesKey;
	    }
	    self._lastPos = pos;
	  }

	  return pos;
	}

	function skipValBytes(self, chunk, pos, len) {
	  // Skip bytes if we've truncated
	  if (self._bytesVal > self.fieldSizeLimit) {
	    if (!self._valTrunc) {
	      if (self._lastPos < pos)
	        self._val += chunk.latin1Slice(self._lastPos, pos - 1);
	    }
	    self._valTrunc = true;
	    for (; pos < len; ++pos) {
	      if (chunk[pos] === 38/* '&' */)
	        break;
	      ++self._bytesVal;
	    }
	    self._lastPos = pos;
	  }

	  return pos;
	}

	/* eslint-disable no-multi-spaces */
	const HEX_VALUES = [
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	   0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
	  -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	];
	/* eslint-enable no-multi-spaces */

	urlencoded = URLEncoded;
	return urlencoded;
}

var lib$1;
var hasRequiredLib$1;

function requireLib$1 () {
	if (hasRequiredLib$1) return lib$1;
	hasRequiredLib$1 = 1;

	const { parseContentType } = requireUtils();

	function getInstance(cfg) {
	  const headers = cfg.headers;
	  const conType = parseContentType(headers['content-type']);
	  if (!conType)
	    throw new Error('Malformed content type');

	  for (const type of TYPES) {
	    const matched = type.detect(conType);
	    if (!matched)
	      continue;

	    const instanceCfg = {
	      limits: cfg.limits,
	      headers,
	      conType,
	      highWaterMark: undefined,
	      fileHwm: undefined,
	      defCharset: undefined,
	      defParamCharset: undefined,
	      preservePath: false,
	    };
	    if (cfg.highWaterMark)
	      instanceCfg.highWaterMark = cfg.highWaterMark;
	    if (cfg.fileHwm)
	      instanceCfg.fileHwm = cfg.fileHwm;
	    instanceCfg.defCharset = cfg.defCharset;
	    instanceCfg.defParamCharset = cfg.defParamCharset;
	    instanceCfg.preservePath = cfg.preservePath;
	    return new type(instanceCfg);
	  }

	  throw new Error(`Unsupported content type: ${headers['content-type']}`);
	}

	// Note: types are explicitly listed here for easier bundling
	// See: https://github.com/mscdex/busboy/issues/121
	const TYPES = [
	  requireMultipart(),
	  requireUrlencoded(),
	].filter(function(typemod) { return typeof typemod.detect === 'function'; });

	lib$1 = (cfg) => {
	  if (typeof cfg !== 'object' || cfg === null)
	    cfg = {};

	  if (typeof cfg.headers !== 'object'
	      || cfg.headers === null
	      || typeof cfg.headers['content-type'] !== 'string') {
	    throw new Error('Missing Content-Type');
	  }

	  return getInstance(cfg);
	};
	return lib$1;
}

var parsePath_1;
var hasRequiredParsePath;

function requireParsePath () {
	if (hasRequiredParsePath) return parsePath_1;
	hasRequiredParsePath = 1;
	var reFirstKey = /^[^\[]*/;
	var reDigitPath = /^\[(\d+)\]/;
	var reNormalPath = /^\[([^\]]+)\]/;

	function parsePath (key) {
	  function failure () {
	    return [{ type: 'object', key: key, last: true }]
	  }

	  var firstKey = reFirstKey.exec(key)[0];
	  if (!firstKey) return failure()

	  var len = key.length;
	  var pos = firstKey.length;
	  var tail = { type: 'object', key: firstKey };
	  var steps = [tail];

	  while (pos < len) {
	    var m;

	    if (key[pos] === '[' && key[pos + 1] === ']') {
	      pos += 2;
	      tail.append = true;
	      if (pos !== len) return failure()
	      continue
	    }

	    m = reDigitPath.exec(key.substring(pos));
	    if (m !== null) {
	      pos += m[0].length;
	      tail.nextType = 'array';
	      tail = { type: 'array', key: parseInt(m[1], 10) };
	      steps.push(tail);
	      continue
	    }

	    m = reNormalPath.exec(key.substring(pos));
	    if (m !== null) {
	      pos += m[0].length;
	      tail.nextType = 'object';
	      tail = { type: 'object', key: m[1] };
	      steps.push(tail);
	      continue
	    }

	    return failure()
	  }

	  tail.last = true;
	  return steps
	}

	parsePath_1 = parsePath;
	return parsePath_1;
}

var setValue_1;
var hasRequiredSetValue;

function requireSetValue () {
	if (hasRequiredSetValue) return setValue_1;
	hasRequiredSetValue = 1;
	function valueType (value) {
	  if (value === undefined) return 'undefined'
	  if (Array.isArray(value)) return 'array'
	  if (typeof value === 'object') return 'object'
	  return 'scalar'
	}

	function setLastValue (context, step, currentValue, entryValue) {
	  switch (valueType(currentValue)) {
	    case 'undefined':
	      if (step.append) {
	        context[step.key] = [entryValue];
	      } else {
	        context[step.key] = entryValue;
	      }
	      break
	    case 'array':
	      context[step.key].push(entryValue);
	      break
	    case 'object':
	      return setLastValue(currentValue, { key: ''}, currentValue[''], entryValue)
	    case 'scalar':
	      context[step.key] = [context[step.key], entryValue];
	      break
	  }

	  return context
	}

	function setValue (context, step, currentValue, entryValue) {
	  if (step.last) return setLastValue(context, step, currentValue, entryValue)

	  var obj;
	  switch (valueType(currentValue)) {
	    case 'undefined':
	      if (step.nextType === 'array') {
	        context[step.key] = [];
	      } else {
	        context[step.key] = Object.create(null);
	      }
	      return context[step.key]
	    case 'object':
	      return context[step.key]
	    case 'array':
	      if (step.nextType === 'array') {
	        return currentValue
	      }

	      obj = Object.create(null);
	      context[step.key] = obj;
	      currentValue.forEach(function (item, i) {
	        if (item !== undefined) obj['' + i] = item;
	      });

	      return obj
	    case 'scalar':
	      obj = Object.create(null);
	      obj[''] = currentValue;
	      context[step.key] = obj;
	      return obj
	  }
	}

	setValue_1 = setValue;
	return setValue_1;
}

var appendField_1;
var hasRequiredAppendField;

function requireAppendField () {
	if (hasRequiredAppendField) return appendField_1;
	hasRequiredAppendField = 1;
	var parsePath = requireParsePath();
	var setValue = requireSetValue();

	function appendField (store, key, value) {
	  var steps = parsePath(key);

	  steps.reduce(function (context, step) {
	    return setValue(context, step, context[step.key], value)
	  }, store);
	}

	appendField_1 = appendField;
	return appendField_1;
}

var counter;
var hasRequiredCounter;

function requireCounter () {
	if (hasRequiredCounter) return counter;
	hasRequiredCounter = 1;
	var EventEmitter = require$$0$5.EventEmitter;

	function Counter () {
	  EventEmitter.call(this);
	  this.value = 0;
	}

	Counter.prototype = Object.create(EventEmitter.prototype);

	Counter.prototype.increment = function increment () {
	  this.value++;
	};

	Counter.prototype.decrement = function decrement () {
	  if (--this.value === 0) this.emit('zero');
	};

	Counter.prototype.isZero = function isZero () {
	  return (this.value === 0)
	};

	Counter.prototype.onceZero = function onceZero (fn) {
	  if (this.isZero()) return fn()

	  this.once('zero', fn);
	};

	counter = Counter;
	return counter;
}

var multerError;
var hasRequiredMulterError;

function requireMulterError () {
	if (hasRequiredMulterError) return multerError;
	hasRequiredMulterError = 1;
	var util = require$$0$6;

	var errorMessages = {
	  LIMIT_PART_COUNT: 'Too many parts',
	  LIMIT_FILE_SIZE: 'File too large',
	  LIMIT_FILE_COUNT: 'Too many files',
	  LIMIT_FIELD_KEY: 'Field name too long',
	  LIMIT_FIELD_VALUE: 'Field value too long',
	  LIMIT_FIELD_COUNT: 'Too many fields',
	  LIMIT_UNEXPECTED_FILE: 'Unexpected field',
	  MISSING_FIELD_NAME: 'Field name missing'
	};

	function MulterError (code, field) {
	  Error.captureStackTrace(this, this.constructor);
	  this.name = this.constructor.name;
	  this.message = errorMessages[code];
	  this.code = code;
	  if (field) this.field = field;
	}

	util.inherits(MulterError, Error);

	multerError = MulterError;
	return multerError;
}

/*
object-assign
(c) Sindre Sorhus
@license MIT
*/

var objectAssign;
var hasRequiredObjectAssign;

function requireObjectAssign () {
	if (hasRequiredObjectAssign) return objectAssign;
	hasRequiredObjectAssign = 1;
	/* eslint-disable no-unused-vars */
	var getOwnPropertySymbols = Object.getOwnPropertySymbols;
	var hasOwnProperty = Object.prototype.hasOwnProperty;
	var propIsEnumerable = Object.prototype.propertyIsEnumerable;

	function toObject(val) {
		if (val === null || val === undefined) {
			throw new TypeError('Object.assign cannot be called with null or undefined');
		}

		return Object(val);
	}

	function shouldUseNative() {
		try {
			if (!Object.assign) {
				return false;
			}

			// Detect buggy property enumeration order in older V8 versions.

			// https://bugs.chromium.org/p/v8/issues/detail?id=4118
			var test1 = new String('abc');  // eslint-disable-line no-new-wrappers
			test1[5] = 'de';
			if (Object.getOwnPropertyNames(test1)[0] === '5') {
				return false;
			}

			// https://bugs.chromium.org/p/v8/issues/detail?id=3056
			var test2 = {};
			for (var i = 0; i < 10; i++) {
				test2['_' + String.fromCharCode(i)] = i;
			}
			var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
				return test2[n];
			});
			if (order2.join('') !== '0123456789') {
				return false;
			}

			// https://bugs.chromium.org/p/v8/issues/detail?id=3056
			var test3 = {};
			'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
				test3[letter] = letter;
			});
			if (Object.keys(Object.assign({}, test3)).join('') !==
					'abcdefghijklmnopqrst') {
				return false;
			}

			return true;
		} catch (err) {
			// We don't expect any of the above to throw, but better to be safe.
			return false;
		}
	}

	objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
		var from;
		var to = toObject(target);
		var symbols;

		for (var s = 1; s < arguments.length; s++) {
			from = Object(arguments[s]);

			for (var key in from) {
				if (hasOwnProperty.call(from, key)) {
					to[key] = from[key];
				}
			}

			if (getOwnPropertySymbols) {
				symbols = getOwnPropertySymbols(from);
				for (var i = 0; i < symbols.length; i++) {
					if (propIsEnumerable.call(from, symbols[i])) {
						to[symbols[i]] = from[symbols[i]];
					}
				}
			}
		}

		return to;
	};
	return objectAssign;
}

var fileAppender;
var hasRequiredFileAppender;

function requireFileAppender () {
	if (hasRequiredFileAppender) return fileAppender;
	hasRequiredFileAppender = 1;
	var objectAssign = requireObjectAssign();

	function arrayRemove (arr, item) {
	  var idx = arr.indexOf(item);
	  if (~idx) arr.splice(idx, 1);
	}

	function FileAppender (strategy, req) {
	  this.strategy = strategy;
	  this.req = req;

	  switch (strategy) {
	    case 'NONE': break
	    case 'VALUE': break
	    case 'ARRAY': req.files = []; break
	    case 'OBJECT': req.files = Object.create(null); break
	    default: throw new Error('Unknown file strategy: ' + strategy)
	  }
	}

	FileAppender.prototype.insertPlaceholder = function (file) {
	  var placeholder = {
	    fieldname: file.fieldname
	  };

	  switch (this.strategy) {
	    case 'NONE': break
	    case 'VALUE': break
	    case 'ARRAY': this.req.files.push(placeholder); break
	    case 'OBJECT':
	      if (this.req.files[file.fieldname]) {
	        this.req.files[file.fieldname].push(placeholder);
	      } else {
	        this.req.files[file.fieldname] = [placeholder];
	      }
	      break
	  }

	  return placeholder
	};

	FileAppender.prototype.removePlaceholder = function (placeholder) {
	  switch (this.strategy) {
	    case 'NONE': break
	    case 'VALUE': break
	    case 'ARRAY': arrayRemove(this.req.files, placeholder); break
	    case 'OBJECT':
	      if (this.req.files[placeholder.fieldname].length === 1) {
	        delete this.req.files[placeholder.fieldname];
	      } else {
	        arrayRemove(this.req.files[placeholder.fieldname], placeholder);
	      }
	      break
	  }
	};

	FileAppender.prototype.replacePlaceholder = function (placeholder, file) {
	  if (this.strategy === 'VALUE') {
	    this.req.file = file;
	    return
	  }

	  delete placeholder.fieldname;
	  objectAssign(placeholder, file);
	};

	fileAppender = FileAppender;
	return fileAppender;
}

var removeUploadedFiles_1;
var hasRequiredRemoveUploadedFiles;

function requireRemoveUploadedFiles () {
	if (hasRequiredRemoveUploadedFiles) return removeUploadedFiles_1;
	hasRequiredRemoveUploadedFiles = 1;
	function removeUploadedFiles (uploadedFiles, remove, cb) {
	  var length = uploadedFiles.length;
	  var errors = [];

	  if (length === 0) return cb(null, errors)

	  function handleFile (idx) {
	    var file = uploadedFiles[idx];

	    remove(file, function (err) {
	      if (err) {
	        err.file = file;
	        err.field = file.fieldname;
	        errors.push(err);
	      }

	      if (idx < length - 1) {
	        handleFile(idx + 1);
	      } else {
	        cb(null, errors);
	      }
	    });
	  }

	  handleFile(0);
	}

	removeUploadedFiles_1 = removeUploadedFiles;
	return removeUploadedFiles_1;
}

var makeMiddleware_1;
var hasRequiredMakeMiddleware;

function requireMakeMiddleware () {
	if (hasRequiredMakeMiddleware) return makeMiddleware_1;
	hasRequiredMakeMiddleware = 1;
	var is = requireTypeIs();
	var Busboy = requireLib$1();
	var extend = requireImmutable();
	var appendField = requireAppendField();

	var Counter = requireCounter();
	var MulterError = requireMulterError();
	var FileAppender = requireFileAppender();
	var removeUploadedFiles = requireRemoveUploadedFiles();

	function drainStream (stream) {
	  stream.on('readable', () => {
	    while (stream.read() !== null) {}
	  });
	}

	function makeMiddleware (setup) {
	  return function multerMiddleware (req, res, next) {
	    if (!is(req, ['multipart'])) return next()

	    var options = setup();

	    var limits = options.limits;
	    var storage = options.storage;
	    var fileFilter = options.fileFilter;
	    var fileStrategy = options.fileStrategy;
	    var preservePath = options.preservePath;

	    req.body = Object.create(null);

	    req.on('error', function (err) {
	      abortWithError(err);
	    });

	    var busboy;

	    try {
	      busboy = Busboy({ headers: req.headers, limits: limits, preservePath: preservePath });
	    } catch (err) {
	      return next(err)
	    }

	    var appender = new FileAppender(fileStrategy, req);
	    var isDone = false;
	    var readFinished = false;
	    var errorOccured = false;
	    var pendingWrites = new Counter();
	    var uploadedFiles = [];

	    function done (err) {
	      if (isDone) return
	      isDone = true;
	      req.unpipe(busboy);
	      drainStream(req);
	      req.resume();
	      setImmediate(() => {
	        busboy.removeAllListeners();
	      });
	      next(err);
	    }

	    function indicateDone () {
	      if (readFinished && pendingWrites.isZero() && !errorOccured) done();
	    }

	    function abortWithError (uploadError) {
	      if (errorOccured) return
	      errorOccured = true;

	      pendingWrites.onceZero(function () {
	        function remove (file, cb) {
	          storage._removeFile(req, file, cb);
	        }

	        removeUploadedFiles(uploadedFiles, remove, function (err, storageErrors) {
	          if (err) return done(err)

	          uploadError.storageErrors = storageErrors;
	          done(uploadError);
	        });
	      });
	    }

	    function abortWithCode (code, optionalField) {
	      abortWithError(new MulterError(code, optionalField));
	    }

	    // handle text field data
	    busboy.on('field', function (fieldname, value, { nameTruncated, valueTruncated }) {
	      if (fieldname == null) return abortWithCode('MISSING_FIELD_NAME')
	      if (nameTruncated) return abortWithCode('LIMIT_FIELD_KEY')
	      if (valueTruncated) return abortWithCode('LIMIT_FIELD_VALUE', fieldname)

	      // Work around bug in Busboy (https://github.com/mscdex/busboy/issues/6)
	      if (limits && Object.prototype.hasOwnProperty.call(limits, 'fieldNameSize')) {
	        if (fieldname.length > limits.fieldNameSize) return abortWithCode('LIMIT_FIELD_KEY')
	      }

	      appendField(req.body, fieldname, value);
	    });

	    // handle files
	    busboy.on('file', function (fieldname, fileStream, { filename, encoding, mimeType }) {
	      var pendingWritesIncremented = false;

	      fileStream.on('error', function (err) {
	        if (pendingWritesIncremented) {
	          pendingWrites.decrement();
	        }
	        abortWithError(err);
	      });

	      if (fieldname == null) return abortWithCode('MISSING_FIELD_NAME')

	      // don't attach to the files object, if there is no file
	      if (!filename) return fileStream.resume()

	      // Work around bug in Busboy (https://github.com/mscdex/busboy/issues/6)
	      if (limits && Object.prototype.hasOwnProperty.call(limits, 'fieldNameSize')) {
	        if (fieldname.length > limits.fieldNameSize) return abortWithCode('LIMIT_FIELD_KEY')
	      }

	      var file = {
	        fieldname: fieldname,
	        originalname: filename,
	        encoding: encoding,
	        mimetype: mimeType
	      };

	      var placeholder = appender.insertPlaceholder(file);

	      fileFilter(req, file, function (err, includeFile) {
	        if (err) {
	          appender.removePlaceholder(placeholder);
	          return abortWithError(err)
	        }

	        if (!includeFile) {
	          appender.removePlaceholder(placeholder);
	          return fileStream.resume()
	        }

	        var aborting = false;
	        pendingWritesIncremented = true;
	        pendingWrites.increment();

	        Object.defineProperty(file, 'stream', {
	          configurable: true,
	          enumerable: false,
	          value: fileStream
	        });

	        fileStream.on('limit', function () {
	          aborting = true;
	          abortWithCode('LIMIT_FILE_SIZE', fieldname);
	        });

	        storage._handleFile(req, file, function (err, info) {
	          if (aborting) {
	            appender.removePlaceholder(placeholder);
	            uploadedFiles.push(extend(file, info));
	            return pendingWrites.decrement()
	          }

	          if (err) {
	            appender.removePlaceholder(placeholder);
	            pendingWrites.decrement();
	            return abortWithError(err)
	          }

	          var fileInfo = extend(file, info);

	          appender.replacePlaceholder(placeholder, fileInfo);
	          uploadedFiles.push(fileInfo);
	          pendingWrites.decrement();
	          indicateDone();
	        });
	      });
	    });

	    busboy.on('error', function (err) { abortWithError(err); });
	    busboy.on('partsLimit', function () { abortWithCode('LIMIT_PART_COUNT'); });
	    busboy.on('filesLimit', function () { abortWithCode('LIMIT_FILE_COUNT'); });
	    busboy.on('fieldsLimit', function () { abortWithCode('LIMIT_FIELD_COUNT'); });
	    busboy.on('close', function () {
	      readFinished = true;
	      indicateDone();
	    });

	    req.pipe(busboy);
	  }
	}

	makeMiddleware_1 = makeMiddleware;
	return makeMiddleware_1;
}

var disk;
var hasRequiredDisk;

function requireDisk () {
	if (hasRequiredDisk) return disk;
	hasRequiredDisk = 1;
	var fs = fs__default;
	var os = os__default;
	var path = path__default;
	var crypto = crypto__default;
	var mkdirp = requireMkdirp();

	function getFilename (req, file, cb) {
	  crypto.randomBytes(16, function (err, raw) {
	    cb(err, err ? undefined : raw.toString('hex'));
	  });
	}

	function getDestination (req, file, cb) {
	  cb(null, os.tmpdir());
	}

	function DiskStorage (opts) {
	  this.getFilename = (opts.filename || getFilename);

	  if (typeof opts.destination === 'string') {
	    mkdirp.sync(opts.destination);
	    this.getDestination = function ($0, $1, cb) { cb(null, opts.destination); };
	  } else {
	    this.getDestination = (opts.destination || getDestination);
	  }
	}

	DiskStorage.prototype._handleFile = function _handleFile (req, file, cb) {
	  var that = this;

	  that.getDestination(req, file, function (err, destination) {
	    if (err) return cb(err)

	    that.getFilename(req, file, function (err, filename) {
	      if (err) return cb(err)

	      var finalPath = path.join(destination, filename);
	      var outStream = fs.createWriteStream(finalPath);

	      file.stream.pipe(outStream);
	      outStream.on('error', cb);
	      outStream.on('finish', function () {
	        cb(null, {
	          destination: destination,
	          filename: filename,
	          path: finalPath,
	          size: outStream.bytesWritten
	        });
	      });
	    });
	  });
	};

	DiskStorage.prototype._removeFile = function _removeFile (req, file, cb) {
	  var path = file.path;

	  delete file.destination;
	  delete file.filename;
	  delete file.path;

	  fs.unlink(path, cb);
	};

	disk = function (opts) {
	  return new DiskStorage(opts)
	};
	return disk;
}

/* eslint-disable node/no-deprecated-api */

var bufferFrom_1;
var hasRequiredBufferFrom;

function requireBufferFrom () {
	if (hasRequiredBufferFrom) return bufferFrom_1;
	hasRequiredBufferFrom = 1;
	var toString = Object.prototype.toString;

	var isModern = (
	  typeof Buffer !== 'undefined' &&
	  typeof Buffer.alloc === 'function' &&
	  typeof Buffer.allocUnsafe === 'function' &&
	  typeof Buffer.from === 'function'
	);

	function isArrayBuffer (input) {
	  return toString.call(input).slice(8, -1) === 'ArrayBuffer'
	}

	function fromArrayBuffer (obj, byteOffset, length) {
	  byteOffset >>>= 0;

	  var maxLength = obj.byteLength - byteOffset;

	  if (maxLength < 0) {
	    throw new RangeError("'offset' is out of bounds")
	  }

	  if (length === undefined) {
	    length = maxLength;
	  } else {
	    length >>>= 0;

	    if (length > maxLength) {
	      throw new RangeError("'length' is out of bounds")
	    }
	  }

	  return isModern
	    ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
	    : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
	}

	function fromString (string, encoding) {
	  if (typeof encoding !== 'string' || encoding === '') {
	    encoding = 'utf8';
	  }

	  if (!Buffer.isEncoding(encoding)) {
	    throw new TypeError('"encoding" must be a valid string encoding')
	  }

	  return isModern
	    ? Buffer.from(string, encoding)
	    : new Buffer(string, encoding)
	}

	function bufferFrom (value, encodingOrOffset, length) {
	  if (typeof value === 'number') {
	    throw new TypeError('"value" argument must not be a number')
	  }

	  if (isArrayBuffer(value)) {
	    return fromArrayBuffer(value, encodingOrOffset, length)
	  }

	  if (typeof value === 'string') {
	    return fromString(value, encodingOrOffset)
	  }

	  return isModern
	    ? Buffer.from(value)
	    : new Buffer(value)
	}

	bufferFrom_1 = bufferFrom;
	return bufferFrom_1;
}

var typedarray = {};

var hasRequiredTypedarray;

function requireTypedarray () {
	if (hasRequiredTypedarray) return typedarray;
	hasRequiredTypedarray = 1;
	(function (exports$1) {
		var undefined$1 = (void 0); // Paranoia

		// Beyond this value, index getters/setters (i.e. array[0], array[1]) are so slow to
		// create, and consume so much memory, that the browser appears frozen.
		var MAX_ARRAY_LENGTH = 1e5;

		// Approximations of internal ECMAScript conversion functions
		var ECMAScript = (function() {
		  // Stash a copy in case other scripts modify these
		  var opts = Object.prototype.toString,
		      ophop = Object.prototype.hasOwnProperty;

		  return {
		    // Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues:
		    Class: function(v) { return opts.call(v).replace(/^\[object *|\]$/g, ''); },
		    HasProperty: function(o, p) { return p in o; },
		    HasOwnProperty: function(o, p) { return ophop.call(o, p); },
		    IsCallable: function(o) { return typeof o === 'function'; },
		    ToInt32: function(v) { return v >> 0; },
		    ToUint32: function(v) { return v >>> 0; }
		  };
		}());

		// Snapshot intrinsics
		var LN2 = Math.LN2,
		    abs = Math.abs,
		    floor = Math.floor,
		    log = Math.log,
		    min = Math.min,
		    pow = Math.pow,
		    round = Math.round;

		// ES5: lock down object properties
		function configureProperties(obj) {
		  if (getOwnPropNames && defineProp) {
		    var props = getOwnPropNames(obj), i;
		    for (i = 0; i < props.length; i += 1) {
		      defineProp(obj, props[i], {
		        value: obj[props[i]],
		        writable: false,
		        enumerable: false,
		        configurable: false
		      });
		    }
		  }
		}

		// emulate ES5 getter/setter API using legacy APIs
		// http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx
		// (second clause tests for Object.defineProperty() in IE<9 that only supports extending DOM prototypes, but
		// note that IE<9 does not support __defineGetter__ or __defineSetter__ so it just renders the method harmless)
		var defineProp;
		if (Object.defineProperty && (function() {
		      try {
		        Object.defineProperty({}, 'x', {});
		        return true;
		      } catch (e) {
		        return false;
		      }
		    })()) {
		  defineProp = Object.defineProperty;
		} else {
		  defineProp = function(o, p, desc) {
		    if (!o === Object(o)) throw new TypeError("Object.defineProperty called on non-object");
		    if (ECMAScript.HasProperty(desc, 'get') && Object.prototype.__defineGetter__) { Object.prototype.__defineGetter__.call(o, p, desc.get); }
		    if (ECMAScript.HasProperty(desc, 'set') && Object.prototype.__defineSetter__) { Object.prototype.__defineSetter__.call(o, p, desc.set); }
		    if (ECMAScript.HasProperty(desc, 'value')) { o[p] = desc.value; }
		    return o;
		  };
		}

		var getOwnPropNames = Object.getOwnPropertyNames || function (o) {
		  if (o !== Object(o)) throw new TypeError("Object.getOwnPropertyNames called on non-object");
		  var props = [], p;
		  for (p in o) {
		    if (ECMAScript.HasOwnProperty(o, p)) {
		      props.push(p);
		    }
		  }
		  return props;
		};

		// ES5: Make obj[index] an alias for obj._getter(index)/obj._setter(index, value)
		// for index in 0 ... obj.length
		function makeArrayAccessors(obj) {
		  if (!defineProp) { return; }

		  if (obj.length > MAX_ARRAY_LENGTH) throw new RangeError("Array too large for polyfill");

		  function makeArrayAccessor(index) {
		    defineProp(obj, index, {
		      'get': function() { return obj._getter(index); },
		      'set': function(v) { obj._setter(index, v); },
		      enumerable: true,
		      configurable: false
		    });
		  }

		  var i;
		  for (i = 0; i < obj.length; i += 1) {
		    makeArrayAccessor(i);
		  }
		}

		// Internal conversion functions:
		//    pack<Type>()   - take a number (interpreted as Type), output a byte array
		//    unpack<Type>() - take a byte array, output a Type-like number

		function as_signed(value, bits) { var s = 32 - bits; return (value << s) >> s; }
		function as_unsigned(value, bits) { var s = 32 - bits; return (value << s) >>> s; }

		function packI8(n) { return [n & 0xff]; }
		function unpackI8(bytes) { return as_signed(bytes[0], 8); }

		function packU8(n) { return [n & 0xff]; }
		function unpackU8(bytes) { return as_unsigned(bytes[0], 8); }

		function packU8Clamped(n) { n = round(Number(n)); return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff]; }

		function packI16(n) { return [(n >> 8) & 0xff, n & 0xff]; }
		function unpackI16(bytes) { return as_signed(bytes[0] << 8 | bytes[1], 16); }

		function packU16(n) { return [(n >> 8) & 0xff, n & 0xff]; }
		function unpackU16(bytes) { return as_unsigned(bytes[0] << 8 | bytes[1], 16); }

		function packI32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; }
		function unpackI32(bytes) { return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); }

		function packU32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; }
		function unpackU32(bytes) { return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); }

		function packIEEE754(v, ebits, fbits) {

		  var bias = (1 << (ebits - 1)) - 1,
		      s, e, f, i, bits, str, bytes;

		  function roundToEven(n) {
		    var w = floor(n), f = n - w;
		    if (f < 0.5)
		      return w;
		    if (f > 0.5)
		      return w + 1;
		    return w % 2 ? w + 1 : w;
		  }

		  // Compute sign, exponent, fraction
		  if (v !== v) {
		    // NaN
		    // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping
		    e = (1 << ebits) - 1; f = pow(2, fbits - 1); s = 0;
		  } else if (v === Infinity || v === -Infinity) {
		    e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0;
		  } else if (v === 0) {
		    e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0;
		  } else {
		    s = v < 0;
		    v = abs(v);

		    if (v >= pow(2, 1 - bias)) {
		      e = min(floor(log(v) / LN2), 1023);
		      f = roundToEven(v / pow(2, e) * pow(2, fbits));
		      if (f / pow(2, fbits) >= 2) {
		        e = e + 1;
		        f = 1;
		      }
		      if (e > bias) {
		        // Overflow
		        e = (1 << ebits) - 1;
		        f = 0;
		      } else {
		        // Normalized
		        e = e + bias;
		        f = f - pow(2, fbits);
		      }
		    } else {
		      // Denormalized
		      e = 0;
		      f = roundToEven(v / pow(2, 1 - bias - fbits));
		    }
		  }

		  // Pack sign, exponent, fraction
		  bits = [];
		  for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = floor(f / 2); }
		  for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = floor(e / 2); }
		  bits.push(s ? 1 : 0);
		  bits.reverse();
		  str = bits.join('');

		  // Bits to bytes
		  bytes = [];
		  while (str.length) {
		    bytes.push(parseInt(str.substring(0, 8), 2));
		    str = str.substring(8);
		  }
		  return bytes;
		}

		function unpackIEEE754(bytes, ebits, fbits) {

		  // Bytes to bits
		  var bits = [], i, j, b, str,
		      bias, s, e, f;

		  for (i = bytes.length; i; i -= 1) {
		    b = bytes[i - 1];
		    for (j = 8; j; j -= 1) {
		      bits.push(b % 2 ? 1 : 0); b = b >> 1;
		    }
		  }
		  bits.reverse();
		  str = bits.join('');

		  // Unpack sign, exponent, fraction
		  bias = (1 << (ebits - 1)) - 1;
		  s = parseInt(str.substring(0, 1), 2) ? -1 : 1;
		  e = parseInt(str.substring(1, 1 + ebits), 2);
		  f = parseInt(str.substring(1 + ebits), 2);

		  // Produce number
		  if (e === (1 << ebits) - 1) {
		    return f !== 0 ? NaN : s * Infinity;
		  } else if (e > 0) {
		    // Normalized
		    return s * pow(2, e - bias) * (1 + f / pow(2, fbits));
		  } else if (f !== 0) {
		    // Denormalized
		    return s * pow(2, -(bias - 1)) * (f / pow(2, fbits));
		  } else {
		    return s < 0 ? -0 : 0;
		  }
		}

		function unpackF64(b) { return unpackIEEE754(b, 11, 52); }
		function packF64(v) { return packIEEE754(v, 11, 52); }
		function unpackF32(b) { return unpackIEEE754(b, 8, 23); }
		function packF32(v) { return packIEEE754(v, 8, 23); }


		//
		// 3 The ArrayBuffer Type
		//

		(function() {

		  /** @constructor */
		  var ArrayBuffer = function ArrayBuffer(length) {
		    length = ECMAScript.ToInt32(length);
		    if (length < 0) throw new RangeError('ArrayBuffer size is not a small enough positive integer');

		    this.byteLength = length;
		    this._bytes = [];
		    this._bytes.length = length;

		    var i;
		    for (i = 0; i < this.byteLength; i += 1) {
		      this._bytes[i] = 0;
		    }

		    configureProperties(this);
		  };

		  exports$1.ArrayBuffer = exports$1.ArrayBuffer || ArrayBuffer;

		  //
		  // 4 The ArrayBufferView Type
		  //

		  // NOTE: this constructor is not exported
		  /** @constructor */
		  var ArrayBufferView = function ArrayBufferView() {
		    //this.buffer = null;
		    //this.byteOffset = 0;
		    //this.byteLength = 0;
		  };

		  //
		  // 5 The Typed Array View Types
		  //

		  function makeConstructor(bytesPerElement, pack, unpack) {
		    // Each TypedArray type requires a distinct constructor instance with
		    // identical logic, which this produces.

		    var ctor;
		    ctor = function(buffer, byteOffset, length) {
		      var array, sequence, i, s;

		      if (!arguments.length || typeof arguments[0] === 'number') {
		        // Constructor(unsigned long length)
		        this.length = ECMAScript.ToInt32(arguments[0]);
		        if (length < 0) throw new RangeError('ArrayBufferView size is not a small enough positive integer');

		        this.byteLength = this.length * this.BYTES_PER_ELEMENT;
		        this.buffer = new ArrayBuffer(this.byteLength);
		        this.byteOffset = 0;
		      } else if (typeof arguments[0] === 'object' && arguments[0].constructor === ctor) {
		        // Constructor(TypedArray array)
		        array = arguments[0];

		        this.length = array.length;
		        this.byteLength = this.length * this.BYTES_PER_ELEMENT;
		        this.buffer = new ArrayBuffer(this.byteLength);
		        this.byteOffset = 0;

		        for (i = 0; i < this.length; i += 1) {
		          this._setter(i, array._getter(i));
		        }
		      } else if (typeof arguments[0] === 'object' &&
		                 !(arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) {
		        // Constructor(sequence<type> array)
		        sequence = arguments[0];

		        this.length = ECMAScript.ToUint32(sequence.length);
		        this.byteLength = this.length * this.BYTES_PER_ELEMENT;
		        this.buffer = new ArrayBuffer(this.byteLength);
		        this.byteOffset = 0;

		        for (i = 0; i < this.length; i += 1) {
		          s = sequence[i];
		          this._setter(i, Number(s));
		        }
		      } else if (typeof arguments[0] === 'object' &&
		                 (arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) {
		        // Constructor(ArrayBuffer buffer,
		        //             optional unsigned long byteOffset, optional unsigned long length)
		        this.buffer = buffer;

		        this.byteOffset = ECMAScript.ToUint32(byteOffset);
		        if (this.byteOffset > this.buffer.byteLength) {
		          throw new RangeError("byteOffset out of range");
		        }

		        if (this.byteOffset % this.BYTES_PER_ELEMENT) {
		          // The given byteOffset must be a multiple of the element
		          // size of the specific type, otherwise an exception is raised.
		          throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size.");
		        }

		        if (arguments.length < 3) {
		          this.byteLength = this.buffer.byteLength - this.byteOffset;

		          if (this.byteLength % this.BYTES_PER_ELEMENT) {
		            throw new RangeError("length of buffer minus byteOffset not a multiple of the element size");
		          }
		          this.length = this.byteLength / this.BYTES_PER_ELEMENT;
		        } else {
		          this.length = ECMAScript.ToUint32(length);
		          this.byteLength = this.length * this.BYTES_PER_ELEMENT;
		        }

		        if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) {
		          throw new RangeError("byteOffset and length reference an area beyond the end of the buffer");
		        }
		      } else {
		        throw new TypeError("Unexpected argument type(s)");
		      }

		      this.constructor = ctor;

		      configureProperties(this);
		      makeArrayAccessors(this);
		    };

		    ctor.prototype = new ArrayBufferView();
		    ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement;
		    ctor.prototype._pack = pack;
		    ctor.prototype._unpack = unpack;
		    ctor.BYTES_PER_ELEMENT = bytesPerElement;

		    // getter type (unsigned long index);
		    ctor.prototype._getter = function(index) {
		      if (arguments.length < 1) throw new SyntaxError("Not enough arguments");

		      index = ECMAScript.ToUint32(index);
		      if (index >= this.length) {
		        return undefined$1;
		      }

		      var bytes = [], i, o;
		      for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT;
		           i < this.BYTES_PER_ELEMENT;
		           i += 1, o += 1) {
		        bytes.push(this.buffer._bytes[o]);
		      }
		      return this._unpack(bytes);
		    };

		    // NONSTANDARD: convenience alias for getter: type get(unsigned long index);
		    ctor.prototype.get = ctor.prototype._getter;

		    // setter void (unsigned long index, type value);
		    ctor.prototype._setter = function(index, value) {
		      if (arguments.length < 2) throw new SyntaxError("Not enough arguments");

		      index = ECMAScript.ToUint32(index);
		      if (index >= this.length) {
		        return undefined$1;
		      }

		      var bytes = this._pack(value), i, o;
		      for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT;
		           i < this.BYTES_PER_ELEMENT;
		           i += 1, o += 1) {
		        this.buffer._bytes[o] = bytes[i];
		      }
		    };

		    // void set(TypedArray array, optional unsigned long offset);
		    // void set(sequence<type> array, optional unsigned long offset);
		    ctor.prototype.set = function(index, value) {
		      if (arguments.length < 1) throw new SyntaxError("Not enough arguments");
		      var array, sequence, offset, len,
		          i, s, d,
		          byteOffset, byteLength, tmp;

		      if (typeof arguments[0] === 'object' && arguments[0].constructor === this.constructor) {
		        // void set(TypedArray array, optional unsigned long offset);
		        array = arguments[0];
		        offset = ECMAScript.ToUint32(arguments[1]);

		        if (offset + array.length > this.length) {
		          throw new RangeError("Offset plus length of array is out of range");
		        }

		        byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT;
		        byteLength = array.length * this.BYTES_PER_ELEMENT;

		        if (array.buffer === this.buffer) {
		          tmp = [];
		          for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) {
		            tmp[i] = array.buffer._bytes[s];
		          }
		          for (i = 0, d = byteOffset; i < byteLength; i += 1, d += 1) {
		            this.buffer._bytes[d] = tmp[i];
		          }
		        } else {
		          for (i = 0, s = array.byteOffset, d = byteOffset;
		               i < byteLength; i += 1, s += 1, d += 1) {
		            this.buffer._bytes[d] = array.buffer._bytes[s];
		          }
		        }
		      } else if (typeof arguments[0] === 'object' && typeof arguments[0].length !== 'undefined') {
		        // void set(sequence<type> array, optional unsigned long offset);
		        sequence = arguments[0];
		        len = ECMAScript.ToUint32(sequence.length);
		        offset = ECMAScript.ToUint32(arguments[1]);

		        if (offset + len > this.length) {
		          throw new RangeError("Offset plus length of array is out of range");
		        }

		        for (i = 0; i < len; i += 1) {
		          s = sequence[i];
		          this._setter(offset + i, Number(s));
		        }
		      } else {
		        throw new TypeError("Unexpected argument type(s)");
		      }
		    };

		    // TypedArray subarray(long begin, optional long end);
		    ctor.prototype.subarray = function(start, end) {
		      function clamp(v, min, max) { return v < min ? min : v > max ? max : v; }

		      start = ECMAScript.ToInt32(start);
		      end = ECMAScript.ToInt32(end);

		      if (arguments.length < 1) { start = 0; }
		      if (arguments.length < 2) { end = this.length; }

		      if (start < 0) { start = this.length + start; }
		      if (end < 0) { end = this.length + end; }

		      start = clamp(start, 0, this.length);
		      end = clamp(end, 0, this.length);

		      var len = end - start;
		      if (len < 0) {
		        len = 0;
		      }

		      return new this.constructor(
		        this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len);
		    };

		    return ctor;
		  }

		  var Int8Array = makeConstructor(1, packI8, unpackI8);
		  var Uint8Array = makeConstructor(1, packU8, unpackU8);
		  var Uint8ClampedArray = makeConstructor(1, packU8Clamped, unpackU8);
		  var Int16Array = makeConstructor(2, packI16, unpackI16);
		  var Uint16Array = makeConstructor(2, packU16, unpackU16);
		  var Int32Array = makeConstructor(4, packI32, unpackI32);
		  var Uint32Array = makeConstructor(4, packU32, unpackU32);
		  var Float32Array = makeConstructor(4, packF32, unpackF32);
		  var Float64Array = makeConstructor(8, packF64, unpackF64);

		  exports$1.Int8Array = exports$1.Int8Array || Int8Array;
		  exports$1.Uint8Array = exports$1.Uint8Array || Uint8Array;
		  exports$1.Uint8ClampedArray = exports$1.Uint8ClampedArray || Uint8ClampedArray;
		  exports$1.Int16Array = exports$1.Int16Array || Int16Array;
		  exports$1.Uint16Array = exports$1.Uint16Array || Uint16Array;
		  exports$1.Int32Array = exports$1.Int32Array || Int32Array;
		  exports$1.Uint32Array = exports$1.Uint32Array || Uint32Array;
		  exports$1.Float32Array = exports$1.Float32Array || Float32Array;
		  exports$1.Float64Array = exports$1.Float64Array || Float64Array;
		}());

		//
		// 6 The DataView View Type
		//

		(function() {
		  function r(array, index) {
		    return ECMAScript.IsCallable(array.get) ? array.get(index) : array[index];
		  }

		  var IS_BIG_ENDIAN = (function() {
		    var u16array = new(exports$1.Uint16Array)([0x1234]),
		        u8array = new(exports$1.Uint8Array)(u16array.buffer);
		    return r(u8array, 0) === 0x12;
		  }());

		  // Constructor(ArrayBuffer buffer,
		  //             optional unsigned long byteOffset,
		  //             optional unsigned long byteLength)
		  /** @constructor */
		  var DataView = function DataView(buffer, byteOffset, byteLength) {
		    if (arguments.length === 0) {
		      buffer = new exports$1.ArrayBuffer(0);
		    } else if (!(buffer instanceof exports$1.ArrayBuffer || ECMAScript.Class(buffer) === 'ArrayBuffer')) {
		      throw new TypeError("TypeError");
		    }

		    this.buffer = buffer || new exports$1.ArrayBuffer(0);

		    this.byteOffset = ECMAScript.ToUint32(byteOffset);
		    if (this.byteOffset > this.buffer.byteLength) {
		      throw new RangeError("byteOffset out of range");
		    }

		    if (arguments.length < 3) {
		      this.byteLength = this.buffer.byteLength - this.byteOffset;
		    } else {
		      this.byteLength = ECMAScript.ToUint32(byteLength);
		    }

		    if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) {
		      throw new RangeError("byteOffset and length reference an area beyond the end of the buffer");
		    }

		    configureProperties(this);
		  };

		  function makeGetter(arrayType) {
		    return function(byteOffset, littleEndian) {

		      byteOffset = ECMAScript.ToUint32(byteOffset);

		      if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) {
		        throw new RangeError("Array index out of range");
		      }
		      byteOffset += this.byteOffset;

		      var uint8Array = new exports$1.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT),
		          bytes = [], i;
		      for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) {
		        bytes.push(r(uint8Array, i));
		      }

		      if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) {
		        bytes.reverse();
		      }

		      return r(new arrayType(new exports$1.Uint8Array(bytes).buffer), 0);
		    };
		  }

		  DataView.prototype.getUint8 = makeGetter(exports$1.Uint8Array);
		  DataView.prototype.getInt8 = makeGetter(exports$1.Int8Array);
		  DataView.prototype.getUint16 = makeGetter(exports$1.Uint16Array);
		  DataView.prototype.getInt16 = makeGetter(exports$1.Int16Array);
		  DataView.prototype.getUint32 = makeGetter(exports$1.Uint32Array);
		  DataView.prototype.getInt32 = makeGetter(exports$1.Int32Array);
		  DataView.prototype.getFloat32 = makeGetter(exports$1.Float32Array);
		  DataView.prototype.getFloat64 = makeGetter(exports$1.Float64Array);

		  function makeSetter(arrayType) {
		    return function(byteOffset, value, littleEndian) {

		      byteOffset = ECMAScript.ToUint32(byteOffset);
		      if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) {
		        throw new RangeError("Array index out of range");
		      }

		      // Get bytes
		      var typeArray = new arrayType([value]),
		          byteArray = new exports$1.Uint8Array(typeArray.buffer),
		          bytes = [], i, byteView;

		      for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) {
		        bytes.push(r(byteArray, i));
		      }

		      // Flip if necessary
		      if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) {
		        bytes.reverse();
		      }

		      // Write them
		      byteView = new exports$1.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT);
		      byteView.set(bytes);
		    };
		  }

		  DataView.prototype.setUint8 = makeSetter(exports$1.Uint8Array);
		  DataView.prototype.setInt8 = makeSetter(exports$1.Int8Array);
		  DataView.prototype.setUint16 = makeSetter(exports$1.Uint16Array);
		  DataView.prototype.setInt16 = makeSetter(exports$1.Int16Array);
		  DataView.prototype.setUint32 = makeSetter(exports$1.Uint32Array);
		  DataView.prototype.setInt32 = makeSetter(exports$1.Int32Array);
		  DataView.prototype.setFloat32 = makeSetter(exports$1.Float32Array);
		  DataView.prototype.setFloat64 = makeSetter(exports$1.Float64Array);

		  exports$1.DataView = exports$1.DataView || DataView;

		}()); 
	} (typedarray));
	return typedarray;
}

var concatStream;
var hasRequiredConcatStream;

function requireConcatStream () {
	if (hasRequiredConcatStream) return concatStream;
	hasRequiredConcatStream = 1;
	var Writable = requireReadableBrowser().Writable;
	var inherits = requireInherits_browser();
	var bufferFrom = requireBufferFrom();

	if (typeof Uint8Array === 'undefined') {
	  var U8 = requireTypedarray().Uint8Array;
	} else {
	  var U8 = Uint8Array;
	}

	function ConcatStream(opts, cb) {
	  if (!(this instanceof ConcatStream)) return new ConcatStream(opts, cb)

	  if (typeof opts === 'function') {
	    cb = opts;
	    opts = {};
	  }
	  if (!opts) opts = {};

	  var encoding = opts.encoding;
	  var shouldInferEncoding = false;

	  if (!encoding) {
	    shouldInferEncoding = true;
	  } else {
	    encoding =  String(encoding).toLowerCase();
	    if (encoding === 'u8' || encoding === 'uint8') {
	      encoding = 'uint8array';
	    }
	  }

	  Writable.call(this, { objectMode: true });

	  this.encoding = encoding;
	  this.shouldInferEncoding = shouldInferEncoding;

	  if (cb) this.on('finish', function () { cb(this.getBody()); });
	  this.body = [];
	}

	concatStream = ConcatStream;
	inherits(ConcatStream, Writable);

	ConcatStream.prototype._write = function(chunk, enc, next) {
	  this.body.push(chunk);
	  next();
	};

	ConcatStream.prototype.inferEncoding = function (buff) {
	  var firstBuffer = buff === undefined ? this.body[0] : buff;
	  if (Buffer.isBuffer(firstBuffer)) return 'buffer'
	  if (typeof Uint8Array !== 'undefined' && firstBuffer instanceof Uint8Array) return 'uint8array'
	  if (Array.isArray(firstBuffer)) return 'array'
	  if (typeof firstBuffer === 'string') return 'string'
	  if (Object.prototype.toString.call(firstBuffer) === "[object Object]") return 'object'
	  return 'buffer'
	};

	ConcatStream.prototype.getBody = function () {
	  if (!this.encoding && this.body.length === 0) return []
	  if (this.shouldInferEncoding) this.encoding = this.inferEncoding();
	  if (this.encoding === 'array') return arrayConcat(this.body)
	  if (this.encoding === 'string') return stringConcat(this.body)
	  if (this.encoding === 'buffer') return bufferConcat(this.body)
	  if (this.encoding === 'uint8array') return u8Concat(this.body)
	  return this.body
	};

	function isArrayish (arr) {
	  return /Array\]$/.test(Object.prototype.toString.call(arr))
	}

	function isBufferish (p) {
	  return typeof p === 'string' || isArrayish(p) || (p && typeof p.subarray === 'function')
	}

	function stringConcat (parts) {
	  var strings = [];
	  for (var i = 0; i < parts.length; i++) {
	    var p = parts[i];
	    if (typeof p === 'string') {
	      strings.push(p);
	    } else if (Buffer.isBuffer(p)) {
	      strings.push(p);
	    } else if (isBufferish(p)) {
	      strings.push(bufferFrom(p));
	    } else {
	      strings.push(bufferFrom(String(p)));
	    }
	  }
	  if (Buffer.isBuffer(parts[0])) {
	    strings = Buffer.concat(strings);
	    strings = strings.toString('utf8');
	  } else {
	    strings = strings.join('');
	  }
	  return strings
	}

	function bufferConcat (parts) {
	  var bufs = [];
	  for (var i = 0; i < parts.length; i++) {
	    var p = parts[i];
	    if (Buffer.isBuffer(p)) {
	      bufs.push(p);
	    } else if (isBufferish(p)) {
	      bufs.push(bufferFrom(p));
	    } else {
	      bufs.push(bufferFrom(String(p)));
	    }
	  }
	  return Buffer.concat(bufs)
	}

	function arrayConcat (parts) {
	  var res = [];
	  for (var i = 0; i < parts.length; i++) {
	    res.push.apply(res, parts[i]);
	  }
	  return res
	}

	function u8Concat (parts) {
	  var len = 0;
	  for (var i = 0; i < parts.length; i++) {
	    if (typeof parts[i] === 'string') {
	      parts[i] = bufferFrom(parts[i]);
	    }
	    len += parts[i].length;
	  }
	  var u8 = new U8(len);
	  for (var i = 0, offset = 0; i < parts.length; i++) {
	    var part = parts[i];
	    for (var j = 0; j < part.length; j++) {
	      u8[offset++] = part[j];
	    }
	  }
	  return u8
	}
	return concatStream;
}

var memory;
var hasRequiredMemory;

function requireMemory () {
	if (hasRequiredMemory) return memory;
	hasRequiredMemory = 1;
	var concat = requireConcatStream();

	function MemoryStorage (opts) {}

	MemoryStorage.prototype._handleFile = function _handleFile (req, file, cb) {
	  file.stream.pipe(concat({ encoding: 'buffer' }, function (data) {
	    cb(null, {
	      buffer: data,
	      size: data.length
	    });
	  }));
	};

	MemoryStorage.prototype._removeFile = function _removeFile (req, file, cb) {
	  delete file.buffer;
	  cb(null);
	};

	memory = function (opts) {
	  return new MemoryStorage()
	};
	return memory;
}

var hasRequiredMulter;

function requireMulter () {
	if (hasRequiredMulter) return multer$1.exports;
	hasRequiredMulter = 1;
	var makeMiddleware = requireMakeMiddleware();

	var diskStorage = requireDisk();
	var memoryStorage = requireMemory();
	var MulterError = requireMulterError();

	function allowAll (req, file, cb) {
	  cb(null, true);
	}

	function Multer (options) {
	  if (options.storage) {
	    this.storage = options.storage;
	  } else if (options.dest) {
	    this.storage = diskStorage({ destination: options.dest });
	  } else {
	    this.storage = memoryStorage();
	  }

	  this.limits = options.limits;
	  this.preservePath = options.preservePath;
	  this.fileFilter = options.fileFilter || allowAll;
	}

	Multer.prototype._makeMiddleware = function (fields, fileStrategy) {
	  function setup () {
	    var fileFilter = this.fileFilter;
	    var filesLeft = Object.create(null);

	    fields.forEach(function (field) {
	      if (typeof field.maxCount === 'number') {
	        filesLeft[field.name] = field.maxCount;
	      } else {
	        filesLeft[field.name] = Infinity;
	      }
	    });

	    function wrappedFileFilter (req, file, cb) {
	      if ((filesLeft[file.fieldname] || 0) <= 0) {
	        return cb(new MulterError('LIMIT_UNEXPECTED_FILE', file.fieldname))
	      }

	      filesLeft[file.fieldname] -= 1;
	      fileFilter(req, file, cb);
	    }

	    return {
	      limits: this.limits,
	      preservePath: this.preservePath,
	      storage: this.storage,
	      fileFilter: wrappedFileFilter,
	      fileStrategy: fileStrategy
	    }
	  }

	  return makeMiddleware(setup.bind(this))
	};

	Multer.prototype.single = function (name) {
	  return this._makeMiddleware([{ name: name, maxCount: 1 }], 'VALUE')
	};

	Multer.prototype.array = function (name, maxCount) {
	  return this._makeMiddleware([{ name: name, maxCount: maxCount }], 'ARRAY')
	};

	Multer.prototype.fields = function (fields) {
	  return this._makeMiddleware(fields, 'OBJECT')
	};

	Multer.prototype.none = function () {
	  return this._makeMiddleware([], 'NONE')
	};

	Multer.prototype.any = function () {
	  function setup () {
	    return {
	      limits: this.limits,
	      preservePath: this.preservePath,
	      storage: this.storage,
	      fileFilter: this.fileFilter,
	      fileStrategy: 'ARRAY'
	    }
	  }

	  return makeMiddleware(setup.bind(this))
	};

	function multer (options) {
	  if (options === undefined) {
	    return new Multer({})
	  }

	  if (typeof options === 'object' && options !== null) {
	    return new Multer(options)
	  }

	  throw new TypeError('Expected object for argument options')
	}

	multer$1.exports = multer;
	multer$1.exports.diskStorage = diskStorage;
	multer$1.exports.memoryStorage = memoryStorage;
	multer$1.exports.MulterError = MulterError;
	return multer$1.exports;
}

var multerExports = requireMulter();
const multer = /*@__PURE__*/getDefaultExportFromCjs(multerExports);

const SUPPORTED_FONT_EXTENSIONS = [".woff", ".woff2", ".ttf", ".otf"];
const cleanOldFontFiles = (fontsPath) => {
  for (const ext of SUPPORTED_FONT_EXTENSIONS) {
    const fontPath = path__default.join(fontsPath, `webui${ext}`);
    try {
      if (fs__default.existsSync(fontPath)) {
        fs__default.unlinkSync(fontPath);
      }
    } catch {
    }
  }
};
const webUIFontStorage = multer.diskStorage({
  destination: (_, __, cb) => {
    try {
      const fontsPath = path__default.dirname(WebUiConfig.GetWebUIFontPathSync());
      fs__default.mkdirSync(fontsPath, { recursive: true });
      cleanOldFontFiles(fontsPath);
      cb(null, fontsPath);
    } catch (error) {
      cb(new Error(`创建字体目录失败：${error.message}`), "");
    }
  },
  filename: (_, file, cb) => {
    const ext = path__default.extname(file.originalname).toLowerCase();
    cb(null, `webui${ext}`);
  }
});
const webUIFontUpload = multer({
  storage: webUIFontStorage,
  fileFilter: (_, file, cb) => {
    const ext = path__default.extname(file.originalname).toLowerCase();
    if (!SUPPORTED_FONT_EXTENSIONS.includes(ext)) {
      cb(new Error("只支持 WOFF/WOFF2/TTF/OTF 格式的字体文件"));
      return;
    }
    cb(null, true);
  },
  limits: {
    fileSize: 40 * 1024 * 1024
    // 限制40MB
  }
}).single("file");
const webUIFontUploader = (req, res) => {
  return new Promise((resolve, reject) => {
    webUIFontUpload(req, res, (error) => {
      if (error) {
        return reject(error);
      }
      return resolve(true);
    });
  });
};

const isWindows$1 = process.platform === "win32";
const decodeFileName = (fileName) => {
  try {
    return Buffer.from(fileName, "binary").toString("utf8");
  } catch {
    return fileName;
  }
};
const createDiskStorage = (uploadPath) => {
  return multer.diskStorage({
    destination: (_, file, cb) => {
      try {
        const decodedName = decodeFileName(file.originalname);
        if (!uploadPath) {
          return cb(new Error("上传路径不能为空"), "");
        }
        if (isWindows$1 && uploadPath === "\\") {
          return cb(new Error("根目录不允许上传文件"), "");
        }
        if (decodedName.includes("/") || decodedName.includes("\\")) {
          const fullPath = path__default.join(uploadPath, path__default.dirname(decodedName));
          fs__default.mkdirSync(fullPath, { recursive: true });
          cb(null, fullPath);
        } else {
          cb(null, uploadPath);
        }
      } catch (error) {
        cb(error, "");
      }
    },
    filename: (_, file, cb) => {
      try {
        const decodedName = decodeFileName(file.originalname);
        const fileName = path__default.basename(decodedName);
        const fullPath = path__default.join(uploadPath, decodedName);
        if (fs__default.existsSync(fullPath)) {
          const ext = path__default.extname(fileName);
          const name = path__default.basename(fileName, ext);
          cb(null, `${name}-${randomUUID()}${ext}`);
        } else {
          cb(null, fileName);
        }
      } catch (error) {
        cb(error, "");
      }
    }
  });
};
const createDiskUpload = (uploadPath) => {
  const upload = multer({
    storage: createDiskStorage(uploadPath),
    limits: {
      fileSize: 100 * 1024 * 1024,
      // 100MB 文件大小限制
      files: 20,
      // 最多同时上传20个文件
      fieldSize: 1024 * 1024,
      // 1MB 字段大小限制
      fields: 10
      // 最多10个字段
    }
  }).array("files");
  return upload;
};
const diskUploader = (req, res) => {
  const uploadPath = req.query["path"] || "";
  return new Promise((resolve, reject) => {
    createDiskUpload(uploadPath)(req, res, (error) => {
      if (error) {
        if (error.code === "LIMIT_FILE_SIZE") {
          return reject(new Error("文件大小超过限制（最大100MB）"));
        }
        if (error.code === "LIMIT_FILE_COUNT") {
          return reject(new Error("文件数量超过限制（最多20个文件）"));
        }
        if (error.code === "LIMIT_FIELD_VALUE") {
          return reject(new Error("字段值大小超过限制"));
        }
        if (error.code === "LIMIT_FIELD_COUNT") {
          return reject(new Error("字段数量超过限制"));
        }
        return reject(error);
      }
      return resolve(true);
    });
  });
};

const isWindows = os__default.platform() === "win32";
const getQueryStringParam = (param) => {
  if (Array.isArray(param)) {
    return String(param[0] || "");
  }
  return String(param || "");
};
const getRootDirs = async () => {
  if (!isWindows) return ["/"];
  const drives = [];
  for (let i = 65; i <= 90; i++) {
    const driveLetter = String.fromCharCode(i);
    try {
      await fsProm.access(`${driveLetter}:\\`);
      drives.push(`${driveLetter}:`);
    } catch {
      continue;
    }
  }
  return drives.length > 0 ? drives : ["C:"];
};
const normalizePath = (inputPath) => {
  if (!inputPath) {
    return isWindows ? process.env["USERPROFILE"] || "C:\\" : "/";
  }
  const cleanedPath = inputPath.replace(/[\x01-\x1f\x7f]/g, "");
  if (isWindows && /^[A-Z]:[\\/]*$/i.test(cleanedPath)) {
    return cleanedPath.slice(0, 2) + "\\";
  }
  if (containsPathTraversal(cleanedPath)) {
    throw new Error("Invalid path: path traversal detected");
  }
  const normalized = path__default.resolve(cleanedPath);
  if (containsPathTraversal(normalized)) {
    throw new Error("Invalid path: path traversal detected after normalization");
  }
  const finalPath = normalized.replace(/[\\/]+/g, path__default.sep);
  return finalPath;
};
const containsPathTraversal = (inputPath) => {
  let decodedPath = inputPath;
  try {
    decodedPath = decodeURIComponent(inputPath);
  } catch {
  }
  const normalizedForCheck = decodedPath.replace(/\\/g, "/");
  const dangerousPatterns = [
    /\.\.\//,
    // ../ 模式
    /\/\.\./,
    // /.. 模式
    /^\.\./,
    // 以.. 开头
    /\.\.$/,
    // 以.. 结尾
    /\.\.\\/,
    // ..\ 模式（Windows）
    /\\\.\./,
    // \.. 模式（Windows）
    /%2e%2e/i,
    // URL编码的..
    /%252e%252e/i,
    // 双重URL编码的..
    // eslint-disable-next-line no-control-regex
    /\.\.\x00/,
    // null字节攻击
    /\0/
    // null字节
  ];
  return dangerousPatterns.some((pattern) => pattern.test(normalizedForCheck));
};
const SYSTEM_FILES = /* @__PURE__ */ new Set(["pagefile.sys", "swapfile.sys", "hiberfil.sys", "System Volume Information"]);
const isWebUIConfigFile = (filePath) => {
  if (!filePath.includes("webui.json")) {
    return false;
  }
  const webUIConfigPath = path__default.resolve(webUiPathWrapper.configPath, "webui.json").replace(/\\/g, "/");
  const targetPath = path__default.resolve(filePath).replace(/\\/g, "/");
  return targetPath === webUIConfigPath;
};
const sanitizeWebUIConfig = (content) => {
  try {
    const config = JSON.parse(content);
    if (config.token) {
      config.token = "******";
    }
    return JSON.stringify(config, null, 4);
  } catch {
    return content;
  }
};
const checkSameTypeExists = async (pathToCheck, isDirectory) => {
  try {
    const stat = await fsProm.stat(pathToCheck);
    return stat.isDirectory() === isDirectory;
  } catch {
    return false;
  }
};
const ListFilesHandler = async (req, res) => {
  try {
    const requestPath = getQueryStringParam(req.query["path"]) || (isWindows ? process.env["USERPROFILE"] || "C:\\" : "/");
    let normalizedPath;
    try {
      normalizedPath = normalizePath(requestPath);
    } catch (_pathError) {
      return sendError(res, "无效的文件路径");
    }
    const onlyDirectory = req.query["onlyDirectory"] === "true";
    if (isWindows && (!requestPath || requestPath === "/" || requestPath === "\\")) {
      const drives = await getRootDirs();
      const driveInfos = await Promise.all(
        drives.map(async (drive) => {
          try {
            const stat = await fsProm.stat(`${drive}\\`);
            return {
              name: drive,
              isDirectory: true,
              size: 0,
              mtime: stat.mtime
            };
          } catch {
            return {
              name: drive,
              isDirectory: true,
              size: 0,
              mtime: /* @__PURE__ */ new Date()
            };
          }
        })
      );
      return sendSuccess(res, driveInfos);
    }
    const files = await fsProm.readdir(normalizedPath);
    let fileInfos = [];
    for (const file of files) {
      if (SYSTEM_FILES.has(file)) continue;
      try {
        const fullPath = path__default.join(normalizedPath, file);
        const stat = await fsProm.stat(fullPath);
        fileInfos.push({
          name: file,
          isDirectory: stat.isDirectory(),
          size: stat.size,
          mtime: stat.mtime
        });
      } catch (_error) {
        continue;
      }
    }
    if (onlyDirectory) {
      fileInfos = fileInfos.filter((info) => info.isDirectory);
    }
    return sendSuccess(res, fileInfos);
  } catch (_error) {
    console.error("读取目录失败:", _error);
    return sendError(res, "读取目录失败");
  }
};
const CreateDirHandler = async (req, res) => {
  try {
    const { path: dirPath } = req.body;
    let normalizedPath;
    try {
      normalizedPath = normalizePath(dirPath);
    } catch (_pathError) {
      return sendError(res, "无效的文件路径");
    }
    if (!path__default.isAbsolute(normalizedPath)) {
      return sendError(res, "路径必须是绝对路径");
    }
    if (await checkSameTypeExists(normalizedPath, true)) {
      return sendError(res, "同名目录已存在");
    }
    await fsProm.mkdir(normalizedPath, { recursive: true });
    return sendSuccess(res, true);
  } catch (_error) {
    return sendError(res, "创建目录失败");
  }
};
const DeleteHandler = async (req, res) => {
  try {
    const { path: targetPath } = req.body;
    let normalizedPath;
    try {
      normalizedPath = normalizePath(targetPath);
    } catch (_pathError) {
      return sendError(res, "无效的文件路径");
    }
    if (!path__default.isAbsolute(normalizedPath)) {
      return sendError(res, "路径必须是绝对路径");
    }
    const stat = await fsProm.stat(normalizedPath);
    if (stat.isDirectory()) {
      await fsProm.rm(normalizedPath, { recursive: true });
    } else {
      await fsProm.unlink(normalizedPath);
    }
    return sendSuccess(res, true);
  } catch (_error) {
    return sendError(res, "删除失败");
  }
};
const BatchDeleteHandler = async (req, res) => {
  try {
    const { paths } = req.body;
    for (const targetPath of paths) {
      let normalizedPath;
      try {
        normalizedPath = normalizePath(targetPath);
      } catch (_pathError) {
        return sendError(res, "无效的文件路径");
      }
      if (!path__default.isAbsolute(normalizedPath)) {
        return sendError(res, "路径必须是绝对路径");
      }
      const stat = await fsProm.stat(normalizedPath);
      if (stat.isDirectory()) {
        await fsProm.rm(normalizedPath, { recursive: true });
      } else {
        await fsProm.unlink(normalizedPath);
      }
    }
    return sendSuccess(res, true);
  } catch (_error) {
    return sendError(res, "批量删除失败");
  }
};
const ReadFileHandler = async (req, res) => {
  try {
    let filePath;
    try {
      filePath = normalizePath(getQueryStringParam(req.query["path"]));
    } catch (_pathError) {
      return sendError(res, "无效的文件路径");
    }
    if (!path__default.isAbsolute(filePath)) {
      return sendError(res, "路径必须是绝对路径");
    }
    let content = await fsProm.readFile(filePath, "utf-8");
    if (isWebUIConfigFile(filePath)) {
      content = sanitizeWebUIConfig(content);
    }
    return sendSuccess(res, content);
  } catch (_error) {
    return sendError(res, "读取文件失败");
  }
};
const WriteFileHandler = async (req, res) => {
  try {
    const { path: filePath, content } = req.body;
    let normalizedPath;
    try {
      normalizedPath = normalizePath(filePath);
    } catch (_pathError) {
      return sendError(res, "无效的文件路径");
    }
    if (!path__default.isAbsolute(normalizedPath)) {
      return sendError(res, "路径必须是绝对路径");
    }
    let finalContent = content;
    if (isWebUIConfigFile(normalizedPath)) {
      try {
        const configToWrite = JSON.parse(content);
        const memoryToken = getInitialWebUiToken();
        if (memoryToken) {
          configToWrite.token = memoryToken;
          finalContent = JSON.stringify(configToWrite, null, 4);
        }
      } catch (_e) {
        return sendError(res, "写入的WebUI配置文件内容格式错误，必须是合法的JSON");
      }
    }
    await fsProm.writeFile(normalizedPath, finalContent, "utf-8");
    return sendSuccess(res, true);
  } catch (_error) {
    return sendError(res, "写入文件失败");
  }
};
const CreateFileHandler = async (req, res) => {
  try {
    const { path: filePath } = req.body;
    let normalizedPath;
    try {
      normalizedPath = normalizePath(filePath);
    } catch (_pathError) {
      return sendError(res, "无效的文件路径");
    }
    if (!path__default.isAbsolute(normalizedPath)) {
      return sendError(res, "路径必须是绝对路径");
    }
    if (await checkSameTypeExists(normalizedPath, false)) {
      return sendError(res, "同名文件已存在");
    }
    await fsProm.writeFile(normalizedPath, "", "utf-8");
    return sendSuccess(res, true);
  } catch (_error) {
    return sendError(res, "创建文件失败");
  }
};
const RenameHandler = async (req, res) => {
  try {
    const { oldPath, newPath } = req.body;
    let normalizedOldPath;
    let normalizedNewPath;
    try {
      normalizedOldPath = normalizePath(oldPath);
      normalizedNewPath = normalizePath(newPath);
    } catch (_pathError) {
      return sendError(res, "无效的文件路径");
    }
    if (!path__default.isAbsolute(normalizedOldPath) || !path__default.isAbsolute(normalizedNewPath)) {
      return sendError(res, "路径必须是绝对路径");
    }
    await fsProm.rename(normalizedOldPath, normalizedNewPath);
    return sendSuccess(res, true);
  } catch (_error) {
    return sendError(res, "重命名失败");
  }
};
const MoveHandler = async (req, res) => {
  try {
    const { sourcePath, targetPath } = req.body;
    let normalizedSourcePath;
    let normalizedTargetPath;
    try {
      normalizedSourcePath = normalizePath(sourcePath);
      normalizedTargetPath = normalizePath(targetPath);
    } catch (_pathError) {
      return sendError(res, "无效的文件路径");
    }
    if (!path__default.isAbsolute(normalizedSourcePath) || !path__default.isAbsolute(normalizedTargetPath)) {
      return sendError(res, "路径必须是绝对路径");
    }
    await fsProm.rename(normalizedSourcePath, normalizedTargetPath);
    return sendSuccess(res, true);
  } catch (_error) {
    return sendError(res, "移动失败");
  }
};
const BatchMoveHandler = async (req, res) => {
  try {
    const { items } = req.body;
    for (const { sourcePath, targetPath } of items) {
      let normalizedSourcePath;
      let normalizedTargetPath;
      try {
        normalizedSourcePath = normalizePath(sourcePath);
        normalizedTargetPath = normalizePath(targetPath);
      } catch (_pathError) {
        return sendError(res, "无效的文件路径");
      }
      if (!path__default.isAbsolute(normalizedSourcePath) || !path__default.isAbsolute(normalizedTargetPath)) {
        return sendError(res, "路径必须是绝对路径");
      }
      await fsProm.rename(normalizedSourcePath, normalizedTargetPath);
    }
    return sendSuccess(res, true);
  } catch (_error) {
    return sendError(res, "批量移动失败");
  }
};
const DownloadHandler = async (req, res) => {
  try {
    let filePath;
    try {
      filePath = normalizePath(getQueryStringParam(req.query["path"]));
    } catch (_pathError) {
      return sendError(res, "无效的文件路径");
    }
    if (!filePath) {
      return sendError(res, "参数错误");
    }
    if (!path__default.isAbsolute(filePath)) {
      return sendError(res, "路径必须是绝对路径");
    }
    const stat = await fsProm.stat(filePath);
    res.setHeader("Content-Type", "application/octet-stream");
    let filename = path__default.basename(filePath);
    if (stat.isDirectory()) {
      filename = path__default.basename(filePath) + ".zip";
      res.setHeader("Content-Disposition", `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`);
      const zipStream = new PassThrough$1();
      compressing.zip.compressDir(filePath, zipStream).catch((err) => {
        console.error("压缩目录失败:", err);
        res.end();
      });
      zipStream.pipe(res);
      return;
    }
    res.setHeader("Content-Length", stat.size);
    res.setHeader("Content-Disposition", `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`);
    const stream = fs__default.createReadStream(filePath);
    stream.pipe(res);
  } catch (_error) {
    return sendError(res, "下载失败");
  }
};
const BatchDownloadHandler = async (req, res) => {
  try {
    const { paths } = req.body;
    if (!paths || !Array.isArray(paths) || paths.length === 0) {
      return sendError(res, "参数错误");
    }
    res.setHeader("Content-Type", "application/octet-stream");
    res.setHeader("Content-Disposition", "attachment; filename=files.zip");
    const zipStream = new compressing.zip.Stream();
    for (const filePath of paths) {
      let normalizedPath;
      try {
        normalizedPath = normalizePath(filePath);
      } catch (_pathError) {
        return sendError(res, "无效的文件路径");
      }
      if (!path__default.isAbsolute(normalizedPath)) {
        return sendError(res, "路径必须是绝对路径");
      }
      const stat = await fsProm.stat(normalizedPath);
      if (stat.isDirectory()) {
        zipStream.addEntry(normalizedPath, { relativePath: "" });
      } else {
        const safeName = path__default.basename(normalizedPath);
        zipStream.addEntry(normalizedPath, { relativePath: safeName });
      }
    }
    zipStream.pipe(res);
    res.on("finish", () => {
      zipStream.destroy();
    });
  } catch (_error) {
    return sendError(res, "下载失败");
  }
};
const UploadHandler = async (req, res) => {
  try {
    await diskUploader(req, res);
    return sendSuccess(res, true, "文件上传成功", true);
  } catch (_error) {
    let errorMessage = "文件上传失败";
    if (_error instanceof multer.MulterError) {
      switch (_error.code) {
        case "LIMIT_FILE_SIZE":
          errorMessage = "文件大小超过限制（40MB）";
          break;
        case "LIMIT_UNEXPECTED_FILE":
          errorMessage = "无效的文件上传字段";
          break;
        default:
          errorMessage = `上传错误: ${_error.message}`;
      }
    } else if (_error instanceof Error) {
      errorMessage = _error.message;
    }
    return sendError(res, errorMessage, true);
  }
};
const UploadWebUIFontHandler = async (req, res) => {
  try {
    await webUIFontUploader(req, res);
    return sendSuccess(res, true, "字体文件上传成功", true);
  } catch (error) {
    let errorMessage = "字体文件上传失败";
    if (error instanceof multer.MulterError) {
      switch (error.code) {
        case "LIMIT_FILE_SIZE":
          errorMessage = "字体文件大小超过限制（40MB）";
          break;
        case "LIMIT_UNEXPECTED_FILE":
          errorMessage = "无效的文件上传字段";
          break;
        default:
          errorMessage = `上传错误: ${error.message}`;
      }
    } else if (error instanceof Error) {
      errorMessage = error.message;
    }
    return sendError(res, errorMessage, true);
  }
};
const DeleteWebUIFontHandler = async (_req, res) => {
  try {
    const fontPath = await WebUiConfig.GetWebUIFontPath();
    const exists = await WebUiConfig.CheckWebUIFontExist();
    if (!exists || !fontPath) {
      return sendSuccess(res, true);
    }
    await fsProm.unlink(fontPath);
    return sendSuccess(res, true);
  } catch (_error) {
    return sendError(res, "删除字体文件失败");
  }
};

const router$4 = Router();
const apiLimiter = lib_default({
  windowMs: 1 * 60 * 1e3,
  // 1分钟内
  max: 60,
  // 最大60个请求
  validate: {
    xForwardedForHeader: false
  }
});
router$4.use(apiLimiter);
router$4.get("/list", ListFilesHandler);
router$4.post("/mkdir", CreateDirHandler);
router$4.post("/delete", DeleteHandler);
router$4.get("/read", ReadFileHandler);
router$4.post("/write", WriteFileHandler);
router$4.post("/create", CreateFileHandler);
router$4.post("/batchDelete", BatchDeleteHandler);
router$4.post("/rename", RenameHandler);
router$4.post("/move", MoveHandler);
router$4.post("/batchMove", BatchMoveHandler);
router$4.post("/download", DownloadHandler);
router$4.post("/batchDownload", BatchDownloadHandler);
router$4.post("/upload", UploadHandler);
router$4.post("/font/upload/webui", UploadWebUIFontHandler);
router$4.post("/font/delete/webui", DeleteWebUIFontHandler);

const GetWebUIConfigHandler = async (_, res) => {
  try {
    const config = await WebUiConfig.GetWebUIConfig();
    return sendSuccess(res, {
      host: config.host,
      port: config.port,
      loginRate: config.loginRate,
      disableWebUI: config.disableWebUI,
      disableNonLANAccess: config.disableNonLANAccess
    });
  } catch (error) {
    const msg = error.message;
    return sendError(res, `获取WebUI配置失败: ${msg}`);
  }
};
const GetDisableWebUIHandler = async (_, res) => {
  try {
    const disable = await WebUiConfig.GetDisableWebUI();
    return sendSuccess(res, disable);
  } catch (error) {
    const msg = error.message;
    return sendError(res, `获取WebUI禁用状态失败: ${msg}`);
  }
};
const UpdateDisableWebUIHandler = async (req, res) => {
  try {
    const { disable } = req.body;
    if (typeof disable !== "boolean") {
      return sendError(res, "disable参数必须是布尔值");
    }
    await WebUiConfig.UpdateDisableWebUI(disable);
    return sendSuccess(res, null);
  } catch (error) {
    const msg = error.message;
    return sendError(res, `更新WebUI禁用状态失败: ${msg}`);
  }
};
const GetDisableNonLANAccessHandler = async (_, res) => {
  try {
    const disable = await WebUiConfig.GetDisableNonLANAccess();
    return sendSuccess(res, disable);
  } catch (error) {
    const msg = error.message;
    return sendError(res, `获取非局域网访问禁用状态失败: ${msg}`);
  }
};
const UpdateDisableNonLANAccessHandler = async (req, res) => {
  try {
    const { disable } = req.body;
    if (typeof disable !== "boolean") {
      return sendError(res, "disable参数必须是布尔值");
    }
    await WebUiConfig.UpdateDisableNonLANAccess(disable);
    return sendSuccess(res, null);
  } catch (error) {
    const msg = error.message;
    return sendError(res, `更新非局域网访问禁用状态失败: ${msg}`);
  }
};
const UpdateWebUIConfigHandler = async (req, res) => {
  try {
    const { host, port, loginRate, disableWebUI, disableNonLANAccess } = req.body;
    const updateConfig = {};
    if (host !== void 0) {
      if (isEmpty(host)) {
        return sendError(res, "host不能为空");
      }
      updateConfig.host = host;
    }
    if (port !== void 0) {
      if (!Number.isInteger(port) || port < 1 || port > 65535) {
        return sendError(res, "port必须是1-65535之间的整数");
      }
      updateConfig.port = port;
    }
    if (loginRate !== void 0) {
      if (!Number.isInteger(loginRate) || loginRate < 1) {
        return sendError(res, "loginRate必须是大于0的整数");
      }
      updateConfig.loginRate = loginRate;
    }
    if (disableWebUI !== void 0) {
      if (typeof disableWebUI !== "boolean") {
        return sendError(res, "disableWebUI必须是布尔值");
      }
      updateConfig.disableWebUI = disableWebUI;
    }
    if (disableNonLANAccess !== void 0) {
      if (typeof disableNonLANAccess !== "boolean") {
        return sendError(res, "disableNonLANAccess必须是布尔值");
      }
      updateConfig.disableNonLANAccess = disableNonLANAccess;
    }
    await WebUiConfig.UpdateWebUIConfig(updateConfig);
    return sendSuccess(res, null);
  } catch (error) {
    const msg = error.message;
    return sendError(res, `更新WebUI配置失败: ${msg}`);
  }
};

const router$3 = Router();
router$3.get("/GetConfig", GetWebUIConfigHandler);
router$3.post("/UpdateConfig", UpdateWebUIConfigHandler);
router$3.get("/GetDisableWebUI", GetDisableWebUIHandler);
router$3.post("/UpdateDisableWebUI", UpdateDisableWebUIHandler);
router$3.get("/GetDisableNonLANAccess", GetDisableNonLANAccessHandler);
router$3.post("/UpdateDisableNonLANAccess", UpdateDisableNonLANAccessHandler);

const SKIP_UPDATE_FILES = [
  "NapCatWinBootMain.exe",
  "NapCatWinBootHook.dll"
];
function scanFilesRecursively(dirPath, basePath = dirPath) {
  const files = [];
  const items = fs.readdirSync(dirPath);
  for (const item of items) {
    const fullPath = path.join(dirPath, item);
    const relativePath = path.relative(basePath, fullPath);
    const stat = fs.statSync(fullPath);
    if (stat.isDirectory()) {
      files.push(...scanFilesRecursively(fullPath, basePath));
    } else if (stat.isFile()) {
      files.push({
        sourcePath: fullPath,
        relativePath
      });
    }
  }
  return files;
}
const mirrorUrls = [
  "https://j.1win.ggff.net/",
  "https://git.yylx.win/",
  "https://ghfile.geekertao.top/",
  "https://gh-proxy.net/",
  "https://ghm.078465.xyz/",
  "https://gitproxy.127731.xyz/",
  "https://jiashu.1win.eu.org/",
  ""
  // 原始URL
];
async function testUrl(url) {
  return new Promise((resolve) => {
    const req = https.get(url, { timeout: 5e3 }, (res) => {
      const statusCode = res.statusCode || 0;
      if (statusCode >= 200 && statusCode < 300) {
        req.destroy();
        resolve(true);
      } else {
        req.destroy();
        resolve(false);
      }
    });
    req.on("error", () => resolve(false));
    req.on("timeout", () => {
      req.destroy();
      resolve(false);
    });
  });
}
function buildMirrorUrl(originalUrl, mirror) {
  if (!mirror) return originalUrl;
  return mirror + originalUrl;
}
async function findAvailableUrl(originalUrl) {
  console.log("Testing download URLs...");
  if (await testUrl(originalUrl)) {
    console.log("Using original URL:", originalUrl);
    return originalUrl;
  }
  for (const mirror of mirrorUrls) {
    const mirrorUrl = buildMirrorUrl(originalUrl, mirror);
    console.log("Testing mirror:", mirrorUrl);
    if (await testUrl(mirrorUrl)) {
      console.log("Using mirror URL:", mirrorUrl);
      return mirrorUrl;
    }
  }
  throw new Error("所有下载源都不可用");
}
async function downloadFile(url, dest) {
  console.log("Starting download from:", url);
  const file = fs.createWriteStream(dest);
  return new Promise((resolve, reject) => {
    const request = https.get(url, {
      headers: { "User-Agent": "NapCat-WebUI" }
    }, (res) => {
      console.log("Response status:", res.statusCode);
      console.log("Content-Type:", res.headers["content-type"]);
      if (res.statusCode === 302 || res.statusCode === 301) {
        console.log("Following redirect to:", res.headers.location);
        file.close();
        fs.unlinkSync(dest);
        downloadFile(res.headers.location, dest).then(resolve).catch(reject);
        return;
      }
      if (res.statusCode !== 200) {
        file.close();
        fs.unlinkSync(dest);
        reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`));
        return;
      }
      res.pipe(file);
      file.on("finish", () => {
        file.close();
        console.log("Download completed");
        resolve();
      });
    });
    request.on("error", (err) => {
      console.error("Download error:", err);
      file.close();
      fs.unlink(dest, () => {
      });
      reject(err);
    });
  });
}
const UpdateNapCatHandler = async (_req, res) => {
  try {
    const latestRelease = await getLatestRelease();
    const ReleaseName = WebUiDataRuntime.getWorkingEnv() === NapCatCoreWorkingEnv.Framework ? "NapCat.Framework.zip" : "NapCat.Shell.zip";
    const shellZipAsset = latestRelease.assets.find((asset) => asset.name === ReleaseName);
    if (!shellZipAsset) {
      throw new Error(`未找到${ReleaseName}文件`);
    }
    const tempDir = path.join(webUiPathWrapper.binaryPath, "./temp");
    if (!fs.existsSync(tempDir)) {
      fs.mkdirSync(tempDir, { recursive: true });
    }
    const downloadUrl = await findAvailableUrl(shellZipAsset.browser_download_url);
    const zipPath = path.join(tempDir, "napcat-latest.zip");
    console.log("[NapCat Update] Saving to:", zipPath);
    await downloadFile(downloadUrl, zipPath);
    const stats = fs.statSync(zipPath);
    console.log("[NapCat Update] Downloaded file size:", stats.size, "bytes");
    const extractPath = path.join(tempDir, "napcat-extract");
    console.log("[NapCat Update] Extracting to:", extractPath);
    await compressing.zip.uncompress(zipPath, extractPath);
    const sourcePath = extractPath;
    try {
      const allFiles = scanFilesRecursively(sourcePath);
      const failedFiles = [];
      for (const fileInfo of allFiles) {
        const targetFilePath = path.join(webUiPathWrapper.binaryPath, fileInfo.relativePath);
        if (SKIP_UPDATE_FILES.includes(path.basename(fileInfo.relativePath))) {
          console.log(`[NapCat Update] Skipping update for ${fileInfo.relativePath}`);
          continue;
        }
        try {
          const targetDir = path.dirname(targetFilePath);
          if (!fs.existsSync(targetDir)) {
            fs.mkdirSync(targetDir, { recursive: true });
          }
          if (fs.existsSync(targetFilePath)) {
            fs.unlinkSync(targetFilePath);
          }
          fs.copyFileSync(fileInfo.sourcePath, targetFilePath);
        } catch (error) {
          console.log(`[NapCat Update] Failed to update ${targetFilePath}, will retry on next startup:`, error);
          failedFiles.push({
            sourcePath: fileInfo.sourcePath,
            targetPath: targetFilePath
          });
        }
      }
      if (failedFiles.length > 0) {
        const updateConfig = {
          version: latestRelease.tag_name,
          updateTime: (/* @__PURE__ */ new Date()).toISOString(),
          files: failedFiles,
          changelog: latestRelease.body || ""
        };
        const configPath = path.join(webUiPathWrapper.configPath, "napcat-update.json");
        fs.writeFileSync(configPath, JSON.stringify(updateConfig, null, 2));
        console.log(`[NapCat Update] Update config saved for ${failedFiles.length} failed files: ${configPath}`);
      }
      const message = failedFiles.length > 0 ? `更新完成，重启应用以应用剩余${failedFiles.length}个文件的更新` : "更新完成";
      sendSuccess(res, {
        status: "completed",
        message,
        newVersion: latestRelease.tag_name,
        failedFilesCount: failedFiles.length
      });
    } catch (error) {
      console.error("更新失败:", error);
      sendError(res, "更新失败: " + (error instanceof Error ? error.message : "未知错误"));
    }
  } catch (error) {
    console.error("更新失败:", error);
    sendError(res, "更新失败: " + error.message);
  }
};
async function getLatestRelease() {
  return new Promise((resolve, reject) => {
    https.get("https://api.github.com/repos/NapNeko/NapCatQQ/releases/latest", {
      headers: { "User-Agent": "NapCat-WebUI" }
    }, (res) => {
      let data = "";
      res.on("data", (chunk) => data += chunk);
      res.on("end", () => {
        try {
          const release = JSON.parse(data);
          console.log("Release info:", {
            tag_name: release.tag_name,
            assets: release.assets?.map((a) => ({ name: a.name, url: a.browser_download_url }))
          });
          resolve(release);
        } catch (e) {
          reject(e);
        }
      });
    }).on("error", reject);
  });
}
async function applyPendingUpdates(webUiPathWrapper2) {
  const configPath = path.join(webUiPathWrapper2.configPath, "napcat-update.json");
  if (!fs.existsSync(configPath)) {
    console.log("No pending updates found");
    return;
  }
  try {
    console.log("[NapCat Update] Applying pending updates...");
    const updateConfig = JSON.parse(fs.readFileSync(configPath, "utf8"));
    const remainingFiles = [];
    for (const file of updateConfig.files) {
      try {
        if (!fs.existsSync(file.sourcePath)) {
          console.warn(`[NapCat Update] Source file not found: ${file.sourcePath}`);
          continue;
        }
        const targetDir = path.dirname(file.targetPath);
        if (!fs.existsSync(targetDir)) {
          fs.mkdirSync(targetDir, { recursive: true });
        }
        if (fs.existsSync(file.targetPath)) {
          fs.unlinkSync(file.targetPath);
        }
        fs.copyFileSync(file.sourcePath, file.targetPath);
        console.log(`[NapCat Update] Updated ${path.basename(file.targetPath)} on startup`);
      } catch (error) {
        console.error(`[NapCat Update] Failed to update ${file.targetPath} on startup:`, error);
        remainingFiles.push(file);
      }
    }
    if (remainingFiles.length > 0) {
      const updatedConfig = {
        ...updateConfig,
        files: remainingFiles
      };
      fs.writeFileSync(configPath, JSON.stringify(updatedConfig, null, 2));
      console.log(`${remainingFiles.length} files still pending update`);
    } else {
      fs.unlinkSync(configPath);
      console.log("[NapCat Update] All pending updates applied successfully");
    }
  } catch (error) {
    console.error("[NapCat Update] Failed to apply pending updates:", error);
  }
}

const router$2 = Router();
router$2.post("/update", UpdateNapCatHandler);

var EventType = /* @__PURE__ */ ((EventType2) => {
  EventType2["META"] = "meta_event";
  EventType2["REQUEST"] = "request";
  EventType2["NOTICE"] = "notice";
  EventType2["MESSAGE"] = "message";
  EventType2["MESSAGE_SENT"] = "message_sent";
  return EventType2;
})(EventType || {});
class OneBotEvent {
  time = Math.floor(Date.now() / 1e3);
  self_id;
  constructor(core) {
    this.self_id = parseInt(core.selfInfo.uin);
  }
}

class OB11BaseMetaEvent extends OneBotEvent {
  post_type = EventType.META;
}

var LifeCycleSubType = /* @__PURE__ */ ((LifeCycleSubType2) => {
  LifeCycleSubType2["ENABLE"] = "enable";
  LifeCycleSubType2["DISABLE"] = "disable";
  LifeCycleSubType2["CONNECT"] = "connect";
  return LifeCycleSubType2;
})(LifeCycleSubType || {});
class OB11LifeCycleEvent extends OB11BaseMetaEvent {
  meta_event_type = "lifecycle";
  sub_type;
  constructor(core, subType) {
    super(core);
    this.sub_type = subType;
  }
}

const router$1 = Router();
const DEFAULT_ADAPTER_NAME = "debug-primary";
class DebugAdapter {
  name;
  isEnable = true;
  // 安全令牌
  token;
  // 添加 config 属性，模拟 PluginConfig 结构
  config;
  wsClients = /* @__PURE__ */ new Set();
  lastActivityTime = Date.now();
  inactivityTimer = null;
  INACTIVITY_TIMEOUT = 5 * 60 * 1e3;
  // 5分钟不活跃
  constructor(sessionId) {
    this.name = `debug-${sessionId}`;
    this.token = Math.random().toString(36).substring(2) + Math.random().toString(36).substring(2);
    this.config = {
      enable: true,
      name: this.name,
      messagePostFormat: "array",
      reportSelfMessage: true,
      debug: true,
      token: this.token,
      heartInterval: 3e4
    };
    this.startInactivityCheck();
  }
  // 实现 IOB11NetworkAdapter 接口所需的抽象方法
  async open() {
  }
  async close() {
    this.cleanup();
  }
  async reload(_config) {
    return 0;
  }
  /**
   * OneBot 事件回调 - 转发给所有 WebSocket 客户端 (原始流)
   */
  async onEvent(event) {
    this.updateActivity();
    const payload = JSON.stringify(event);
    if (this.wsClients.size === 0) {
      return;
    }
    this.wsClients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        try {
          client.send(payload);
        } catch (error) {
          console.error("[Debug] 发送事件到 WebSocket 失败:", error);
        }
      }
    });
  }
  /**
   * 调用 OneBot API (HTTP 接口使用)
   */
  async callApi(actionName, params) {
    this.updateActivity();
    const oneBotContext = WebUiDataRuntime.getOneBotContext();
    if (!oneBotContext) {
      throw new Error("OneBot 未初始化");
    }
    const action = oneBotContext.actions.get(actionName);
    if (!action) {
      throw new Error(`不支持的 API: ${actionName}`);
    }
    return await action.handle(params, this.name, {
      name: this.name,
      enable: true,
      messagePostFormat: "array",
      reportSelfMessage: true,
      debug: true
    });
  }
  /**
   * 处理 WebSocket 消息 (OneBot 标准)
   */
  async handleWsMessage(ws, message) {
    this.updateActivity();
    let receiveData = { action: ActionName.Unknown, params: {} };
    let echo;
    try {
      receiveData = JSON.parse(message.toString());
      echo = receiveData.echo;
    } catch {
      this.sendWsResponse(ws, OB11Response.error("json解析失败,请检查数据格式", 1400, echo));
      return;
    }
    receiveData.params = receiveData?.params ? receiveData.params : {};
    const oneBotContext = WebUiDataRuntime.getOneBotContext();
    if (!oneBotContext) {
      this.sendWsResponse(ws, OB11Response.error("OneBot 未初始化", 1404, echo));
      return;
    }
    const action = oneBotContext.actions.get(receiveData.action);
    if (!action) {
      this.sendWsResponse(ws, OB11Response.error("不支持的API " + receiveData.action, 1404, echo));
      return;
    }
    try {
      const retdata = await action.websocketHandle(receiveData.params, echo ?? "", this.name, this.config, {
        send: async (data) => {
          this.sendWsResponse(ws, OB11Response.ok(data, echo ?? "", true));
        }
      });
      this.sendWsResponse(ws, retdata);
    } catch (e) {
      this.sendWsResponse(ws, OB11Response.error(e.message || "内部错误", 1200, echo));
    }
  }
  sendWsResponse(ws, data) {
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify(data));
    }
  }
  /**
   * 添加 WebSocket 客户端
   */
  addWsClient(ws) {
    this.wsClients.add(ws);
    this.updateActivity();
    const oneBotContext = WebUiDataRuntime.getOneBotContext();
    if (oneBotContext && oneBotContext.core) {
      try {
        const event = new OB11LifeCycleEvent(oneBotContext.core, LifeCycleSubType.CONNECT);
        ws.send(JSON.stringify(event));
      } catch (e) {
        console.error("[Debug] 发送生命周期事件失败", e);
      }
    }
  }
  /**
   * 移除 WebSocket 客户端
   */
  removeWsClient(ws) {
    this.wsClients.delete(ws);
  }
  updateActivity() {
    this.lastActivityTime = Date.now();
  }
  startInactivityCheck() {
    this.inactivityTimer = setInterval(() => {
      const inactive = Date.now() - this.lastActivityTime;
      if (inactive > this.INACTIVITY_TIMEOUT && this.wsClients.size === 0) {
        console.log(`[Debug] Adapter ${this.name} 不活跃，自动关闭`);
        this.cleanup();
      }
    }, 3e4);
  }
  cleanup() {
    if (this.inactivityTimer) {
      clearInterval(this.inactivityTimer);
      this.inactivityTimer = null;
    }
    this.wsClients.forEach((client) => {
      try {
        client.close();
      } catch (error) {
      }
    });
    this.wsClients.clear();
    const oneBotContext = WebUiDataRuntime.getOneBotContext();
    if (oneBotContext) {
      oneBotContext.networkManager.adapters.delete(this.name);
    }
    debugAdapterManager.removeAdapter(this.name);
  }
  /**
   * 验证 Token
   */
  validateToken(inputToken) {
    return this.token === inputToken;
  }
}
class DebugAdapterManager {
  currentAdapter = null;
  getOrCreateAdapter() {
    if (this.currentAdapter) {
      this.currentAdapter.updateActivity();
      return this.currentAdapter;
    }
    const adapter = new DebugAdapter("primary");
    this.currentAdapter = adapter;
    const oneBotContext = WebUiDataRuntime.getOneBotContext();
    if (oneBotContext) {
      oneBotContext.networkManager.adapters.set(adapter.name, adapter);
    } else {
      console.warn("[Debug] OneBot 未初始化，无法注册适配器");
    }
    return adapter;
  }
  getAdapter(name) {
    if (this.currentAdapter && this.currentAdapter.name === name) {
      return this.currentAdapter;
    }
    return void 0;
  }
  removeAdapter(name) {
    if (this.currentAdapter && this.currentAdapter.name === name) {
      this.currentAdapter = null;
    }
  }
}
const debugAdapterManager = new DebugAdapterManager();
router$1.post("/create", async (_req, res) => {
  try {
    const adapter = debugAdapterManager.getOrCreateAdapter();
    sendSuccess(res, {
      adapterName: adapter.name,
      token: adapter.token,
      message: "调试适配器已就绪"
    });
  } catch (error) {
    sendError(res, error.message);
  }
});
const handleCallApi = async (req, res) => {
  try {
    let adapterName = req.params["adapterName"] || req.body.adapterName || DEFAULT_ADAPTER_NAME;
    let adapter = debugAdapterManager.getAdapter(adapterName);
    if (!adapter && adapterName === DEFAULT_ADAPTER_NAME) {
      adapter = debugAdapterManager.getOrCreateAdapter();
    }
    if (!adapter) {
      return sendError(res, "调试适配器不存在");
    }
    const { action, params } = req.body;
    const result = await adapter.callApi(action, params || {});
    sendSuccess(res, result);
  } catch (error) {
    sendError(res, error.message);
  }
};
router$1.post("/call/:adapterName", handleCallApi);
router$1.post("/call", handleCallApi);
router$1.post("/close/:adapterName", async (req, res) => {
  try {
    const { adapterName } = req.params;
    if (!adapterName) {
      return sendError(res, "缺少 adapterName 参数");
    }
    debugAdapterManager.removeAdapter(adapterName);
    sendSuccess(res, { message: "调试适配器已关闭" });
  } catch (error) {
    sendError(res, error.message);
  }
});
function handleDebugWebSocket(request, socket, head) {
  const url = new URL(request.url || "", `http://${request.headers.host}`);
  let adapterName = url.searchParams.get("adapterName");
  const token = url.searchParams.get("token") || url.searchParams.get("access_token");
  if (!adapterName) {
    adapterName = DEFAULT_ADAPTER_NAME;
  }
  if (!token) {
    console.log("[Debug] WebSocket 连接被拒绝: 缺少 Token");
    socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
    socket.destroy();
    return;
  }
  let adapter = debugAdapterManager.getAdapter(adapterName);
  if (!adapter && adapterName === DEFAULT_ADAPTER_NAME) {
    adapter = debugAdapterManager.getOrCreateAdapter();
  }
  if (!adapter) {
    console.log("[Debug] WebSocket 连接被拒绝: 适配器不存在");
    socket.write("HTTP/1.1 404 Not Found\r\n\r\n");
    socket.destroy();
    return;
  }
  if (!adapter.validateToken(token)) {
    console.log("[Debug] WebSocket 连接被拒绝: Token 无效");
    socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
    socket.destroy();
    return;
  }
  const wsServer = new WebSocketServer({ noServer: true });
  wsServer.handleUpgrade(request, socket, head, (ws) => {
    adapter.addWsClient(ws);
    ws.on("message", async (data) => {
      try {
        await adapter.handleWsMessage(ws, data);
      } catch (error) {
        console.error("[Debug] handleWsMessage error", error);
      }
    });
    ws.on("close", () => {
      adapter.removeWsClient(ws);
    });
    ws.on("error", () => {
      adapter.removeWsClient(ws);
    });
  });
}

const router = Router();
router.use(auth);
router.all("/test", (_, res) => {
  return sendSuccess(res);
});
router.use("/base", router$5);
router.use("/auth", router$7);
router.use("/QQLogin", router$8);
router.use("/OB11Config", router$9);
router.use("/Log", router$6);
router.use("/File", router$4);
router.use("/WebUIConfig", router$3);
router.use("/UpdateNapCat", router$2);
router.use("/Debug", router$1);

function isLANIP(ip) {
  if (!ip) return false;
  const cleanIP = ip.replace(/^::ffff:/, "");
  if (cleanIP === "127.0.0.1" || cleanIP === "localhost" || cleanIP === "::1") {
    return true;
  }
  const ipv4Regex = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
  const match = cleanIP.match(ipv4Regex);
  if (match) {
    const [, a, b] = match.map(Number);
    if (a === 10) return true;
    if (a === 172 && b !== void 0 && b >= 16 && b <= 31) return true;
    if (a === 192 && b === 168) return true;
    if (a === 169 && b === 254) return true;
  }
  return false;
}
const cors$1 = async (req, res, next) => {
  const config = await WebUiConfig.GetWebUIConfig();
  if (config.disableNonLANAccess) {
    const clientIP = req.ip || req.socket.remoteAddress || "";
    if (!isLANIP(clientIP)) {
      res.status(403).json({ error: "非局域网访问被禁止" });
      return;
    }
  }
  const origin = req.headers.origin || "*";
  res.header("Access-Control-Allow-Origin", origin);
  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  res.header("Access-Control-Allow-Credentials", "true");
  if (req.method === "OPTIONS") {
    res.sendStatus(204);
    return;
  }
  next();
};

var compression$1 = {exports: {}};

var negotiator = {exports: {}};

var charset = {exports: {}};

/**
 * negotiator
 * Copyright(c) 2012 Isaac Z. Schlueter
 * Copyright(c) 2014 Federico Romero
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
 * MIT Licensed
 */

var hasRequiredCharset;

function requireCharset () {
	if (hasRequiredCharset) return charset.exports;
	hasRequiredCharset = 1;

	/**
	 * Module exports.
	 * @public
	 */

	charset.exports = preferredCharsets;
	charset.exports.preferredCharsets = preferredCharsets;

	/**
	 * Module variables.
	 * @private
	 */

	var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/;

	/**
	 * Parse the Accept-Charset header.
	 * @private
	 */

	function parseAcceptCharset(accept) {
	  var accepts = accept.split(',');

	  for (var i = 0, j = 0; i < accepts.length; i++) {
	    var charset = parseCharset(accepts[i].trim(), i);

	    if (charset) {
	      accepts[j++] = charset;
	    }
	  }

	  // trim accepts
	  accepts.length = j;

	  return accepts;
	}

	/**
	 * Parse a charset from the Accept-Charset header.
	 * @private
	 */

	function parseCharset(str, i) {
	  var match = simpleCharsetRegExp.exec(str);
	  if (!match) return null;

	  var charset = match[1];
	  var q = 1;
	  if (match[2]) {
	    var params = match[2].split(';');
	    for (var j = 0; j < params.length; j++) {
	      var p = params[j].trim().split('=');
	      if (p[0] === 'q') {
	        q = parseFloat(p[1]);
	        break;
	      }
	    }
	  }

	  return {
	    charset: charset,
	    q: q,
	    i: i
	  };
	}

	/**
	 * Get the priority of a charset.
	 * @private
	 */

	function getCharsetPriority(charset, accepted, index) {
	  var priority = {o: -1, q: 0, s: 0};

	  for (var i = 0; i < accepted.length; i++) {
	    var spec = specify(charset, accepted[i], index);

	    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
	      priority = spec;
	    }
	  }

	  return priority;
	}

	/**
	 * Get the specificity of the charset.
	 * @private
	 */

	function specify(charset, spec, index) {
	  var s = 0;
	  if(spec.charset.toLowerCase() === charset.toLowerCase()){
	    s |= 1;
	  } else if (spec.charset !== '*' ) {
	    return null
	  }

	  return {
	    i: index,
	    o: spec.i,
	    q: spec.q,
	    s: s
	  }
	}

	/**
	 * Get the preferred charsets from an Accept-Charset header.
	 * @public
	 */

	function preferredCharsets(accept, provided) {
	  // RFC 2616 sec 14.2: no header = *
	  var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || '');

	  if (!provided) {
	    // sorted list of all charsets
	    return accepts
	      .filter(isQuality)
	      .sort(compareSpecs)
	      .map(getFullCharset);
	  }

	  var priorities = provided.map(function getPriority(type, index) {
	    return getCharsetPriority(type, accepts, index);
	  });

	  // sorted list of accepted charsets
	  return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) {
	    return provided[priorities.indexOf(priority)];
	  });
	}

	/**
	 * Compare two specs.
	 * @private
	 */

	function compareSpecs(a, b) {
	  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
	}

	/**
	 * Get full charset string.
	 * @private
	 */

	function getFullCharset(spec) {
	  return spec.charset;
	}

	/**
	 * Check if a spec has any quality.
	 * @private
	 */

	function isQuality(spec) {
	  return spec.q > 0;
	}
	return charset.exports;
}

var encoding = {exports: {}};

/**
 * negotiator
 * Copyright(c) 2012 Isaac Z. Schlueter
 * Copyright(c) 2014 Federico Romero
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
 * MIT Licensed
 */

var hasRequiredEncoding;

function requireEncoding () {
	if (hasRequiredEncoding) return encoding.exports;
	hasRequiredEncoding = 1;

	/**
	 * Module exports.
	 * @public
	 */

	encoding.exports = preferredEncodings;
	encoding.exports.preferredEncodings = preferredEncodings;

	/**
	 * Module variables.
	 * @private
	 */

	var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/;

	/**
	 * Parse the Accept-Encoding header.
	 * @private
	 */

	function parseAcceptEncoding(accept) {
	  var accepts = accept.split(',');
	  var hasIdentity = false;
	  var minQuality = 1;

	  for (var i = 0, j = 0; i < accepts.length; i++) {
	    var encoding = parseEncoding(accepts[i].trim(), i);

	    if (encoding) {
	      accepts[j++] = encoding;
	      hasIdentity = hasIdentity || specify('identity', encoding);
	      minQuality = Math.min(minQuality, encoding.q || 1);
	    }
	  }

	  if (!hasIdentity) {
	    /*
	     * If identity doesn't explicitly appear in the accept-encoding header,
	     * it's added to the list of acceptable encoding with the lowest q
	     */
	    accepts[j++] = {
	      encoding: 'identity',
	      q: minQuality,
	      i: i
	    };
	  }

	  // trim accepts
	  accepts.length = j;

	  return accepts;
	}

	/**
	 * Parse an encoding from the Accept-Encoding header.
	 * @private
	 */

	function parseEncoding(str, i) {
	  var match = simpleEncodingRegExp.exec(str);
	  if (!match) return null;

	  var encoding = match[1];
	  var q = 1;
	  if (match[2]) {
	    var params = match[2].split(';');
	    for (var j = 0; j < params.length; j++) {
	      var p = params[j].trim().split('=');
	      if (p[0] === 'q') {
	        q = parseFloat(p[1]);
	        break;
	      }
	    }
	  }

	  return {
	    encoding: encoding,
	    q: q,
	    i: i
	  };
	}

	/**
	 * Get the priority of an encoding.
	 * @private
	 */

	function getEncodingPriority(encoding, accepted, index) {
	  var priority = {encoding: encoding, o: -1, q: 0, s: 0};

	  for (var i = 0; i < accepted.length; i++) {
	    var spec = specify(encoding, accepted[i], index);

	    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
	      priority = spec;
	    }
	  }

	  return priority;
	}

	/**
	 * Get the specificity of the encoding.
	 * @private
	 */

	function specify(encoding, spec, index) {
	  var s = 0;
	  if(spec.encoding.toLowerCase() === encoding.toLowerCase()){
	    s |= 1;
	  } else if (spec.encoding !== '*' ) {
	    return null
	  }

	  return {
	    encoding: encoding,
	    i: index,
	    o: spec.i,
	    q: spec.q,
	    s: s
	  }
	}
	/**
	 * Get the preferred encodings from an Accept-Encoding header.
	 * @public
	 */

	function preferredEncodings(accept, provided, preferred) {
	  var accepts = parseAcceptEncoding(accept || '');

	  var comparator = preferred ? function comparator (a, b) {
	    if (a.q !== b.q) {
	      return b.q - a.q // higher quality first
	    }

	    var aPreferred = preferred.indexOf(a.encoding);
	    var bPreferred = preferred.indexOf(b.encoding);

	    if (aPreferred === -1 && bPreferred === -1) {
	      // consider the original specifity/order
	      return (b.s - a.s) || (a.o - b.o) || (a.i - b.i)
	    }

	    if (aPreferred !== -1 && bPreferred !== -1) {
	      return aPreferred - bPreferred // consider the preferred order
	    }

	    return aPreferred === -1 ? 1 : -1 // preferred first
	  } : compareSpecs;

	  if (!provided) {
	    // sorted list of all encodings
	    return accepts
	      .filter(isQuality)
	      .sort(comparator)
	      .map(getFullEncoding);
	  }

	  var priorities = provided.map(function getPriority(type, index) {
	    return getEncodingPriority(type, accepts, index);
	  });

	  // sorted list of accepted encodings
	  return priorities.filter(isQuality).sort(comparator).map(function getEncoding(priority) {
	    return provided[priorities.indexOf(priority)];
	  });
	}

	/**
	 * Compare two specs.
	 * @private
	 */

	function compareSpecs(a, b) {
	  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i);
	}

	/**
	 * Get full encoding string.
	 * @private
	 */

	function getFullEncoding(spec) {
	  return spec.encoding;
	}

	/**
	 * Check if a spec has any quality.
	 * @private
	 */

	function isQuality(spec) {
	  return spec.q > 0;
	}
	return encoding.exports;
}

var language = {exports: {}};

/**
 * negotiator
 * Copyright(c) 2012 Isaac Z. Schlueter
 * Copyright(c) 2014 Federico Romero
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
 * MIT Licensed
 */

var hasRequiredLanguage;

function requireLanguage () {
	if (hasRequiredLanguage) return language.exports;
	hasRequiredLanguage = 1;

	/**
	 * Module exports.
	 * @public
	 */

	language.exports = preferredLanguages;
	language.exports.preferredLanguages = preferredLanguages;

	/**
	 * Module variables.
	 * @private
	 */

	var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/;

	/**
	 * Parse the Accept-Language header.
	 * @private
	 */

	function parseAcceptLanguage(accept) {
	  var accepts = accept.split(',');

	  for (var i = 0, j = 0; i < accepts.length; i++) {
	    var language = parseLanguage(accepts[i].trim(), i);

	    if (language) {
	      accepts[j++] = language;
	    }
	  }

	  // trim accepts
	  accepts.length = j;

	  return accepts;
	}

	/**
	 * Parse a language from the Accept-Language header.
	 * @private
	 */

	function parseLanguage(str, i) {
	  var match = simpleLanguageRegExp.exec(str);
	  if (!match) return null;

	  var prefix = match[1];
	  var suffix = match[2];
	  var full = prefix;

	  if (suffix) full += "-" + suffix;

	  var q = 1;
	  if (match[3]) {
	    var params = match[3].split(';');
	    for (var j = 0; j < params.length; j++) {
	      var p = params[j].split('=');
	      if (p[0] === 'q') q = parseFloat(p[1]);
	    }
	  }

	  return {
	    prefix: prefix,
	    suffix: suffix,
	    q: q,
	    i: i,
	    full: full
	  };
	}

	/**
	 * Get the priority of a language.
	 * @private
	 */

	function getLanguagePriority(language, accepted, index) {
	  var priority = {o: -1, q: 0, s: 0};

	  for (var i = 0; i < accepted.length; i++) {
	    var spec = specify(language, accepted[i], index);

	    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
	      priority = spec;
	    }
	  }

	  return priority;
	}

	/**
	 * Get the specificity of the language.
	 * @private
	 */

	function specify(language, spec, index) {
	  var p = parseLanguage(language);
	  if (!p) return null;
	  var s = 0;
	  if(spec.full.toLowerCase() === p.full.toLowerCase()){
	    s |= 4;
	  } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) {
	    s |= 2;
	  } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) {
	    s |= 1;
	  } else if (spec.full !== '*' ) {
	    return null
	  }

	  return {
	    i: index,
	    o: spec.i,
	    q: spec.q,
	    s: s
	  }
	}
	/**
	 * Get the preferred languages from an Accept-Language header.
	 * @public
	 */

	function preferredLanguages(accept, provided) {
	  // RFC 2616 sec 14.4: no header = *
	  var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || '');

	  if (!provided) {
	    // sorted list of all languages
	    return accepts
	      .filter(isQuality)
	      .sort(compareSpecs)
	      .map(getFullLanguage);
	  }

	  var priorities = provided.map(function getPriority(type, index) {
	    return getLanguagePriority(type, accepts, index);
	  });

	  // sorted list of accepted languages
	  return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) {
	    return provided[priorities.indexOf(priority)];
	  });
	}

	/**
	 * Compare two specs.
	 * @private
	 */

	function compareSpecs(a, b) {
	  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
	}

	/**
	 * Get full language string.
	 * @private
	 */

	function getFullLanguage(spec) {
	  return spec.full;
	}

	/**
	 * Check if a spec has any quality.
	 * @private
	 */

	function isQuality(spec) {
	  return spec.q > 0;
	}
	return language.exports;
}

var mediaType = {exports: {}};

/**
 * negotiator
 * Copyright(c) 2012 Isaac Z. Schlueter
 * Copyright(c) 2014 Federico Romero
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
 * MIT Licensed
 */

var hasRequiredMediaType;

function requireMediaType () {
	if (hasRequiredMediaType) return mediaType.exports;
	hasRequiredMediaType = 1;

	/**
	 * Module exports.
	 * @public
	 */

	mediaType.exports = preferredMediaTypes;
	mediaType.exports.preferredMediaTypes = preferredMediaTypes;

	/**
	 * Module variables.
	 * @private
	 */

	var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/;

	/**
	 * Parse the Accept header.
	 * @private
	 */

	function parseAccept(accept) {
	  var accepts = splitMediaTypes(accept);

	  for (var i = 0, j = 0; i < accepts.length; i++) {
	    var mediaType = parseMediaType(accepts[i].trim(), i);

	    if (mediaType) {
	      accepts[j++] = mediaType;
	    }
	  }

	  // trim accepts
	  accepts.length = j;

	  return accepts;
	}

	/**
	 * Parse a media type from the Accept header.
	 * @private
	 */

	function parseMediaType(str, i) {
	  var match = simpleMediaTypeRegExp.exec(str);
	  if (!match) return null;

	  var params = Object.create(null);
	  var q = 1;
	  var subtype = match[2];
	  var type = match[1];

	  if (match[3]) {
	    var kvps = splitParameters(match[3]).map(splitKeyValuePair);

	    for (var j = 0; j < kvps.length; j++) {
	      var pair = kvps[j];
	      var key = pair[0].toLowerCase();
	      var val = pair[1];

	      // get the value, unwrapping quotes
	      var value = val && val[0] === '"' && val[val.length - 1] === '"'
	        ? val.slice(1, -1)
	        : val;

	      if (key === 'q') {
	        q = parseFloat(value);
	        break;
	      }

	      // store parameter
	      params[key] = value;
	    }
	  }

	  return {
	    type: type,
	    subtype: subtype,
	    params: params,
	    q: q,
	    i: i
	  };
	}

	/**
	 * Get the priority of a media type.
	 * @private
	 */

	function getMediaTypePriority(type, accepted, index) {
	  var priority = {o: -1, q: 0, s: 0};

	  for (var i = 0; i < accepted.length; i++) {
	    var spec = specify(type, accepted[i], index);

	    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
	      priority = spec;
	    }
	  }

	  return priority;
	}

	/**
	 * Get the specificity of the media type.
	 * @private
	 */

	function specify(type, spec, index) {
	  var p = parseMediaType(type);
	  var s = 0;

	  if (!p) {
	    return null;
	  }

	  if(spec.type.toLowerCase() == p.type.toLowerCase()) {
	    s |= 4;
	  } else if(spec.type != '*') {
	    return null;
	  }

	  if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) {
	    s |= 2;
	  } else if(spec.subtype != '*') {
	    return null;
	  }

	  var keys = Object.keys(spec.params);
	  if (keys.length > 0) {
	    if (keys.every(function (k) {
	      return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase();
	    })) {
	      s |= 1;
	    } else {
	      return null
	    }
	  }

	  return {
	    i: index,
	    o: spec.i,
	    q: spec.q,
	    s: s,
	  }
	}

	/**
	 * Get the preferred media types from an Accept header.
	 * @public
	 */

	function preferredMediaTypes(accept, provided) {
	  // RFC 2616 sec 14.2: no header = */*
	  var accepts = parseAccept(accept === undefined ? '*/*' : accept || '');

	  if (!provided) {
	    // sorted list of all types
	    return accepts
	      .filter(isQuality)
	      .sort(compareSpecs)
	      .map(getFullType);
	  }

	  var priorities = provided.map(function getPriority(type, index) {
	    return getMediaTypePriority(type, accepts, index);
	  });

	  // sorted list of accepted types
	  return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) {
	    return provided[priorities.indexOf(priority)];
	  });
	}

	/**
	 * Compare two specs.
	 * @private
	 */

	function compareSpecs(a, b) {
	  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
	}

	/**
	 * Get full type string.
	 * @private
	 */

	function getFullType(spec) {
	  return spec.type + '/' + spec.subtype;
	}

	/**
	 * Check if a spec has any quality.
	 * @private
	 */

	function isQuality(spec) {
	  return spec.q > 0;
	}

	/**
	 * Count the number of quotes in a string.
	 * @private
	 */

	function quoteCount(string) {
	  var count = 0;
	  var index = 0;

	  while ((index = string.indexOf('"', index)) !== -1) {
	    count++;
	    index++;
	  }

	  return count;
	}

	/**
	 * Split a key value pair.
	 * @private
	 */

	function splitKeyValuePair(str) {
	  var index = str.indexOf('=');
	  var key;
	  var val;

	  if (index === -1) {
	    key = str;
	  } else {
	    key = str.slice(0, index);
	    val = str.slice(index + 1);
	  }

	  return [key, val];
	}

	/**
	 * Split an Accept header into media types.
	 * @private
	 */

	function splitMediaTypes(accept) {
	  var accepts = accept.split(',');

	  for (var i = 1, j = 0; i < accepts.length; i++) {
	    if (quoteCount(accepts[j]) % 2 == 0) {
	      accepts[++j] = accepts[i];
	    } else {
	      accepts[j] += ',' + accepts[i];
	    }
	  }

	  // trim accepts
	  accepts.length = j + 1;

	  return accepts;
	}

	/**
	 * Split a string of parameters.
	 * @private
	 */

	function splitParameters(str) {
	  var parameters = str.split(';');

	  for (var i = 1, j = 0; i < parameters.length; i++) {
	    if (quoteCount(parameters[j]) % 2 == 0) {
	      parameters[++j] = parameters[i];
	    } else {
	      parameters[j] += ';' + parameters[i];
	    }
	  }

	  // trim parameters
	  parameters.length = j + 1;

	  for (var i = 0; i < parameters.length; i++) {
	    parameters[i] = parameters[i].trim();
	  }

	  return parameters;
	}
	return mediaType.exports;
}

/*!
 * negotiator
 * Copyright(c) 2012 Federico Romero
 * Copyright(c) 2012-2014 Isaac Z. Schlueter
 * Copyright(c) 2015 Douglas Christopher Wilson
 * MIT Licensed
 */

var hasRequiredNegotiator;

function requireNegotiator () {
	if (hasRequiredNegotiator) return negotiator.exports;
	hasRequiredNegotiator = 1;

	var preferredCharsets = requireCharset();
	var preferredEncodings = requireEncoding();
	var preferredLanguages = requireLanguage();
	var preferredMediaTypes = requireMediaType();

	/**
	 * Module exports.
	 * @public
	 */

	negotiator.exports = Negotiator;
	negotiator.exports.Negotiator = Negotiator;

	/**
	 * Create a Negotiator instance from a request.
	 * @param {object} request
	 * @public
	 */

	function Negotiator(request) {
	  if (!(this instanceof Negotiator)) {
	    return new Negotiator(request);
	  }

	  this.request = request;
	}

	Negotiator.prototype.charset = function charset(available) {
	  var set = this.charsets(available);
	  return set && set[0];
	};

	Negotiator.prototype.charsets = function charsets(available) {
	  return preferredCharsets(this.request.headers['accept-charset'], available);
	};

	Negotiator.prototype.encoding = function encoding(available, preferred) {
	  var set = this.encodings(available, preferred);
	  return set && set[0];
	};

	Negotiator.prototype.encodings = function encodings(available, preferred) {
	  return preferredEncodings(this.request.headers['accept-encoding'], available, preferred);
	};

	Negotiator.prototype.language = function language(available) {
	  var set = this.languages(available);
	  return set && set[0];
	};

	Negotiator.prototype.languages = function languages(available) {
	  return preferredLanguages(this.request.headers['accept-language'], available);
	};

	Negotiator.prototype.mediaType = function mediaType(available) {
	  var set = this.mediaTypes(available);
	  return set && set[0];
	};

	Negotiator.prototype.mediaTypes = function mediaTypes(available) {
	  return preferredMediaTypes(this.request.headers.accept, available);
	};

	// Backwards compatibility
	Negotiator.prototype.preferredCharset = Negotiator.prototype.charset;
	Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets;
	Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding;
	Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings;
	Negotiator.prototype.preferredLanguage = Negotiator.prototype.language;
	Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages;
	Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType;
	Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes;
	return negotiator.exports;
}

var bytes = {exports: {}};

/*!
 * bytes
 * Copyright(c) 2012-2014 TJ Holowaychuk
 * Copyright(c) 2015 Jed Watson
 * MIT Licensed
 */

var hasRequiredBytes;

function requireBytes () {
	if (hasRequiredBytes) return bytes.exports;
	hasRequiredBytes = 1;

	/**
	 * Module exports.
	 * @public
	 */

	bytes.exports = bytes$1;
	bytes.exports.format = format;
	bytes.exports.parse = parse;

	/**
	 * Module variables.
	 * @private
	 */

	var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g;

	var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/;

	var map = {
	  b:  1,
	  kb: 1 << 10,
	  mb: 1 << 20,
	  gb: 1 << 30,
	  tb: Math.pow(1024, 4),
	  pb: Math.pow(1024, 5),
	};

	var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;

	/**
	 * Convert the given value in bytes into a string or parse to string to an integer in bytes.
	 *
	 * @param {string|number} value
	 * @param {{
	 *  case: [string],
	 *  decimalPlaces: [number]
	 *  fixedDecimals: [boolean]
	 *  thousandsSeparator: [string]
	 *  unitSeparator: [string]
	 *  }} [options] bytes options.
	 *
	 * @returns {string|number|null}
	 */

	function bytes$1(value, options) {
	  if (typeof value === 'string') {
	    return parse(value);
	  }

	  if (typeof value === 'number') {
	    return format(value, options);
	  }

	  return null;
	}

	/**
	 * Format the given value in bytes into a string.
	 *
	 * If the value is negative, it is kept as such. If it is a float,
	 * it is rounded.
	 *
	 * @param {number} value
	 * @param {object} [options]
	 * @param {number} [options.decimalPlaces=2]
	 * @param {number} [options.fixedDecimals=false]
	 * @param {string} [options.thousandsSeparator=]
	 * @param {string} [options.unit=]
	 * @param {string} [options.unitSeparator=]
	 *
	 * @returns {string|null}
	 * @public
	 */

	function format(value, options) {
	  if (!Number.isFinite(value)) {
	    return null;
	  }

	  var mag = Math.abs(value);
	  var thousandsSeparator = (options && options.thousandsSeparator) || '';
	  var unitSeparator = (options && options.unitSeparator) || '';
	  var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2;
	  var fixedDecimals = Boolean(options && options.fixedDecimals);
	  var unit = (options && options.unit) || '';

	  if (!unit || !map[unit.toLowerCase()]) {
	    if (mag >= map.pb) {
	      unit = 'PB';
	    } else if (mag >= map.tb) {
	      unit = 'TB';
	    } else if (mag >= map.gb) {
	      unit = 'GB';
	    } else if (mag >= map.mb) {
	      unit = 'MB';
	    } else if (mag >= map.kb) {
	      unit = 'KB';
	    } else {
	      unit = 'B';
	    }
	  }

	  var val = value / map[unit.toLowerCase()];
	  var str = val.toFixed(decimalPlaces);

	  if (!fixedDecimals) {
	    str = str.replace(formatDecimalsRegExp, '$1');
	  }

	  if (thousandsSeparator) {
	    str = str.split('.').map(function (s, i) {
	      return i === 0
	        ? s.replace(formatThousandsRegExp, thousandsSeparator)
	        : s
	    }).join('.');
	  }

	  return str + unitSeparator + unit;
	}

	/**
	 * Parse the string value into an integer in bytes.
	 *
	 * If no unit is given, it is assumed the value is in bytes.
	 *
	 * @param {number|string} val
	 *
	 * @returns {number|null}
	 * @public
	 */

	function parse(val) {
	  if (typeof val === 'number' && !isNaN(val)) {
	    return val;
	  }

	  if (typeof val !== 'string') {
	    return null;
	  }

	  // Test if the string passed is valid
	  var results = parseRegExp.exec(val);
	  var floatValue;
	  var unit = 'b';

	  if (!results) {
	    // Nothing could be extracted from the given string
	    floatValue = parseInt(val, 10);
	    unit = 'b';
	  } else {
	    // Retrieve the value and the unit
	    floatValue = parseFloat(results[1]);
	    unit = results[4].toLowerCase();
	  }

	  if (isNaN(floatValue)) {
	    return null;
	  }

	  return Math.floor(map[unit] * floatValue);
	}
	return bytes.exports;
}

const require$$0 = {
  "application/1d-interleaved-parityfec": {"source":"iana"},
  "application/3gpdash-qoe-report+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/3gpp-ims+xml": {"source":"iana","compressible":true},
  "application/3gpphal+json": {"source":"iana","compressible":true},
  "application/3gpphalforms+json": {"source":"iana","compressible":true},
  "application/a2l": {"source":"iana"},
  "application/ace+cbor": {"source":"iana"},
  "application/ace+json": {"source":"iana","compressible":true},
  "application/ace-groupcomm+cbor": {"source":"iana"},
  "application/ace-trl+cbor": {"source":"iana"},
  "application/activemessage": {"source":"iana"},
  "application/activity+json": {"source":"iana","compressible":true},
  "application/aif+cbor": {"source":"iana"},
  "application/aif+json": {"source":"iana","compressible":true},
  "application/alto-cdni+json": {"source":"iana","compressible":true},
  "application/alto-cdnifilter+json": {"source":"iana","compressible":true},
  "application/alto-costmap+json": {"source":"iana","compressible":true},
  "application/alto-costmapfilter+json": {"source":"iana","compressible":true},
  "application/alto-directory+json": {"source":"iana","compressible":true},
  "application/alto-endpointcost+json": {"source":"iana","compressible":true},
  "application/alto-endpointcostparams+json": {"source":"iana","compressible":true},
  "application/alto-endpointprop+json": {"source":"iana","compressible":true},
  "application/alto-endpointpropparams+json": {"source":"iana","compressible":true},
  "application/alto-error+json": {"source":"iana","compressible":true},
  "application/alto-networkmap+json": {"source":"iana","compressible":true},
  "application/alto-networkmapfilter+json": {"source":"iana","compressible":true},
  "application/alto-propmap+json": {"source":"iana","compressible":true},
  "application/alto-propmapparams+json": {"source":"iana","compressible":true},
  "application/alto-tips+json": {"source":"iana","compressible":true},
  "application/alto-tipsparams+json": {"source":"iana","compressible":true},
  "application/alto-updatestreamcontrol+json": {"source":"iana","compressible":true},
  "application/alto-updatestreamparams+json": {"source":"iana","compressible":true},
  "application/aml": {"source":"iana"},
  "application/andrew-inset": {"source":"iana","extensions":["ez"]},
  "application/appinstaller": {"compressible":false,"extensions":["appinstaller"]},
  "application/applefile": {"source":"iana"},
  "application/applixware": {"source":"apache","extensions":["aw"]},
  "application/appx": {"compressible":false,"extensions":["appx"]},
  "application/appxbundle": {"compressible":false,"extensions":["appxbundle"]},
  "application/at+jwt": {"source":"iana"},
  "application/atf": {"source":"iana"},
  "application/atfx": {"source":"iana"},
  "application/atom+xml": {"source":"iana","compressible":true,"extensions":["atom"]},
  "application/atomcat+xml": {"source":"iana","compressible":true,"extensions":["atomcat"]},
  "application/atomdeleted+xml": {"source":"iana","compressible":true,"extensions":["atomdeleted"]},
  "application/atomicmail": {"source":"iana"},
  "application/atomsvc+xml": {"source":"iana","compressible":true,"extensions":["atomsvc"]},
  "application/atsc-dwd+xml": {"source":"iana","compressible":true,"extensions":["dwd"]},
  "application/atsc-dynamic-event-message": {"source":"iana"},
  "application/atsc-held+xml": {"source":"iana","compressible":true,"extensions":["held"]},
  "application/atsc-rdt+json": {"source":"iana","compressible":true},
  "application/atsc-rsat+xml": {"source":"iana","compressible":true,"extensions":["rsat"]},
  "application/atxml": {"source":"iana"},
  "application/auth-policy+xml": {"source":"iana","compressible":true},
  "application/automationml-aml+xml": {"source":"iana","compressible":true,"extensions":["aml"]},
  "application/automationml-amlx+zip": {"source":"iana","compressible":false,"extensions":["amlx"]},
  "application/bacnet-xdd+zip": {"source":"iana","compressible":false},
  "application/batch-smtp": {"source":"iana"},
  "application/bdoc": {"compressible":false,"extensions":["bdoc"]},
  "application/beep+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/bufr": {"source":"iana"},
  "application/c2pa": {"source":"iana"},
  "application/calendar+json": {"source":"iana","compressible":true},
  "application/calendar+xml": {"source":"iana","compressible":true,"extensions":["xcs"]},
  "application/call-completion": {"source":"iana"},
  "application/cals-1840": {"source":"iana"},
  "application/captive+json": {"source":"iana","compressible":true},
  "application/cbor": {"source":"iana"},
  "application/cbor-seq": {"source":"iana"},
  "application/cccex": {"source":"iana"},
  "application/ccmp+xml": {"source":"iana","compressible":true},
  "application/ccxml+xml": {"source":"iana","compressible":true,"extensions":["ccxml"]},
  "application/cda+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/cdfx+xml": {"source":"iana","compressible":true,"extensions":["cdfx"]},
  "application/cdmi-capability": {"source":"iana","extensions":["cdmia"]},
  "application/cdmi-container": {"source":"iana","extensions":["cdmic"]},
  "application/cdmi-domain": {"source":"iana","extensions":["cdmid"]},
  "application/cdmi-object": {"source":"iana","extensions":["cdmio"]},
  "application/cdmi-queue": {"source":"iana","extensions":["cdmiq"]},
  "application/cdni": {"source":"iana"},
  "application/ce+cbor": {"source":"iana"},
  "application/cea": {"source":"iana"},
  "application/cea-2018+xml": {"source":"iana","compressible":true},
  "application/cellml+xml": {"source":"iana","compressible":true},
  "application/cfw": {"source":"iana"},
  "application/cid-edhoc+cbor-seq": {"source":"iana"},
  "application/city+json": {"source":"iana","compressible":true},
  "application/city+json-seq": {"source":"iana"},
  "application/clr": {"source":"iana"},
  "application/clue+xml": {"source":"iana","compressible":true},
  "application/clue_info+xml": {"source":"iana","compressible":true},
  "application/cms": {"source":"iana"},
  "application/cnrp+xml": {"source":"iana","compressible":true},
  "application/coap-eap": {"source":"iana"},
  "application/coap-group+json": {"source":"iana","compressible":true},
  "application/coap-payload": {"source":"iana"},
  "application/commonground": {"source":"iana"},
  "application/concise-problem-details+cbor": {"source":"iana"},
  "application/conference-info+xml": {"source":"iana","compressible":true},
  "application/cose": {"source":"iana"},
  "application/cose-key": {"source":"iana"},
  "application/cose-key-set": {"source":"iana"},
  "application/cose-x509": {"source":"iana"},
  "application/cpl+xml": {"source":"iana","compressible":true,"extensions":["cpl"]},
  "application/csrattrs": {"source":"iana"},
  "application/csta+xml": {"source":"iana","compressible":true},
  "application/cstadata+xml": {"source":"iana","compressible":true},
  "application/csvm+json": {"source":"iana","compressible":true},
  "application/cu-seeme": {"source":"apache","extensions":["cu"]},
  "application/cwl": {"source":"iana","extensions":["cwl"]},
  "application/cwl+json": {"source":"iana","compressible":true},
  "application/cwl+yaml": {"source":"iana"},
  "application/cwt": {"source":"iana"},
  "application/cybercash": {"source":"iana"},
  "application/dart": {"compressible":true},
  "application/dash+xml": {"source":"iana","compressible":true,"extensions":["mpd"]},
  "application/dash-patch+xml": {"source":"iana","compressible":true,"extensions":["mpp"]},
  "application/dashdelta": {"source":"iana"},
  "application/davmount+xml": {"source":"iana","compressible":true,"extensions":["davmount"]},
  "application/dca-rft": {"source":"iana"},
  "application/dcd": {"source":"iana"},
  "application/dec-dx": {"source":"iana"},
  "application/dialog-info+xml": {"source":"iana","compressible":true},
  "application/dicom": {"source":"iana","extensions":["dcm"]},
  "application/dicom+json": {"source":"iana","compressible":true},
  "application/dicom+xml": {"source":"iana","compressible":true},
  "application/dii": {"source":"iana"},
  "application/dit": {"source":"iana"},
  "application/dns": {"source":"iana"},
  "application/dns+json": {"source":"iana","compressible":true},
  "application/dns-message": {"source":"iana"},
  "application/docbook+xml": {"source":"apache","compressible":true,"extensions":["dbk"]},
  "application/dots+cbor": {"source":"iana"},
  "application/dpop+jwt": {"source":"iana"},
  "application/dskpp+xml": {"source":"iana","compressible":true},
  "application/dssc+der": {"source":"iana","extensions":["dssc"]},
  "application/dssc+xml": {"source":"iana","compressible":true,"extensions":["xdssc"]},
  "application/dvcs": {"source":"iana"},
  "application/eat+cwt": {"source":"iana"},
  "application/eat+jwt": {"source":"iana"},
  "application/eat-bun+cbor": {"source":"iana"},
  "application/eat-bun+json": {"source":"iana","compressible":true},
  "application/eat-ucs+cbor": {"source":"iana"},
  "application/eat-ucs+json": {"source":"iana","compressible":true},
  "application/ecmascript": {"source":"apache","compressible":true,"extensions":["ecma"]},
  "application/edhoc+cbor-seq": {"source":"iana"},
  "application/edi-consent": {"source":"iana"},
  "application/edi-x12": {"source":"iana","compressible":false},
  "application/edifact": {"source":"iana","compressible":false},
  "application/efi": {"source":"iana"},
  "application/elm+json": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/elm+xml": {"source":"iana","compressible":true},
  "application/emergencycalldata.cap+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/emergencycalldata.comment+xml": {"source":"iana","compressible":true},
  "application/emergencycalldata.control+xml": {"source":"iana","compressible":true},
  "application/emergencycalldata.deviceinfo+xml": {"source":"iana","compressible":true},
  "application/emergencycalldata.ecall.msd": {"source":"iana"},
  "application/emergencycalldata.legacyesn+json": {"source":"iana","compressible":true},
  "application/emergencycalldata.providerinfo+xml": {"source":"iana","compressible":true},
  "application/emergencycalldata.serviceinfo+xml": {"source":"iana","compressible":true},
  "application/emergencycalldata.subscriberinfo+xml": {"source":"iana","compressible":true},
  "application/emergencycalldata.veds+xml": {"source":"iana","compressible":true},
  "application/emma+xml": {"source":"iana","compressible":true,"extensions":["emma"]},
  "application/emotionml+xml": {"source":"iana","compressible":true,"extensions":["emotionml"]},
  "application/encaprtp": {"source":"iana"},
  "application/entity-statement+jwt": {"source":"iana"},
  "application/epp+xml": {"source":"iana","compressible":true},
  "application/epub+zip": {"source":"iana","compressible":false,"extensions":["epub"]},
  "application/eshop": {"source":"iana"},
  "application/exi": {"source":"iana","extensions":["exi"]},
  "application/expect-ct-report+json": {"source":"iana","compressible":true},
  "application/express": {"source":"iana","extensions":["exp"]},
  "application/fastinfoset": {"source":"iana"},
  "application/fastsoap": {"source":"iana"},
  "application/fdf": {"source":"iana","extensions":["fdf"]},
  "application/fdt+xml": {"source":"iana","compressible":true,"extensions":["fdt"]},
  "application/fhir+json": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/fhir+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/fido.trusted-apps+json": {"compressible":true},
  "application/fits": {"source":"iana"},
  "application/flexfec": {"source":"iana"},
  "application/font-sfnt": {"source":"iana"},
  "application/font-tdpfr": {"source":"iana","extensions":["pfr"]},
  "application/font-woff": {"source":"iana","compressible":false},
  "application/framework-attributes+xml": {"source":"iana","compressible":true},
  "application/geo+json": {"source":"iana","compressible":true,"extensions":["geojson"]},
  "application/geo+json-seq": {"source":"iana"},
  "application/geopackage+sqlite3": {"source":"iana"},
  "application/geopose+json": {"source":"iana","compressible":true},
  "application/geoxacml+json": {"source":"iana","compressible":true},
  "application/geoxacml+xml": {"source":"iana","compressible":true},
  "application/gltf-buffer": {"source":"iana"},
  "application/gml+xml": {"source":"iana","compressible":true,"extensions":["gml"]},
  "application/gnap-binding-jws": {"source":"iana"},
  "application/gnap-binding-jwsd": {"source":"iana"},
  "application/gnap-binding-rotation-jws": {"source":"iana"},
  "application/gnap-binding-rotation-jwsd": {"source":"iana"},
  "application/gpx+xml": {"source":"apache","compressible":true,"extensions":["gpx"]},
  "application/grib": {"source":"iana"},
  "application/gxf": {"source":"apache","extensions":["gxf"]},
  "application/gzip": {"source":"iana","compressible":false,"extensions":["gz"]},
  "application/h224": {"source":"iana"},
  "application/held+xml": {"source":"iana","compressible":true},
  "application/hjson": {"extensions":["hjson"]},
  "application/hl7v2+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/http": {"source":"iana"},
  "application/hyperstudio": {"source":"iana","extensions":["stk"]},
  "application/ibe-key-request+xml": {"source":"iana","compressible":true},
  "application/ibe-pkg-reply+xml": {"source":"iana","compressible":true},
  "application/ibe-pp-data": {"source":"iana"},
  "application/iges": {"source":"iana"},
  "application/im-iscomposing+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/index": {"source":"iana"},
  "application/index.cmd": {"source":"iana"},
  "application/index.obj": {"source":"iana"},
  "application/index.response": {"source":"iana"},
  "application/index.vnd": {"source":"iana"},
  "application/inkml+xml": {"source":"iana","compressible":true,"extensions":["ink","inkml"]},
  "application/iotp": {"source":"iana"},
  "application/ipfix": {"source":"iana","extensions":["ipfix"]},
  "application/ipp": {"source":"iana"},
  "application/isup": {"source":"iana"},
  "application/its+xml": {"source":"iana","compressible":true,"extensions":["its"]},
  "application/java-archive": {"source":"iana","compressible":false,"extensions":["jar","war","ear"]},
  "application/java-serialized-object": {"source":"apache","compressible":false,"extensions":["ser"]},
  "application/java-vm": {"source":"apache","compressible":false,"extensions":["class"]},
  "application/javascript": {"source":"apache","charset":"UTF-8","compressible":true,"extensions":["js"]},
  "application/jf2feed+json": {"source":"iana","compressible":true},
  "application/jose": {"source":"iana"},
  "application/jose+json": {"source":"iana","compressible":true},
  "application/jrd+json": {"source":"iana","compressible":true},
  "application/jscalendar+json": {"source":"iana","compressible":true},
  "application/jscontact+json": {"source":"iana","compressible":true},
  "application/json": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["json","map"]},
  "application/json-patch+json": {"source":"iana","compressible":true},
  "application/json-seq": {"source":"iana"},
  "application/json5": {"extensions":["json5"]},
  "application/jsonml+json": {"source":"apache","compressible":true,"extensions":["jsonml"]},
  "application/jsonpath": {"source":"iana"},
  "application/jwk+json": {"source":"iana","compressible":true},
  "application/jwk-set+json": {"source":"iana","compressible":true},
  "application/jwk-set+jwt": {"source":"iana"},
  "application/jwt": {"source":"iana"},
  "application/kpml-request+xml": {"source":"iana","compressible":true},
  "application/kpml-response+xml": {"source":"iana","compressible":true},
  "application/ld+json": {"source":"iana","compressible":true,"extensions":["jsonld"]},
  "application/lgr+xml": {"source":"iana","compressible":true,"extensions":["lgr"]},
  "application/link-format": {"source":"iana"},
  "application/linkset": {"source":"iana"},
  "application/linkset+json": {"source":"iana","compressible":true},
  "application/load-control+xml": {"source":"iana","compressible":true},
  "application/logout+jwt": {"source":"iana"},
  "application/lost+xml": {"source":"iana","compressible":true,"extensions":["lostxml"]},
  "application/lostsync+xml": {"source":"iana","compressible":true},
  "application/lpf+zip": {"source":"iana","compressible":false},
  "application/lxf": {"source":"iana"},
  "application/mac-binhex40": {"source":"iana","extensions":["hqx"]},
  "application/mac-compactpro": {"source":"apache","extensions":["cpt"]},
  "application/macwriteii": {"source":"iana"},
  "application/mads+xml": {"source":"iana","compressible":true,"extensions":["mads"]},
  "application/manifest+json": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["webmanifest"]},
  "application/marc": {"source":"iana","extensions":["mrc"]},
  "application/marcxml+xml": {"source":"iana","compressible":true,"extensions":["mrcx"]},
  "application/mathematica": {"source":"iana","extensions":["ma","nb","mb"]},
  "application/mathml+xml": {"source":"iana","compressible":true,"extensions":["mathml"]},
  "application/mathml-content+xml": {"source":"iana","compressible":true},
  "application/mathml-presentation+xml": {"source":"iana","compressible":true},
  "application/mbms-associated-procedure-description+xml": {"source":"iana","compressible":true},
  "application/mbms-deregister+xml": {"source":"iana","compressible":true},
  "application/mbms-envelope+xml": {"source":"iana","compressible":true},
  "application/mbms-msk+xml": {"source":"iana","compressible":true},
  "application/mbms-msk-response+xml": {"source":"iana","compressible":true},
  "application/mbms-protection-description+xml": {"source":"iana","compressible":true},
  "application/mbms-reception-report+xml": {"source":"iana","compressible":true},
  "application/mbms-register+xml": {"source":"iana","compressible":true},
  "application/mbms-register-response+xml": {"source":"iana","compressible":true},
  "application/mbms-schedule+xml": {"source":"iana","compressible":true},
  "application/mbms-user-service-description+xml": {"source":"iana","compressible":true},
  "application/mbox": {"source":"iana","extensions":["mbox"]},
  "application/media-policy-dataset+xml": {"source":"iana","compressible":true,"extensions":["mpf"]},
  "application/media_control+xml": {"source":"iana","compressible":true},
  "application/mediaservercontrol+xml": {"source":"iana","compressible":true,"extensions":["mscml"]},
  "application/merge-patch+json": {"source":"iana","compressible":true},
  "application/metalink+xml": {"source":"apache","compressible":true,"extensions":["metalink"]},
  "application/metalink4+xml": {"source":"iana","compressible":true,"extensions":["meta4"]},
  "application/mets+xml": {"source":"iana","compressible":true,"extensions":["mets"]},
  "application/mf4": {"source":"iana"},
  "application/mikey": {"source":"iana"},
  "application/mipc": {"source":"iana"},
  "application/missing-blocks+cbor-seq": {"source":"iana"},
  "application/mmt-aei+xml": {"source":"iana","compressible":true,"extensions":["maei"]},
  "application/mmt-usd+xml": {"source":"iana","compressible":true,"extensions":["musd"]},
  "application/mods+xml": {"source":"iana","compressible":true,"extensions":["mods"]},
  "application/moss-keys": {"source":"iana"},
  "application/moss-signature": {"source":"iana"},
  "application/mosskey-data": {"source":"iana"},
  "application/mosskey-request": {"source":"iana"},
  "application/mp21": {"source":"iana","extensions":["m21","mp21"]},
  "application/mp4": {"source":"iana","extensions":["mp4","mpg4","mp4s","m4p"]},
  "application/mpeg4-generic": {"source":"iana"},
  "application/mpeg4-iod": {"source":"iana"},
  "application/mpeg4-iod-xmt": {"source":"iana"},
  "application/mrb-consumer+xml": {"source":"iana","compressible":true},
  "application/mrb-publish+xml": {"source":"iana","compressible":true},
  "application/msc-ivr+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/msc-mixer+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/msix": {"compressible":false,"extensions":["msix"]},
  "application/msixbundle": {"compressible":false,"extensions":["msixbundle"]},
  "application/msword": {"source":"iana","compressible":false,"extensions":["doc","dot"]},
  "application/mud+json": {"source":"iana","compressible":true},
  "application/multipart-core": {"source":"iana"},
  "application/mxf": {"source":"iana","extensions":["mxf"]},
  "application/n-quads": {"source":"iana","extensions":["nq"]},
  "application/n-triples": {"source":"iana","extensions":["nt"]},
  "application/nasdata": {"source":"iana"},
  "application/news-checkgroups": {"source":"iana","charset":"US-ASCII"},
  "application/news-groupinfo": {"source":"iana","charset":"US-ASCII"},
  "application/news-transmission": {"source":"iana"},
  "application/nlsml+xml": {"source":"iana","compressible":true},
  "application/node": {"source":"iana","extensions":["cjs"]},
  "application/nss": {"source":"iana"},
  "application/oauth-authz-req+jwt": {"source":"iana"},
  "application/oblivious-dns-message": {"source":"iana"},
  "application/ocsp-request": {"source":"iana"},
  "application/ocsp-response": {"source":"iana"},
  "application/octet-stream": {"source":"iana","compressible":true,"extensions":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]},
  "application/oda": {"source":"iana","extensions":["oda"]},
  "application/odm+xml": {"source":"iana","compressible":true},
  "application/odx": {"source":"iana"},
  "application/oebps-package+xml": {"source":"iana","compressible":true,"extensions":["opf"]},
  "application/ogg": {"source":"iana","compressible":false,"extensions":["ogx"]},
  "application/ohttp-keys": {"source":"iana"},
  "application/omdoc+xml": {"source":"apache","compressible":true,"extensions":["omdoc"]},
  "application/onenote": {"source":"apache","extensions":["onetoc","onetoc2","onetmp","onepkg","one","onea"]},
  "application/opc-nodeset+xml": {"source":"iana","compressible":true},
  "application/oscore": {"source":"iana"},
  "application/oxps": {"source":"iana","extensions":["oxps"]},
  "application/p21": {"source":"iana"},
  "application/p21+zip": {"source":"iana","compressible":false},
  "application/p2p-overlay+xml": {"source":"iana","compressible":true,"extensions":["relo"]},
  "application/parityfec": {"source":"iana"},
  "application/passport": {"source":"iana"},
  "application/patch-ops-error+xml": {"source":"iana","compressible":true,"extensions":["xer"]},
  "application/pdf": {"source":"iana","compressible":false,"extensions":["pdf"]},
  "application/pdx": {"source":"iana"},
  "application/pem-certificate-chain": {"source":"iana"},
  "application/pgp-encrypted": {"source":"iana","compressible":false,"extensions":["pgp"]},
  "application/pgp-keys": {"source":"iana","extensions":["asc"]},
  "application/pgp-signature": {"source":"iana","extensions":["sig","asc"]},
  "application/pics-rules": {"source":"apache","extensions":["prf"]},
  "application/pidf+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/pidf-diff+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/pkcs10": {"source":"iana","extensions":["p10"]},
  "application/pkcs12": {"source":"iana"},
  "application/pkcs7-mime": {"source":"iana","extensions":["p7m","p7c"]},
  "application/pkcs7-signature": {"source":"iana","extensions":["p7s"]},
  "application/pkcs8": {"source":"iana","extensions":["p8"]},
  "application/pkcs8-encrypted": {"source":"iana"},
  "application/pkix-attr-cert": {"source":"iana","extensions":["ac"]},
  "application/pkix-cert": {"source":"iana","extensions":["cer"]},
  "application/pkix-crl": {"source":"iana","extensions":["crl"]},
  "application/pkix-pkipath": {"source":"iana","extensions":["pkipath"]},
  "application/pkixcmp": {"source":"iana","extensions":["pki"]},
  "application/pls+xml": {"source":"iana","compressible":true,"extensions":["pls"]},
  "application/poc-settings+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/postscript": {"source":"iana","compressible":true,"extensions":["ai","eps","ps"]},
  "application/ppsp-tracker+json": {"source":"iana","compressible":true},
  "application/private-token-issuer-directory": {"source":"iana"},
  "application/private-token-request": {"source":"iana"},
  "application/private-token-response": {"source":"iana"},
  "application/problem+json": {"source":"iana","compressible":true},
  "application/problem+xml": {"source":"iana","compressible":true},
  "application/provenance+xml": {"source":"iana","compressible":true,"extensions":["provx"]},
  "application/provided-claims+jwt": {"source":"iana"},
  "application/prs.alvestrand.titrax-sheet": {"source":"iana"},
  "application/prs.cww": {"source":"iana","extensions":["cww"]},
  "application/prs.cyn": {"source":"iana","charset":"7-BIT"},
  "application/prs.hpub+zip": {"source":"iana","compressible":false},
  "application/prs.implied-document+xml": {"source":"iana","compressible":true},
  "application/prs.implied-executable": {"source":"iana"},
  "application/prs.implied-object+json": {"source":"iana","compressible":true},
  "application/prs.implied-object+json-seq": {"source":"iana"},
  "application/prs.implied-object+yaml": {"source":"iana"},
  "application/prs.implied-structure": {"source":"iana"},
  "application/prs.mayfile": {"source":"iana"},
  "application/prs.nprend": {"source":"iana"},
  "application/prs.plucker": {"source":"iana"},
  "application/prs.rdf-xml-crypt": {"source":"iana"},
  "application/prs.vcfbzip2": {"source":"iana"},
  "application/prs.xsf+xml": {"source":"iana","compressible":true,"extensions":["xsf"]},
  "application/pskc+xml": {"source":"iana","compressible":true,"extensions":["pskcxml"]},
  "application/pvd+json": {"source":"iana","compressible":true},
  "application/qsig": {"source":"iana"},
  "application/raml+yaml": {"compressible":true,"extensions":["raml"]},
  "application/raptorfec": {"source":"iana"},
  "application/rdap+json": {"source":"iana","compressible":true},
  "application/rdf+xml": {"source":"iana","compressible":true,"extensions":["rdf","owl"]},
  "application/reginfo+xml": {"source":"iana","compressible":true,"extensions":["rif"]},
  "application/relax-ng-compact-syntax": {"source":"iana","extensions":["rnc"]},
  "application/remote-printing": {"source":"apache"},
  "application/reputon+json": {"source":"iana","compressible":true},
  "application/resolve-response+jwt": {"source":"iana"},
  "application/resource-lists+xml": {"source":"iana","compressible":true,"extensions":["rl"]},
  "application/resource-lists-diff+xml": {"source":"iana","compressible":true,"extensions":["rld"]},
  "application/rfc+xml": {"source":"iana","compressible":true},
  "application/riscos": {"source":"iana"},
  "application/rlmi+xml": {"source":"iana","compressible":true},
  "application/rls-services+xml": {"source":"iana","compressible":true,"extensions":["rs"]},
  "application/route-apd+xml": {"source":"iana","compressible":true,"extensions":["rapd"]},
  "application/route-s-tsid+xml": {"source":"iana","compressible":true,"extensions":["sls"]},
  "application/route-usd+xml": {"source":"iana","compressible":true,"extensions":["rusd"]},
  "application/rpki-checklist": {"source":"iana"},
  "application/rpki-ghostbusters": {"source":"iana","extensions":["gbr"]},
  "application/rpki-manifest": {"source":"iana","extensions":["mft"]},
  "application/rpki-publication": {"source":"iana"},
  "application/rpki-roa": {"source":"iana","extensions":["roa"]},
  "application/rpki-signed-tal": {"source":"iana"},
  "application/rpki-updown": {"source":"iana"},
  "application/rsd+xml": {"source":"apache","compressible":true,"extensions":["rsd"]},
  "application/rss+xml": {"source":"apache","compressible":true,"extensions":["rss"]},
  "application/rtf": {"source":"iana","compressible":true,"extensions":["rtf"]},
  "application/rtploopback": {"source":"iana"},
  "application/rtx": {"source":"iana"},
  "application/samlassertion+xml": {"source":"iana","compressible":true},
  "application/samlmetadata+xml": {"source":"iana","compressible":true},
  "application/sarif+json": {"source":"iana","compressible":true},
  "application/sarif-external-properties+json": {"source":"iana","compressible":true},
  "application/sbe": {"source":"iana"},
  "application/sbml+xml": {"source":"iana","compressible":true,"extensions":["sbml"]},
  "application/scaip+xml": {"source":"iana","compressible":true},
  "application/scim+json": {"source":"iana","compressible":true},
  "application/scvp-cv-request": {"source":"iana","extensions":["scq"]},
  "application/scvp-cv-response": {"source":"iana","extensions":["scs"]},
  "application/scvp-vp-request": {"source":"iana","extensions":["spq"]},
  "application/scvp-vp-response": {"source":"iana","extensions":["spp"]},
  "application/sdp": {"source":"iana","extensions":["sdp"]},
  "application/secevent+jwt": {"source":"iana"},
  "application/senml+cbor": {"source":"iana"},
  "application/senml+json": {"source":"iana","compressible":true},
  "application/senml+xml": {"source":"iana","compressible":true,"extensions":["senmlx"]},
  "application/senml-etch+cbor": {"source":"iana"},
  "application/senml-etch+json": {"source":"iana","compressible":true},
  "application/senml-exi": {"source":"iana"},
  "application/sensml+cbor": {"source":"iana"},
  "application/sensml+json": {"source":"iana","compressible":true},
  "application/sensml+xml": {"source":"iana","compressible":true,"extensions":["sensmlx"]},
  "application/sensml-exi": {"source":"iana"},
  "application/sep+xml": {"source":"iana","compressible":true},
  "application/sep-exi": {"source":"iana"},
  "application/session-info": {"source":"iana"},
  "application/set-payment": {"source":"iana"},
  "application/set-payment-initiation": {"source":"iana","extensions":["setpay"]},
  "application/set-registration": {"source":"iana"},
  "application/set-registration-initiation": {"source":"iana","extensions":["setreg"]},
  "application/sgml": {"source":"iana"},
  "application/sgml-open-catalog": {"source":"iana"},
  "application/shf+xml": {"source":"iana","compressible":true,"extensions":["shf"]},
  "application/sieve": {"source":"iana","extensions":["siv","sieve"]},
  "application/simple-filter+xml": {"source":"iana","compressible":true},
  "application/simple-message-summary": {"source":"iana"},
  "application/simplesymbolcontainer": {"source":"iana"},
  "application/sipc": {"source":"iana"},
  "application/slate": {"source":"iana"},
  "application/smil": {"source":"apache"},
  "application/smil+xml": {"source":"iana","compressible":true,"extensions":["smi","smil"]},
  "application/smpte336m": {"source":"iana"},
  "application/soap+fastinfoset": {"source":"iana"},
  "application/soap+xml": {"source":"iana","compressible":true},
  "application/sparql-query": {"source":"iana","extensions":["rq"]},
  "application/sparql-results+xml": {"source":"iana","compressible":true,"extensions":["srx"]},
  "application/spdx+json": {"source":"iana","compressible":true},
  "application/spirits-event+xml": {"source":"iana","compressible":true},
  "application/sql": {"source":"iana","extensions":["sql"]},
  "application/srgs": {"source":"iana","extensions":["gram"]},
  "application/srgs+xml": {"source":"iana","compressible":true,"extensions":["grxml"]},
  "application/sru+xml": {"source":"iana","compressible":true,"extensions":["sru"]},
  "application/ssdl+xml": {"source":"apache","compressible":true,"extensions":["ssdl"]},
  "application/sslkeylogfile": {"source":"iana"},
  "application/ssml+xml": {"source":"iana","compressible":true,"extensions":["ssml"]},
  "application/st2110-41": {"source":"iana"},
  "application/stix+json": {"source":"iana","compressible":true},
  "application/stratum": {"source":"iana"},
  "application/swid+cbor": {"source":"iana"},
  "application/swid+xml": {"source":"iana","compressible":true,"extensions":["swidtag"]},
  "application/tamp-apex-update": {"source":"iana"},
  "application/tamp-apex-update-confirm": {"source":"iana"},
  "application/tamp-community-update": {"source":"iana"},
  "application/tamp-community-update-confirm": {"source":"iana"},
  "application/tamp-error": {"source":"iana"},
  "application/tamp-sequence-adjust": {"source":"iana"},
  "application/tamp-sequence-adjust-confirm": {"source":"iana"},
  "application/tamp-status-query": {"source":"iana"},
  "application/tamp-status-response": {"source":"iana"},
  "application/tamp-update": {"source":"iana"},
  "application/tamp-update-confirm": {"source":"iana"},
  "application/tar": {"compressible":true},
  "application/taxii+json": {"source":"iana","compressible":true},
  "application/td+json": {"source":"iana","compressible":true},
  "application/tei+xml": {"source":"iana","compressible":true,"extensions":["tei","teicorpus"]},
  "application/tetra_isi": {"source":"iana"},
  "application/thraud+xml": {"source":"iana","compressible":true,"extensions":["tfi"]},
  "application/timestamp-query": {"source":"iana"},
  "application/timestamp-reply": {"source":"iana"},
  "application/timestamped-data": {"source":"iana","extensions":["tsd"]},
  "application/tlsrpt+gzip": {"source":"iana"},
  "application/tlsrpt+json": {"source":"iana","compressible":true},
  "application/tm+json": {"source":"iana","compressible":true},
  "application/tnauthlist": {"source":"iana"},
  "application/toc+cbor": {"source":"iana"},
  "application/token-introspection+jwt": {"source":"iana"},
  "application/toml": {"source":"iana","compressible":true,"extensions":["toml"]},
  "application/trickle-ice-sdpfrag": {"source":"iana"},
  "application/trig": {"source":"iana","extensions":["trig"]},
  "application/trust-chain+json": {"source":"iana","compressible":true},
  "application/trust-mark+jwt": {"source":"iana"},
  "application/trust-mark-delegation+jwt": {"source":"iana"},
  "application/ttml+xml": {"source":"iana","compressible":true,"extensions":["ttml"]},
  "application/tve-trigger": {"source":"iana"},
  "application/tzif": {"source":"iana"},
  "application/tzif-leap": {"source":"iana"},
  "application/ubjson": {"compressible":false,"extensions":["ubj"]},
  "application/uccs+cbor": {"source":"iana"},
  "application/ujcs+json": {"source":"iana","compressible":true},
  "application/ulpfec": {"source":"iana"},
  "application/urc-grpsheet+xml": {"source":"iana","compressible":true},
  "application/urc-ressheet+xml": {"source":"iana","compressible":true,"extensions":["rsheet"]},
  "application/urc-targetdesc+xml": {"source":"iana","compressible":true,"extensions":["td"]},
  "application/urc-uisocketdesc+xml": {"source":"iana","compressible":true},
  "application/vc": {"source":"iana"},
  "application/vc+cose": {"source":"iana"},
  "application/vc+jwt": {"source":"iana"},
  "application/vcard+json": {"source":"iana","compressible":true},
  "application/vcard+xml": {"source":"iana","compressible":true},
  "application/vemmi": {"source":"iana"},
  "application/vividence.scriptfile": {"source":"apache"},
  "application/vnd.1000minds.decision-model+xml": {"source":"iana","compressible":true,"extensions":["1km"]},
  "application/vnd.1ob": {"source":"iana"},
  "application/vnd.3gpp-prose+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp-prose-pc3a+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp-prose-pc3ach+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp-prose-pc3ch+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp-prose-pc8+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp-v2x-local-service-information": {"source":"iana"},
  "application/vnd.3gpp.5gnas": {"source":"iana"},
  "application/vnd.3gpp.5gsa2x": {"source":"iana"},
  "application/vnd.3gpp.5gsa2x-local-service-information": {"source":"iana"},
  "application/vnd.3gpp.5gsv2x": {"source":"iana"},
  "application/vnd.3gpp.5gsv2x-local-service-information": {"source":"iana"},
  "application/vnd.3gpp.access-transfer-events+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.bsf+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.crs+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.current-location-discovery+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.gmop+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.gtpc": {"source":"iana"},
  "application/vnd.3gpp.interworking-data": {"source":"iana"},
  "application/vnd.3gpp.lpp": {"source":"iana"},
  "application/vnd.3gpp.mc-signalling-ear": {"source":"iana"},
  "application/vnd.3gpp.mcdata-affiliation-command+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcdata-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcdata-msgstore-ctrl-request+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcdata-payload": {"source":"iana"},
  "application/vnd.3gpp.mcdata-regroup+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcdata-service-config+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcdata-signalling": {"source":"iana"},
  "application/vnd.3gpp.mcdata-ue-config+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcdata-user-profile+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-affiliation-command+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-floor-request+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-location-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-mbms-usage-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-regroup+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-service-config+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-signed+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-ue-config+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-ue-init-config+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcptt-user-profile+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-affiliation-command+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-location-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-regroup+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-service-config+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-transmission-request+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-ue-config+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mcvideo-user-profile+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.mid-call+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.ngap": {"source":"iana"},
  "application/vnd.3gpp.pfcp": {"source":"iana"},
  "application/vnd.3gpp.pic-bw-large": {"source":"iana","extensions":["plb"]},
  "application/vnd.3gpp.pic-bw-small": {"source":"iana","extensions":["psb"]},
  "application/vnd.3gpp.pic-bw-var": {"source":"iana","extensions":["pvb"]},
  "application/vnd.3gpp.pinapp-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.s1ap": {"source":"iana"},
  "application/vnd.3gpp.seal-group-doc+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.seal-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.seal-location-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.seal-mbms-usage-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.seal-network-qos-management-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.seal-ue-config-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.seal-unicast-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.seal-user-profile-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.sms": {"source":"iana"},
  "application/vnd.3gpp.sms+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.srvcc-ext+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.srvcc-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.state-and-event-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.ussd+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp.v2x": {"source":"iana"},
  "application/vnd.3gpp.vae-info+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp2.bcmcsinfo+xml": {"source":"iana","compressible":true},
  "application/vnd.3gpp2.sms": {"source":"iana"},
  "application/vnd.3gpp2.tcap": {"source":"iana","extensions":["tcap"]},
  "application/vnd.3lightssoftware.imagescal": {"source":"iana"},
  "application/vnd.3m.post-it-notes": {"source":"iana","extensions":["pwn"]},
  "application/vnd.accpac.simply.aso": {"source":"iana","extensions":["aso"]},
  "application/vnd.accpac.simply.imp": {"source":"iana","extensions":["imp"]},
  "application/vnd.acm.addressxfer+json": {"source":"iana","compressible":true},
  "application/vnd.acm.chatbot+json": {"source":"iana","compressible":true},
  "application/vnd.acucobol": {"source":"iana","extensions":["acu"]},
  "application/vnd.acucorp": {"source":"iana","extensions":["atc","acutc"]},
  "application/vnd.adobe.air-application-installer-package+zip": {"source":"apache","compressible":false,"extensions":["air"]},
  "application/vnd.adobe.flash.movie": {"source":"iana"},
  "application/vnd.adobe.formscentral.fcdt": {"source":"iana","extensions":["fcdt"]},
  "application/vnd.adobe.fxp": {"source":"iana","extensions":["fxp","fxpl"]},
  "application/vnd.adobe.partial-upload": {"source":"iana"},
  "application/vnd.adobe.xdp+xml": {"source":"iana","compressible":true,"extensions":["xdp"]},
  "application/vnd.adobe.xfdf": {"source":"apache","extensions":["xfdf"]},
  "application/vnd.aether.imp": {"source":"iana"},
  "application/vnd.afpc.afplinedata": {"source":"iana"},
  "application/vnd.afpc.afplinedata-pagedef": {"source":"iana"},
  "application/vnd.afpc.cmoca-cmresource": {"source":"iana"},
  "application/vnd.afpc.foca-charset": {"source":"iana"},
  "application/vnd.afpc.foca-codedfont": {"source":"iana"},
  "application/vnd.afpc.foca-codepage": {"source":"iana"},
  "application/vnd.afpc.modca": {"source":"iana"},
  "application/vnd.afpc.modca-cmtable": {"source":"iana"},
  "application/vnd.afpc.modca-formdef": {"source":"iana"},
  "application/vnd.afpc.modca-mediummap": {"source":"iana"},
  "application/vnd.afpc.modca-objectcontainer": {"source":"iana"},
  "application/vnd.afpc.modca-overlay": {"source":"iana"},
  "application/vnd.afpc.modca-pagesegment": {"source":"iana"},
  "application/vnd.age": {"source":"iana","extensions":["age"]},
  "application/vnd.ah-barcode": {"source":"apache"},
  "application/vnd.ahead.space": {"source":"iana","extensions":["ahead"]},
  "application/vnd.airzip.filesecure.azf": {"source":"iana","extensions":["azf"]},
  "application/vnd.airzip.filesecure.azs": {"source":"iana","extensions":["azs"]},
  "application/vnd.amadeus+json": {"source":"iana","compressible":true},
  "application/vnd.amazon.ebook": {"source":"apache","extensions":["azw"]},
  "application/vnd.amazon.mobi8-ebook": {"source":"iana"},
  "application/vnd.americandynamics.acc": {"source":"iana","extensions":["acc"]},
  "application/vnd.amiga.ami": {"source":"iana","extensions":["ami"]},
  "application/vnd.amundsen.maze+xml": {"source":"iana","compressible":true},
  "application/vnd.android.ota": {"source":"iana"},
  "application/vnd.android.package-archive": {"source":"apache","compressible":false,"extensions":["apk"]},
  "application/vnd.anki": {"source":"iana"},
  "application/vnd.anser-web-certificate-issue-initiation": {"source":"iana","extensions":["cii"]},
  "application/vnd.anser-web-funds-transfer-initiation": {"source":"apache","extensions":["fti"]},
  "application/vnd.antix.game-component": {"source":"iana","extensions":["atx"]},
  "application/vnd.apache.arrow.file": {"source":"iana"},
  "application/vnd.apache.arrow.stream": {"source":"iana"},
  "application/vnd.apache.parquet": {"source":"iana"},
  "application/vnd.apache.thrift.binary": {"source":"iana"},
  "application/vnd.apache.thrift.compact": {"source":"iana"},
  "application/vnd.apache.thrift.json": {"source":"iana"},
  "application/vnd.apexlang": {"source":"iana"},
  "application/vnd.api+json": {"source":"iana","compressible":true},
  "application/vnd.aplextor.warrp+json": {"source":"iana","compressible":true},
  "application/vnd.apothekende.reservation+json": {"source":"iana","compressible":true},
  "application/vnd.apple.installer+xml": {"source":"iana","compressible":true,"extensions":["mpkg"]},
  "application/vnd.apple.keynote": {"source":"iana","extensions":["key"]},
  "application/vnd.apple.mpegurl": {"source":"iana","extensions":["m3u8"]},
  "application/vnd.apple.numbers": {"source":"iana","extensions":["numbers"]},
  "application/vnd.apple.pages": {"source":"iana","extensions":["pages"]},
  "application/vnd.apple.pkpass": {"compressible":false,"extensions":["pkpass"]},
  "application/vnd.arastra.swi": {"source":"apache"},
  "application/vnd.aristanetworks.swi": {"source":"iana","extensions":["swi"]},
  "application/vnd.artisan+json": {"source":"iana","compressible":true},
  "application/vnd.artsquare": {"source":"iana"},
  "application/vnd.astraea-software.iota": {"source":"iana","extensions":["iota"]},
  "application/vnd.audiograph": {"source":"iana","extensions":["aep"]},
  "application/vnd.autodesk.fbx": {"extensions":["fbx"]},
  "application/vnd.autopackage": {"source":"iana"},
  "application/vnd.avalon+json": {"source":"iana","compressible":true},
  "application/vnd.avistar+xml": {"source":"iana","compressible":true},
  "application/vnd.balsamiq.bmml+xml": {"source":"iana","compressible":true,"extensions":["bmml"]},
  "application/vnd.balsamiq.bmpr": {"source":"iana"},
  "application/vnd.banana-accounting": {"source":"iana"},
  "application/vnd.bbf.usp.error": {"source":"iana"},
  "application/vnd.bbf.usp.msg": {"source":"iana"},
  "application/vnd.bbf.usp.msg+json": {"source":"iana","compressible":true},
  "application/vnd.bekitzur-stech+json": {"source":"iana","compressible":true},
  "application/vnd.belightsoft.lhzd+zip": {"source":"iana","compressible":false},
  "application/vnd.belightsoft.lhzl+zip": {"source":"iana","compressible":false},
  "application/vnd.bint.med-content": {"source":"iana"},
  "application/vnd.biopax.rdf+xml": {"source":"iana","compressible":true},
  "application/vnd.blink-idb-value-wrapper": {"source":"iana"},
  "application/vnd.blueice.multipass": {"source":"iana","extensions":["mpm"]},
  "application/vnd.bluetooth.ep.oob": {"source":"iana"},
  "application/vnd.bluetooth.le.oob": {"source":"iana"},
  "application/vnd.bmi": {"source":"iana","extensions":["bmi"]},
  "application/vnd.bpf": {"source":"iana"},
  "application/vnd.bpf3": {"source":"iana"},
  "application/vnd.businessobjects": {"source":"iana","extensions":["rep"]},
  "application/vnd.byu.uapi+json": {"source":"iana","compressible":true},
  "application/vnd.bzip3": {"source":"iana"},
  "application/vnd.c3voc.schedule+xml": {"source":"iana","compressible":true},
  "application/vnd.cab-jscript": {"source":"iana"},
  "application/vnd.canon-cpdl": {"source":"iana"},
  "application/vnd.canon-lips": {"source":"iana"},
  "application/vnd.capasystems-pg+json": {"source":"iana","compressible":true},
  "application/vnd.cendio.thinlinc.clientconf": {"source":"iana"},
  "application/vnd.century-systems.tcp_stream": {"source":"iana"},
  "application/vnd.chemdraw+xml": {"source":"iana","compressible":true,"extensions":["cdxml"]},
  "application/vnd.chess-pgn": {"source":"iana"},
  "application/vnd.chipnuts.karaoke-mmd": {"source":"iana","extensions":["mmd"]},
  "application/vnd.ciedi": {"source":"iana"},
  "application/vnd.cinderella": {"source":"iana","extensions":["cdy"]},
  "application/vnd.cirpack.isdn-ext": {"source":"iana"},
  "application/vnd.citationstyles.style+xml": {"source":"iana","compressible":true,"extensions":["csl"]},
  "application/vnd.claymore": {"source":"iana","extensions":["cla"]},
  "application/vnd.cloanto.rp9": {"source":"iana","extensions":["rp9"]},
  "application/vnd.clonk.c4group": {"source":"iana","extensions":["c4g","c4d","c4f","c4p","c4u"]},
  "application/vnd.cluetrust.cartomobile-config": {"source":"iana","extensions":["c11amc"]},
  "application/vnd.cluetrust.cartomobile-config-pkg": {"source":"iana","extensions":["c11amz"]},
  "application/vnd.cncf.helm.chart.content.v1.tar+gzip": {"source":"iana"},
  "application/vnd.cncf.helm.chart.provenance.v1.prov": {"source":"iana"},
  "application/vnd.cncf.helm.config.v1+json": {"source":"iana","compressible":true},
  "application/vnd.coffeescript": {"source":"iana"},
  "application/vnd.collabio.xodocuments.document": {"source":"iana"},
  "application/vnd.collabio.xodocuments.document-template": {"source":"iana"},
  "application/vnd.collabio.xodocuments.presentation": {"source":"iana"},
  "application/vnd.collabio.xodocuments.presentation-template": {"source":"iana"},
  "application/vnd.collabio.xodocuments.spreadsheet": {"source":"iana"},
  "application/vnd.collabio.xodocuments.spreadsheet-template": {"source":"iana"},
  "application/vnd.collection+json": {"source":"iana","compressible":true},
  "application/vnd.collection.doc+json": {"source":"iana","compressible":true},
  "application/vnd.collection.next+json": {"source":"iana","compressible":true},
  "application/vnd.comicbook+zip": {"source":"iana","compressible":false},
  "application/vnd.comicbook-rar": {"source":"iana"},
  "application/vnd.commerce-battelle": {"source":"iana"},
  "application/vnd.commonspace": {"source":"iana","extensions":["csp"]},
  "application/vnd.contact.cmsg": {"source":"iana","extensions":["cdbcmsg"]},
  "application/vnd.coreos.ignition+json": {"source":"iana","compressible":true},
  "application/vnd.cosmocaller": {"source":"iana","extensions":["cmc"]},
  "application/vnd.crick.clicker": {"source":"iana","extensions":["clkx"]},
  "application/vnd.crick.clicker.keyboard": {"source":"iana","extensions":["clkk"]},
  "application/vnd.crick.clicker.palette": {"source":"iana","extensions":["clkp"]},
  "application/vnd.crick.clicker.template": {"source":"iana","extensions":["clkt"]},
  "application/vnd.crick.clicker.wordbank": {"source":"iana","extensions":["clkw"]},
  "application/vnd.criticaltools.wbs+xml": {"source":"iana","compressible":true,"extensions":["wbs"]},
  "application/vnd.cryptii.pipe+json": {"source":"iana","compressible":true},
  "application/vnd.crypto-shade-file": {"source":"iana"},
  "application/vnd.cryptomator.encrypted": {"source":"iana"},
  "application/vnd.cryptomator.vault": {"source":"iana"},
  "application/vnd.ctc-posml": {"source":"iana","extensions":["pml"]},
  "application/vnd.ctct.ws+xml": {"source":"iana","compressible":true},
  "application/vnd.cups-pdf": {"source":"iana"},
  "application/vnd.cups-postscript": {"source":"iana"},
  "application/vnd.cups-ppd": {"source":"iana","extensions":["ppd"]},
  "application/vnd.cups-raster": {"source":"iana"},
  "application/vnd.cups-raw": {"source":"iana"},
  "application/vnd.curl": {"source":"iana"},
  "application/vnd.curl.car": {"source":"apache","extensions":["car"]},
  "application/vnd.curl.pcurl": {"source":"apache","extensions":["pcurl"]},
  "application/vnd.cyan.dean.root+xml": {"source":"iana","compressible":true},
  "application/vnd.cybank": {"source":"iana"},
  "application/vnd.cyclonedx+json": {"source":"iana","compressible":true},
  "application/vnd.cyclonedx+xml": {"source":"iana","compressible":true},
  "application/vnd.d2l.coursepackage1p0+zip": {"source":"iana","compressible":false},
  "application/vnd.d3m-dataset": {"source":"iana"},
  "application/vnd.d3m-problem": {"source":"iana"},
  "application/vnd.dart": {"source":"iana","compressible":true,"extensions":["dart"]},
  "application/vnd.data-vision.rdz": {"source":"iana","extensions":["rdz"]},
  "application/vnd.datalog": {"source":"iana"},
  "application/vnd.datapackage+json": {"source":"iana","compressible":true},
  "application/vnd.dataresource+json": {"source":"iana","compressible":true},
  "application/vnd.dbf": {"source":"iana","extensions":["dbf"]},
  "application/vnd.dcmp+xml": {"source":"iana","compressible":true,"extensions":["dcmp"]},
  "application/vnd.debian.binary-package": {"source":"iana"},
  "application/vnd.dece.data": {"source":"iana","extensions":["uvf","uvvf","uvd","uvvd"]},
  "application/vnd.dece.ttml+xml": {"source":"iana","compressible":true,"extensions":["uvt","uvvt"]},
  "application/vnd.dece.unspecified": {"source":"iana","extensions":["uvx","uvvx"]},
  "application/vnd.dece.zip": {"source":"iana","extensions":["uvz","uvvz"]},
  "application/vnd.denovo.fcselayout-link": {"source":"iana","extensions":["fe_launch"]},
  "application/vnd.desmume.movie": {"source":"iana"},
  "application/vnd.dir-bi.plate-dl-nosuffix": {"source":"iana"},
  "application/vnd.dm.delegation+xml": {"source":"iana","compressible":true},
  "application/vnd.dna": {"source":"iana","extensions":["dna"]},
  "application/vnd.document+json": {"source":"iana","compressible":true},
  "application/vnd.dolby.mlp": {"source":"apache","extensions":["mlp"]},
  "application/vnd.dolby.mobile.1": {"source":"iana"},
  "application/vnd.dolby.mobile.2": {"source":"iana"},
  "application/vnd.doremir.scorecloud-binary-document": {"source":"iana"},
  "application/vnd.dpgraph": {"source":"iana","extensions":["dpg"]},
  "application/vnd.dreamfactory": {"source":"iana","extensions":["dfac"]},
  "application/vnd.drive+json": {"source":"iana","compressible":true},
  "application/vnd.ds-keypoint": {"source":"apache","extensions":["kpxx"]},
  "application/vnd.dtg.local": {"source":"iana"},
  "application/vnd.dtg.local.flash": {"source":"iana"},
  "application/vnd.dtg.local.html": {"source":"iana"},
  "application/vnd.dvb.ait": {"source":"iana","extensions":["ait"]},
  "application/vnd.dvb.dvbisl+xml": {"source":"iana","compressible":true},
  "application/vnd.dvb.dvbj": {"source":"iana"},
  "application/vnd.dvb.esgcontainer": {"source":"iana"},
  "application/vnd.dvb.ipdcdftnotifaccess": {"source":"iana"},
  "application/vnd.dvb.ipdcesgaccess": {"source":"iana"},
  "application/vnd.dvb.ipdcesgaccess2": {"source":"iana"},
  "application/vnd.dvb.ipdcesgpdd": {"source":"iana"},
  "application/vnd.dvb.ipdcroaming": {"source":"iana"},
  "application/vnd.dvb.iptv.alfec-base": {"source":"iana"},
  "application/vnd.dvb.iptv.alfec-enhancement": {"source":"iana"},
  "application/vnd.dvb.notif-aggregate-root+xml": {"source":"iana","compressible":true},
  "application/vnd.dvb.notif-container+xml": {"source":"iana","compressible":true},
  "application/vnd.dvb.notif-generic+xml": {"source":"iana","compressible":true},
  "application/vnd.dvb.notif-ia-msglist+xml": {"source":"iana","compressible":true},
  "application/vnd.dvb.notif-ia-registration-request+xml": {"source":"iana","compressible":true},
  "application/vnd.dvb.notif-ia-registration-response+xml": {"source":"iana","compressible":true},
  "application/vnd.dvb.notif-init+xml": {"source":"iana","compressible":true},
  "application/vnd.dvb.pfr": {"source":"iana"},
  "application/vnd.dvb.service": {"source":"iana","extensions":["svc"]},
  "application/vnd.dxr": {"source":"iana"},
  "application/vnd.dynageo": {"source":"iana","extensions":["geo"]},
  "application/vnd.dzr": {"source":"iana"},
  "application/vnd.easykaraoke.cdgdownload": {"source":"iana"},
  "application/vnd.ecdis-update": {"source":"iana"},
  "application/vnd.ecip.rlp": {"source":"iana"},
  "application/vnd.eclipse.ditto+json": {"source":"iana","compressible":true},
  "application/vnd.ecowin.chart": {"source":"iana","extensions":["mag"]},
  "application/vnd.ecowin.filerequest": {"source":"iana"},
  "application/vnd.ecowin.fileupdate": {"source":"iana"},
  "application/vnd.ecowin.series": {"source":"iana"},
  "application/vnd.ecowin.seriesrequest": {"source":"iana"},
  "application/vnd.ecowin.seriesupdate": {"source":"iana"},
  "application/vnd.efi.img": {"source":"iana"},
  "application/vnd.efi.iso": {"source":"iana"},
  "application/vnd.eln+zip": {"source":"iana","compressible":false},
  "application/vnd.emclient.accessrequest+xml": {"source":"iana","compressible":true},
  "application/vnd.enliven": {"source":"iana","extensions":["nml"]},
  "application/vnd.enphase.envoy": {"source":"iana"},
  "application/vnd.eprints.data+xml": {"source":"iana","compressible":true},
  "application/vnd.epson.esf": {"source":"iana","extensions":["esf"]},
  "application/vnd.epson.msf": {"source":"iana","extensions":["msf"]},
  "application/vnd.epson.quickanime": {"source":"iana","extensions":["qam"]},
  "application/vnd.epson.salt": {"source":"iana","extensions":["slt"]},
  "application/vnd.epson.ssf": {"source":"iana","extensions":["ssf"]},
  "application/vnd.ericsson.quickcall": {"source":"iana"},
  "application/vnd.erofs": {"source":"iana"},
  "application/vnd.espass-espass+zip": {"source":"iana","compressible":false},
  "application/vnd.eszigno3+xml": {"source":"iana","compressible":true,"extensions":["es3","et3"]},
  "application/vnd.etsi.aoc+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.asic-e+zip": {"source":"iana","compressible":false},
  "application/vnd.etsi.asic-s+zip": {"source":"iana","compressible":false},
  "application/vnd.etsi.cug+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvcommand+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvdiscovery+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvprofile+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvsad-bc+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvsad-cod+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvsad-npvr+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvservice+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvsync+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.iptvueprofile+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.mcid+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.mheg5": {"source":"iana"},
  "application/vnd.etsi.overload-control-policy-dataset+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.pstn+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.sci+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.simservs+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.timestamp-token": {"source":"iana"},
  "application/vnd.etsi.tsl+xml": {"source":"iana","compressible":true},
  "application/vnd.etsi.tsl.der": {"source":"iana"},
  "application/vnd.eu.kasparian.car+json": {"source":"iana","compressible":true},
  "application/vnd.eudora.data": {"source":"iana"},
  "application/vnd.evolv.ecig.profile": {"source":"iana"},
  "application/vnd.evolv.ecig.settings": {"source":"iana"},
  "application/vnd.evolv.ecig.theme": {"source":"iana"},
  "application/vnd.exstream-empower+zip": {"source":"iana","compressible":false},
  "application/vnd.exstream-package": {"source":"iana"},
  "application/vnd.ezpix-album": {"source":"iana","extensions":["ez2"]},
  "application/vnd.ezpix-package": {"source":"iana","extensions":["ez3"]},
  "application/vnd.f-secure.mobile": {"source":"iana"},
  "application/vnd.familysearch.gedcom+zip": {"source":"iana","compressible":false},
  "application/vnd.fastcopy-disk-image": {"source":"iana"},
  "application/vnd.fdf": {"source":"apache","extensions":["fdf"]},
  "application/vnd.fdsn.mseed": {"source":"iana","extensions":["mseed"]},
  "application/vnd.fdsn.seed": {"source":"iana","extensions":["seed","dataless"]},
  "application/vnd.fdsn.stationxml+xml": {"source":"iana","charset":"XML-BASED","compressible":true},
  "application/vnd.ffsns": {"source":"iana"},
  "application/vnd.ficlab.flb+zip": {"source":"iana","compressible":false},
  "application/vnd.filmit.zfc": {"source":"iana"},
  "application/vnd.fints": {"source":"iana"},
  "application/vnd.firemonkeys.cloudcell": {"source":"iana"},
  "application/vnd.flographit": {"source":"iana","extensions":["gph"]},
  "application/vnd.fluxtime.clip": {"source":"iana","extensions":["ftc"]},
  "application/vnd.font-fontforge-sfd": {"source":"iana"},
  "application/vnd.framemaker": {"source":"iana","extensions":["fm","frame","maker","book"]},
  "application/vnd.freelog.comic": {"source":"iana"},
  "application/vnd.frogans.fnc": {"source":"apache","extensions":["fnc"]},
  "application/vnd.frogans.ltf": {"source":"apache","extensions":["ltf"]},
  "application/vnd.fsc.weblaunch": {"source":"iana","extensions":["fsc"]},
  "application/vnd.fujifilm.fb.docuworks": {"source":"iana"},
  "application/vnd.fujifilm.fb.docuworks.binder": {"source":"iana"},
  "application/vnd.fujifilm.fb.docuworks.container": {"source":"iana"},
  "application/vnd.fujifilm.fb.jfi+xml": {"source":"iana","compressible":true},
  "application/vnd.fujitsu.oasys": {"source":"iana","extensions":["oas"]},
  "application/vnd.fujitsu.oasys2": {"source":"iana","extensions":["oa2"]},
  "application/vnd.fujitsu.oasys3": {"source":"iana","extensions":["oa3"]},
  "application/vnd.fujitsu.oasysgp": {"source":"iana","extensions":["fg5"]},
  "application/vnd.fujitsu.oasysprs": {"source":"iana","extensions":["bh2"]},
  "application/vnd.fujixerox.art-ex": {"source":"iana"},
  "application/vnd.fujixerox.art4": {"source":"iana"},
  "application/vnd.fujixerox.ddd": {"source":"iana","extensions":["ddd"]},
  "application/vnd.fujixerox.docuworks": {"source":"iana","extensions":["xdw"]},
  "application/vnd.fujixerox.docuworks.binder": {"source":"iana","extensions":["xbd"]},
  "application/vnd.fujixerox.docuworks.container": {"source":"iana"},
  "application/vnd.fujixerox.hbpl": {"source":"iana"},
  "application/vnd.fut-misnet": {"source":"iana"},
  "application/vnd.futoin+cbor": {"source":"iana"},
  "application/vnd.futoin+json": {"source":"iana","compressible":true},
  "application/vnd.fuzzysheet": {"source":"iana","extensions":["fzs"]},
  "application/vnd.ga4gh.passport+jwt": {"source":"iana"},
  "application/vnd.genomatix.tuxedo": {"source":"iana","extensions":["txd"]},
  "application/vnd.genozip": {"source":"iana"},
  "application/vnd.gentics.grd+json": {"source":"iana","compressible":true},
  "application/vnd.gentoo.catmetadata+xml": {"source":"iana","compressible":true},
  "application/vnd.gentoo.ebuild": {"source":"iana"},
  "application/vnd.gentoo.eclass": {"source":"iana"},
  "application/vnd.gentoo.gpkg": {"source":"iana"},
  "application/vnd.gentoo.manifest": {"source":"iana"},
  "application/vnd.gentoo.pkgmetadata+xml": {"source":"iana","compressible":true},
  "application/vnd.gentoo.xpak": {"source":"iana"},
  "application/vnd.geo+json": {"source":"apache","compressible":true},
  "application/vnd.geocube+xml": {"source":"apache","compressible":true},
  "application/vnd.geogebra.file": {"source":"iana","extensions":["ggb"]},
  "application/vnd.geogebra.pinboard": {"source":"iana"},
  "application/vnd.geogebra.slides": {"source":"iana","extensions":["ggs"]},
  "application/vnd.geogebra.tool": {"source":"iana","extensions":["ggt"]},
  "application/vnd.geometry-explorer": {"source":"iana","extensions":["gex","gre"]},
  "application/vnd.geonext": {"source":"iana","extensions":["gxt"]},
  "application/vnd.geoplan": {"source":"iana","extensions":["g2w"]},
  "application/vnd.geospace": {"source":"iana","extensions":["g3w"]},
  "application/vnd.gerber": {"source":"iana"},
  "application/vnd.globalplatform.card-content-mgt": {"source":"iana"},
  "application/vnd.globalplatform.card-content-mgt-response": {"source":"iana"},
  "application/vnd.gmx": {"source":"iana","extensions":["gmx"]},
  "application/vnd.gnu.taler.exchange+json": {"source":"iana","compressible":true},
  "application/vnd.gnu.taler.merchant+json": {"source":"iana","compressible":true},
  "application/vnd.google-apps.audio": {},
  "application/vnd.google-apps.document": {"compressible":false,"extensions":["gdoc"]},
  "application/vnd.google-apps.drawing": {"compressible":false,"extensions":["gdraw"]},
  "application/vnd.google-apps.drive-sdk": {"compressible":false},
  "application/vnd.google-apps.file": {},
  "application/vnd.google-apps.folder": {"compressible":false},
  "application/vnd.google-apps.form": {"compressible":false,"extensions":["gform"]},
  "application/vnd.google-apps.fusiontable": {},
  "application/vnd.google-apps.jam": {"compressible":false,"extensions":["gjam"]},
  "application/vnd.google-apps.mail-layout": {},
  "application/vnd.google-apps.map": {"compressible":false,"extensions":["gmap"]},
  "application/vnd.google-apps.photo": {},
  "application/vnd.google-apps.presentation": {"compressible":false,"extensions":["gslides"]},
  "application/vnd.google-apps.script": {"compressible":false,"extensions":["gscript"]},
  "application/vnd.google-apps.shortcut": {},
  "application/vnd.google-apps.site": {"compressible":false,"extensions":["gsite"]},
  "application/vnd.google-apps.spreadsheet": {"compressible":false,"extensions":["gsheet"]},
  "application/vnd.google-apps.unknown": {},
  "application/vnd.google-apps.video": {},
  "application/vnd.google-earth.kml+xml": {"source":"iana","compressible":true,"extensions":["kml"]},
  "application/vnd.google-earth.kmz": {"source":"iana","compressible":false,"extensions":["kmz"]},
  "application/vnd.gov.sk.e-form+xml": {"source":"apache","compressible":true},
  "application/vnd.gov.sk.e-form+zip": {"source":"iana","compressible":false},
  "application/vnd.gov.sk.xmldatacontainer+xml": {"source":"iana","compressible":true,"extensions":["xdcf"]},
  "application/vnd.gpxsee.map+xml": {"source":"iana","compressible":true},
  "application/vnd.grafeq": {"source":"iana","extensions":["gqf","gqs"]},
  "application/vnd.gridmp": {"source":"iana"},
  "application/vnd.groove-account": {"source":"iana","extensions":["gac"]},
  "application/vnd.groove-help": {"source":"iana","extensions":["ghf"]},
  "application/vnd.groove-identity-message": {"source":"iana","extensions":["gim"]},
  "application/vnd.groove-injector": {"source":"iana","extensions":["grv"]},
  "application/vnd.groove-tool-message": {"source":"iana","extensions":["gtm"]},
  "application/vnd.groove-tool-template": {"source":"iana","extensions":["tpl"]},
  "application/vnd.groove-vcard": {"source":"iana","extensions":["vcg"]},
  "application/vnd.hal+json": {"source":"iana","compressible":true},
  "application/vnd.hal+xml": {"source":"iana","compressible":true,"extensions":["hal"]},
  "application/vnd.handheld-entertainment+xml": {"source":"iana","compressible":true,"extensions":["zmm"]},
  "application/vnd.hbci": {"source":"iana","extensions":["hbci"]},
  "application/vnd.hc+json": {"source":"iana","compressible":true},
  "application/vnd.hcl-bireports": {"source":"iana"},
  "application/vnd.hdt": {"source":"iana"},
  "application/vnd.heroku+json": {"source":"iana","compressible":true},
  "application/vnd.hhe.lesson-player": {"source":"iana","extensions":["les"]},
  "application/vnd.hp-hpgl": {"source":"iana","extensions":["hpgl"]},
  "application/vnd.hp-hpid": {"source":"iana","extensions":["hpid"]},
  "application/vnd.hp-hps": {"source":"iana","extensions":["hps"]},
  "application/vnd.hp-jlyt": {"source":"iana","extensions":["jlt"]},
  "application/vnd.hp-pcl": {"source":"iana","extensions":["pcl"]},
  "application/vnd.hp-pclxl": {"source":"iana","extensions":["pclxl"]},
  "application/vnd.hsl": {"source":"iana"},
  "application/vnd.httphone": {"source":"iana"},
  "application/vnd.hydrostatix.sof-data": {"source":"iana","extensions":["sfd-hdstx"]},
  "application/vnd.hyper+json": {"source":"iana","compressible":true},
  "application/vnd.hyper-item+json": {"source":"iana","compressible":true},
  "application/vnd.hyperdrive+json": {"source":"iana","compressible":true},
  "application/vnd.hzn-3d-crossword": {"source":"iana"},
  "application/vnd.ibm.afplinedata": {"source":"apache"},
  "application/vnd.ibm.electronic-media": {"source":"iana"},
  "application/vnd.ibm.minipay": {"source":"iana","extensions":["mpy"]},
  "application/vnd.ibm.modcap": {"source":"apache","extensions":["afp","listafp","list3820"]},
  "application/vnd.ibm.rights-management": {"source":"iana","extensions":["irm"]},
  "application/vnd.ibm.secure-container": {"source":"iana","extensions":["sc"]},
  "application/vnd.iccprofile": {"source":"iana","extensions":["icc","icm"]},
  "application/vnd.ieee.1905": {"source":"iana"},
  "application/vnd.igloader": {"source":"iana","extensions":["igl"]},
  "application/vnd.imagemeter.folder+zip": {"source":"iana","compressible":false},
  "application/vnd.imagemeter.image+zip": {"source":"iana","compressible":false},
  "application/vnd.immervision-ivp": {"source":"iana","extensions":["ivp"]},
  "application/vnd.immervision-ivu": {"source":"iana","extensions":["ivu"]},
  "application/vnd.ims.imsccv1p1": {"source":"iana"},
  "application/vnd.ims.imsccv1p2": {"source":"iana"},
  "application/vnd.ims.imsccv1p3": {"source":"iana"},
  "application/vnd.ims.lis.v2.result+json": {"source":"iana","compressible":true},
  "application/vnd.ims.lti.v2.toolconsumerprofile+json": {"source":"iana","compressible":true},
  "application/vnd.ims.lti.v2.toolproxy+json": {"source":"iana","compressible":true},
  "application/vnd.ims.lti.v2.toolproxy.id+json": {"source":"iana","compressible":true},
  "application/vnd.ims.lti.v2.toolsettings+json": {"source":"iana","compressible":true},
  "application/vnd.ims.lti.v2.toolsettings.simple+json": {"source":"iana","compressible":true},
  "application/vnd.informedcontrol.rms+xml": {"source":"iana","compressible":true},
  "application/vnd.informix-visionary": {"source":"apache"},
  "application/vnd.infotech.project": {"source":"iana"},
  "application/vnd.infotech.project+xml": {"source":"iana","compressible":true},
  "application/vnd.innopath.wamp.notification": {"source":"iana"},
  "application/vnd.insors.igm": {"source":"iana","extensions":["igm"]},
  "application/vnd.intercon.formnet": {"source":"iana","extensions":["xpw","xpx"]},
  "application/vnd.intergeo": {"source":"iana","extensions":["i2g"]},
  "application/vnd.intertrust.digibox": {"source":"iana"},
  "application/vnd.intertrust.nncp": {"source":"iana"},
  "application/vnd.intu.qbo": {"source":"iana","extensions":["qbo"]},
  "application/vnd.intu.qfx": {"source":"iana","extensions":["qfx"]},
  "application/vnd.ipfs.ipns-record": {"source":"iana"},
  "application/vnd.ipld.car": {"source":"iana"},
  "application/vnd.ipld.dag-cbor": {"source":"iana"},
  "application/vnd.ipld.dag-json": {"source":"iana"},
  "application/vnd.ipld.raw": {"source":"iana"},
  "application/vnd.iptc.g2.catalogitem+xml": {"source":"iana","compressible":true},
  "application/vnd.iptc.g2.conceptitem+xml": {"source":"iana","compressible":true},
  "application/vnd.iptc.g2.knowledgeitem+xml": {"source":"iana","compressible":true},
  "application/vnd.iptc.g2.newsitem+xml": {"source":"iana","compressible":true},
  "application/vnd.iptc.g2.newsmessage+xml": {"source":"iana","compressible":true},
  "application/vnd.iptc.g2.packageitem+xml": {"source":"iana","compressible":true},
  "application/vnd.iptc.g2.planningitem+xml": {"source":"iana","compressible":true},
  "application/vnd.ipunplugged.rcprofile": {"source":"iana","extensions":["rcprofile"]},
  "application/vnd.irepository.package+xml": {"source":"iana","compressible":true,"extensions":["irp"]},
  "application/vnd.is-xpr": {"source":"iana","extensions":["xpr"]},
  "application/vnd.isac.fcs": {"source":"iana","extensions":["fcs"]},
  "application/vnd.iso11783-10+zip": {"source":"iana","compressible":false},
  "application/vnd.jam": {"source":"iana","extensions":["jam"]},
  "application/vnd.japannet-directory-service": {"source":"iana"},
  "application/vnd.japannet-jpnstore-wakeup": {"source":"iana"},
  "application/vnd.japannet-payment-wakeup": {"source":"iana"},
  "application/vnd.japannet-registration": {"source":"iana"},
  "application/vnd.japannet-registration-wakeup": {"source":"iana"},
  "application/vnd.japannet-setstore-wakeup": {"source":"iana"},
  "application/vnd.japannet-verification": {"source":"iana"},
  "application/vnd.japannet-verification-wakeup": {"source":"iana"},
  "application/vnd.jcp.javame.midlet-rms": {"source":"iana","extensions":["rms"]},
  "application/vnd.jisp": {"source":"iana","extensions":["jisp"]},
  "application/vnd.joost.joda-archive": {"source":"iana","extensions":["joda"]},
  "application/vnd.jsk.isdn-ngn": {"source":"iana"},
  "application/vnd.kahootz": {"source":"iana","extensions":["ktz","ktr"]},
  "application/vnd.kde.karbon": {"source":"iana","extensions":["karbon"]},
  "application/vnd.kde.kchart": {"source":"iana","extensions":["chrt"]},
  "application/vnd.kde.kformula": {"source":"iana","extensions":["kfo"]},
  "application/vnd.kde.kivio": {"source":"iana","extensions":["flw"]},
  "application/vnd.kde.kontour": {"source":"iana","extensions":["kon"]},
  "application/vnd.kde.kpresenter": {"source":"iana","extensions":["kpr","kpt"]},
  "application/vnd.kde.kspread": {"source":"iana","extensions":["ksp"]},
  "application/vnd.kde.kword": {"source":"iana","extensions":["kwd","kwt"]},
  "application/vnd.kdl": {"source":"iana"},
  "application/vnd.kenameaapp": {"source":"iana","extensions":["htke"]},
  "application/vnd.keyman.kmp+zip": {"source":"iana","compressible":false},
  "application/vnd.keyman.kmx": {"source":"iana"},
  "application/vnd.kidspiration": {"source":"iana","extensions":["kia"]},
  "application/vnd.kinar": {"source":"iana","extensions":["kne","knp"]},
  "application/vnd.koan": {"source":"iana","extensions":["skp","skd","skt","skm"]},
  "application/vnd.kodak-descriptor": {"source":"iana","extensions":["sse"]},
  "application/vnd.las": {"source":"iana"},
  "application/vnd.las.las+json": {"source":"iana","compressible":true},
  "application/vnd.las.las+xml": {"source":"iana","compressible":true,"extensions":["lasxml"]},
  "application/vnd.laszip": {"source":"iana"},
  "application/vnd.ldev.productlicensing": {"source":"iana"},
  "application/vnd.leap+json": {"source":"iana","compressible":true},
  "application/vnd.liberty-request+xml": {"source":"iana","compressible":true},
  "application/vnd.llamagraphics.life-balance.desktop": {"source":"iana","extensions":["lbd"]},
  "application/vnd.llamagraphics.life-balance.exchange+xml": {"source":"iana","compressible":true,"extensions":["lbe"]},
  "application/vnd.logipipe.circuit+zip": {"source":"iana","compressible":false},
  "application/vnd.loom": {"source":"iana"},
  "application/vnd.lotus-1-2-3": {"source":"iana","extensions":["123"]},
  "application/vnd.lotus-approach": {"source":"iana","extensions":["apr"]},
  "application/vnd.lotus-freelance": {"source":"iana","extensions":["pre"]},
  "application/vnd.lotus-notes": {"source":"iana","extensions":["nsf"]},
  "application/vnd.lotus-organizer": {"source":"iana","extensions":["org"]},
  "application/vnd.lotus-screencam": {"source":"iana","extensions":["scm"]},
  "application/vnd.lotus-wordpro": {"source":"iana","extensions":["lwp"]},
  "application/vnd.macports.portpkg": {"source":"iana","extensions":["portpkg"]},
  "application/vnd.mapbox-vector-tile": {"source":"iana","extensions":["mvt"]},
  "application/vnd.marlin.drm.actiontoken+xml": {"source":"iana","compressible":true},
  "application/vnd.marlin.drm.conftoken+xml": {"source":"iana","compressible":true},
  "application/vnd.marlin.drm.license+xml": {"source":"iana","compressible":true},
  "application/vnd.marlin.drm.mdcf": {"source":"iana"},
  "application/vnd.mason+json": {"source":"iana","compressible":true},
  "application/vnd.maxar.archive.3tz+zip": {"source":"iana","compressible":false},
  "application/vnd.maxmind.maxmind-db": {"source":"iana"},
  "application/vnd.mcd": {"source":"iana","extensions":["mcd"]},
  "application/vnd.mdl": {"source":"iana"},
  "application/vnd.mdl-mbsdf": {"source":"iana"},
  "application/vnd.medcalcdata": {"source":"iana","extensions":["mc1"]},
  "application/vnd.mediastation.cdkey": {"source":"iana","extensions":["cdkey"]},
  "application/vnd.medicalholodeck.recordxr": {"source":"iana"},
  "application/vnd.meridian-slingshot": {"source":"iana"},
  "application/vnd.mermaid": {"source":"iana"},
  "application/vnd.mfer": {"source":"iana","extensions":["mwf"]},
  "application/vnd.mfmp": {"source":"iana","extensions":["mfm"]},
  "application/vnd.micro+json": {"source":"iana","compressible":true},
  "application/vnd.micrografx.flo": {"source":"iana","extensions":["flo"]},
  "application/vnd.micrografx.igx": {"source":"iana","extensions":["igx"]},
  "application/vnd.microsoft.portable-executable": {"source":"iana"},
  "application/vnd.microsoft.windows.thumbnail-cache": {"source":"iana"},
  "application/vnd.miele+json": {"source":"iana","compressible":true},
  "application/vnd.mif": {"source":"iana","extensions":["mif"]},
  "application/vnd.minisoft-hp3000-save": {"source":"iana"},
  "application/vnd.mitsubishi.misty-guard.trustweb": {"source":"iana"},
  "application/vnd.mobius.daf": {"source":"iana","extensions":["daf"]},
  "application/vnd.mobius.dis": {"source":"iana","extensions":["dis"]},
  "application/vnd.mobius.mbk": {"source":"iana","extensions":["mbk"]},
  "application/vnd.mobius.mqy": {"source":"iana","extensions":["mqy"]},
  "application/vnd.mobius.msl": {"source":"iana","extensions":["msl"]},
  "application/vnd.mobius.plc": {"source":"iana","extensions":["plc"]},
  "application/vnd.mobius.txf": {"source":"iana","extensions":["txf"]},
  "application/vnd.modl": {"source":"iana"},
  "application/vnd.mophun.application": {"source":"iana","extensions":["mpn"]},
  "application/vnd.mophun.certificate": {"source":"iana","extensions":["mpc"]},
  "application/vnd.motorola.flexsuite": {"source":"iana"},
  "application/vnd.motorola.flexsuite.adsi": {"source":"iana"},
  "application/vnd.motorola.flexsuite.fis": {"source":"iana"},
  "application/vnd.motorola.flexsuite.gotap": {"source":"iana"},
  "application/vnd.motorola.flexsuite.kmr": {"source":"iana"},
  "application/vnd.motorola.flexsuite.ttc": {"source":"iana"},
  "application/vnd.motorola.flexsuite.wem": {"source":"iana"},
  "application/vnd.motorola.iprm": {"source":"iana"},
  "application/vnd.mozilla.xul+xml": {"source":"iana","compressible":true,"extensions":["xul"]},
  "application/vnd.ms-3mfdocument": {"source":"iana"},
  "application/vnd.ms-artgalry": {"source":"iana","extensions":["cil"]},
  "application/vnd.ms-asf": {"source":"iana"},
  "application/vnd.ms-cab-compressed": {"source":"iana","extensions":["cab"]},
  "application/vnd.ms-color.iccprofile": {"source":"apache"},
  "application/vnd.ms-excel": {"source":"iana","compressible":false,"extensions":["xls","xlm","xla","xlc","xlt","xlw"]},
  "application/vnd.ms-excel.addin.macroenabled.12": {"source":"iana","extensions":["xlam"]},
  "application/vnd.ms-excel.sheet.binary.macroenabled.12": {"source":"iana","extensions":["xlsb"]},
  "application/vnd.ms-excel.sheet.macroenabled.12": {"source":"iana","extensions":["xlsm"]},
  "application/vnd.ms-excel.template.macroenabled.12": {"source":"iana","extensions":["xltm"]},
  "application/vnd.ms-fontobject": {"source":"iana","compressible":true,"extensions":["eot"]},
  "application/vnd.ms-htmlhelp": {"source":"iana","extensions":["chm"]},
  "application/vnd.ms-ims": {"source":"iana","extensions":["ims"]},
  "application/vnd.ms-lrm": {"source":"iana","extensions":["lrm"]},
  "application/vnd.ms-office.activex+xml": {"source":"iana","compressible":true},
  "application/vnd.ms-officetheme": {"source":"iana","extensions":["thmx"]},
  "application/vnd.ms-opentype": {"source":"apache","compressible":true},
  "application/vnd.ms-outlook": {"compressible":false,"extensions":["msg"]},
  "application/vnd.ms-package.obfuscated-opentype": {"source":"apache"},
  "application/vnd.ms-pki.seccat": {"source":"apache","extensions":["cat"]},
  "application/vnd.ms-pki.stl": {"source":"apache","extensions":["stl"]},
  "application/vnd.ms-playready.initiator+xml": {"source":"iana","compressible":true},
  "application/vnd.ms-powerpoint": {"source":"iana","compressible":false,"extensions":["ppt","pps","pot"]},
  "application/vnd.ms-powerpoint.addin.macroenabled.12": {"source":"iana","extensions":["ppam"]},
  "application/vnd.ms-powerpoint.presentation.macroenabled.12": {"source":"iana","extensions":["pptm"]},
  "application/vnd.ms-powerpoint.slide.macroenabled.12": {"source":"iana","extensions":["sldm"]},
  "application/vnd.ms-powerpoint.slideshow.macroenabled.12": {"source":"iana","extensions":["ppsm"]},
  "application/vnd.ms-powerpoint.template.macroenabled.12": {"source":"iana","extensions":["potm"]},
  "application/vnd.ms-printdevicecapabilities+xml": {"source":"iana","compressible":true},
  "application/vnd.ms-printing.printticket+xml": {"source":"apache","compressible":true},
  "application/vnd.ms-printschematicket+xml": {"source":"iana","compressible":true},
  "application/vnd.ms-project": {"source":"iana","extensions":["mpp","mpt"]},
  "application/vnd.ms-tnef": {"source":"iana"},
  "application/vnd.ms-visio.viewer": {"extensions":["vdx"]},
  "application/vnd.ms-windows.devicepairing": {"source":"iana"},
  "application/vnd.ms-windows.nwprinting.oob": {"source":"iana"},
  "application/vnd.ms-windows.printerpairing": {"source":"iana"},
  "application/vnd.ms-windows.wsd.oob": {"source":"iana"},
  "application/vnd.ms-wmdrm.lic-chlg-req": {"source":"iana"},
  "application/vnd.ms-wmdrm.lic-resp": {"source":"iana"},
  "application/vnd.ms-wmdrm.meter-chlg-req": {"source":"iana"},
  "application/vnd.ms-wmdrm.meter-resp": {"source":"iana"},
  "application/vnd.ms-word.document.macroenabled.12": {"source":"iana","extensions":["docm"]},
  "application/vnd.ms-word.template.macroenabled.12": {"source":"iana","extensions":["dotm"]},
  "application/vnd.ms-works": {"source":"iana","extensions":["wps","wks","wcm","wdb"]},
  "application/vnd.ms-wpl": {"source":"iana","extensions":["wpl"]},
  "application/vnd.ms-xpsdocument": {"source":"iana","compressible":false,"extensions":["xps"]},
  "application/vnd.msa-disk-image": {"source":"iana"},
  "application/vnd.mseq": {"source":"iana","extensions":["mseq"]},
  "application/vnd.msgpack": {"source":"iana"},
  "application/vnd.msign": {"source":"iana"},
  "application/vnd.multiad.creator": {"source":"iana"},
  "application/vnd.multiad.creator.cif": {"source":"iana"},
  "application/vnd.music-niff": {"source":"iana"},
  "application/vnd.musician": {"source":"iana","extensions":["mus"]},
  "application/vnd.muvee.style": {"source":"iana","extensions":["msty"]},
  "application/vnd.mynfc": {"source":"iana","extensions":["taglet"]},
  "application/vnd.nacamar.ybrid+json": {"source":"iana","compressible":true},
  "application/vnd.nato.bindingdataobject+cbor": {"source":"iana"},
  "application/vnd.nato.bindingdataobject+json": {"source":"iana","compressible":true},
  "application/vnd.nato.bindingdataobject+xml": {"source":"iana","compressible":true,"extensions":["bdo"]},
  "application/vnd.nato.openxmlformats-package.iepd+zip": {"source":"iana","compressible":false},
  "application/vnd.ncd.control": {"source":"iana"},
  "application/vnd.ncd.reference": {"source":"iana"},
  "application/vnd.nearst.inv+json": {"source":"iana","compressible":true},
  "application/vnd.nebumind.line": {"source":"iana"},
  "application/vnd.nervana": {"source":"iana"},
  "application/vnd.netfpx": {"source":"iana"},
  "application/vnd.neurolanguage.nlu": {"source":"iana","extensions":["nlu"]},
  "application/vnd.nimn": {"source":"iana"},
  "application/vnd.nintendo.nitro.rom": {"source":"iana"},
  "application/vnd.nintendo.snes.rom": {"source":"iana"},
  "application/vnd.nitf": {"source":"iana","extensions":["ntf","nitf"]},
  "application/vnd.noblenet-directory": {"source":"iana","extensions":["nnd"]},
  "application/vnd.noblenet-sealer": {"source":"iana","extensions":["nns"]},
  "application/vnd.noblenet-web": {"source":"iana","extensions":["nnw"]},
  "application/vnd.nokia.catalogs": {"source":"iana"},
  "application/vnd.nokia.conml+wbxml": {"source":"iana"},
  "application/vnd.nokia.conml+xml": {"source":"iana","compressible":true},
  "application/vnd.nokia.iptv.config+xml": {"source":"iana","compressible":true},
  "application/vnd.nokia.isds-radio-presets": {"source":"iana"},
  "application/vnd.nokia.landmark+wbxml": {"source":"iana"},
  "application/vnd.nokia.landmark+xml": {"source":"iana","compressible":true},
  "application/vnd.nokia.landmarkcollection+xml": {"source":"iana","compressible":true},
  "application/vnd.nokia.n-gage.ac+xml": {"source":"iana","compressible":true,"extensions":["ac"]},
  "application/vnd.nokia.n-gage.data": {"source":"iana","extensions":["ngdat"]},
  "application/vnd.nokia.n-gage.symbian.install": {"source":"apache","extensions":["n-gage"]},
  "application/vnd.nokia.ncd": {"source":"iana"},
  "application/vnd.nokia.pcd+wbxml": {"source":"iana"},
  "application/vnd.nokia.pcd+xml": {"source":"iana","compressible":true},
  "application/vnd.nokia.radio-preset": {"source":"iana","extensions":["rpst"]},
  "application/vnd.nokia.radio-presets": {"source":"iana","extensions":["rpss"]},
  "application/vnd.novadigm.edm": {"source":"iana","extensions":["edm"]},
  "application/vnd.novadigm.edx": {"source":"iana","extensions":["edx"]},
  "application/vnd.novadigm.ext": {"source":"iana","extensions":["ext"]},
  "application/vnd.ntt-local.content-share": {"source":"iana"},
  "application/vnd.ntt-local.file-transfer": {"source":"iana"},
  "application/vnd.ntt-local.ogw_remote-access": {"source":"iana"},
  "application/vnd.ntt-local.sip-ta_remote": {"source":"iana"},
  "application/vnd.ntt-local.sip-ta_tcp_stream": {"source":"iana"},
  "application/vnd.oai.workflows": {"source":"iana"},
  "application/vnd.oai.workflows+json": {"source":"iana","compressible":true},
  "application/vnd.oai.workflows+yaml": {"source":"iana"},
  "application/vnd.oasis.opendocument.base": {"source":"iana"},
  "application/vnd.oasis.opendocument.chart": {"source":"iana","extensions":["odc"]},
  "application/vnd.oasis.opendocument.chart-template": {"source":"iana","extensions":["otc"]},
  "application/vnd.oasis.opendocument.database": {"source":"apache","extensions":["odb"]},
  "application/vnd.oasis.opendocument.formula": {"source":"iana","extensions":["odf"]},
  "application/vnd.oasis.opendocument.formula-template": {"source":"iana","extensions":["odft"]},
  "application/vnd.oasis.opendocument.graphics": {"source":"iana","compressible":false,"extensions":["odg"]},
  "application/vnd.oasis.opendocument.graphics-template": {"source":"iana","extensions":["otg"]},
  "application/vnd.oasis.opendocument.image": {"source":"iana","extensions":["odi"]},
  "application/vnd.oasis.opendocument.image-template": {"source":"iana","extensions":["oti"]},
  "application/vnd.oasis.opendocument.presentation": {"source":"iana","compressible":false,"extensions":["odp"]},
  "application/vnd.oasis.opendocument.presentation-template": {"source":"iana","extensions":["otp"]},
  "application/vnd.oasis.opendocument.spreadsheet": {"source":"iana","compressible":false,"extensions":["ods"]},
  "application/vnd.oasis.opendocument.spreadsheet-template": {"source":"iana","extensions":["ots"]},
  "application/vnd.oasis.opendocument.text": {"source":"iana","compressible":false,"extensions":["odt"]},
  "application/vnd.oasis.opendocument.text-master": {"source":"iana","extensions":["odm"]},
  "application/vnd.oasis.opendocument.text-master-template": {"source":"iana"},
  "application/vnd.oasis.opendocument.text-template": {"source":"iana","extensions":["ott"]},
  "application/vnd.oasis.opendocument.text-web": {"source":"iana","extensions":["oth"]},
  "application/vnd.obn": {"source":"iana"},
  "application/vnd.ocf+cbor": {"source":"iana"},
  "application/vnd.oci.image.manifest.v1+json": {"source":"iana","compressible":true},
  "application/vnd.oftn.l10n+json": {"source":"iana","compressible":true},
  "application/vnd.oipf.contentaccessdownload+xml": {"source":"iana","compressible":true},
  "application/vnd.oipf.contentaccessstreaming+xml": {"source":"iana","compressible":true},
  "application/vnd.oipf.cspg-hexbinary": {"source":"iana"},
  "application/vnd.oipf.dae.svg+xml": {"source":"iana","compressible":true},
  "application/vnd.oipf.dae.xhtml+xml": {"source":"iana","compressible":true},
  "application/vnd.oipf.mippvcontrolmessage+xml": {"source":"iana","compressible":true},
  "application/vnd.oipf.pae.gem": {"source":"iana"},
  "application/vnd.oipf.spdiscovery+xml": {"source":"iana","compressible":true},
  "application/vnd.oipf.spdlist+xml": {"source":"iana","compressible":true},
  "application/vnd.oipf.ueprofile+xml": {"source":"iana","compressible":true},
  "application/vnd.oipf.userprofile+xml": {"source":"iana","compressible":true},
  "application/vnd.olpc-sugar": {"source":"iana","extensions":["xo"]},
  "application/vnd.oma-scws-config": {"source":"iana"},
  "application/vnd.oma-scws-http-request": {"source":"iana"},
  "application/vnd.oma-scws-http-response": {"source":"iana"},
  "application/vnd.oma.bcast.associated-procedure-parameter+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.bcast.drm-trigger+xml": {"source":"apache","compressible":true},
  "application/vnd.oma.bcast.imd+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.bcast.ltkm": {"source":"iana"},
  "application/vnd.oma.bcast.notification+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.bcast.provisioningtrigger": {"source":"iana"},
  "application/vnd.oma.bcast.sgboot": {"source":"iana"},
  "application/vnd.oma.bcast.sgdd+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.bcast.sgdu": {"source":"iana"},
  "application/vnd.oma.bcast.simple-symbol-container": {"source":"iana"},
  "application/vnd.oma.bcast.smartcard-trigger+xml": {"source":"apache","compressible":true},
  "application/vnd.oma.bcast.sprov+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.bcast.stkm": {"source":"iana"},
  "application/vnd.oma.cab-address-book+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.cab-feature-handler+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.cab-pcc+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.cab-subs-invite+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.cab-user-prefs+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.dcd": {"source":"iana"},
  "application/vnd.oma.dcdc": {"source":"iana"},
  "application/vnd.oma.dd2+xml": {"source":"iana","compressible":true,"extensions":["dd2"]},
  "application/vnd.oma.drm.risd+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.group-usage-list+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.lwm2m+cbor": {"source":"iana"},
  "application/vnd.oma.lwm2m+json": {"source":"iana","compressible":true},
  "application/vnd.oma.lwm2m+tlv": {"source":"iana"},
  "application/vnd.oma.pal+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.poc.detailed-progress-report+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.poc.final-report+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.poc.groups+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.poc.invocation-descriptor+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.poc.optimized-progress-report+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.push": {"source":"iana"},
  "application/vnd.oma.scidm.messages+xml": {"source":"iana","compressible":true},
  "application/vnd.oma.xcap-directory+xml": {"source":"iana","compressible":true},
  "application/vnd.omads-email+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/vnd.omads-file+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/vnd.omads-folder+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/vnd.omaloc-supl-init": {"source":"iana"},
  "application/vnd.onepager": {"source":"iana"},
  "application/vnd.onepagertamp": {"source":"iana"},
  "application/vnd.onepagertamx": {"source":"iana"},
  "application/vnd.onepagertat": {"source":"iana"},
  "application/vnd.onepagertatp": {"source":"iana"},
  "application/vnd.onepagertatx": {"source":"iana"},
  "application/vnd.onvif.metadata": {"source":"iana"},
  "application/vnd.openblox.game+xml": {"source":"iana","compressible":true,"extensions":["obgx"]},
  "application/vnd.openblox.game-binary": {"source":"iana"},
  "application/vnd.openeye.oeb": {"source":"iana"},
  "application/vnd.openofficeorg.extension": {"source":"apache","extensions":["oxt"]},
  "application/vnd.openstreetmap.data+xml": {"source":"iana","compressible":true,"extensions":["osm"]},
  "application/vnd.opentimestamps.ots": {"source":"iana"},
  "application/vnd.openvpi.dspx+json": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.custom-properties+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.drawing+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.extended-properties+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.presentation": {"source":"iana","compressible":false,"extensions":["pptx"]},
  "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.slide": {"source":"iana","extensions":["sldx"]},
  "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.slideshow": {"source":"iana","extensions":["ppsx"]},
  "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.template": {"source":"iana","extensions":["potx"]},
  "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {"source":"iana","compressible":false,"extensions":["xlsx"]},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.template": {"source":"iana","extensions":["xltx"]},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.theme+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.themeoverride+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.vmldrawing": {"source":"iana"},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document": {"source":"iana","compressible":false,"extensions":["docx"]},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.template": {"source":"iana","extensions":["dotx"]},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-package.core-properties+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": {"source":"iana","compressible":true},
  "application/vnd.openxmlformats-package.relationships+xml": {"source":"iana","compressible":true},
  "application/vnd.oracle.resource+json": {"source":"iana","compressible":true},
  "application/vnd.orange.indata": {"source":"iana"},
  "application/vnd.osa.netdeploy": {"source":"iana"},
  "application/vnd.osgeo.mapguide.package": {"source":"iana","extensions":["mgp"]},
  "application/vnd.osgi.bundle": {"source":"iana"},
  "application/vnd.osgi.dp": {"source":"iana","extensions":["dp"]},
  "application/vnd.osgi.subsystem": {"source":"iana","extensions":["esa"]},
  "application/vnd.otps.ct-kip+xml": {"source":"iana","compressible":true},
  "application/vnd.oxli.countgraph": {"source":"iana"},
  "application/vnd.pagerduty+json": {"source":"iana","compressible":true},
  "application/vnd.palm": {"source":"iana","extensions":["pdb","pqa","oprc"]},
  "application/vnd.panoply": {"source":"iana"},
  "application/vnd.paos.xml": {"source":"iana"},
  "application/vnd.patentdive": {"source":"iana"},
  "application/vnd.patientecommsdoc": {"source":"iana"},
  "application/vnd.pawaafile": {"source":"iana","extensions":["paw"]},
  "application/vnd.pcos": {"source":"iana"},
  "application/vnd.pg.format": {"source":"iana","extensions":["str"]},
  "application/vnd.pg.osasli": {"source":"iana","extensions":["ei6"]},
  "application/vnd.piaccess.application-licence": {"source":"iana"},
  "application/vnd.picsel": {"source":"iana","extensions":["efif"]},
  "application/vnd.pmi.widget": {"source":"iana","extensions":["wg"]},
  "application/vnd.poc.group-advertisement+xml": {"source":"iana","compressible":true},
  "application/vnd.pocketlearn": {"source":"iana","extensions":["plf"]},
  "application/vnd.powerbuilder6": {"source":"iana","extensions":["pbd"]},
  "application/vnd.powerbuilder6-s": {"source":"iana"},
  "application/vnd.powerbuilder7": {"source":"iana"},
  "application/vnd.powerbuilder7-s": {"source":"iana"},
  "application/vnd.powerbuilder75": {"source":"iana"},
  "application/vnd.powerbuilder75-s": {"source":"iana"},
  "application/vnd.preminet": {"source":"iana"},
  "application/vnd.previewsystems.box": {"source":"iana","extensions":["box"]},
  "application/vnd.procrate.brushset": {"extensions":["brushset"]},
  "application/vnd.procreate.brush": {"extensions":["brush"]},
  "application/vnd.procreate.dream": {"extensions":["drm"]},
  "application/vnd.proteus.magazine": {"source":"iana","extensions":["mgz"]},
  "application/vnd.psfs": {"source":"iana"},
  "application/vnd.pt.mundusmundi": {"source":"iana"},
  "application/vnd.publishare-delta-tree": {"source":"iana","extensions":["qps"]},
  "application/vnd.pvi.ptid1": {"source":"iana","extensions":["ptid"]},
  "application/vnd.pwg-multiplexed": {"source":"iana"},
  "application/vnd.pwg-xhtml-print+xml": {"source":"iana","compressible":true,"extensions":["xhtm"]},
  "application/vnd.qualcomm.brew-app-res": {"source":"iana"},
  "application/vnd.quarantainenet": {"source":"iana"},
  "application/vnd.quark.quarkxpress": {"source":"iana","extensions":["qxd","qxt","qwd","qwt","qxl","qxb"]},
  "application/vnd.quobject-quoxdocument": {"source":"iana"},
  "application/vnd.radisys.moml+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-audit+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-audit-conf+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-audit-conn+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-audit-dialog+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-audit-stream+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-conf+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-dialog+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-dialog-base+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-dialog-fax-detect+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-dialog-group+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-dialog-speech+xml": {"source":"iana","compressible":true},
  "application/vnd.radisys.msml-dialog-transform+xml": {"source":"iana","compressible":true},
  "application/vnd.rainstor.data": {"source":"iana"},
  "application/vnd.rapid": {"source":"iana"},
  "application/vnd.rar": {"source":"iana","extensions":["rar"]},
  "application/vnd.realvnc.bed": {"source":"iana","extensions":["bed"]},
  "application/vnd.recordare.musicxml": {"source":"iana","extensions":["mxl"]},
  "application/vnd.recordare.musicxml+xml": {"source":"iana","compressible":true,"extensions":["musicxml"]},
  "application/vnd.relpipe": {"source":"iana"},
  "application/vnd.renlearn.rlprint": {"source":"iana"},
  "application/vnd.resilient.logic": {"source":"iana"},
  "application/vnd.restful+json": {"source":"iana","compressible":true},
  "application/vnd.rig.cryptonote": {"source":"iana","extensions":["cryptonote"]},
  "application/vnd.rim.cod": {"source":"apache","extensions":["cod"]},
  "application/vnd.rn-realmedia": {"source":"apache","extensions":["rm"]},
  "application/vnd.rn-realmedia-vbr": {"source":"apache","extensions":["rmvb"]},
  "application/vnd.route66.link66+xml": {"source":"iana","compressible":true,"extensions":["link66"]},
  "application/vnd.rs-274x": {"source":"iana"},
  "application/vnd.ruckus.download": {"source":"iana"},
  "application/vnd.s3sms": {"source":"iana"},
  "application/vnd.sailingtracker.track": {"source":"iana","extensions":["st"]},
  "application/vnd.sar": {"source":"iana"},
  "application/vnd.sbm.cid": {"source":"iana"},
  "application/vnd.sbm.mid2": {"source":"iana"},
  "application/vnd.scribus": {"source":"iana"},
  "application/vnd.sealed.3df": {"source":"iana"},
  "application/vnd.sealed.csf": {"source":"iana"},
  "application/vnd.sealed.doc": {"source":"iana"},
  "application/vnd.sealed.eml": {"source":"iana"},
  "application/vnd.sealed.mht": {"source":"iana"},
  "application/vnd.sealed.net": {"source":"iana"},
  "application/vnd.sealed.ppt": {"source":"iana"},
  "application/vnd.sealed.tiff": {"source":"iana"},
  "application/vnd.sealed.xls": {"source":"iana"},
  "application/vnd.sealedmedia.softseal.html": {"source":"iana"},
  "application/vnd.sealedmedia.softseal.pdf": {"source":"iana"},
  "application/vnd.seemail": {"source":"iana","extensions":["see"]},
  "application/vnd.seis+json": {"source":"iana","compressible":true},
  "application/vnd.sema": {"source":"iana","extensions":["sema"]},
  "application/vnd.semd": {"source":"iana","extensions":["semd"]},
  "application/vnd.semf": {"source":"iana","extensions":["semf"]},
  "application/vnd.shade-save-file": {"source":"iana"},
  "application/vnd.shana.informed.formdata": {"source":"iana","extensions":["ifm"]},
  "application/vnd.shana.informed.formtemplate": {"source":"iana","extensions":["itp"]},
  "application/vnd.shana.informed.interchange": {"source":"iana","extensions":["iif"]},
  "application/vnd.shana.informed.package": {"source":"iana","extensions":["ipk"]},
  "application/vnd.shootproof+json": {"source":"iana","compressible":true},
  "application/vnd.shopkick+json": {"source":"iana","compressible":true},
  "application/vnd.shp": {"source":"iana"},
  "application/vnd.shx": {"source":"iana"},
  "application/vnd.sigrok.session": {"source":"iana"},
  "application/vnd.simtech-mindmapper": {"source":"iana","extensions":["twd","twds"]},
  "application/vnd.siren+json": {"source":"iana","compressible":true},
  "application/vnd.sketchometry": {"source":"iana"},
  "application/vnd.smaf": {"source":"iana","extensions":["mmf"]},
  "application/vnd.smart.notebook": {"source":"iana"},
  "application/vnd.smart.teacher": {"source":"iana","extensions":["teacher"]},
  "application/vnd.smintio.portals.archive": {"source":"iana"},
  "application/vnd.snesdev-page-table": {"source":"iana"},
  "application/vnd.software602.filler.form+xml": {"source":"iana","compressible":true,"extensions":["fo"]},
  "application/vnd.software602.filler.form-xml-zip": {"source":"iana"},
  "application/vnd.solent.sdkm+xml": {"source":"iana","compressible":true,"extensions":["sdkm","sdkd"]},
  "application/vnd.spotfire.dxp": {"source":"iana","extensions":["dxp"]},
  "application/vnd.spotfire.sfs": {"source":"iana","extensions":["sfs"]},
  "application/vnd.sqlite3": {"source":"iana"},
  "application/vnd.sss-cod": {"source":"iana"},
  "application/vnd.sss-dtf": {"source":"iana"},
  "application/vnd.sss-ntf": {"source":"iana"},
  "application/vnd.stardivision.calc": {"source":"apache","extensions":["sdc"]},
  "application/vnd.stardivision.draw": {"source":"apache","extensions":["sda"]},
  "application/vnd.stardivision.impress": {"source":"apache","extensions":["sdd"]},
  "application/vnd.stardivision.math": {"source":"apache","extensions":["smf"]},
  "application/vnd.stardivision.writer": {"source":"apache","extensions":["sdw","vor"]},
  "application/vnd.stardivision.writer-global": {"source":"apache","extensions":["sgl"]},
  "application/vnd.stepmania.package": {"source":"iana","extensions":["smzip"]},
  "application/vnd.stepmania.stepchart": {"source":"iana","extensions":["sm"]},
  "application/vnd.street-stream": {"source":"iana"},
  "application/vnd.sun.wadl+xml": {"source":"iana","compressible":true,"extensions":["wadl"]},
  "application/vnd.sun.xml.calc": {"source":"apache","extensions":["sxc"]},
  "application/vnd.sun.xml.calc.template": {"source":"apache","extensions":["stc"]},
  "application/vnd.sun.xml.draw": {"source":"apache","extensions":["sxd"]},
  "application/vnd.sun.xml.draw.template": {"source":"apache","extensions":["std"]},
  "application/vnd.sun.xml.impress": {"source":"apache","extensions":["sxi"]},
  "application/vnd.sun.xml.impress.template": {"source":"apache","extensions":["sti"]},
  "application/vnd.sun.xml.math": {"source":"apache","extensions":["sxm"]},
  "application/vnd.sun.xml.writer": {"source":"apache","extensions":["sxw"]},
  "application/vnd.sun.xml.writer.global": {"source":"apache","extensions":["sxg"]},
  "application/vnd.sun.xml.writer.template": {"source":"apache","extensions":["stw"]},
  "application/vnd.sus-calendar": {"source":"iana","extensions":["sus","susp"]},
  "application/vnd.svd": {"source":"iana","extensions":["svd"]},
  "application/vnd.swiftview-ics": {"source":"iana"},
  "application/vnd.sybyl.mol2": {"source":"iana"},
  "application/vnd.sycle+xml": {"source":"iana","compressible":true},
  "application/vnd.syft+json": {"source":"iana","compressible":true},
  "application/vnd.symbian.install": {"source":"apache","extensions":["sis","sisx"]},
  "application/vnd.syncml+xml": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["xsm"]},
  "application/vnd.syncml.dm+wbxml": {"source":"iana","charset":"UTF-8","extensions":["bdm"]},
  "application/vnd.syncml.dm+xml": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["xdm"]},
  "application/vnd.syncml.dm.notification": {"source":"iana"},
  "application/vnd.syncml.dmddf+wbxml": {"source":"iana"},
  "application/vnd.syncml.dmddf+xml": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["ddf"]},
  "application/vnd.syncml.dmtnds+wbxml": {"source":"iana"},
  "application/vnd.syncml.dmtnds+xml": {"source":"iana","charset":"UTF-8","compressible":true},
  "application/vnd.syncml.ds.notification": {"source":"iana"},
  "application/vnd.tableschema+json": {"source":"iana","compressible":true},
  "application/vnd.tao.intent-module-archive": {"source":"iana","extensions":["tao"]},
  "application/vnd.tcpdump.pcap": {"source":"iana","extensions":["pcap","cap","dmp"]},
  "application/vnd.think-cell.ppttc+json": {"source":"iana","compressible":true},
  "application/vnd.tmd.mediaflex.api+xml": {"source":"iana","compressible":true},
  "application/vnd.tml": {"source":"iana"},
  "application/vnd.tmobile-livetv": {"source":"iana","extensions":["tmo"]},
  "application/vnd.tri.onesource": {"source":"iana"},
  "application/vnd.trid.tpt": {"source":"iana","extensions":["tpt"]},
  "application/vnd.triscape.mxs": {"source":"iana","extensions":["mxs"]},
  "application/vnd.trueapp": {"source":"iana","extensions":["tra"]},
  "application/vnd.truedoc": {"source":"iana"},
  "application/vnd.ubisoft.webplayer": {"source":"iana"},
  "application/vnd.ufdl": {"source":"iana","extensions":["ufd","ufdl"]},
  "application/vnd.uic.osdm+json": {"source":"iana","compressible":true},
  "application/vnd.uiq.theme": {"source":"iana","extensions":["utz"]},
  "application/vnd.umajin": {"source":"iana","extensions":["umj"]},
  "application/vnd.unity": {"source":"iana","extensions":["unityweb"]},
  "application/vnd.uoml+xml": {"source":"iana","compressible":true,"extensions":["uoml","uo"]},
  "application/vnd.uplanet.alert": {"source":"iana"},
  "application/vnd.uplanet.alert-wbxml": {"source":"iana"},
  "application/vnd.uplanet.bearer-choice": {"source":"iana"},
  "application/vnd.uplanet.bearer-choice-wbxml": {"source":"iana"},
  "application/vnd.uplanet.cacheop": {"source":"iana"},
  "application/vnd.uplanet.cacheop-wbxml": {"source":"iana"},
  "application/vnd.uplanet.channel": {"source":"iana"},
  "application/vnd.uplanet.channel-wbxml": {"source":"iana"},
  "application/vnd.uplanet.list": {"source":"iana"},
  "application/vnd.uplanet.list-wbxml": {"source":"iana"},
  "application/vnd.uplanet.listcmd": {"source":"iana"},
  "application/vnd.uplanet.listcmd-wbxml": {"source":"iana"},
  "application/vnd.uplanet.signal": {"source":"iana"},
  "application/vnd.uri-map": {"source":"iana"},
  "application/vnd.valve.source.material": {"source":"iana"},
  "application/vnd.vcx": {"source":"iana","extensions":["vcx"]},
  "application/vnd.vd-study": {"source":"iana"},
  "application/vnd.vectorworks": {"source":"iana"},
  "application/vnd.vel+json": {"source":"iana","compressible":true},
  "application/vnd.veraison.tsm-report+cbor": {"source":"iana"},
  "application/vnd.veraison.tsm-report+json": {"source":"iana","compressible":true},
  "application/vnd.verimatrix.vcas": {"source":"iana"},
  "application/vnd.veritone.aion+json": {"source":"iana","compressible":true},
  "application/vnd.veryant.thin": {"source":"iana"},
  "application/vnd.ves.encrypted": {"source":"iana"},
  "application/vnd.vidsoft.vidconference": {"source":"iana"},
  "application/vnd.visio": {"source":"iana","extensions":["vsd","vst","vss","vsw","vsdx","vtx"]},
  "application/vnd.visionary": {"source":"iana","extensions":["vis"]},
  "application/vnd.vividence.scriptfile": {"source":"iana"},
  "application/vnd.vocalshaper.vsp4": {"source":"iana"},
  "application/vnd.vsf": {"source":"iana","extensions":["vsf"]},
  "application/vnd.wap.sic": {"source":"iana"},
  "application/vnd.wap.slc": {"source":"iana"},
  "application/vnd.wap.wbxml": {"source":"iana","charset":"UTF-8","extensions":["wbxml"]},
  "application/vnd.wap.wmlc": {"source":"iana","extensions":["wmlc"]},
  "application/vnd.wap.wmlscriptc": {"source":"iana","extensions":["wmlsc"]},
  "application/vnd.wasmflow.wafl": {"source":"iana"},
  "application/vnd.webturbo": {"source":"iana","extensions":["wtb"]},
  "application/vnd.wfa.dpp": {"source":"iana"},
  "application/vnd.wfa.p2p": {"source":"iana"},
  "application/vnd.wfa.wsc": {"source":"iana"},
  "application/vnd.windows.devicepairing": {"source":"iana"},
  "application/vnd.wmc": {"source":"iana"},
  "application/vnd.wmf.bootstrap": {"source":"iana"},
  "application/vnd.wolfram.mathematica": {"source":"iana"},
  "application/vnd.wolfram.mathematica.package": {"source":"iana"},
  "application/vnd.wolfram.player": {"source":"iana","extensions":["nbp"]},
  "application/vnd.wordlift": {"source":"iana"},
  "application/vnd.wordperfect": {"source":"iana","extensions":["wpd"]},
  "application/vnd.wqd": {"source":"iana","extensions":["wqd"]},
  "application/vnd.wrq-hp3000-labelled": {"source":"iana"},
  "application/vnd.wt.stf": {"source":"iana","extensions":["stf"]},
  "application/vnd.wv.csp+wbxml": {"source":"iana"},
  "application/vnd.wv.csp+xml": {"source":"iana","compressible":true},
  "application/vnd.wv.ssp+xml": {"source":"iana","compressible":true},
  "application/vnd.xacml+json": {"source":"iana","compressible":true},
  "application/vnd.xara": {"source":"iana","extensions":["xar"]},
  "application/vnd.xarin.cpj": {"source":"iana"},
  "application/vnd.xecrets-encrypted": {"source":"iana"},
  "application/vnd.xfdl": {"source":"iana","extensions":["xfdl"]},
  "application/vnd.xfdl.webform": {"source":"iana"},
  "application/vnd.xmi+xml": {"source":"iana","compressible":true},
  "application/vnd.xmpie.cpkg": {"source":"iana"},
  "application/vnd.xmpie.dpkg": {"source":"iana"},
  "application/vnd.xmpie.plan": {"source":"iana"},
  "application/vnd.xmpie.ppkg": {"source":"iana"},
  "application/vnd.xmpie.xlim": {"source":"iana"},
  "application/vnd.yamaha.hv-dic": {"source":"iana","extensions":["hvd"]},
  "application/vnd.yamaha.hv-script": {"source":"iana","extensions":["hvs"]},
  "application/vnd.yamaha.hv-voice": {"source":"iana","extensions":["hvp"]},
  "application/vnd.yamaha.openscoreformat": {"source":"iana","extensions":["osf"]},
  "application/vnd.yamaha.openscoreformat.osfpvg+xml": {"source":"iana","compressible":true,"extensions":["osfpvg"]},
  "application/vnd.yamaha.remote-setup": {"source":"iana"},
  "application/vnd.yamaha.smaf-audio": {"source":"iana","extensions":["saf"]},
  "application/vnd.yamaha.smaf-phrase": {"source":"iana","extensions":["spf"]},
  "application/vnd.yamaha.through-ngn": {"source":"iana"},
  "application/vnd.yamaha.tunnel-udpencap": {"source":"iana"},
  "application/vnd.yaoweme": {"source":"iana"},
  "application/vnd.yellowriver-custom-menu": {"source":"iana","extensions":["cmp"]},
  "application/vnd.zul": {"source":"iana","extensions":["zir","zirz"]},
  "application/vnd.zzazz.deck+xml": {"source":"iana","compressible":true,"extensions":["zaz"]},
  "application/voicexml+xml": {"source":"iana","compressible":true,"extensions":["vxml"]},
  "application/voucher-cms+json": {"source":"iana","compressible":true},
  "application/voucher-jws+json": {"source":"iana","compressible":true},
  "application/vp": {"source":"iana"},
  "application/vp+cose": {"source":"iana"},
  "application/vp+jwt": {"source":"iana"},
  "application/vq-rtcpxr": {"source":"iana"},
  "application/wasm": {"source":"iana","compressible":true,"extensions":["wasm"]},
  "application/watcherinfo+xml": {"source":"iana","compressible":true,"extensions":["wif"]},
  "application/webpush-options+json": {"source":"iana","compressible":true},
  "application/whoispp-query": {"source":"iana"},
  "application/whoispp-response": {"source":"iana"},
  "application/widget": {"source":"iana","extensions":["wgt"]},
  "application/winhlp": {"source":"apache","extensions":["hlp"]},
  "application/wita": {"source":"iana"},
  "application/wordperfect5.1": {"source":"iana"},
  "application/wsdl+xml": {"source":"iana","compressible":true,"extensions":["wsdl"]},
  "application/wspolicy+xml": {"source":"iana","compressible":true,"extensions":["wspolicy"]},
  "application/x-7z-compressed": {"source":"apache","compressible":false,"extensions":["7z"]},
  "application/x-abiword": {"source":"apache","extensions":["abw"]},
  "application/x-ace-compressed": {"source":"apache","extensions":["ace"]},
  "application/x-amf": {"source":"apache"},
  "application/x-apple-diskimage": {"source":"apache","extensions":["dmg"]},
  "application/x-arj": {"compressible":false,"extensions":["arj"]},
  "application/x-authorware-bin": {"source":"apache","extensions":["aab","x32","u32","vox"]},
  "application/x-authorware-map": {"source":"apache","extensions":["aam"]},
  "application/x-authorware-seg": {"source":"apache","extensions":["aas"]},
  "application/x-bcpio": {"source":"apache","extensions":["bcpio"]},
  "application/x-bdoc": {"compressible":false,"extensions":["bdoc"]},
  "application/x-bittorrent": {"source":"apache","extensions":["torrent"]},
  "application/x-blender": {"extensions":["blend"]},
  "application/x-blorb": {"source":"apache","extensions":["blb","blorb"]},
  "application/x-bzip": {"source":"apache","compressible":false,"extensions":["bz"]},
  "application/x-bzip2": {"source":"apache","compressible":false,"extensions":["bz2","boz"]},
  "application/x-cbr": {"source":"apache","extensions":["cbr","cba","cbt","cbz","cb7"]},
  "application/x-cdlink": {"source":"apache","extensions":["vcd"]},
  "application/x-cfs-compressed": {"source":"apache","extensions":["cfs"]},
  "application/x-chat": {"source":"apache","extensions":["chat"]},
  "application/x-chess-pgn": {"source":"apache","extensions":["pgn"]},
  "application/x-chrome-extension": {"extensions":["crx"]},
  "application/x-cocoa": {"source":"nginx","extensions":["cco"]},
  "application/x-compress": {"source":"apache"},
  "application/x-compressed": {"extensions":["rar"]},
  "application/x-conference": {"source":"apache","extensions":["nsc"]},
  "application/x-cpio": {"source":"apache","extensions":["cpio"]},
  "application/x-csh": {"source":"apache","extensions":["csh"]},
  "application/x-deb": {"compressible":false},
  "application/x-debian-package": {"source":"apache","extensions":["deb","udeb"]},
  "application/x-dgc-compressed": {"source":"apache","extensions":["dgc"]},
  "application/x-director": {"source":"apache","extensions":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]},
  "application/x-doom": {"source":"apache","extensions":["wad"]},
  "application/x-dtbncx+xml": {"source":"apache","compressible":true,"extensions":["ncx"]},
  "application/x-dtbook+xml": {"source":"apache","compressible":true,"extensions":["dtb"]},
  "application/x-dtbresource+xml": {"source":"apache","compressible":true,"extensions":["res"]},
  "application/x-dvi": {"source":"apache","compressible":false,"extensions":["dvi"]},
  "application/x-envoy": {"source":"apache","extensions":["evy"]},
  "application/x-eva": {"source":"apache","extensions":["eva"]},
  "application/x-font-bdf": {"source":"apache","extensions":["bdf"]},
  "application/x-font-dos": {"source":"apache"},
  "application/x-font-framemaker": {"source":"apache"},
  "application/x-font-ghostscript": {"source":"apache","extensions":["gsf"]},
  "application/x-font-libgrx": {"source":"apache"},
  "application/x-font-linux-psf": {"source":"apache","extensions":["psf"]},
  "application/x-font-pcf": {"source":"apache","extensions":["pcf"]},
  "application/x-font-snf": {"source":"apache","extensions":["snf"]},
  "application/x-font-speedo": {"source":"apache"},
  "application/x-font-sunos-news": {"source":"apache"},
  "application/x-font-type1": {"source":"apache","extensions":["pfa","pfb","pfm","afm"]},
  "application/x-font-vfont": {"source":"apache"},
  "application/x-freearc": {"source":"apache","extensions":["arc"]},
  "application/x-futuresplash": {"source":"apache","extensions":["spl"]},
  "application/x-gca-compressed": {"source":"apache","extensions":["gca"]},
  "application/x-glulx": {"source":"apache","extensions":["ulx"]},
  "application/x-gnumeric": {"source":"apache","extensions":["gnumeric"]},
  "application/x-gramps-xml": {"source":"apache","extensions":["gramps"]},
  "application/x-gtar": {"source":"apache","extensions":["gtar"]},
  "application/x-gzip": {"source":"apache"},
  "application/x-hdf": {"source":"apache","extensions":["hdf"]},
  "application/x-httpd-php": {"compressible":true,"extensions":["php"]},
  "application/x-install-instructions": {"source":"apache","extensions":["install"]},
  "application/x-ipynb+json": {"compressible":true,"extensions":["ipynb"]},
  "application/x-iso9660-image": {"source":"apache","extensions":["iso"]},
  "application/x-iwork-keynote-sffkey": {"extensions":["key"]},
  "application/x-iwork-numbers-sffnumbers": {"extensions":["numbers"]},
  "application/x-iwork-pages-sffpages": {"extensions":["pages"]},
  "application/x-java-archive-diff": {"source":"nginx","extensions":["jardiff"]},
  "application/x-java-jnlp-file": {"source":"apache","compressible":false,"extensions":["jnlp"]},
  "application/x-javascript": {"compressible":true},
  "application/x-keepass2": {"extensions":["kdbx"]},
  "application/x-latex": {"source":"apache","compressible":false,"extensions":["latex"]},
  "application/x-lua-bytecode": {"extensions":["luac"]},
  "application/x-lzh-compressed": {"source":"apache","extensions":["lzh","lha"]},
  "application/x-makeself": {"source":"nginx","extensions":["run"]},
  "application/x-mie": {"source":"apache","extensions":["mie"]},
  "application/x-mobipocket-ebook": {"source":"apache","extensions":["prc","mobi"]},
  "application/x-mpegurl": {"compressible":false},
  "application/x-ms-application": {"source":"apache","extensions":["application"]},
  "application/x-ms-shortcut": {"source":"apache","extensions":["lnk"]},
  "application/x-ms-wmd": {"source":"apache","extensions":["wmd"]},
  "application/x-ms-wmz": {"source":"apache","extensions":["wmz"]},
  "application/x-ms-xbap": {"source":"apache","extensions":["xbap"]},
  "application/x-msaccess": {"source":"apache","extensions":["mdb"]},
  "application/x-msbinder": {"source":"apache","extensions":["obd"]},
  "application/x-mscardfile": {"source":"apache","extensions":["crd"]},
  "application/x-msclip": {"source":"apache","extensions":["clp"]},
  "application/x-msdos-program": {"extensions":["exe"]},
  "application/x-msdownload": {"source":"apache","extensions":["exe","dll","com","bat","msi"]},
  "application/x-msmediaview": {"source":"apache","extensions":["mvb","m13","m14"]},
  "application/x-msmetafile": {"source":"apache","extensions":["wmf","wmz","emf","emz"]},
  "application/x-msmoney": {"source":"apache","extensions":["mny"]},
  "application/x-mspublisher": {"source":"apache","extensions":["pub"]},
  "application/x-msschedule": {"source":"apache","extensions":["scd"]},
  "application/x-msterminal": {"source":"apache","extensions":["trm"]},
  "application/x-mswrite": {"source":"apache","extensions":["wri"]},
  "application/x-netcdf": {"source":"apache","extensions":["nc","cdf"]},
  "application/x-ns-proxy-autoconfig": {"compressible":true,"extensions":["pac"]},
  "application/x-nzb": {"source":"apache","extensions":["nzb"]},
  "application/x-perl": {"source":"nginx","extensions":["pl","pm"]},
  "application/x-pilot": {"source":"nginx","extensions":["prc","pdb"]},
  "application/x-pkcs12": {"source":"apache","compressible":false,"extensions":["p12","pfx"]},
  "application/x-pkcs7-certificates": {"source":"apache","extensions":["p7b","spc"]},
  "application/x-pkcs7-certreqresp": {"source":"apache","extensions":["p7r"]},
  "application/x-pki-message": {"source":"iana"},
  "application/x-rar-compressed": {"source":"apache","compressible":false,"extensions":["rar"]},
  "application/x-redhat-package-manager": {"source":"nginx","extensions":["rpm"]},
  "application/x-research-info-systems": {"source":"apache","extensions":["ris"]},
  "application/x-sea": {"source":"nginx","extensions":["sea"]},
  "application/x-sh": {"source":"apache","compressible":true,"extensions":["sh"]},
  "application/x-shar": {"source":"apache","extensions":["shar"]},
  "application/x-shockwave-flash": {"source":"apache","compressible":false,"extensions":["swf"]},
  "application/x-silverlight-app": {"source":"apache","extensions":["xap"]},
  "application/x-sql": {"source":"apache","extensions":["sql"]},
  "application/x-stuffit": {"source":"apache","compressible":false,"extensions":["sit"]},
  "application/x-stuffitx": {"source":"apache","extensions":["sitx"]},
  "application/x-subrip": {"source":"apache","extensions":["srt"]},
  "application/x-sv4cpio": {"source":"apache","extensions":["sv4cpio"]},
  "application/x-sv4crc": {"source":"apache","extensions":["sv4crc"]},
  "application/x-t3vm-image": {"source":"apache","extensions":["t3"]},
  "application/x-tads": {"source":"apache","extensions":["gam"]},
  "application/x-tar": {"source":"apache","compressible":true,"extensions":["tar"]},
  "application/x-tcl": {"source":"apache","extensions":["tcl","tk"]},
  "application/x-tex": {"source":"apache","extensions":["tex"]},
  "application/x-tex-tfm": {"source":"apache","extensions":["tfm"]},
  "application/x-texinfo": {"source":"apache","extensions":["texinfo","texi"]},
  "application/x-tgif": {"source":"apache","extensions":["obj"]},
  "application/x-ustar": {"source":"apache","extensions":["ustar"]},
  "application/x-virtualbox-hdd": {"compressible":true,"extensions":["hdd"]},
  "application/x-virtualbox-ova": {"compressible":true,"extensions":["ova"]},
  "application/x-virtualbox-ovf": {"compressible":true,"extensions":["ovf"]},
  "application/x-virtualbox-vbox": {"compressible":true,"extensions":["vbox"]},
  "application/x-virtualbox-vbox-extpack": {"compressible":false,"extensions":["vbox-extpack"]},
  "application/x-virtualbox-vdi": {"compressible":true,"extensions":["vdi"]},
  "application/x-virtualbox-vhd": {"compressible":true,"extensions":["vhd"]},
  "application/x-virtualbox-vmdk": {"compressible":true,"extensions":["vmdk"]},
  "application/x-wais-source": {"source":"apache","extensions":["src"]},
  "application/x-web-app-manifest+json": {"compressible":true,"extensions":["webapp"]},
  "application/x-www-form-urlencoded": {"source":"iana","compressible":true},
  "application/x-x509-ca-cert": {"source":"iana","extensions":["der","crt","pem"]},
  "application/x-x509-ca-ra-cert": {"source":"iana"},
  "application/x-x509-next-ca-cert": {"source":"iana"},
  "application/x-xfig": {"source":"apache","extensions":["fig"]},
  "application/x-xliff+xml": {"source":"apache","compressible":true,"extensions":["xlf"]},
  "application/x-xpinstall": {"source":"apache","compressible":false,"extensions":["xpi"]},
  "application/x-xz": {"source":"apache","extensions":["xz"]},
  "application/x-zip-compressed": {"extensions":["zip"]},
  "application/x-zmachine": {"source":"apache","extensions":["z1","z2","z3","z4","z5","z6","z7","z8"]},
  "application/x400-bp": {"source":"iana"},
  "application/xacml+xml": {"source":"iana","compressible":true},
  "application/xaml+xml": {"source":"apache","compressible":true,"extensions":["xaml"]},
  "application/xcap-att+xml": {"source":"iana","compressible":true,"extensions":["xav"]},
  "application/xcap-caps+xml": {"source":"iana","compressible":true,"extensions":["xca"]},
  "application/xcap-diff+xml": {"source":"iana","compressible":true,"extensions":["xdf"]},
  "application/xcap-el+xml": {"source":"iana","compressible":true,"extensions":["xel"]},
  "application/xcap-error+xml": {"source":"iana","compressible":true},
  "application/xcap-ns+xml": {"source":"iana","compressible":true,"extensions":["xns"]},
  "application/xcon-conference-info+xml": {"source":"iana","compressible":true},
  "application/xcon-conference-info-diff+xml": {"source":"iana","compressible":true},
  "application/xenc+xml": {"source":"iana","compressible":true,"extensions":["xenc"]},
  "application/xfdf": {"source":"iana","extensions":["xfdf"]},
  "application/xhtml+xml": {"source":"iana","compressible":true,"extensions":["xhtml","xht"]},
  "application/xhtml-voice+xml": {"source":"apache","compressible":true},
  "application/xliff+xml": {"source":"iana","compressible":true,"extensions":["xlf"]},
  "application/xml": {"source":"iana","compressible":true,"extensions":["xml","xsl","xsd","rng"]},
  "application/xml-dtd": {"source":"iana","compressible":true,"extensions":["dtd"]},
  "application/xml-external-parsed-entity": {"source":"iana"},
  "application/xml-patch+xml": {"source":"iana","compressible":true},
  "application/xmpp+xml": {"source":"iana","compressible":true},
  "application/xop+xml": {"source":"iana","compressible":true,"extensions":["xop"]},
  "application/xproc+xml": {"source":"apache","compressible":true,"extensions":["xpl"]},
  "application/xslt+xml": {"source":"iana","compressible":true,"extensions":["xsl","xslt"]},
  "application/xspf+xml": {"source":"apache","compressible":true,"extensions":["xspf"]},
  "application/xv+xml": {"source":"iana","compressible":true,"extensions":["mxml","xhvml","xvml","xvm"]},
  "application/yaml": {"source":"iana"},
  "application/yang": {"source":"iana","extensions":["yang"]},
  "application/yang-data+cbor": {"source":"iana"},
  "application/yang-data+json": {"source":"iana","compressible":true},
  "application/yang-data+xml": {"source":"iana","compressible":true},
  "application/yang-patch+json": {"source":"iana","compressible":true},
  "application/yang-patch+xml": {"source":"iana","compressible":true},
  "application/yang-sid+json": {"source":"iana","compressible":true},
  "application/yin+xml": {"source":"iana","compressible":true,"extensions":["yin"]},
  "application/zip": {"source":"iana","compressible":false,"extensions":["zip"]},
  "application/zip+dotlottie": {"extensions":["lottie"]},
  "application/zlib": {"source":"iana"},
  "application/zstd": {"source":"iana"},
  "audio/1d-interleaved-parityfec": {"source":"iana"},
  "audio/32kadpcm": {"source":"iana"},
  "audio/3gpp": {"source":"iana","compressible":false,"extensions":["3gpp"]},
  "audio/3gpp2": {"source":"iana"},
  "audio/aac": {"source":"iana","extensions":["adts","aac"]},
  "audio/ac3": {"source":"iana"},
  "audio/adpcm": {"source":"apache","extensions":["adp"]},
  "audio/amr": {"source":"iana","extensions":["amr"]},
  "audio/amr-wb": {"source":"iana"},
  "audio/amr-wb+": {"source":"iana"},
  "audio/aptx": {"source":"iana"},
  "audio/asc": {"source":"iana"},
  "audio/atrac-advanced-lossless": {"source":"iana"},
  "audio/atrac-x": {"source":"iana"},
  "audio/atrac3": {"source":"iana"},
  "audio/basic": {"source":"iana","compressible":false,"extensions":["au","snd"]},
  "audio/bv16": {"source":"iana"},
  "audio/bv32": {"source":"iana"},
  "audio/clearmode": {"source":"iana"},
  "audio/cn": {"source":"iana"},
  "audio/dat12": {"source":"iana"},
  "audio/dls": {"source":"iana"},
  "audio/dsr-es201108": {"source":"iana"},
  "audio/dsr-es202050": {"source":"iana"},
  "audio/dsr-es202211": {"source":"iana"},
  "audio/dsr-es202212": {"source":"iana"},
  "audio/dv": {"source":"iana"},
  "audio/dvi4": {"source":"iana"},
  "audio/eac3": {"source":"iana"},
  "audio/encaprtp": {"source":"iana"},
  "audio/evrc": {"source":"iana"},
  "audio/evrc-qcp": {"source":"iana"},
  "audio/evrc0": {"source":"iana"},
  "audio/evrc1": {"source":"iana"},
  "audio/evrcb": {"source":"iana"},
  "audio/evrcb0": {"source":"iana"},
  "audio/evrcb1": {"source":"iana"},
  "audio/evrcnw": {"source":"iana"},
  "audio/evrcnw0": {"source":"iana"},
  "audio/evrcnw1": {"source":"iana"},
  "audio/evrcwb": {"source":"iana"},
  "audio/evrcwb0": {"source":"iana"},
  "audio/evrcwb1": {"source":"iana"},
  "audio/evs": {"source":"iana"},
  "audio/flac": {"source":"iana"},
  "audio/flexfec": {"source":"iana"},
  "audio/fwdred": {"source":"iana"},
  "audio/g711-0": {"source":"iana"},
  "audio/g719": {"source":"iana"},
  "audio/g722": {"source":"iana"},
  "audio/g7221": {"source":"iana"},
  "audio/g723": {"source":"iana"},
  "audio/g726-16": {"source":"iana"},
  "audio/g726-24": {"source":"iana"},
  "audio/g726-32": {"source":"iana"},
  "audio/g726-40": {"source":"iana"},
  "audio/g728": {"source":"iana"},
  "audio/g729": {"source":"iana"},
  "audio/g7291": {"source":"iana"},
  "audio/g729d": {"source":"iana"},
  "audio/g729e": {"source":"iana"},
  "audio/gsm": {"source":"iana"},
  "audio/gsm-efr": {"source":"iana"},
  "audio/gsm-hr-08": {"source":"iana"},
  "audio/ilbc": {"source":"iana"},
  "audio/ip-mr_v2.5": {"source":"iana"},
  "audio/isac": {"source":"apache"},
  "audio/l16": {"source":"iana"},
  "audio/l20": {"source":"iana"},
  "audio/l24": {"source":"iana","compressible":false},
  "audio/l8": {"source":"iana"},
  "audio/lpc": {"source":"iana"},
  "audio/matroska": {"source":"iana"},
  "audio/melp": {"source":"iana"},
  "audio/melp1200": {"source":"iana"},
  "audio/melp2400": {"source":"iana"},
  "audio/melp600": {"source":"iana"},
  "audio/mhas": {"source":"iana"},
  "audio/midi": {"source":"apache","extensions":["mid","midi","kar","rmi"]},
  "audio/midi-clip": {"source":"iana"},
  "audio/mobile-xmf": {"source":"iana","extensions":["mxmf"]},
  "audio/mp3": {"compressible":false,"extensions":["mp3"]},
  "audio/mp4": {"source":"iana","compressible":false,"extensions":["m4a","mp4a","m4b"]},
  "audio/mp4a-latm": {"source":"iana"},
  "audio/mpa": {"source":"iana"},
  "audio/mpa-robust": {"source":"iana"},
  "audio/mpeg": {"source":"iana","compressible":false,"extensions":["mpga","mp2","mp2a","mp3","m2a","m3a"]},
  "audio/mpeg4-generic": {"source":"iana"},
  "audio/musepack": {"source":"apache"},
  "audio/ogg": {"source":"iana","compressible":false,"extensions":["oga","ogg","spx","opus"]},
  "audio/opus": {"source":"iana"},
  "audio/parityfec": {"source":"iana"},
  "audio/pcma": {"source":"iana"},
  "audio/pcma-wb": {"source":"iana"},
  "audio/pcmu": {"source":"iana"},
  "audio/pcmu-wb": {"source":"iana"},
  "audio/prs.sid": {"source":"iana"},
  "audio/qcelp": {"source":"iana"},
  "audio/raptorfec": {"source":"iana"},
  "audio/red": {"source":"iana"},
  "audio/rtp-enc-aescm128": {"source":"iana"},
  "audio/rtp-midi": {"source":"iana"},
  "audio/rtploopback": {"source":"iana"},
  "audio/rtx": {"source":"iana"},
  "audio/s3m": {"source":"apache","extensions":["s3m"]},
  "audio/scip": {"source":"iana"},
  "audio/silk": {"source":"apache","extensions":["sil"]},
  "audio/smv": {"source":"iana"},
  "audio/smv-qcp": {"source":"iana"},
  "audio/smv0": {"source":"iana"},
  "audio/sofa": {"source":"iana"},
  "audio/sp-midi": {"source":"iana"},
  "audio/speex": {"source":"iana"},
  "audio/t140c": {"source":"iana"},
  "audio/t38": {"source":"iana"},
  "audio/telephone-event": {"source":"iana"},
  "audio/tetra_acelp": {"source":"iana"},
  "audio/tetra_acelp_bb": {"source":"iana"},
  "audio/tone": {"source":"iana"},
  "audio/tsvcis": {"source":"iana"},
  "audio/uemclip": {"source":"iana"},
  "audio/ulpfec": {"source":"iana"},
  "audio/usac": {"source":"iana"},
  "audio/vdvi": {"source":"iana"},
  "audio/vmr-wb": {"source":"iana"},
  "audio/vnd.3gpp.iufp": {"source":"iana"},
  "audio/vnd.4sb": {"source":"iana"},
  "audio/vnd.audiokoz": {"source":"iana"},
  "audio/vnd.celp": {"source":"iana"},
  "audio/vnd.cisco.nse": {"source":"iana"},
  "audio/vnd.cmles.radio-events": {"source":"iana"},
  "audio/vnd.cns.anp1": {"source":"iana"},
  "audio/vnd.cns.inf1": {"source":"iana"},
  "audio/vnd.dece.audio": {"source":"iana","extensions":["uva","uvva"]},
  "audio/vnd.digital-winds": {"source":"iana","extensions":["eol"]},
  "audio/vnd.dlna.adts": {"source":"iana"},
  "audio/vnd.dolby.heaac.1": {"source":"iana"},
  "audio/vnd.dolby.heaac.2": {"source":"iana"},
  "audio/vnd.dolby.mlp": {"source":"iana"},
  "audio/vnd.dolby.mps": {"source":"iana"},
  "audio/vnd.dolby.pl2": {"source":"iana"},
  "audio/vnd.dolby.pl2x": {"source":"iana"},
  "audio/vnd.dolby.pl2z": {"source":"iana"},
  "audio/vnd.dolby.pulse.1": {"source":"iana"},
  "audio/vnd.dra": {"source":"iana","extensions":["dra"]},
  "audio/vnd.dts": {"source":"iana","extensions":["dts"]},
  "audio/vnd.dts.hd": {"source":"iana","extensions":["dtshd"]},
  "audio/vnd.dts.uhd": {"source":"iana"},
  "audio/vnd.dvb.file": {"source":"iana"},
  "audio/vnd.everad.plj": {"source":"iana"},
  "audio/vnd.hns.audio": {"source":"iana"},
  "audio/vnd.lucent.voice": {"source":"iana","extensions":["lvp"]},
  "audio/vnd.ms-playready.media.pya": {"source":"iana","extensions":["pya"]},
  "audio/vnd.nokia.mobile-xmf": {"source":"iana"},
  "audio/vnd.nortel.vbk": {"source":"iana"},
  "audio/vnd.nuera.ecelp4800": {"source":"iana","extensions":["ecelp4800"]},
  "audio/vnd.nuera.ecelp7470": {"source":"iana","extensions":["ecelp7470"]},
  "audio/vnd.nuera.ecelp9600": {"source":"iana","extensions":["ecelp9600"]},
  "audio/vnd.octel.sbc": {"source":"iana"},
  "audio/vnd.presonus.multitrack": {"source":"iana"},
  "audio/vnd.qcelp": {"source":"apache"},
  "audio/vnd.rhetorex.32kadpcm": {"source":"iana"},
  "audio/vnd.rip": {"source":"iana","extensions":["rip"]},
  "audio/vnd.rn-realaudio": {"compressible":false},
  "audio/vnd.sealedmedia.softseal.mpeg": {"source":"iana"},
  "audio/vnd.vmx.cvsd": {"source":"iana"},
  "audio/vnd.wave": {"compressible":false},
  "audio/vorbis": {"source":"iana","compressible":false},
  "audio/vorbis-config": {"source":"iana"},
  "audio/wav": {"compressible":false,"extensions":["wav"]},
  "audio/wave": {"compressible":false,"extensions":["wav"]},
  "audio/webm": {"source":"apache","compressible":false,"extensions":["weba"]},
  "audio/x-aac": {"source":"apache","compressible":false,"extensions":["aac"]},
  "audio/x-aiff": {"source":"apache","extensions":["aif","aiff","aifc"]},
  "audio/x-caf": {"source":"apache","compressible":false,"extensions":["caf"]},
  "audio/x-flac": {"source":"apache","extensions":["flac"]},
  "audio/x-m4a": {"source":"nginx","extensions":["m4a"]},
  "audio/x-matroska": {"source":"apache","extensions":["mka"]},
  "audio/x-mpegurl": {"source":"apache","extensions":["m3u"]},
  "audio/x-ms-wax": {"source":"apache","extensions":["wax"]},
  "audio/x-ms-wma": {"source":"apache","extensions":["wma"]},
  "audio/x-pn-realaudio": {"source":"apache","extensions":["ram","ra"]},
  "audio/x-pn-realaudio-plugin": {"source":"apache","extensions":["rmp"]},
  "audio/x-realaudio": {"source":"nginx","extensions":["ra"]},
  "audio/x-tta": {"source":"apache"},
  "audio/x-wav": {"source":"apache","extensions":["wav"]},
  "audio/xm": {"source":"apache","extensions":["xm"]},
  "chemical/x-cdx": {"source":"apache","extensions":["cdx"]},
  "chemical/x-cif": {"source":"apache","extensions":["cif"]},
  "chemical/x-cmdf": {"source":"apache","extensions":["cmdf"]},
  "chemical/x-cml": {"source":"apache","extensions":["cml"]},
  "chemical/x-csml": {"source":"apache","extensions":["csml"]},
  "chemical/x-pdb": {"source":"apache"},
  "chemical/x-xyz": {"source":"apache","extensions":["xyz"]},
  "font/collection": {"source":"iana","extensions":["ttc"]},
  "font/otf": {"source":"iana","compressible":true,"extensions":["otf"]},
  "font/sfnt": {"source":"iana"},
  "font/ttf": {"source":"iana","compressible":true,"extensions":["ttf"]},
  "font/woff": {"source":"iana","extensions":["woff"]},
  "font/woff2": {"source":"iana","extensions":["woff2"]},
  "image/aces": {"source":"iana","extensions":["exr"]},
  "image/apng": {"source":"iana","compressible":false,"extensions":["apng"]},
  "image/avci": {"source":"iana","extensions":["avci"]},
  "image/avcs": {"source":"iana","extensions":["avcs"]},
  "image/avif": {"source":"iana","compressible":false,"extensions":["avif"]},
  "image/bmp": {"source":"iana","compressible":true,"extensions":["bmp","dib"]},
  "image/cgm": {"source":"iana","extensions":["cgm"]},
  "image/dicom-rle": {"source":"iana","extensions":["drle"]},
  "image/dpx": {"source":"iana","extensions":["dpx"]},
  "image/emf": {"source":"iana","extensions":["emf"]},
  "image/fits": {"source":"iana","extensions":["fits"]},
  "image/g3fax": {"source":"iana","extensions":["g3"]},
  "image/gif": {"source":"iana","compressible":false,"extensions":["gif"]},
  "image/heic": {"source":"iana","extensions":["heic"]},
  "image/heic-sequence": {"source":"iana","extensions":["heics"]},
  "image/heif": {"source":"iana","extensions":["heif"]},
  "image/heif-sequence": {"source":"iana","extensions":["heifs"]},
  "image/hej2k": {"source":"iana","extensions":["hej2"]},
  "image/ief": {"source":"iana","extensions":["ief"]},
  "image/j2c": {"source":"iana"},
  "image/jaii": {"source":"iana","extensions":["jaii"]},
  "image/jais": {"source":"iana","extensions":["jais"]},
  "image/jls": {"source":"iana","extensions":["jls"]},
  "image/jp2": {"source":"iana","compressible":false,"extensions":["jp2","jpg2"]},
  "image/jpeg": {"source":"iana","compressible":false,"extensions":["jpg","jpeg","jpe"]},
  "image/jph": {"source":"iana","extensions":["jph"]},
  "image/jphc": {"source":"iana","extensions":["jhc"]},
  "image/jpm": {"source":"iana","compressible":false,"extensions":["jpm","jpgm"]},
  "image/jpx": {"source":"iana","compressible":false,"extensions":["jpx","jpf"]},
  "image/jxl": {"source":"iana","extensions":["jxl"]},
  "image/jxr": {"source":"iana","extensions":["jxr"]},
  "image/jxra": {"source":"iana","extensions":["jxra"]},
  "image/jxrs": {"source":"iana","extensions":["jxrs"]},
  "image/jxs": {"source":"iana","extensions":["jxs"]},
  "image/jxsc": {"source":"iana","extensions":["jxsc"]},
  "image/jxsi": {"source":"iana","extensions":["jxsi"]},
  "image/jxss": {"source":"iana","extensions":["jxss"]},
  "image/ktx": {"source":"iana","extensions":["ktx"]},
  "image/ktx2": {"source":"iana","extensions":["ktx2"]},
  "image/naplps": {"source":"iana"},
  "image/pjpeg": {"compressible":false,"extensions":["jfif"]},
  "image/png": {"source":"iana","compressible":false,"extensions":["png"]},
  "image/prs.btif": {"source":"iana","extensions":["btif","btf"]},
  "image/prs.pti": {"source":"iana","extensions":["pti"]},
  "image/pwg-raster": {"source":"iana"},
  "image/sgi": {"source":"apache","extensions":["sgi"]},
  "image/svg+xml": {"source":"iana","compressible":true,"extensions":["svg","svgz"]},
  "image/t38": {"source":"iana","extensions":["t38"]},
  "image/tiff": {"source":"iana","compressible":false,"extensions":["tif","tiff"]},
  "image/tiff-fx": {"source":"iana","extensions":["tfx"]},
  "image/vnd.adobe.photoshop": {"source":"iana","compressible":true,"extensions":["psd"]},
  "image/vnd.airzip.accelerator.azv": {"source":"iana","extensions":["azv"]},
  "image/vnd.clip": {"source":"iana"},
  "image/vnd.cns.inf2": {"source":"iana"},
  "image/vnd.dece.graphic": {"source":"iana","extensions":["uvi","uvvi","uvg","uvvg"]},
  "image/vnd.djvu": {"source":"iana","extensions":["djvu","djv"]},
  "image/vnd.dvb.subtitle": {"source":"iana","extensions":["sub"]},
  "image/vnd.dwg": {"source":"iana","extensions":["dwg"]},
  "image/vnd.dxf": {"source":"iana","extensions":["dxf"]},
  "image/vnd.fastbidsheet": {"source":"iana","extensions":["fbs"]},
  "image/vnd.fpx": {"source":"iana","extensions":["fpx"]},
  "image/vnd.fst": {"source":"iana","extensions":["fst"]},
  "image/vnd.fujixerox.edmics-mmr": {"source":"iana","extensions":["mmr"]},
  "image/vnd.fujixerox.edmics-rlc": {"source":"iana","extensions":["rlc"]},
  "image/vnd.globalgraphics.pgb": {"source":"iana"},
  "image/vnd.microsoft.icon": {"source":"iana","compressible":true,"extensions":["ico"]},
  "image/vnd.mix": {"source":"iana"},
  "image/vnd.mozilla.apng": {"source":"iana"},
  "image/vnd.ms-dds": {"compressible":true,"extensions":["dds"]},
  "image/vnd.ms-modi": {"source":"iana","extensions":["mdi"]},
  "image/vnd.ms-photo": {"source":"apache","extensions":["wdp"]},
  "image/vnd.net-fpx": {"source":"iana","extensions":["npx"]},
  "image/vnd.pco.b16": {"source":"iana","extensions":["b16"]},
  "image/vnd.radiance": {"source":"iana"},
  "image/vnd.sealed.png": {"source":"iana"},
  "image/vnd.sealedmedia.softseal.gif": {"source":"iana"},
  "image/vnd.sealedmedia.softseal.jpg": {"source":"iana"},
  "image/vnd.svf": {"source":"iana"},
  "image/vnd.tencent.tap": {"source":"iana","extensions":["tap"]},
  "image/vnd.valve.source.texture": {"source":"iana","extensions":["vtf"]},
  "image/vnd.wap.wbmp": {"source":"iana","extensions":["wbmp"]},
  "image/vnd.xiff": {"source":"iana","extensions":["xif"]},
  "image/vnd.zbrush.pcx": {"source":"iana","extensions":["pcx"]},
  "image/webp": {"source":"iana","extensions":["webp"]},
  "image/wmf": {"source":"iana","extensions":["wmf"]},
  "image/x-3ds": {"source":"apache","extensions":["3ds"]},
  "image/x-adobe-dng": {"extensions":["dng"]},
  "image/x-cmu-raster": {"source":"apache","extensions":["ras"]},
  "image/x-cmx": {"source":"apache","extensions":["cmx"]},
  "image/x-emf": {"source":"iana"},
  "image/x-freehand": {"source":"apache","extensions":["fh","fhc","fh4","fh5","fh7"]},
  "image/x-icon": {"source":"apache","compressible":true,"extensions":["ico"]},
  "image/x-jng": {"source":"nginx","extensions":["jng"]},
  "image/x-mrsid-image": {"source":"apache","extensions":["sid"]},
  "image/x-ms-bmp": {"source":"nginx","compressible":true,"extensions":["bmp"]},
  "image/x-pcx": {"source":"apache","extensions":["pcx"]},
  "image/x-pict": {"source":"apache","extensions":["pic","pct"]},
  "image/x-portable-anymap": {"source":"apache","extensions":["pnm"]},
  "image/x-portable-bitmap": {"source":"apache","extensions":["pbm"]},
  "image/x-portable-graymap": {"source":"apache","extensions":["pgm"]},
  "image/x-portable-pixmap": {"source":"apache","extensions":["ppm"]},
  "image/x-rgb": {"source":"apache","extensions":["rgb"]},
  "image/x-tga": {"source":"apache","extensions":["tga"]},
  "image/x-wmf": {"source":"iana"},
  "image/x-xbitmap": {"source":"apache","extensions":["xbm"]},
  "image/x-xcf": {"compressible":false},
  "image/x-xpixmap": {"source":"apache","extensions":["xpm"]},
  "image/x-xwindowdump": {"source":"apache","extensions":["xwd"]},
  "message/bhttp": {"source":"iana"},
  "message/cpim": {"source":"iana"},
  "message/delivery-status": {"source":"iana"},
  "message/disposition-notification": {"source":"iana","extensions":["disposition-notification"]},
  "message/external-body": {"source":"iana"},
  "message/feedback-report": {"source":"iana"},
  "message/global": {"source":"iana","extensions":["u8msg"]},
  "message/global-delivery-status": {"source":"iana","extensions":["u8dsn"]},
  "message/global-disposition-notification": {"source":"iana","extensions":["u8mdn"]},
  "message/global-headers": {"source":"iana","extensions":["u8hdr"]},
  "message/http": {"source":"iana","compressible":false},
  "message/imdn+xml": {"source":"iana","compressible":true},
  "message/mls": {"source":"iana"},
  "message/news": {"source":"apache"},
  "message/ohttp-req": {"source":"iana"},
  "message/ohttp-res": {"source":"iana"},
  "message/partial": {"source":"iana","compressible":false},
  "message/rfc822": {"source":"iana","compressible":true,"extensions":["eml","mime","mht","mhtml"]},
  "message/s-http": {"source":"apache"},
  "message/sip": {"source":"iana"},
  "message/sipfrag": {"source":"iana"},
  "message/tracking-status": {"source":"iana"},
  "message/vnd.si.simp": {"source":"apache"},
  "message/vnd.wfa.wsc": {"source":"iana","extensions":["wsc"]},
  "model/3mf": {"source":"iana","extensions":["3mf"]},
  "model/e57": {"source":"iana"},
  "model/gltf+json": {"source":"iana","compressible":true,"extensions":["gltf"]},
  "model/gltf-binary": {"source":"iana","compressible":true,"extensions":["glb"]},
  "model/iges": {"source":"iana","compressible":false,"extensions":["igs","iges"]},
  "model/jt": {"source":"iana","extensions":["jt"]},
  "model/mesh": {"source":"iana","compressible":false,"extensions":["msh","mesh","silo"]},
  "model/mtl": {"source":"iana","extensions":["mtl"]},
  "model/obj": {"source":"iana","extensions":["obj"]},
  "model/prc": {"source":"iana","extensions":["prc"]},
  "model/step": {"source":"iana","extensions":["step","stp","stpnc","p21","210"]},
  "model/step+xml": {"source":"iana","compressible":true,"extensions":["stpx"]},
  "model/step+zip": {"source":"iana","compressible":false,"extensions":["stpz"]},
  "model/step-xml+zip": {"source":"iana","compressible":false,"extensions":["stpxz"]},
  "model/stl": {"source":"iana","extensions":["stl"]},
  "model/u3d": {"source":"iana","extensions":["u3d"]},
  "model/vnd.bary": {"source":"iana","extensions":["bary"]},
  "model/vnd.cld": {"source":"iana","extensions":["cld"]},
  "model/vnd.collada+xml": {"source":"iana","compressible":true,"extensions":["dae"]},
  "model/vnd.dwf": {"source":"iana","extensions":["dwf"]},
  "model/vnd.flatland.3dml": {"source":"iana"},
  "model/vnd.gdl": {"source":"iana","extensions":["gdl"]},
  "model/vnd.gs-gdl": {"source":"apache"},
  "model/vnd.gs.gdl": {"source":"iana"},
  "model/vnd.gtw": {"source":"iana","extensions":["gtw"]},
  "model/vnd.moml+xml": {"source":"iana","compressible":true},
  "model/vnd.mts": {"source":"iana","extensions":["mts"]},
  "model/vnd.opengex": {"source":"iana","extensions":["ogex"]},
  "model/vnd.parasolid.transmit.binary": {"source":"iana","extensions":["x_b"]},
  "model/vnd.parasolid.transmit.text": {"source":"iana","extensions":["x_t"]},
  "model/vnd.pytha.pyox": {"source":"iana","extensions":["pyo","pyox"]},
  "model/vnd.rosette.annotated-data-model": {"source":"iana"},
  "model/vnd.sap.vds": {"source":"iana","extensions":["vds"]},
  "model/vnd.usda": {"source":"iana","extensions":["usda"]},
  "model/vnd.usdz+zip": {"source":"iana","compressible":false,"extensions":["usdz"]},
  "model/vnd.valve.source.compiled-map": {"source":"iana","extensions":["bsp"]},
  "model/vnd.vtu": {"source":"iana","extensions":["vtu"]},
  "model/vrml": {"source":"iana","compressible":false,"extensions":["wrl","vrml"]},
  "model/x3d+binary": {"source":"apache","compressible":false,"extensions":["x3db","x3dbz"]},
  "model/x3d+fastinfoset": {"source":"iana","extensions":["x3db"]},
  "model/x3d+vrml": {"source":"apache","compressible":false,"extensions":["x3dv","x3dvz"]},
  "model/x3d+xml": {"source":"iana","compressible":true,"extensions":["x3d","x3dz"]},
  "model/x3d-vrml": {"source":"iana","extensions":["x3dv"]},
  "multipart/alternative": {"source":"iana","compressible":false},
  "multipart/appledouble": {"source":"iana"},
  "multipart/byteranges": {"source":"iana"},
  "multipart/digest": {"source":"iana"},
  "multipart/encrypted": {"source":"iana","compressible":false},
  "multipart/form-data": {"source":"iana","compressible":false},
  "multipart/header-set": {"source":"iana"},
  "multipart/mixed": {"source":"iana"},
  "multipart/multilingual": {"source":"iana"},
  "multipart/parallel": {"source":"iana"},
  "multipart/related": {"source":"iana","compressible":false},
  "multipart/report": {"source":"iana"},
  "multipart/signed": {"source":"iana","compressible":false},
  "multipart/vnd.bint.med-plus": {"source":"iana"},
  "multipart/voice-message": {"source":"iana"},
  "multipart/x-mixed-replace": {"source":"iana"},
  "text/1d-interleaved-parityfec": {"source":"iana"},
  "text/cache-manifest": {"source":"iana","compressible":true,"extensions":["appcache","manifest"]},
  "text/calendar": {"source":"iana","extensions":["ics","ifb"]},
  "text/calender": {"compressible":true},
  "text/cmd": {"compressible":true},
  "text/coffeescript": {"extensions":["coffee","litcoffee"]},
  "text/cql": {"source":"iana"},
  "text/cql-expression": {"source":"iana"},
  "text/cql-identifier": {"source":"iana"},
  "text/css": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["css"]},
  "text/csv": {"source":"iana","compressible":true,"extensions":["csv"]},
  "text/csv-schema": {"source":"iana"},
  "text/directory": {"source":"iana"},
  "text/dns": {"source":"iana"},
  "text/ecmascript": {"source":"apache"},
  "text/encaprtp": {"source":"iana"},
  "text/enriched": {"source":"iana"},
  "text/fhirpath": {"source":"iana"},
  "text/flexfec": {"source":"iana"},
  "text/fwdred": {"source":"iana"},
  "text/gff3": {"source":"iana"},
  "text/grammar-ref-list": {"source":"iana"},
  "text/hl7v2": {"source":"iana"},
  "text/html": {"source":"iana","compressible":true,"extensions":["html","htm","shtml"]},
  "text/jade": {"extensions":["jade"]},
  "text/javascript": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["js","mjs"]},
  "text/jcr-cnd": {"source":"iana"},
  "text/jsx": {"compressible":true,"extensions":["jsx"]},
  "text/less": {"compressible":true,"extensions":["less"]},
  "text/markdown": {"source":"iana","compressible":true,"extensions":["md","markdown"]},
  "text/mathml": {"source":"nginx","extensions":["mml"]},
  "text/mdx": {"compressible":true,"extensions":["mdx"]},
  "text/mizar": {"source":"iana"},
  "text/n3": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["n3"]},
  "text/parameters": {"source":"iana","charset":"UTF-8"},
  "text/parityfec": {"source":"iana"},
  "text/plain": {"source":"iana","compressible":true,"extensions":["txt","text","conf","def","list","log","in","ini"]},
  "text/provenance-notation": {"source":"iana","charset":"UTF-8"},
  "text/prs.fallenstein.rst": {"source":"iana"},
  "text/prs.lines.tag": {"source":"iana","extensions":["dsc"]},
  "text/prs.prop.logic": {"source":"iana"},
  "text/prs.texi": {"source":"iana"},
  "text/raptorfec": {"source":"iana"},
  "text/red": {"source":"iana"},
  "text/rfc822-headers": {"source":"iana"},
  "text/richtext": {"source":"iana","compressible":true,"extensions":["rtx"]},
  "text/rtf": {"source":"iana","compressible":true,"extensions":["rtf"]},
  "text/rtp-enc-aescm128": {"source":"iana"},
  "text/rtploopback": {"source":"iana"},
  "text/rtx": {"source":"iana"},
  "text/sgml": {"source":"iana","extensions":["sgml","sgm"]},
  "text/shaclc": {"source":"iana"},
  "text/shex": {"source":"iana","extensions":["shex"]},
  "text/slim": {"extensions":["slim","slm"]},
  "text/spdx": {"source":"iana","extensions":["spdx"]},
  "text/strings": {"source":"iana"},
  "text/stylus": {"extensions":["stylus","styl"]},
  "text/t140": {"source":"iana"},
  "text/tab-separated-values": {"source":"iana","compressible":true,"extensions":["tsv"]},
  "text/troff": {"source":"iana","extensions":["t","tr","roff","man","me","ms"]},
  "text/turtle": {"source":"iana","charset":"UTF-8","extensions":["ttl"]},
  "text/ulpfec": {"source":"iana"},
  "text/uri-list": {"source":"iana","compressible":true,"extensions":["uri","uris","urls"]},
  "text/vcard": {"source":"iana","compressible":true,"extensions":["vcard"]},
  "text/vnd.a": {"source":"iana"},
  "text/vnd.abc": {"source":"iana"},
  "text/vnd.ascii-art": {"source":"iana"},
  "text/vnd.curl": {"source":"iana","extensions":["curl"]},
  "text/vnd.curl.dcurl": {"source":"apache","extensions":["dcurl"]},
  "text/vnd.curl.mcurl": {"source":"apache","extensions":["mcurl"]},
  "text/vnd.curl.scurl": {"source":"apache","extensions":["scurl"]},
  "text/vnd.debian.copyright": {"source":"iana","charset":"UTF-8"},
  "text/vnd.dmclientscript": {"source":"iana"},
  "text/vnd.dvb.subtitle": {"source":"iana","extensions":["sub"]},
  "text/vnd.esmertec.theme-descriptor": {"source":"iana","charset":"UTF-8"},
  "text/vnd.exchangeable": {"source":"iana"},
  "text/vnd.familysearch.gedcom": {"source":"iana","extensions":["ged"]},
  "text/vnd.ficlab.flt": {"source":"iana"},
  "text/vnd.fly": {"source":"iana","extensions":["fly"]},
  "text/vnd.fmi.flexstor": {"source":"iana","extensions":["flx"]},
  "text/vnd.gml": {"source":"iana"},
  "text/vnd.graphviz": {"source":"iana","extensions":["gv"]},
  "text/vnd.hans": {"source":"iana"},
  "text/vnd.hgl": {"source":"iana"},
  "text/vnd.in3d.3dml": {"source":"iana","extensions":["3dml"]},
  "text/vnd.in3d.spot": {"source":"iana","extensions":["spot"]},
  "text/vnd.iptc.newsml": {"source":"iana"},
  "text/vnd.iptc.nitf": {"source":"iana"},
  "text/vnd.latex-z": {"source":"iana"},
  "text/vnd.motorola.reflex": {"source":"iana"},
  "text/vnd.ms-mediapackage": {"source":"iana"},
  "text/vnd.net2phone.commcenter.command": {"source":"iana"},
  "text/vnd.radisys.msml-basic-layout": {"source":"iana"},
  "text/vnd.senx.warpscript": {"source":"iana"},
  "text/vnd.si.uricatalogue": {"source":"apache"},
  "text/vnd.sosi": {"source":"iana"},
  "text/vnd.sun.j2me.app-descriptor": {"source":"iana","charset":"UTF-8","extensions":["jad"]},
  "text/vnd.trolltech.linguist": {"source":"iana","charset":"UTF-8"},
  "text/vnd.vcf": {"source":"iana"},
  "text/vnd.wap.si": {"source":"iana"},
  "text/vnd.wap.sl": {"source":"iana"},
  "text/vnd.wap.wml": {"source":"iana","extensions":["wml"]},
  "text/vnd.wap.wmlscript": {"source":"iana","extensions":["wmls"]},
  "text/vnd.zoo.kcl": {"source":"iana"},
  "text/vtt": {"source":"iana","charset":"UTF-8","compressible":true,"extensions":["vtt"]},
  "text/wgsl": {"source":"iana","extensions":["wgsl"]},
  "text/x-asm": {"source":"apache","extensions":["s","asm"]},
  "text/x-c": {"source":"apache","extensions":["c","cc","cxx","cpp","h","hh","dic"]},
  "text/x-component": {"source":"nginx","extensions":["htc"]},
  "text/x-fortran": {"source":"apache","extensions":["f","for","f77","f90"]},
  "text/x-gwt-rpc": {"compressible":true},
  "text/x-handlebars-template": {"extensions":["hbs"]},
  "text/x-java-source": {"source":"apache","extensions":["java"]},
  "text/x-jquery-tmpl": {"compressible":true},
  "text/x-lua": {"extensions":["lua"]},
  "text/x-markdown": {"compressible":true,"extensions":["mkd"]},
  "text/x-nfo": {"source":"apache","extensions":["nfo"]},
  "text/x-opml": {"source":"apache","extensions":["opml"]},
  "text/x-org": {"compressible":true,"extensions":["org"]},
  "text/x-pascal": {"source":"apache","extensions":["p","pas"]},
  "text/x-processing": {"compressible":true,"extensions":["pde"]},
  "text/x-sass": {"extensions":["sass"]},
  "text/x-scss": {"extensions":["scss"]},
  "text/x-setext": {"source":"apache","extensions":["etx"]},
  "text/x-sfv": {"source":"apache","extensions":["sfv"]},
  "text/x-suse-ymp": {"compressible":true,"extensions":["ymp"]},
  "text/x-uuencode": {"source":"apache","extensions":["uu"]},
  "text/x-vcalendar": {"source":"apache","extensions":["vcs"]},
  "text/x-vcard": {"source":"apache","extensions":["vcf"]},
  "text/xml": {"source":"iana","compressible":true,"extensions":["xml"]},
  "text/xml-external-parsed-entity": {"source":"iana"},
  "text/yaml": {"compressible":true,"extensions":["yaml","yml"]},
  "video/1d-interleaved-parityfec": {"source":"iana"},
  "video/3gpp": {"source":"iana","extensions":["3gp","3gpp"]},
  "video/3gpp-tt": {"source":"iana"},
  "video/3gpp2": {"source":"iana","extensions":["3g2"]},
  "video/av1": {"source":"iana"},
  "video/bmpeg": {"source":"iana"},
  "video/bt656": {"source":"iana"},
  "video/celb": {"source":"iana"},
  "video/dv": {"source":"iana"},
  "video/encaprtp": {"source":"iana"},
  "video/evc": {"source":"iana"},
  "video/ffv1": {"source":"iana"},
  "video/flexfec": {"source":"iana"},
  "video/h261": {"source":"iana","extensions":["h261"]},
  "video/h263": {"source":"iana","extensions":["h263"]},
  "video/h263-1998": {"source":"iana"},
  "video/h263-2000": {"source":"iana"},
  "video/h264": {"source":"iana","extensions":["h264"]},
  "video/h264-rcdo": {"source":"iana"},
  "video/h264-svc": {"source":"iana"},
  "video/h265": {"source":"iana"},
  "video/h266": {"source":"iana"},
  "video/iso.segment": {"source":"iana","extensions":["m4s"]},
  "video/jpeg": {"source":"iana","extensions":["jpgv"]},
  "video/jpeg2000": {"source":"iana"},
  "video/jpm": {"source":"apache","extensions":["jpm","jpgm"]},
  "video/jxsv": {"source":"iana"},
  "video/lottie+json": {"source":"iana","compressible":true},
  "video/matroska": {"source":"iana"},
  "video/matroska-3d": {"source":"iana"},
  "video/mj2": {"source":"iana","extensions":["mj2","mjp2"]},
  "video/mp1s": {"source":"iana"},
  "video/mp2p": {"source":"iana"},
  "video/mp2t": {"source":"iana","extensions":["ts","m2t","m2ts","mts"]},
  "video/mp4": {"source":"iana","compressible":false,"extensions":["mp4","mp4v","mpg4"]},
  "video/mp4v-es": {"source":"iana"},
  "video/mpeg": {"source":"iana","compressible":false,"extensions":["mpeg","mpg","mpe","m1v","m2v"]},
  "video/mpeg4-generic": {"source":"iana"},
  "video/mpv": {"source":"iana"},
  "video/nv": {"source":"iana"},
  "video/ogg": {"source":"iana","compressible":false,"extensions":["ogv"]},
  "video/parityfec": {"source":"iana"},
  "video/pointer": {"source":"iana"},
  "video/quicktime": {"source":"iana","compressible":false,"extensions":["qt","mov"]},
  "video/raptorfec": {"source":"iana"},
  "video/raw": {"source":"iana"},
  "video/rtp-enc-aescm128": {"source":"iana"},
  "video/rtploopback": {"source":"iana"},
  "video/rtx": {"source":"iana"},
  "video/scip": {"source":"iana"},
  "video/smpte291": {"source":"iana"},
  "video/smpte292m": {"source":"iana"},
  "video/ulpfec": {"source":"iana"},
  "video/vc1": {"source":"iana"},
  "video/vc2": {"source":"iana"},
  "video/vnd.cctv": {"source":"iana"},
  "video/vnd.dece.hd": {"source":"iana","extensions":["uvh","uvvh"]},
  "video/vnd.dece.mobile": {"source":"iana","extensions":["uvm","uvvm"]},
  "video/vnd.dece.mp4": {"source":"iana"},
  "video/vnd.dece.pd": {"source":"iana","extensions":["uvp","uvvp"]},
  "video/vnd.dece.sd": {"source":"iana","extensions":["uvs","uvvs"]},
  "video/vnd.dece.video": {"source":"iana","extensions":["uvv","uvvv"]},
  "video/vnd.directv.mpeg": {"source":"iana"},
  "video/vnd.directv.mpeg-tts": {"source":"iana"},
  "video/vnd.dlna.mpeg-tts": {"source":"iana"},
  "video/vnd.dvb.file": {"source":"iana","extensions":["dvb"]},
  "video/vnd.fvt": {"source":"iana","extensions":["fvt"]},
  "video/vnd.hns.video": {"source":"iana"},
  "video/vnd.iptvforum.1dparityfec-1010": {"source":"iana"},
  "video/vnd.iptvforum.1dparityfec-2005": {"source":"iana"},
  "video/vnd.iptvforum.2dparityfec-1010": {"source":"iana"},
  "video/vnd.iptvforum.2dparityfec-2005": {"source":"iana"},
  "video/vnd.iptvforum.ttsavc": {"source":"iana"},
  "video/vnd.iptvforum.ttsmpeg2": {"source":"iana"},
  "video/vnd.motorola.video": {"source":"iana"},
  "video/vnd.motorola.videop": {"source":"iana"},
  "video/vnd.mpegurl": {"source":"iana","extensions":["mxu","m4u"]},
  "video/vnd.ms-playready.media.pyv": {"source":"iana","extensions":["pyv"]},
  "video/vnd.nokia.interleaved-multimedia": {"source":"iana"},
  "video/vnd.nokia.mp4vr": {"source":"iana"},
  "video/vnd.nokia.videovoip": {"source":"iana"},
  "video/vnd.objectvideo": {"source":"iana"},
  "video/vnd.planar": {"source":"iana"},
  "video/vnd.radgamettools.bink": {"source":"iana"},
  "video/vnd.radgamettools.smacker": {"source":"apache"},
  "video/vnd.sealed.mpeg1": {"source":"iana"},
  "video/vnd.sealed.mpeg4": {"source":"iana"},
  "video/vnd.sealed.swf": {"source":"iana"},
  "video/vnd.sealedmedia.softseal.mov": {"source":"iana"},
  "video/vnd.uvvu.mp4": {"source":"iana","extensions":["uvu","uvvu"]},
  "video/vnd.vivo": {"source":"iana","extensions":["viv"]},
  "video/vnd.youtube.yt": {"source":"iana"},
  "video/vp8": {"source":"iana"},
  "video/vp9": {"source":"iana"},
  "video/webm": {"source":"apache","compressible":false,"extensions":["webm"]},
  "video/x-f4v": {"source":"apache","extensions":["f4v"]},
  "video/x-fli": {"source":"apache","extensions":["fli"]},
  "video/x-flv": {"source":"apache","compressible":false,"extensions":["flv"]},
  "video/x-m4v": {"source":"apache","extensions":["m4v"]},
  "video/x-matroska": {"source":"apache","compressible":false,"extensions":["mkv","mk3d","mks"]},
  "video/x-mng": {"source":"apache","extensions":["mng"]},
  "video/x-ms-asf": {"source":"apache","extensions":["asf","asx"]},
  "video/x-ms-vob": {"source":"apache","extensions":["vob"]},
  "video/x-ms-wm": {"source":"apache","extensions":["wm"]},
  "video/x-ms-wmv": {"source":"apache","compressible":false,"extensions":["wmv"]},
  "video/x-ms-wmx": {"source":"apache","extensions":["wmx"]},
  "video/x-ms-wvx": {"source":"apache","extensions":["wvx"]},
  "video/x-msvideo": {"source":"apache","extensions":["avi"]},
  "video/x-sgi-movie": {"source":"apache","extensions":["movie"]},
  "video/x-smv": {"source":"apache","extensions":["smv"]},
  "x-conference/x-cooltalk": {"source":"apache","extensions":["ice"]},
  "x-shader/x-fragment": {"compressible":true},
  "x-shader/x-vertex": {"compressible":true},
};

/*!
 * mime-db
 * Copyright(c) 2014 Jonathan Ong
 * Copyright(c) 2015-2022 Douglas Christopher Wilson
 * MIT Licensed
 */

var mimeDb;
var hasRequiredMimeDb;

function requireMimeDb () {
	if (hasRequiredMimeDb) return mimeDb;
	hasRequiredMimeDb = 1;
	/**
	 * Module exports.
	 */

	mimeDb = require$$0;
	return mimeDb;
}

/*!
 * compressible
 * Copyright(c) 2013 Jonathan Ong
 * Copyright(c) 2014 Jeremiah Senkpiel
 * Copyright(c) 2015 Douglas Christopher Wilson
 * MIT Licensed
 */

var compressible_1;
var hasRequiredCompressible;

function requireCompressible () {
	if (hasRequiredCompressible) return compressible_1;
	hasRequiredCompressible = 1;

	/**
	 * Module dependencies.
	 * @private
	 */

	var db = requireMimeDb();

	/**
	 * Module variables.
	 * @private
	 */

	var COMPRESSIBLE_TYPE_REGEXP = /^text\/|\+(?:json|text|xml)$/i;
	var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/;

	/**
	 * Module exports.
	 * @public
	 */

	compressible_1 = compressible;

	/**
	 * Checks if a type is compressible.
	 *
	 * @param {string} type
	 * @return {Boolean} compressible
	 * @public
	 */

	function compressible (type) {
	  if (!type || typeof type !== 'string') {
	    return false
	  }

	  // strip parameters
	  var match = EXTRACT_TYPE_REGEXP.exec(type);
	  var mime = match && match[1].toLowerCase();
	  var data = db[mime];

	  // return database information
	  if (data && data.compressible !== undefined) {
	    return data.compressible
	  }

	  // fallback to regexp or unknown
	  return COMPRESSIBLE_TYPE_REGEXP.test(mime) || undefined
	}
	return compressible_1;
}

var browser = {exports: {}};

var debug = {exports: {}};

/**
 * Helpers.
 */

var ms;
var hasRequiredMs;

function requireMs () {
	if (hasRequiredMs) return ms;
	hasRequiredMs = 1;
	var s = 1000;
	var m = s * 60;
	var h = m * 60;
	var d = h * 24;
	var y = d * 365.25;

	/**
	 * Parse or format the given `val`.
	 *
	 * Options:
	 *
	 *  - `long` verbose formatting [false]
	 *
	 * @param {String|Number} val
	 * @param {Object} [options]
	 * @throws {Error} throw an error if val is not a non-empty string or a number
	 * @return {String|Number}
	 * @api public
	 */

	ms = function(val, options) {
	  options = options || {};
	  var type = typeof val;
	  if (type === 'string' && val.length > 0) {
	    return parse(val);
	  } else if (type === 'number' && isNaN(val) === false) {
	    return options.long ? fmtLong(val) : fmtShort(val);
	  }
	  throw new Error(
	    'val is not a non-empty string or a valid number. val=' +
	      JSON.stringify(val)
	  );
	};

	/**
	 * Parse the given `str` and return milliseconds.
	 *
	 * @param {String} str
	 * @return {Number}
	 * @api private
	 */

	function parse(str) {
	  str = String(str);
	  if (str.length > 100) {
	    return;
	  }
	  var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
	    str
	  );
	  if (!match) {
	    return;
	  }
	  var n = parseFloat(match[1]);
	  var type = (match[2] || 'ms').toLowerCase();
	  switch (type) {
	    case 'years':
	    case 'year':
	    case 'yrs':
	    case 'yr':
	    case 'y':
	      return n * y;
	    case 'days':
	    case 'day':
	    case 'd':
	      return n * d;
	    case 'hours':
	    case 'hour':
	    case 'hrs':
	    case 'hr':
	    case 'h':
	      return n * h;
	    case 'minutes':
	    case 'minute':
	    case 'mins':
	    case 'min':
	    case 'm':
	      return n * m;
	    case 'seconds':
	    case 'second':
	    case 'secs':
	    case 'sec':
	    case 's':
	      return n * s;
	    case 'milliseconds':
	    case 'millisecond':
	    case 'msecs':
	    case 'msec':
	    case 'ms':
	      return n;
	    default:
	      return undefined;
	  }
	}

	/**
	 * Short format for `ms`.
	 *
	 * @param {Number} ms
	 * @return {String}
	 * @api private
	 */

	function fmtShort(ms) {
	  if (ms >= d) {
	    return Math.round(ms / d) + 'd';
	  }
	  if (ms >= h) {
	    return Math.round(ms / h) + 'h';
	  }
	  if (ms >= m) {
	    return Math.round(ms / m) + 'm';
	  }
	  if (ms >= s) {
	    return Math.round(ms / s) + 's';
	  }
	  return ms + 'ms';
	}

	/**
	 * Long format for `ms`.
	 *
	 * @param {Number} ms
	 * @return {String}
	 * @api private
	 */

	function fmtLong(ms) {
	  return plural(ms, d, 'day') ||
	    plural(ms, h, 'hour') ||
	    plural(ms, m, 'minute') ||
	    plural(ms, s, 'second') ||
	    ms + ' ms';
	}

	/**
	 * Pluralization helper.
	 */

	function plural(ms, n, name) {
	  if (ms < n) {
	    return;
	  }
	  if (ms < n * 1.5) {
	    return Math.floor(ms / n) + ' ' + name;
	  }
	  return Math.ceil(ms / n) + ' ' + name + 's';
	}
	return ms;
}

var hasRequiredDebug;

function requireDebug () {
	if (hasRequiredDebug) return debug.exports;
	hasRequiredDebug = 1;
	(function (module, exports$1) {
		/**
		 * This is the common logic for both the Node.js and web browser
		 * implementations of `debug()`.
		 *
		 * Expose `debug()` as the module.
		 */

		exports$1 = module.exports = createDebug.debug = createDebug['default'] = createDebug;
		exports$1.coerce = coerce;
		exports$1.disable = disable;
		exports$1.enable = enable;
		exports$1.enabled = enabled;
		exports$1.humanize = requireMs();

		/**
		 * The currently active debug mode names, and names to skip.
		 */

		exports$1.names = [];
		exports$1.skips = [];

		/**
		 * Map of special "%n" handling functions, for the debug "format" argument.
		 *
		 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
		 */

		exports$1.formatters = {};

		/**
		 * Previous log timestamp.
		 */

		var prevTime;

		/**
		 * Select a color.
		 * @param {String} namespace
		 * @return {Number}
		 * @api private
		 */

		function selectColor(namespace) {
		  var hash = 0, i;

		  for (i in namespace) {
		    hash  = ((hash << 5) - hash) + namespace.charCodeAt(i);
		    hash |= 0; // Convert to 32bit integer
		  }

		  return exports$1.colors[Math.abs(hash) % exports$1.colors.length];
		}

		/**
		 * Create a debugger with the given `namespace`.
		 *
		 * @param {String} namespace
		 * @return {Function}
		 * @api public
		 */

		function createDebug(namespace) {

		  function debug() {
		    // disabled?
		    if (!debug.enabled) return;

		    var self = debug;

		    // set `diff` timestamp
		    var curr = +new Date();
		    var ms = curr - (prevTime || curr);
		    self.diff = ms;
		    self.prev = prevTime;
		    self.curr = curr;
		    prevTime = curr;

		    // turn the `arguments` into a proper Array
		    var args = new Array(arguments.length);
		    for (var i = 0; i < args.length; i++) {
		      args[i] = arguments[i];
		    }

		    args[0] = exports$1.coerce(args[0]);

		    if ('string' !== typeof args[0]) {
		      // anything else let's inspect with %O
		      args.unshift('%O');
		    }

		    // apply any `formatters` transformations
		    var index = 0;
		    args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
		      // if we encounter an escaped % then don't increase the array index
		      if (match === '%%') return match;
		      index++;
		      var formatter = exports$1.formatters[format];
		      if ('function' === typeof formatter) {
		        var val = args[index];
		        match = formatter.call(self, val);

		        // now we need to remove `args[index]` since it's inlined in the `format`
		        args.splice(index, 1);
		        index--;
		      }
		      return match;
		    });

		    // apply env-specific formatting (colors, etc.)
		    exports$1.formatArgs.call(self, args);

		    var logFn = debug.log || exports$1.log || console.log.bind(console);
		    logFn.apply(self, args);
		  }

		  debug.namespace = namespace;
		  debug.enabled = exports$1.enabled(namespace);
		  debug.useColors = exports$1.useColors();
		  debug.color = selectColor(namespace);

		  // env-specific initialization logic for debug instances
		  if ('function' === typeof exports$1.init) {
		    exports$1.init(debug);
		  }

		  return debug;
		}

		/**
		 * Enables a debug mode by namespaces. This can include modes
		 * separated by a colon and wildcards.
		 *
		 * @param {String} namespaces
		 * @api public
		 */

		function enable(namespaces) {
		  exports$1.save(namespaces);

		  exports$1.names = [];
		  exports$1.skips = [];

		  var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
		  var len = split.length;

		  for (var i = 0; i < len; i++) {
		    if (!split[i]) continue; // ignore empty strings
		    namespaces = split[i].replace(/\*/g, '.*?');
		    if (namespaces[0] === '-') {
		      exports$1.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
		    } else {
		      exports$1.names.push(new RegExp('^' + namespaces + '$'));
		    }
		  }
		}

		/**
		 * Disable debug output.
		 *
		 * @api public
		 */

		function disable() {
		  exports$1.enable('');
		}

		/**
		 * Returns true if the given mode name is enabled, false otherwise.
		 *
		 * @param {String} name
		 * @return {Boolean}
		 * @api public
		 */

		function enabled(name) {
		  var i, len;
		  for (i = 0, len = exports$1.skips.length; i < len; i++) {
		    if (exports$1.skips[i].test(name)) {
		      return false;
		    }
		  }
		  for (i = 0, len = exports$1.names.length; i < len; i++) {
		    if (exports$1.names[i].test(name)) {
		      return true;
		    }
		  }
		  return false;
		}

		/**
		 * Coerce `val`.
		 *
		 * @param {Mixed} val
		 * @return {Mixed}
		 * @api private
		 */

		function coerce(val) {
		  if (val instanceof Error) return val.stack || val.message;
		  return val;
		} 
	} (debug, debug.exports));
	return debug.exports;
}

/**
 * This is the web browser implementation of `debug()`.
 *
 * Expose `debug()` as the module.
 */

var hasRequiredBrowser;

function requireBrowser () {
	if (hasRequiredBrowser) return browser.exports;
	hasRequiredBrowser = 1;
	(function (module, exports$1) {
		exports$1 = module.exports = requireDebug();
		exports$1.log = log;
		exports$1.formatArgs = formatArgs;
		exports$1.save = save;
		exports$1.load = load;
		exports$1.useColors = useColors;
		exports$1.storage = 'undefined' != typeof chrome
		               && 'undefined' != typeof chrome.storage
		                  ? chrome.storage.local
		                  : localstorage();

		/**
		 * Colors.
		 */

		exports$1.colors = [
		  'lightseagreen',
		  'forestgreen',
		  'goldenrod',
		  'dodgerblue',
		  'darkorchid',
		  'crimson'
		];

		/**
		 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
		 * and the Firebug extension (any Firefox version) are known
		 * to support "%c" CSS customizations.
		 *
		 * TODO: add a `localStorage` variable to explicitly enable/disable colors
		 */

		function useColors() {
		  // NB: In an Electron preload script, document will be defined but not fully
		  // initialized. Since we know we're in Chrome, we'll just detect this case
		  // explicitly
		  if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
		    return true;
		  }

		  // is webkit? http://stackoverflow.com/a/16459606/376773
		  // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
		  return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
		    // is firebug? http://stackoverflow.com/a/398120/376773
		    (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
		    // is firefox >= v31?
		    // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
		    (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
		    // double check webkit in userAgent just in case we are in a worker
		    (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
		}

		/**
		 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
		 */

		exports$1.formatters.j = function(v) {
		  try {
		    return JSON.stringify(v);
		  } catch (err) {
		    return '[UnexpectedJSONParseError]: ' + err.message;
		  }
		};


		/**
		 * Colorize log arguments if enabled.
		 *
		 * @api public
		 */

		function formatArgs(args) {
		  var useColors = this.useColors;

		  args[0] = (useColors ? '%c' : '')
		    + this.namespace
		    + (useColors ? ' %c' : ' ')
		    + args[0]
		    + (useColors ? '%c ' : ' ')
		    + '+' + exports$1.humanize(this.diff);

		  if (!useColors) return;

		  var c = 'color: ' + this.color;
		  args.splice(1, 0, c, 'color: inherit');

		  // the final "%c" is somewhat tricky, because there could be other
		  // arguments passed either before or after the %c, so we need to
		  // figure out the correct index to insert the CSS into
		  var index = 0;
		  var lastC = 0;
		  args[0].replace(/%[a-zA-Z%]/g, function(match) {
		    if ('%%' === match) return;
		    index++;
		    if ('%c' === match) {
		      // we only are interested in the *last* %c
		      // (the user may have provided their own)
		      lastC = index;
		    }
		  });

		  args.splice(lastC, 0, c);
		}

		/**
		 * Invokes `console.log()` when available.
		 * No-op when `console.log` is not a "function".
		 *
		 * @api public
		 */

		function log() {
		  // this hackery is required for IE8/9, where
		  // the `console.log` function doesn't have 'apply'
		  return 'object' === typeof console
		    && console.log
		    && Function.prototype.apply.call(console.log, console, arguments);
		}

		/**
		 * Save `namespaces`.
		 *
		 * @param {String} namespaces
		 * @api private
		 */

		function save(namespaces) {
		  try {
		    if (null == namespaces) {
		      exports$1.storage.removeItem('debug');
		    } else {
		      exports$1.storage.debug = namespaces;
		    }
		  } catch(e) {}
		}

		/**
		 * Load `namespaces`.
		 *
		 * @return {String} returns the previously persisted debug modes
		 * @api private
		 */

		function load() {
		  var r;
		  try {
		    r = exports$1.storage.debug;
		  } catch(e) {}

		  // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
		  if (!r && typeof process !== 'undefined' && 'env' in process) {
		    r = process.env.DEBUG;
		  }

		  return r;
		}

		/**
		 * Enable namespaces listed in `localStorage.debug` initially.
		 */

		exports$1.enable(load());

		/**
		 * Localstorage attempts to return the localstorage.
		 *
		 * This is necessary because safari throws
		 * when a user disables cookies/localstorage
		 * and you attempt to access it.
		 *
		 * @return {LocalStorage}
		 * @api private
		 */

		function localstorage() {
		  try {
		    return window.localStorage;
		  } catch (e) {}
		} 
	} (browser, browser.exports));
	return browser.exports;
}

/*!
 * on-headers
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */

var onHeaders_1;
var hasRequiredOnHeaders;

function requireOnHeaders () {
	if (hasRequiredOnHeaders) return onHeaders_1;
	hasRequiredOnHeaders = 1;

	/**
	 * Module exports.
	 * @public
	 */

	onHeaders_1 = onHeaders;

	var http = require$$0$8;

	// older node versions don't have appendHeader
	var isAppendHeaderSupported = typeof http.ServerResponse.prototype.appendHeader === 'function';
	var set1dArray = isAppendHeaderSupported ? set1dArrayWithAppend : set1dArrayWithSet;

	/**
	 * Create a replacement writeHead method.
	 *
	 * @param {function} prevWriteHead
	 * @param {function} listener
	 * @private
	 */

	function createWriteHead (prevWriteHead, listener) {
	  var fired = false;

	  // return function with core name and argument list
	  return function writeHead (statusCode) {
	    // set headers from arguments
	    var args = setWriteHeadHeaders.apply(this, arguments);

	    // fire listener
	    if (!fired) {
	      fired = true;
	      listener.call(this);

	      // pass-along an updated status code
	      if (typeof args[0] === 'number' && this.statusCode !== args[0]) {
	        args[0] = this.statusCode;
	        args.length = 1;
	      }
	    }

	    return prevWriteHead.apply(this, args)
	  }
	}

	/**
	 * Execute a listener when a response is about to write headers.
	 *
	 * @param {object} res
	 * @return {function} listener
	 * @public
	 */

	function onHeaders (res, listener) {
	  if (!res) {
	    throw new TypeError('argument res is required')
	  }

	  if (typeof listener !== 'function') {
	    throw new TypeError('argument listener must be a function')
	  }

	  res.writeHead = createWriteHead(res.writeHead, listener);
	}

	/**
	 * Set headers contained in array on the response object.
	 *
	 * @param {object} res
	 * @param {array} headers
	 * @private
	 */

	function setHeadersFromArray (res, headers) {
	  if (headers.length && Array.isArray(headers[0])) {
	    // 2D
	    set2dArray(res, headers);
	  } else {
	    // 1D
	    if (headers.length % 2 !== 0) {
	      throw new TypeError('headers array is malformed')
	    }

	    set1dArray(res, headers);
	  }
	}

	/**
	 * Set headers contained in object on the response object.
	 *
	 * @param {object} res
	 * @param {object} headers
	 * @private
	 */

	function setHeadersFromObject (res, headers) {
	  var keys = Object.keys(headers);
	  for (var i = 0; i < keys.length; i++) {
	    var k = keys[i];
	    if (k) res.setHeader(k, headers[k]);
	  }
	}

	/**
	 * Set headers and other properties on the response object.
	 *
	 * @param {number} statusCode
	 * @private
	 */

	function setWriteHeadHeaders (statusCode) {
	  var length = arguments.length;
	  var headerIndex = length > 1 && typeof arguments[1] === 'string'
	    ? 2
	    : 1;

	  var headers = length >= headerIndex + 1
	    ? arguments[headerIndex]
	    : undefined;

	  this.statusCode = statusCode;

	  if (Array.isArray(headers)) {
	    // handle array case
	    setHeadersFromArray(this, headers);
	  } else if (headers) {
	    // handle object case
	    setHeadersFromObject(this, headers);
	  }

	  // copy leading arguments
	  var args = new Array(Math.min(length, headerIndex));
	  for (var i = 0; i < args.length; i++) {
	    args[i] = arguments[i];
	  }

	  return args
	}

	function set2dArray (res, headers) {
	  var key;
	  for (var i = 0; i < headers.length; i++) {
	    key = headers[i][0];
	    if (key) {
	      res.setHeader(key, headers[i][1]);
	    }
	  }
	}

	function set1dArrayWithAppend (res, headers) {
	  for (var i = 0; i < headers.length; i += 2) {
	    res.removeHeader(headers[i]);
	  }

	  var key;
	  for (var j = 0; j < headers.length; j += 2) {
	    key = headers[j];
	    if (key) {
	      res.appendHeader(key, headers[j + 1]);
	    }
	  }
	}

	function set1dArrayWithSet (res, headers) {
	  var key;
	  for (var i = 0; i < headers.length; i += 2) {
	    key = headers[i];
	    if (key) {
	      res.setHeader(key, headers[i + 1]);
	    }
	  }
	}
	return onHeaders_1;
}

var vary = {exports: {}};

/*!
 * vary
 * Copyright(c) 2014-2017 Douglas Christopher Wilson
 * MIT Licensed
 */

var hasRequiredVary;

function requireVary () {
	if (hasRequiredVary) return vary.exports;
	hasRequiredVary = 1;

	/**
	 * Module exports.
	 */

	vary.exports = vary$1;
	vary.exports.append = append;

	/**
	 * RegExp to match field-name in RFC 7230 sec 3.2
	 *
	 * field-name    = token
	 * token         = 1*tchar
	 * tchar         = "!" / "#" / "$" / "%" / "&" / "'" / "*"
	 *               / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
	 *               / DIGIT / ALPHA
	 *               ; any VCHAR, except delimiters
	 */

	var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;

	/**
	 * Append a field to a vary header.
	 *
	 * @param {String} header
	 * @param {String|Array} field
	 * @return {String}
	 * @public
	 */

	function append (header, field) {
	  if (typeof header !== 'string') {
	    throw new TypeError('header argument is required')
	  }

	  if (!field) {
	    throw new TypeError('field argument is required')
	  }

	  // get fields array
	  var fields = !Array.isArray(field)
	    ? parse(String(field))
	    : field;

	  // assert on invalid field names
	  for (var j = 0; j < fields.length; j++) {
	    if (!FIELD_NAME_REGEXP.test(fields[j])) {
	      throw new TypeError('field argument contains an invalid header name')
	    }
	  }

	  // existing, unspecified vary
	  if (header === '*') {
	    return header
	  }

	  // enumerate current values
	  var val = header;
	  var vals = parse(header.toLowerCase());

	  // unspecified vary
	  if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) {
	    return '*'
	  }

	  for (var i = 0; i < fields.length; i++) {
	    var fld = fields[i].toLowerCase();

	    // append value (case-preserving)
	    if (vals.indexOf(fld) === -1) {
	      vals.push(fld);
	      val = val
	        ? val + ', ' + fields[i]
	        : fields[i];
	    }
	  }

	  return val
	}

	/**
	 * Parse a vary header into an array.
	 *
	 * @param {String} header
	 * @return {Array}
	 * @private
	 */

	function parse (header) {
	  var end = 0;
	  var list = [];
	  var start = 0;

	  // gather tokens
	  for (var i = 0, len = header.length; i < len; i++) {
	    switch (header.charCodeAt(i)) {
	      case 0x20: /*   */
	        if (start === end) {
	          start = end = i + 1;
	        }
	        break
	      case 0x2c: /* , */
	        list.push(header.substring(start, end));
	        start = end = i + 1;
	        break
	      default:
	        end = i + 1;
	        break
	    }
	  }

	  // final token
	  list.push(header.substring(start, end));

	  return list
	}

	/**
	 * Mark that a request is varied on a header field.
	 *
	 * @param {Object} res
	 * @param {String|Array} field
	 * @public
	 */

	function vary$1 (res, field) {
	  if (!res || !res.getHeader || !res.setHeader) {
	    // quack quack
	    throw new TypeError('res argument is required')
	  }

	  // get existing header
	  var val = res.getHeader('Vary') || '';
	  var header = Array.isArray(val)
	    ? val.join(', ')
	    : String(val);

	  // set new header
	  if ((val = append(header, field))) {
	    res.setHeader('Vary', val);
	  }
	}
	return vary.exports;
}

/*!
 * compression
 * Copyright(c) 2010 Sencha Inc.
 * Copyright(c) 2011 TJ Holowaychuk
 * Copyright(c) 2014 Jonathan Ong
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
 * MIT Licensed
 */

var hasRequiredCompression;

function requireCompression () {
	if (hasRequiredCompression) return compression$1.exports;
	hasRequiredCompression = 1;

	/**
	 * Module dependencies.
	 * @private
	 */

	var Negotiator = requireNegotiator();
	var Buffer = requireSafeBuffer().Buffer;
	var bytes = requireBytes();
	var compressible = requireCompressible();
	var debug = requireBrowser()('compression');
	var onHeaders = requireOnHeaders();
	var vary = requireVary();
	var zlib = require$$1$2;

	/**
	 * Module exports.
	 */

	compression$1.exports = compression;
	compression$1.exports.filter = shouldCompress;

	/**
	 * @const
	 * whether current node version has brotli support
	 */
	var hasBrotliSupport = 'createBrotliCompress' in zlib;

	/**
	 * Module variables.
	 * @private
	 */
	var cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/;
	var SUPPORTED_ENCODING = hasBrotliSupport ? ['br', 'gzip', 'deflate', 'identity'] : ['gzip', 'deflate', 'identity'];
	var PREFERRED_ENCODING = hasBrotliSupport ? ['br', 'gzip'] : ['gzip'];

	var encodingSupported = ['gzip', 'deflate', 'identity', 'br'];

	/**
	 * Compress response data with gzip / deflate.
	 *
	 * @param {Object} [options]
	 * @return {Function} middleware
	 * @public
	 */

	function compression (options) {
	  var opts = options || {};
	  var optsBrotli = {};

	  if (hasBrotliSupport) {
	    Object.assign(optsBrotli, opts.brotli);

	    var brotliParams = {};
	    brotliParams[zlib.constants.BROTLI_PARAM_QUALITY] = 4;

	    // set the default level to a reasonable value with balanced speed/ratio
	    optsBrotli.params = Object.assign(brotliParams, optsBrotli.params);
	  }

	  // options
	  var filter = opts.filter || shouldCompress;
	  var threshold = bytes.parse(opts.threshold);
	  var enforceEncoding = opts.enforceEncoding || 'identity';

	  if (threshold == null) {
	    threshold = 1024;
	  }

	  return function compression (req, res, next) {
	    var ended = false;
	    var length;
	    var listeners = [];
	    var stream;

	    var _end = res.end;
	    var _on = res.on;
	    var _write = res.write;

	    // flush
	    res.flush = function flush () {
	      if (stream) {
	        stream.flush();
	      }
	    };

	    // proxy

	    res.write = function write (chunk, encoding) {
	      if (ended) {
	        return false
	      }

	      if (!headersSent(res)) {
	        this.writeHead(this.statusCode);
	      }

	      return stream
	        ? stream.write(toBuffer(chunk, encoding))
	        : _write.call(this, chunk, encoding)
	    };

	    res.end = function end (chunk, encoding) {
	      if (ended) {
	        return false
	      }

	      if (!headersSent(res)) {
	        // estimate the length
	        if (!this.getHeader('Content-Length')) {
	          length = chunkLength(chunk, encoding);
	        }

	        this.writeHead(this.statusCode);
	      }

	      if (!stream) {
	        return _end.call(this, chunk, encoding)
	      }

	      // mark ended
	      ended = true;

	      // write Buffer for Node.js 0.8
	      return chunk
	        ? stream.end(toBuffer(chunk, encoding))
	        : stream.end()
	    };

	    res.on = function on (type, listener) {
	      if (!listeners || type !== 'drain') {
	        return _on.call(this, type, listener)
	      }

	      if (stream) {
	        return stream.on(type, listener)
	      }

	      // buffer listeners for future stream
	      listeners.push([type, listener]);

	      return this
	    };

	    function nocompress (msg) {
	      debug('no compression: %s', msg);
	      addListeners(res, _on, listeners);
	      listeners = null;
	    }

	    onHeaders(res, function onResponseHeaders () {
	      // determine if request is filtered
	      if (!filter(req, res)) {
	        nocompress('filtered');
	        return
	      }

	      // determine if the entity should be transformed
	      if (!shouldTransform(req, res)) {
	        nocompress('no transform');
	        return
	      }

	      // vary
	      vary(res, 'Accept-Encoding');

	      // content-length below threshold
	      if (Number(res.getHeader('Content-Length')) < threshold || length < threshold) {
	        nocompress('size below threshold');
	        return
	      }

	      var encoding = res.getHeader('Content-Encoding') || 'identity';

	      // already encoded
	      if (encoding !== 'identity') {
	        nocompress('already encoded');
	        return
	      }

	      // head
	      if (req.method === 'HEAD') {
	        nocompress('HEAD request');
	        return
	      }

	      // compression method
	      var negotiator = new Negotiator(req);
	      var method = negotiator.encoding(SUPPORTED_ENCODING, PREFERRED_ENCODING);

	      // if no method is found, use the default encoding
	      if (!req.headers['accept-encoding'] && encodingSupported.indexOf(enforceEncoding) !== -1) {
	        method = enforceEncoding;
	      }

	      // negotiation failed
	      if (!method || method === 'identity') {
	        nocompress('not acceptable');
	        return
	      }

	      // compression stream
	      debug('%s compression', method);
	      stream = method === 'gzip'
	        ? zlib.createGzip(opts)
	        : method === 'br'
	          ? zlib.createBrotliCompress(optsBrotli)
	          : zlib.createDeflate(opts);

	      // add buffered listeners to stream
	      addListeners(stream, stream.on, listeners);

	      // header fields
	      res.setHeader('Content-Encoding', method);
	      res.removeHeader('Content-Length');

	      // compression
	      stream.on('data', function onStreamData (chunk) {
	        if (_write.call(res, chunk) === false) {
	          stream.pause();
	        }
	      });

	      stream.on('end', function onStreamEnd () {
	        _end.call(res);
	      });

	      _on.call(res, 'drain', function onResponseDrain () {
	        stream.resume();
	      });
	    });

	    next();
	  }
	}

	/**
	 * Add bufferred listeners to stream
	 * @private
	 */

	function addListeners (stream, on, listeners) {
	  for (var i = 0; i < listeners.length; i++) {
	    on.apply(stream, listeners[i]);
	  }
	}

	/**
	 * Get the length of a given chunk
	 */

	function chunkLength (chunk, encoding) {
	  if (!chunk) {
	    return 0
	  }

	  return Buffer.isBuffer(chunk)
	    ? chunk.length
	    : Buffer.byteLength(chunk, encoding)
	}

	/**
	 * Default filter function.
	 * @private
	 */

	function shouldCompress (req, res) {
	  var type = res.getHeader('Content-Type');

	  if (type === undefined || !compressible(type)) {
	    debug('%s not compressible', type);
	    return false
	  }

	  return true
	}

	/**
	 * Determine if the entity should be transformed.
	 * @private
	 */

	function shouldTransform (req, res) {
	  var cacheControl = res.getHeader('Cache-Control');

	  // Don't compress for Cache-Control: no-transform
	  // https://tools.ietf.org/html/rfc7234#section-5.2.2.4
	  return !cacheControl ||
	    !cacheControlNoTransformRegExp.test(cacheControl)
	}

	/**
	 * Coerce arguments to Buffer
	 * @private
	 */

	function toBuffer (chunk, encoding) {
	  return Buffer.isBuffer(chunk)
	    ? chunk
	    : Buffer.from(chunk, encoding)
	}

	/**
	 * Determine if the response headers have been sent.
	 *
	 * @param {object} res
	 * @returns {boolean}
	 * @private
	 */

	function headersSent (res) {
	  return typeof res.headersSent !== 'boolean'
	    ? Boolean(res._header)
	    : res.headersSent
	}
	return compression$1.exports;
}

var compressionExports = requireCompression();
const compression = /*@__PURE__*/getDefaultExportFromCjs(compressionExports);

const __filename$1 = fileURLToPath$1(import.meta.url);
const __dirname$1 = dirname$1(__filename$1);
const app = express();
let WebUiConfig;
let webUiPathWrapper;
let logSubscription;
let statusHelperSubscription$1;
const MAX_PORT_TRY = 100;
let pendingTokenToSend = null;
let initialWebUiToken = "";
function setInitialWebUiToken(token) {
  initialWebUiToken = token;
}
function getInitialWebUiToken() {
  return initialWebUiToken;
}
function setPendingTokenToSend(token) {
  pendingTokenToSend = token;
}
async function InitPort(parsedConfig) {
  try {
    await tryUseHost(parsedConfig.host);
    const port = await tryUsePort(parsedConfig.port, parsedConfig.host);
    return [parsedConfig.host, port, parsedConfig.token];
  } catch (error) {
    console.log("host或port不可用", error);
    return ["", 0, randomUUID$1()];
  }
}
async function checkCertificates(logger) {
  try {
    const certPath = join$1(webUiPathWrapper.configPath, "cert.pem");
    const keyPath = join$1(webUiPathWrapper.configPath, "key.pem");
    if (existsSync(certPath) && existsSync(keyPath)) {
      const cert = readFileSync(certPath, "utf8");
      const key = readFileSync(keyPath, "utf8");
      logger.log("[NapCat] [WebUi] 找到SSL证书，将启用HTTPS模式");
      return { cert, key };
    }
    return null;
  } catch (error) {
    logger.log("[NapCat] [WebUi] 检查SSL证书时出错: " + error);
    return null;
  }
}
async function InitWebUi(logger, pathWrapper, Subscription, statusSubscription) {
  webUiPathWrapper = pathWrapper;
  logSubscription = Subscription;
  statusHelperSubscription$1 = statusSubscription;
  WebUiConfig = new WebUiConfigWrapper();
  let config = await WebUiConfig.GetWebUIConfig();
  if (config.disableWebUI) {
    logger.log("[NapCat] [WebUi] WebUI is disabled by configuration.");
    return;
  }
  if (config.token === "napcat" || !config.token) {
    const randomToken = process.env["NAPCAT_WEBUI_SECRET_KEY"] || getRandomToken(8);
    await WebUiConfig.UpdateWebUIConfig({ token: randomToken });
    logger.log("[NapCat] [WebUi] 检测到默认密码，已自动更新为安全密码");
    setPendingTokenToSend(randomToken);
    logger.log("[NapCat] [WebUi] 新密码将在QQ登录成功后发送给用户");
    config = await WebUiConfig.GetWebUIConfig();
  }
  setInitialWebUiToken(config.token);
  const [host, port, token] = await InitPort(config);
  if (port === 0) {
    logger.log("[NapCat] [WebUi] Current WebUi is not run.");
    return;
  }
  WebUiDataRuntime.setWebUiConfigQuickFunction(
    async () => {
      const autoLoginAccount = process.env["NAPCAT_QUICK_ACCOUNT"] || WebUiConfig.getAutoLoginAccount();
      if (autoLoginAccount) {
        try {
          const { result, message } = await WebUiDataRuntime.requestQuickLogin(autoLoginAccount);
          if (!result) {
            throw new Error(message);
          }
          console.log(`[NapCat] [WebUi] Auto login account: ${autoLoginAccount}`);
        } catch (error) {
          console.log("[NapCat] [WebUi] Auto login account failed." + error);
        }
      }
    }
  );
  app.use(express.json());
  app.use(compression({
    level: 6,
    // 压缩级别 1-9，6 是性能和压缩率的平衡点
    threshold: 1024,
    // 只压缩大于 1KB 的响应
    filter: (req, res) => {
      if (req.headers["accept"] === "text/event-stream") {
        return false;
      }
      return compression.filter(req, res);
    }
  }));
  app.use(cors$1);
  app.use("/webui/fonts/CustomFont.woff", async (_req, res) => {
    const fontPath = await WebUiConfig.GetWebUIFontPath();
    if (fontPath) {
      res.sendFile(fontPath);
    } else {
      res.status(404).send("Custom font not found");
    }
  });
  app.use("/files/theme.css", async (_req, res) => {
    const colors = await WebUiConfig.GetTheme();
    let css = ':root, .light, [data-theme="light"] {';
    for (const key in colors.light) {
      css += `${key}: ${colors.light[key]};`;
    }
    css += "}";
    css += '.dark, [data-theme="dark"] {';
    for (const key in colors.dark) {
      css += `${key}: ${colors.dark[key]};`;
    }
    css += "}";
    res.send(css);
  });
  app.get("/webui/sw.js", async (_req, res) => {
    try {
      let templatePath = resolve$1(__dirname$1, "static", "sw_template.js");
      if (!existsSync(templatePath)) {
        templatePath = resolve$1(__dirname$1, "src", "assets", "sw_template.js");
      }
      let swContent = readFileSync(templatePath, "utf-8");
      swContent = swContent.replace("{{VERSION}}", napCatVersion);
      res.header("Content-Type", "application/javascript");
      res.header("Service-Worker-Allowed", "/webui/");
      res.header("Cache-Control", "no-cache, no-store, must-revalidate");
      res.send(swContent);
    } catch (error) {
      console.error("[NapCat] [WebUi] Error generating sw.js", error);
      res.status(500).send("Error generating service worker");
    }
  });
  app.use("/webui", express.static(pathWrapper.staticPath, {
    maxAge: "1d"
  }));
  const sslCerts = await checkCertificates(logger);
  const isHttps = !!sslCerts;
  const server = isHttps && sslCerts ? createServer(sslCerts, app) : createServer$1(app);
  server.on("upgrade", (request, socket, head) => {
    const url = new URL(request.url || "", `http://${request.headers.host}`);
    if (url.pathname.startsWith("/api/Debug/ws")) {
      handleDebugWebSocket(request, socket, head);
    } else {
      terminalManager.initialize(request, socket, head, logger);
    }
  });
  app.use("/api", router);
  const indexFile = join$1(pathWrapper.staticPath, "index.html");
  app.all(/\/webui\/(.*)/, (_req, res) => {
    res.sendFile(indexFile);
  });
  app.all("/", (_req, res) => {
    res.status(301).header("Location", "/webui").send();
  });
  app.use((err, _, res, next) => {
    if (err instanceof multer.MulterError) {
      return sendError(res, err.message, true);
    }
    next(err);
  });
  app.use((_, __, res, ___) => {
    sendError(res, "An unknown error occurred.", true);
  });
  server.listen(port, host, async () => {
    const searchParams = { token };
    logger.log(`[NapCat] [WebUi] WebUi Token: ${token}`);
    logger.log(
      `[NapCat] [WebUi] WebUi User Panel Url: ${createUrl("127.0.0.1", port.toString(), "/webui", searchParams)}`
    );
    if (host !== "") {
      logger.log(
        `[NapCat] [WebUi] WebUi User Panel Url: ${createUrl(host, port.toString(), "/webui", searchParams)}`
      );
    }
  });
}
async function tryUseHost(host) {
  return new Promise((resolve2, reject) => {
    try {
      const server = net.createServer();
      server.on("listening", () => {
        server.close();
        resolve2(host);
      });
      server.on("error", (err) => {
        if (err.code === "EADDRNOTAVAIL") {
          reject(new Error("主机地址验证失败，可能为非本机地址"));
        } else {
          reject(new Error(`遇到错误: ${err.code}`));
        }
      });
      server.listen(0, host);
    } catch (error) {
      reject(new Error(`服务器启动时发生错误: ${error}`));
    }
  });
}
async function tryUsePort(port, host, tryCount = 0) {
  return new Promise((resolve2, reject) => {
    try {
      const server = net.createServer();
      server.on("listening", () => {
        server.close();
        resolve2(port);
      });
      server.on("error", (err) => {
        if (err.code === "EADDRINUSE") {
          if (tryCount < MAX_PORT_TRY) {
            resolve2(tryUsePort(port + 1, host, tryCount + 1));
          } else {
            reject(new Error(`端口尝试失败，达到最大尝试次数: ${MAX_PORT_TRY}`));
          }
        } else {
          reject(new Error(`遇到错误: ${err.code}`));
        }
      });
      server.listen(port, host);
    } catch (error) {
      reject(new Error(`服务器启动时发生错误: ${error}`));
    }
  });
}

class IOB11NetworkAdapter {
  name;
  isEnable = false;
  config;
  logger;
  core;
  obContext;
  actions;
  constructor(name, config, core, obContext, actions) {
    this.name = name;
    this.config = structuredClone(config);
    this.core = core;
    this.obContext = obContext;
    this.actions = actions;
    this.logger = core.context.logger;
  }
}

class OB11HttpClientAdapter extends IOB11NetworkAdapter {
  async onEvent(event) {
    this.emitEventAsync(event).catch((e) => this.logger.logError("[OneBot] [Http Client] 新消息事件HTTP上报返回快速操作失败", e));
  }
  async emitEventAsync(event) {
    if (!this.isEnable) return;
    const headers = {
      "Content-Type": "application/json",
      "x-self-id": this.core.selfInfo.uin
    };
    const msgStr = JSON.stringify(event);
    if (this.config.token) {
      const hmac = createHmac("sha1", this.config.token);
      hmac.update(msgStr);
      headers["x-signature"] = "sha1=" + hmac.digest("hex");
    }
    const data = await RequestUtil.HttpGetText(this.config.url, "POST", msgStr, headers);
    const resJson = data ? lib$2.parse(data) : {};
    await this.obContext.apis.QuickActionApi.handleQuickOperation(event, resJson);
  }
  open() {
    this.isEnable = true;
  }
  close() {
    this.isEnable = false;
  }
  async reload(newConfig) {
    const wasEnabled = this.isEnable;
    const oldUrl = this.config.url;
    this.config = newConfig;
    if (newConfig.enable && !wasEnabled) {
      this.open();
      return OB11NetworkReloadType.NetWorkOpen;
    } else if (!newConfig.enable && wasEnabled) {
      this.close();
      return OB11NetworkReloadType.NetWorkClose;
    }
    if (oldUrl !== newConfig.url) {
      return OB11NetworkReloadType.NetWorkReload;
    }
    return OB11NetworkReloadType.Normal;
  }
}

class OB11HeartbeatEvent extends OB11BaseMetaEvent {
  meta_event_type = "heartbeat";
  status;
  interval;
  constructor(core, interval, isOnline, isGood) {
    super(core);
    this.interval = interval;
    this.status = {
      online: isOnline,
      good: isGood
    };
  }
}

class OB11WebSocketClientAdapter extends IOB11NetworkAdapter {
  connection = null;
  heartbeatRef = null;
  async onEvent(event) {
    if (this.connection && this.connection.readyState === WebSocket.OPEN) {
      this.connection.send(JSON.stringify(event));
    }
  }
  async open() {
    if (this.connection) {
      return;
    }
    if (this.config.heartInterval > 0) {
      this.heartbeatRef = setInterval(() => {
        if (this.connection && this.connection.readyState === WebSocket.OPEN) {
          this.connection.send(JSON.stringify(new OB11HeartbeatEvent(this.core, this.config.heartInterval, this.core.selfInfo.online ?? true, true)));
        }
      }, this.config.heartInterval);
    }
    this.isEnable = true;
    try {
      await this.tryConnect();
    } catch (error) {
      this.logger.logError("[OneBot] [WebSocket Client] TryConnect Error , info -> ", error);
    }
  }
  close() {
    if (!this.isEnable) {
      this.logger.logDebug("Cannot close a closed WebSocket connection");
      return;
    }
    this.isEnable = false;
    if (this.connection) {
      this.connection.close();
      this.connection = null;
    }
    if (this.heartbeatRef) {
      clearInterval(this.heartbeatRef);
      this.heartbeatRef = null;
    }
  }
  async checkStateAndReply(data) {
    return new Promise((resolve, reject) => {
      if (this.connection && this.connection.readyState === WebSocket.OPEN) {
        this.connection.send(JSON.stringify(data));
        resolve();
      } else {
        reject(new Error("WebSocket is not open"));
      }
    });
  }
  async tryConnect() {
    if (!this.connection && this.isEnable) {
      let isClosedByError = false;
      this.connection = new WebSocket(this.config.url, {
        maxPayload: 1024 * 1024 * 1024,
        handshakeTimeout: 2e3,
        perMessageDeflate: false,
        headers: {
          "X-Self-ID": this.core.selfInfo.uin,
          Authorization: `Bearer ${this.config.token}`,
          "x-client-role": "Universal",
          // 为koishi adpter适配
          "User-Agent": "OneBot/11"
        }
      });
      this.connection.on("ping", () => {
        this.connection?.pong();
      });
      this.connection.on("pong", () => {
      });
      this.connection.on("open", () => {
        try {
          this.connectEvent(this.core).catch((e) => this.logger.logError("[OneBot] [WebSocket Client] 发送连接生命周期失败", e));
        } catch (e) {
          this.logger.logError("[OneBot] [WebSocket Client] 发送连接生命周期失败", e);
        }
      });
      this.connection.on("message", (data) => {
        this.handleMessage(data);
      });
      this.connection.once("close", () => {
        if (!isClosedByError) {
          this.logger.logError(`[OneBot] [WebSocket Client] 反向WebSocket (${this.config.url}) 连接意外关闭`);
          this.logger.logError(`[OneBot] [WebSocket Client] 在 ${Math.floor(this.config.reconnectInterval / 1e3)} 秒后尝试重新连接`);
          if (this.isEnable) {
            this.connection = null;
            setTimeout(() => this.tryConnect(), this.config.reconnectInterval);
          }
        }
      });
      this.connection.on("error", (err) => {
        isClosedByError = true;
        this.logger.logError(`[OneBot] [WebSocket Client] 反向WebSocket (${this.config.url}) 连接错误`, err);
        this.logger.logError(`[OneBot] [WebSocket Client] 在 ${Math.floor(this.config.reconnectInterval / 1e3)} 秒后尝试重新连接`);
        if (this.isEnable) {
          this.connection = null;
          setTimeout(() => this.tryConnect(), this.config.reconnectInterval);
        }
      });
    }
  }
  async connectEvent(core) {
    try {
      await this.checkStateAndReply(new OB11LifeCycleEvent(core, LifeCycleSubType.CONNECT));
    } catch (e) {
      this.logger.logError("[OneBot] [WebSocket Client] 发送生命周期失败", e);
    }
  }
  async handleMessage(message) {
    let receiveData = { action: ActionName.Unknown, params: {} };
    let echo;
    try {
      receiveData = lib$2.parse(message.toString());
      echo = receiveData.echo;
      this.logger.logDebug("[OneBot] [WebSocket Client] 收到正向Websocket消息", receiveData);
    } catch {
      await this.checkStateAndReply(OB11Response.error("json解析失败,请检查数据格式", 1400, echo));
      return;
    }
    receiveData.params = receiveData?.params ? receiveData.params : {};
    const action = this.actions.get(receiveData.action);
    if (!action) {
      this.logger.logError("[OneBot] [WebSocket Client] 发生错误", "不支持的Api " + receiveData.action);
      await this.checkStateAndReply(OB11Response.error("不支持的Api " + receiveData.action, 1404, echo));
      return;
    }
    const retdata = await action.websocketHandle(receiveData.params, echo ?? "", this.name, this.config, {
      send: async (data) => {
        await this.checkStateAndReply({ ...OB11Response.ok(data, echo ?? "", true) });
      }
    });
    await this.checkStateAndReply({ ...retdata });
  }
  async reload(newConfig) {
    const wasEnabled = this.isEnable;
    const oldUrl = this.config.url;
    const oldHeartInterval = this.config.heartInterval;
    this.config = newConfig;
    if (newConfig.enable && !wasEnabled) {
      this.open();
      return OB11NetworkReloadType.NetWorkOpen;
    } else if (!newConfig.enable && wasEnabled) {
      this.close();
      return OB11NetworkReloadType.NetWorkClose;
    }
    if (oldUrl !== newConfig.url) {
      this.close();
      if (newConfig.enable) {
        this.open();
      }
      return OB11NetworkReloadType.NetWorkReload;
    }
    if (oldHeartInterval !== newConfig.heartInterval) {
      if (this.heartbeatRef) {
        clearInterval(this.heartbeatRef);
        this.heartbeatRef = null;
      }
      if (newConfig.heartInterval > 0 && this.isEnable) {
        this.heartbeatRef = setInterval(() => {
          if (this.connection && this.connection.readyState === WebSocket.OPEN) {
            this.connection.send(JSON.stringify(new OB11HeartbeatEvent(this.core, newConfig.heartInterval, this.core.selfInfo.online ?? true, true)));
          }
        }, newConfig.heartInterval);
      }
      return OB11NetworkReloadType.NetWorkReload;
    }
    return OB11NetworkReloadType.Normal;
  }
}

var lib = {exports: {}};

var hasRequiredLib;

function requireLib () {
	if (hasRequiredLib) return lib.exports;
	hasRequiredLib = 1;
	(function () {

	  var assign = requireObjectAssign();
	  var vary = requireVary();

	  var defaults = {
	    origin: '*',
	    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
	    preflightContinue: false,
	    optionsSuccessStatus: 204
	  };

	  function isString(s) {
	    return typeof s === 'string' || s instanceof String;
	  }

	  function isOriginAllowed(origin, allowedOrigin) {
	    if (Array.isArray(allowedOrigin)) {
	      for (var i = 0; i < allowedOrigin.length; ++i) {
	        if (isOriginAllowed(origin, allowedOrigin[i])) {
	          return true;
	        }
	      }
	      return false;
	    } else if (isString(allowedOrigin)) {
	      return origin === allowedOrigin;
	    } else if (allowedOrigin instanceof RegExp) {
	      return allowedOrigin.test(origin);
	    } else {
	      return !!allowedOrigin;
	    }
	  }

	  function configureOrigin(options, req) {
	    var requestOrigin = req.headers.origin,
	      headers = [],
	      isAllowed;

	    if (!options.origin || options.origin === '*') {
	      // allow any origin
	      headers.push([{
	        key: 'Access-Control-Allow-Origin',
	        value: '*'
	      }]);
	    } else if (isString(options.origin)) {
	      // fixed origin
	      headers.push([{
	        key: 'Access-Control-Allow-Origin',
	        value: options.origin
	      }]);
	      headers.push([{
	        key: 'Vary',
	        value: 'Origin'
	      }]);
	    } else {
	      isAllowed = isOriginAllowed(requestOrigin, options.origin);
	      // reflect origin
	      headers.push([{
	        key: 'Access-Control-Allow-Origin',
	        value: isAllowed ? requestOrigin : false
	      }]);
	      headers.push([{
	        key: 'Vary',
	        value: 'Origin'
	      }]);
	    }

	    return headers;
	  }

	  function configureMethods(options) {
	    var methods = options.methods;
	    if (methods.join) {
	      methods = options.methods.join(','); // .methods is an array, so turn it into a string
	    }
	    return {
	      key: 'Access-Control-Allow-Methods',
	      value: methods
	    };
	  }

	  function configureCredentials(options) {
	    if (options.credentials === true) {
	      return {
	        key: 'Access-Control-Allow-Credentials',
	        value: 'true'
	      };
	    }
	    return null;
	  }

	  function configureAllowedHeaders(options, req) {
	    var allowedHeaders = options.allowedHeaders || options.headers;
	    var headers = [];

	    if (!allowedHeaders) {
	      allowedHeaders = req.headers['access-control-request-headers']; // .headers wasn't specified, so reflect the request headers
	      headers.push([{
	        key: 'Vary',
	        value: 'Access-Control-Request-Headers'
	      }]);
	    } else if (allowedHeaders.join) {
	      allowedHeaders = allowedHeaders.join(','); // .headers is an array, so turn it into a string
	    }
	    if (allowedHeaders && allowedHeaders.length) {
	      headers.push([{
	        key: 'Access-Control-Allow-Headers',
	        value: allowedHeaders
	      }]);
	    }

	    return headers;
	  }

	  function configureExposedHeaders(options) {
	    var headers = options.exposedHeaders;
	    if (!headers) {
	      return null;
	    } else if (headers.join) {
	      headers = headers.join(','); // .headers is an array, so turn it into a string
	    }
	    if (headers && headers.length) {
	      return {
	        key: 'Access-Control-Expose-Headers',
	        value: headers
	      };
	    }
	    return null;
	  }

	  function configureMaxAge(options) {
	    var maxAge = (typeof options.maxAge === 'number' || options.maxAge) && options.maxAge.toString();
	    if (maxAge && maxAge.length) {
	      return {
	        key: 'Access-Control-Max-Age',
	        value: maxAge
	      };
	    }
	    return null;
	  }

	  function applyHeaders(headers, res) {
	    for (var i = 0, n = headers.length; i < n; i++) {
	      var header = headers[i];
	      if (header) {
	        if (Array.isArray(header)) {
	          applyHeaders(header, res);
	        } else if (header.key === 'Vary' && header.value) {
	          vary(res, header.value);
	        } else if (header.value) {
	          res.setHeader(header.key, header.value);
	        }
	      }
	    }
	  }

	  function cors(options, req, res, next) {
	    var headers = [],
	      method = req.method && req.method.toUpperCase && req.method.toUpperCase();

	    if (method === 'OPTIONS') {
	      // preflight
	      headers.push(configureOrigin(options, req));
	      headers.push(configureCredentials(options));
	      headers.push(configureMethods(options));
	      headers.push(configureAllowedHeaders(options, req));
	      headers.push(configureMaxAge(options));
	      headers.push(configureExposedHeaders(options));
	      applyHeaders(headers, res);

	      if (options.preflightContinue) {
	        next();
	      } else {
	        // Safari (and potentially other browsers) need content-length 0,
	        //   for 204 or they just hang waiting for a body
	        res.statusCode = options.optionsSuccessStatus;
	        res.setHeader('Content-Length', '0');
	        res.end();
	      }
	    } else {
	      // actual response
	      headers.push(configureOrigin(options, req));
	      headers.push(configureCredentials(options));
	      headers.push(configureExposedHeaders(options));
	      applyHeaders(headers, res);
	      next();
	    }
	  }

	  function middlewareWrapper(o) {
	    // if options are static (either via defaults or custom options passed in), wrap in a function
	    var optionsCallback = null;
	    if (typeof o === 'function') {
	      optionsCallback = o;
	    } else {
	      optionsCallback = function (req, cb) {
	        cb(null, o);
	      };
	    }

	    return function corsMiddleware(req, res, next) {
	      optionsCallback(req, function (err, options) {
	        if (err) {
	          next(err);
	        } else {
	          var corsOptions = assign({}, defaults, options);
	          var originCallback = null;
	          if (corsOptions.origin && typeof corsOptions.origin === 'function') {
	            originCallback = corsOptions.origin;
	          } else if (corsOptions.origin) {
	            originCallback = function (origin, cb) {
	              cb(null, corsOptions.origin);
	            };
	          }

	          if (originCallback) {
	            originCallback(req.headers.origin, function (err2, origin) {
	              if (err2 || !origin) {
	                next(err2);
	              } else {
	                corsOptions.origin = origin;
	                cors(corsOptions, req, res, next);
	              }
	            });
	          } else {
	            next();
	          }
	        }
	      });
	    };
	  }

	  // can pass either an options hash, an options delegate, or nothing
	  lib.exports = middlewareWrapper;

	}());
	return lib.exports;
}

var libExports = requireLib();
const cors = /*@__PURE__*/getDefaultExportFromCjs(libExports);

var onFinished = {exports: {}};

/*!
 * ee-first
 * Copyright(c) 2014 Jonathan Ong
 * MIT Licensed
 */

var eeFirst;
var hasRequiredEeFirst;

function requireEeFirst () {
	if (hasRequiredEeFirst) return eeFirst;
	hasRequiredEeFirst = 1;

	/**
	 * Module exports.
	 * @public
	 */

	eeFirst = first;

	/**
	 * Get the first event in a set of event emitters and event pairs.
	 *
	 * @param {array} stuff
	 * @param {function} done
	 * @public
	 */

	function first(stuff, done) {
	  if (!Array.isArray(stuff))
	    throw new TypeError('arg must be an array of [ee, events...] arrays')

	  var cleanups = [];

	  for (var i = 0; i < stuff.length; i++) {
	    var arr = stuff[i];

	    if (!Array.isArray(arr) || arr.length < 2)
	      throw new TypeError('each array member must be [ee, events...]')

	    var ee = arr[0];

	    for (var j = 1; j < arr.length; j++) {
	      var event = arr[j];
	      var fn = listener(event, callback);

	      // listen to the event
	      ee.on(event, fn);
	      // push this listener to the list of cleanups
	      cleanups.push({
	        ee: ee,
	        event: event,
	        fn: fn,
	      });
	    }
	  }

	  function callback() {
	    cleanup();
	    done.apply(null, arguments);
	  }

	  function cleanup() {
	    var x;
	    for (var i = 0; i < cleanups.length; i++) {
	      x = cleanups[i];
	      x.ee.removeListener(x.event, x.fn);
	    }
	  }

	  function thunk(fn) {
	    done = fn;
	  }

	  thunk.cancel = cleanup;

	  return thunk
	}

	/**
	 * Create the event listener.
	 * @private
	 */

	function listener(event, done) {
	  return function onevent(arg1) {
	    var args = new Array(arguments.length);
	    var ee = this;
	    var err = event === 'error'
	      ? arg1
	      : null;

	    // copy args to prevent arguments escaping scope
	    for (var i = 0; i < args.length; i++) {
	      args[i] = arguments[i];
	    }

	    done(err, ee, event, args);
	  }
	}
	return eeFirst;
}

/*!
 * on-finished
 * Copyright(c) 2013 Jonathan Ong
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */

var hasRequiredOnFinished;

function requireOnFinished () {
	if (hasRequiredOnFinished) return onFinished.exports;
	hasRequiredOnFinished = 1;

	/**
	 * Module exports.
	 * @public
	 */

	onFinished.exports = onFinished$1;
	onFinished.exports.isFinished = isFinished;

	/**
	 * Module dependencies.
	 * @private
	 */

	var asyncHooks = tryRequireAsyncHooks();
	var first = requireEeFirst();

	/**
	 * Variables.
	 * @private
	 */

	/* istanbul ignore next */
	var defer = typeof setImmediate === 'function'
	  ? setImmediate
	  : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)); };

	/**
	 * Invoke callback when the response has finished, useful for
	 * cleaning up resources afterwards.
	 *
	 * @param {object} msg
	 * @param {function} listener
	 * @return {object}
	 * @public
	 */

	function onFinished$1 (msg, listener) {
	  if (isFinished(msg) !== false) {
	    defer(listener, null, msg);
	    return msg
	  }

	  // attach the listener to the message
	  attachListener(msg, wrap(listener));

	  return msg
	}

	/**
	 * Determine if message is already finished.
	 *
	 * @param {object} msg
	 * @return {boolean}
	 * @public
	 */

	function isFinished (msg) {
	  var socket = msg.socket;

	  if (typeof msg.finished === 'boolean') {
	    // OutgoingMessage
	    return Boolean(msg.finished || (socket && !socket.writable))
	  }

	  if (typeof msg.complete === 'boolean') {
	    // IncomingMessage
	    return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable))
	  }

	  // don't know
	  return undefined
	}

	/**
	 * Attach a finished listener to the message.
	 *
	 * @param {object} msg
	 * @param {function} callback
	 * @private
	 */

	function attachFinishedListener (msg, callback) {
	  var eeMsg;
	  var eeSocket;
	  var finished = false;

	  function onFinish (error) {
	    eeMsg.cancel();
	    eeSocket.cancel();

	    finished = true;
	    callback(error);
	  }

	  // finished on first message event
	  eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish);

	  function onSocket (socket) {
	    // remove listener
	    msg.removeListener('socket', onSocket);

	    if (finished) return
	    if (eeMsg !== eeSocket) return

	    // finished on first socket event
	    eeSocket = first([[socket, 'error', 'close']], onFinish);
	  }

	  if (msg.socket) {
	    // socket already assigned
	    onSocket(msg.socket);
	    return
	  }

	  // wait for socket to be assigned
	  msg.on('socket', onSocket);

	  if (msg.socket === undefined) {
	    // istanbul ignore next: node.js 0.8 patch
	    patchAssignSocket(msg, onSocket);
	  }
	}

	/**
	 * Attach the listener to the message.
	 *
	 * @param {object} msg
	 * @return {function}
	 * @private
	 */

	function attachListener (msg, listener) {
	  var attached = msg.__onFinished;

	  // create a private single listener with queue
	  if (!attached || !attached.queue) {
	    attached = msg.__onFinished = createListener(msg);
	    attachFinishedListener(msg, attached);
	  }

	  attached.queue.push(listener);
	}

	/**
	 * Create listener on message.
	 *
	 * @param {object} msg
	 * @return {function}
	 * @private
	 */

	function createListener (msg) {
	  function listener (err) {
	    if (msg.__onFinished === listener) msg.__onFinished = null;
	    if (!listener.queue) return

	    var queue = listener.queue;
	    listener.queue = null;

	    for (var i = 0; i < queue.length; i++) {
	      queue[i](err, msg);
	    }
	  }

	  listener.queue = [];

	  return listener
	}

	/**
	 * Patch ServerResponse.prototype.assignSocket for node.js 0.8.
	 *
	 * @param {ServerResponse} res
	 * @param {function} callback
	 * @private
	 */

	// istanbul ignore next: node.js 0.8 patch
	function patchAssignSocket (res, callback) {
	  var assignSocket = res.assignSocket;

	  if (typeof assignSocket !== 'function') return

	  // res.on('socket', callback) is broken in 0.8
	  res.assignSocket = function _assignSocket (socket) {
	    assignSocket.call(this, socket);
	    callback(socket);
	  };
	}

	/**
	 * Try to require async_hooks
	 * @private
	 */

	function tryRequireAsyncHooks () {
	  try {
	    return require('async_hooks')
	  } catch (e) {
	    return {}
	  }
	}

	/**
	 * Wrap function with async resource, if possible.
	 * AsyncResource.bind static method backported.
	 * @private
	 */

	function wrap (fn) {
	  var res;

	  // create anonymous resource
	  if (asyncHooks.AsyncResource) {
	    res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn');
	  }

	  // incompatible node.js
	  if (!res || !res.runInAsyncScope) {
	    return fn
	  }

	  // return bound function
	  return res.runInAsyncScope.bind(res, fn, null)
	}
	return onFinished.exports;
}

var onFinishedExports = requireOnFinished();

var typeIsExports = requireTypeIs();
const typeis = /*@__PURE__*/getDefaultExportFromCjs(typeIsExports);

class OB11HttpServerAdapter extends IOB11NetworkAdapter {
  app;
  server;
  async onEvent(_event) {
  }
  open() {
    try {
      if (this.isEnable) {
        this.core.context.logger.logError("Cannot open a closed HTTP server");
        return;
      }
      if (!this.isEnable) {
        this.initializeServer();
        this.isEnable = true;
      }
    } catch (e) {
      this.core.context.logger.logError(`[OneBot] [HTTP Server Adapter] Boot Error: ${e}`);
    }
  }
  async close() {
    this.isEnable = false;
    this.server?.close();
    this.app = void 0;
  }
  initializeServer() {
    this.app = express();
    this.server = require$$0$8.createServer(this.app);
    this.app.use(cors());
    this.app.use(express.urlencoded({ extended: true, limit: "5000mb" }));
    this.app.use((req, res, next) => {
      if (onFinishedExports.isFinished(req)) {
        next();
        return;
      }
      if (!typeis.hasBody(req)) {
        next();
        return;
      }
      req.headers["content-type"] = "application/json";
      let rawData = "";
      req.on("data", (chunk) => {
        rawData += chunk;
      });
      req.on("end", () => {
        try {
          req.body = { ...lib$2.parse(rawData || "{}"), ...req.body };
          next();
        } catch {
          res.status(400).send("Invalid JSON");
        }
      });
      req.on("error", () => {
        return res.status(400).send("Invalid JSON");
      });
    });
    this.app.use((req, res, next) => this.authorize(this.config.token, req, res, next));
    this.app.use(async (req, res) => {
      await this.handleRequest(req, res);
    });
    this.server.listen(this.config.port, this.config.host, () => {
      this.core.context.logger.log(`[OneBot] [HTTP Server Adapter] Start On ${this.config.host}:${this.config.port}`);
    });
  }
  authorize(token, req, res, next) {
    if (!token || token.length === 0) return next();
    const HeaderClientToken = req.headers.authorization?.split("Bearer ").pop() || "";
    const QueryClientToken = req.query["access_token"];
    const ClientToken = typeof QueryClientToken === "string" && QueryClientToken !== "" ? QueryClientToken : HeaderClientToken;
    if (ClientToken === token) {
      return next();
    } else {
      return res.status(403).send(JSON.stringify({ message: "token verify failed!" }));
    }
  }
  async httpApiRequest(req, res, request_sse = false) {
    let payload = req.body;
    if (req.method === "get") {
      payload = req.query;
    } else if (req.query) {
      payload = { ...req.body, ...req.query };
    }
    if (req.path === "" || req.path === "/") {
      const hello = OB11Response.ok({});
      hello.message = "NapCat4 Is Running";
      return res.json(hello);
    }
    const actionName = req.path.split("/")[1];
    const payload_echo = payload["echo"];
    const real_echo = payload_echo ?? Math.random().toString(36).substring(2, 15);
    const action = this.actions.get(actionName);
    if (action) {
      const useStream = action.useStream;
      try {
        const result = await action.handle(payload, this.name, this.config, {
          send: request_sse ? async (data) => {
            await this.onEvent({ ...OB11Response.ok(data, real_echo, true) });
          } : async (data) => {
            const newPromise = new Promise((resolve, _reject) => {
              res.write(JSON.stringify({ ...OB11Response.ok(data, real_echo, true) }) + "\r\n\r\n", () => {
                resolve();
              });
            });
            return newPromise;
          }
        }, real_echo);
        if (useStream) {
          res.write(JSON.stringify({ ...result }) + "\r\n\r\n");
          return res.end();
        }
        return res.json(result);
      } catch (error) {
        return res.json(OB11Response.error(error?.stack?.toString() || error?.message || "Error Handle", 200, real_echo));
      }
    } else {
      return res.json(OB11Response.error("不支持的Api " + actionName, 200, real_echo));
    }
  }
  async handleRequest(req, res) {
    if (!this.isEnable) {
      this.core.context.logger.log("[OneBot] [HTTP Server Adapter] Server is closed");
      res.json(OB11Response.error("Server is closed", 200));
      return;
    }
    this.httpApiRequest(req, res);
  }
  async reload(newConfig) {
    const wasEnabled = this.isEnable;
    const oldPort = this.config.port;
    this.config = newConfig;
    if (newConfig.enable && !wasEnabled) {
      this.open();
      return OB11NetworkReloadType.NetWorkOpen;
    } else if (!newConfig.enable && wasEnabled) {
      this.close();
      return OB11NetworkReloadType.NetWorkClose;
    }
    if (oldPort !== newConfig.port) {
      this.close();
      if (newConfig.enable) {
        this.open();
      }
      return OB11NetworkReloadType.NetWorkReload;
    }
    return OB11NetworkReloadType.Normal;
  }
}

const E_CANCELED = new Error('request for lock canceled');

var __awaiter$2 = function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
class Semaphore {
    constructor(_value, _cancelError = E_CANCELED) {
        this._value = _value;
        this._cancelError = _cancelError;
        this._queue = [];
        this._weightedWaiters = [];
    }
    acquire(weight = 1, priority = 0) {
        if (weight <= 0)
            throw new Error(`invalid weight ${weight}: must be positive`);
        return new Promise((resolve, reject) => {
            const task = { resolve, reject, weight, priority };
            const i = findIndexFromEnd(this._queue, (other) => priority <= other.priority);
            if (i === -1 && weight <= this._value) {
                // Needs immediate dispatch, skip the queue
                this._dispatchItem(task);
            }
            else {
                this._queue.splice(i + 1, 0, task);
            }
        });
    }
    runExclusive(callback_1) {
        return __awaiter$2(this, arguments, void 0, function* (callback, weight = 1, priority = 0) {
            const [value, release] = yield this.acquire(weight, priority);
            try {
                return yield callback(value);
            }
            finally {
                release();
            }
        });
    }
    waitForUnlock(weight = 1, priority = 0) {
        if (weight <= 0)
            throw new Error(`invalid weight ${weight}: must be positive`);
        if (this._couldLockImmediately(weight, priority)) {
            return Promise.resolve();
        }
        else {
            return new Promise((resolve) => {
                if (!this._weightedWaiters[weight - 1])
                    this._weightedWaiters[weight - 1] = [];
                insertSorted(this._weightedWaiters[weight - 1], { resolve, priority });
            });
        }
    }
    isLocked() {
        return this._value <= 0;
    }
    getValue() {
        return this._value;
    }
    setValue(value) {
        this._value = value;
        this._dispatchQueue();
    }
    release(weight = 1) {
        if (weight <= 0)
            throw new Error(`invalid weight ${weight}: must be positive`);
        this._value += weight;
        this._dispatchQueue();
    }
    cancel() {
        this._queue.forEach((entry) => entry.reject(this._cancelError));
        this._queue = [];
    }
    _dispatchQueue() {
        this._drainUnlockWaiters();
        while (this._queue.length > 0 && this._queue[0].weight <= this._value) {
            this._dispatchItem(this._queue.shift());
            this._drainUnlockWaiters();
        }
    }
    _dispatchItem(item) {
        const previousValue = this._value;
        this._value -= item.weight;
        item.resolve([previousValue, this._newReleaser(item.weight)]);
    }
    _newReleaser(weight) {
        let called = false;
        return () => {
            if (called)
                return;
            called = true;
            this.release(weight);
        };
    }
    _drainUnlockWaiters() {
        if (this._queue.length === 0) {
            for (let weight = this._value; weight > 0; weight--) {
                const waiters = this._weightedWaiters[weight - 1];
                if (!waiters)
                    continue;
                waiters.forEach((waiter) => waiter.resolve());
                this._weightedWaiters[weight - 1] = [];
            }
        }
        else {
            const queuedPriority = this._queue[0].priority;
            for (let weight = this._value; weight > 0; weight--) {
                const waiters = this._weightedWaiters[weight - 1];
                if (!waiters)
                    continue;
                const i = waiters.findIndex((waiter) => waiter.priority <= queuedPriority);
                (i === -1 ? waiters : waiters.splice(0, i))
                    .forEach((waiter => waiter.resolve()));
            }
        }
    }
    _couldLockImmediately(weight, priority) {
        return (this._queue.length === 0 || this._queue[0].priority < priority) &&
            weight <= this._value;
    }
}
function insertSorted(a, v) {
    const i = findIndexFromEnd(a, (other) => v.priority <= other.priority);
    a.splice(i + 1, 0, v);
}
function findIndexFromEnd(a, predicate) {
    for (let i = a.length - 1; i >= 0; i--) {
        if (predicate(a[i])) {
            return i;
        }
    }
    return -1;
}

var __awaiter$1 = function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
class Mutex {
    constructor(cancelError) {
        this._semaphore = new Semaphore(1, cancelError);
    }
    acquire() {
        return __awaiter$1(this, arguments, void 0, function* (priority = 0) {
            const [, releaser] = yield this._semaphore.acquire(1, priority);
            return releaser;
        });
    }
    runExclusive(callback, priority = 0) {
        return this._semaphore.runExclusive(() => callback(), 1, priority);
    }
    isLocked() {
        return this._semaphore.isLocked();
    }
    waitForUnlock(priority = 0) {
        return this._semaphore.waitForUnlock(1, priority);
    }
    release() {
        if (this._semaphore.isLocked())
            this._semaphore.release();
    }
    cancel() {
        return this._semaphore.cancel();
    }
}

class OB11WebSocketServerAdapter extends IOB11NetworkAdapter {
  wsServer;
  wsClients = [];
  wsClientsMutex = new Mutex();
  heartbeatIntervalId = null;
  wsClientWithEvent = [];
  constructor(name, config, core, obContext, actions) {
    super(name, config, core, obContext, actions);
    this.wsServer = new WebSocketServer({
      port: this.config.port,
      host: this.config.host === "0.0.0.0" ? "" : this.config.host,
      maxPayload: 1024 * 1024 * 1024
    });
    this.createServer(this.wsServer);
  }
  createServer(newServer) {
    newServer.on("connection", async (wsClient, wsReq) => {
      if (!this.isEnable) {
        wsClient.close();
        return;
      }
      if (!this.authorize(this.config.token, wsClient, wsReq)) {
        return;
      }
      const paramUrl = wsReq.url?.indexOf("?") !== -1 ? wsReq.url?.substring(0, wsReq.url?.indexOf("?")) : wsReq.url;
      const isApiConnect = paramUrl === "/api" || paramUrl === "/api/";
      if (!isApiConnect) {
        this.connectEvent(this.core, wsClient);
      }
      wsClient.on("error", (err) => this.logger.log("[OneBot] [WebSocket Server] Client Error:", err.message));
      wsClient.on("message", (message) => {
        this.handleMessage(wsClient, message).then().catch((e) => this.logger.logError(e));
      });
      wsClient.on("ping", () => {
        wsClient.pong();
      });
      wsClient.on("pong", () => {
      });
      wsClient.once("close", () => {
        this.wsClientsMutex.runExclusive(async () => {
          const NormolIndex = this.wsClients.indexOf(wsClient);
          if (NormolIndex !== -1) {
            this.wsClients.splice(NormolIndex, 1);
          }
          const EventIndex = this.wsClientWithEvent.indexOf(wsClient);
          if (EventIndex !== -1) {
            this.wsClientWithEvent.splice(EventIndex, 1);
          }
        });
      });
      await this.wsClientsMutex.runExclusive(async () => {
        if (!isApiConnect) {
          this.wsClientWithEvent.push(wsClient);
        }
        this.wsClients.push(wsClient);
      });
    }).on("error", (err) => this.logger.log("[OneBot] [WebSocket Server] Server Error:", err.message));
  }
  connectEvent(core, wsClient) {
    try {
      this.checkStateAndReply(new OB11LifeCycleEvent(core, LifeCycleSubType.CONNECT), wsClient).catch((e) => this.logger.logError("[OneBot] [WebSocket Server] 发送生命周期失败", e));
    } catch (e) {
      this.logger.logError("[OneBot] [WebSocket Server] 发送生命周期失败", e);
    }
  }
  async onEvent(event) {
    this.wsClientsMutex.runExclusive(async () => {
      const promises = this.wsClientWithEvent.map((wsClient) => {
        return new Promise((resolve, reject) => {
          if (wsClient.readyState === WebSocket.OPEN) {
            wsClient.send(JSON.stringify(event));
            resolve();
          } else {
            reject(new Error("WebSocket is not open"));
          }
        });
      });
      await Promise.allSettled(promises);
    });
  }
  open() {
    if (this.isEnable) {
      this.logger.logError("[OneBot] [WebSocket Server] Cannot open a opened WebSocket server");
      return;
    }
    const addressInfo = this.wsServer?.address();
    this.logger.log("[OneBot] [WebSocket Server] Server Started", typeof addressInfo === "string" ? addressInfo : addressInfo?.address + ":" + addressInfo?.port);
    this.isEnable = true;
    if (this.config.heartInterval > 0) {
      this.registerHeartBeat();
    }
  }
  async close() {
    this.isEnable = false;
    this.wsServer?.close((err) => {
      if (err) {
        this.logger.logError("[OneBot] [WebSocket Server] Error closing server:", err.message);
      } else {
        this.logger.log("[OneBot] [WebSocket Server] Server Closed");
      }
    });
    if (this.heartbeatIntervalId) {
      clearInterval(this.heartbeatIntervalId);
      this.heartbeatIntervalId = null;
    }
    await this.wsClientsMutex.runExclusive(async () => {
      this.wsClients.forEach((wsClient) => {
        wsClient.close();
      });
      this.wsClients = [];
      this.wsClientWithEvent = [];
    });
  }
  registerHeartBeat() {
    this.heartbeatIntervalId = setInterval(() => {
      this.wsClientsMutex.runExclusive(async () => {
        this.wsClientWithEvent.forEach((wsClient) => {
          if (wsClient.readyState === WebSocket.OPEN) {
            wsClient.send(JSON.stringify(new OB11HeartbeatEvent(this.core, this.config.heartInterval, this.core.selfInfo.online ?? true, true)));
          }
        });
      });
    }, this.config.heartInterval);
  }
  authorize(token, wsClient, wsReq) {
    if (!token || token.length === 0) return true;
    const url = new URL$2(wsReq?.url || "", `http://${wsReq.headers.host}`);
    const QueryClientToken = url.searchParams.get("access_token");
    const HeaderClientToken = wsReq.headers.authorization?.split("Bearer ").pop() || "";
    const ClientToken = typeof QueryClientToken === "string" && QueryClientToken !== "" ? QueryClientToken : HeaderClientToken;
    if (ClientToken === token) {
      return true;
    }
    wsClient.send(JSON.stringify(OB11Response.res(null, "failed", 1403, "token验证失败")));
    wsClient.close();
    return false;
  }
  async checkStateAndReply(data, wsClient) {
    return await new Promise((resolve, reject) => {
      if (wsClient.readyState === WebSocket.OPEN) {
        wsClient.send(JSON.stringify(data));
        resolve();
      } else {
        reject(new Error("WebSocket is not open"));
      }
    });
  }
  async handleMessage(wsClient, message) {
    let receiveData = { action: ActionName.Unknown, params: {} };
    let echo;
    try {
      receiveData = lib$2.parse(message.toString());
      echo = receiveData.echo;
    } catch {
      await this.checkStateAndReply(OB11Response.error("json解析失败,请检查数据格式", 1400, echo), wsClient);
      return;
    }
    receiveData.params = receiveData?.params ? receiveData.params : {};
    const action = this.actions.get(receiveData.action);
    if (!action) {
      this.logger.logError("[OneBot] [WebSocket Client] 发生错误", "不支持的API " + receiveData.action);
      await this.checkStateAndReply(OB11Response.error("不支持的API " + receiveData.action, 1404, echo), wsClient);
      return;
    }
    const retdata = await action.websocketHandle(receiveData.params, echo ?? "", this.name, this.config, {
      send: async (data) => {
        await this.checkStateAndReply({ ...OB11Response.ok(data, echo ?? "", true) }, wsClient);
      }
    });
    await this.checkStateAndReply({ ...retdata }, wsClient);
  }
  async reload(newConfig) {
    const wasEnabled = this.isEnable;
    const oldPort = this.config.port;
    const oldHost = this.config.host;
    const oldHeartbeatInterval = this.config.heartInterval;
    this.config = newConfig;
    if (newConfig.enable && !wasEnabled) {
      this.open();
      return OB11NetworkReloadType.NetWorkOpen;
    } else if (!newConfig.enable && wasEnabled) {
      this.close();
      return OB11NetworkReloadType.NetWorkClose;
    }
    if (oldPort !== newConfig.port || oldHost !== newConfig.host) {
      this.close();
      this.wsServer = new WebSocketServer({
        port: newConfig.port,
        host: newConfig.host === "0.0.0.0" ? "" : newConfig.host,
        maxPayload: 1024 * 1024 * 1024
      });
      this.createServer(this.wsServer);
      if (newConfig.enable) {
        this.open();
      }
      return OB11NetworkReloadType.NetWorkReload;
    }
    if (oldHeartbeatInterval !== newConfig.heartInterval) {
      if (this.heartbeatIntervalId) {
        clearInterval(this.heartbeatIntervalId);
        this.heartbeatIntervalId = null;
      }
      if (newConfig.heartInterval > 0 && this.isEnable) {
        this.registerHeartBeat();
      }
      return OB11NetworkReloadType.NetWorkReload;
    }
    return OB11NetworkReloadType.Normal;
  }
}

var OB11NetworkReloadType = /* @__PURE__ */ ((OB11NetworkReloadType2) => {
  OB11NetworkReloadType2[OB11NetworkReloadType2["Normal"] = 0] = "Normal";
  OB11NetworkReloadType2[OB11NetworkReloadType2["ConfigChange"] = 1] = "ConfigChange";
  OB11NetworkReloadType2[OB11NetworkReloadType2["NetWorkReload"] = 2] = "NetWorkReload";
  OB11NetworkReloadType2[OB11NetworkReloadType2["NetWorkClose"] = 3] = "NetWorkClose";
  OB11NetworkReloadType2[OB11NetworkReloadType2["NetWorkOpen"] = 4] = "NetWorkOpen";
  return OB11NetworkReloadType2;
})(OB11NetworkReloadType || {});
class OB11NetworkManager {
  adapters = /* @__PURE__ */ new Map();
  async openAllAdapters() {
    return Promise.all(Array.from(this.adapters.values()).map((adapter) => adapter.open()));
  }
  async emitEvent(event) {
    return Promise.all(Array.from(this.adapters.values()).map(async (adapter) => {
      if (adapter.isEnable) {
        return await adapter.onEvent(event);
      }
    }));
  }
  async emitEvents(events) {
    return Promise.all(events.map((event) => this.emitEvent(event)));
  }
  async emitEventByName(names, event) {
    return Promise.all(names.map(async (name) => {
      const adapter = this.adapters.get(name);
      if (adapter && adapter.isEnable) {
        return await adapter.onEvent(event);
      }
    }));
  }
  async emitEventByNames(map) {
    return Promise.all(Array.from(map.entries()).map(async ([name, event]) => {
      const adapter = this.adapters.get(name);
      if (adapter && adapter.isEnable) {
        return await adapter.onEvent(event);
      }
    }));
  }
  registerAdapter(adapter) {
    this.adapters.set(adapter.name, adapter);
  }
  async registerAdapterAndOpen(adapter) {
    this.registerAdapter(adapter);
    await adapter.open();
  }
  async closeSomeAdapters(adaptersToClose) {
    for (const adapter of adaptersToClose) {
      this.adapters.delete(adapter.name);
      await adapter.close();
    }
  }
  async closeSomeAdaterWhenOpen(adaptersToClose) {
    for (const adapter of adaptersToClose) {
      this.adapters.delete(adapter.name);
      if (adapter.isEnable) {
        await adapter.close();
      }
    }
  }
  findSomeAdapter(name) {
    return this.adapters.get(name);
  }
  async closeAdapterByPredicate(closeFilter) {
    const adaptersToClose = Array.from(this.adapters.values()).filter(closeFilter);
    await this.closeSomeAdapters(adaptersToClose);
  }
  async closeAllAdapters() {
    await Promise.all(Array.from(this.adapters.values()).map((adapter) => adapter.close()));
    this.adapters.clear();
  }
  async readloadAdapter(name, config) {
    const adapter = this.adapters.get(name);
    if (adapter) {
      await adapter.reload(config);
    }
  }
  async readloadSomeAdapters(configMap) {
    await Promise.all(Array.from(configMap.entries()).map(([name, config]) => this.readloadAdapter(name, config)));
  }
  async getAllConfig() {
    return Array.from(this.adapters.values()).map((adapter) => adapter.config);
  }
}

class OB11BaseNoticeEvent extends OneBotEvent {
  post_type = EventType.NOTICE;
}

class OB11PokeEvent extends OB11BaseNoticeEvent {
  notice_type = "notify";
  sub_type = "poke";
  target_id = 0;
  user_id = 0;
}
class OB11FriendPokeEvent extends OB11PokeEvent {
  raw_info;
  sender_id;
  // raw_message nb等框架标准为string
  constructor(core, user_id, sender_id, target_id, raw_message) {
    super(core);
    this.target_id = target_id;
    this.user_id = user_id;
    this.sender_id = sender_id;
    this.raw_info = raw_message;
  }
}
class OB11GroupPokeEvent extends OB11PokeEvent {
  group_id;
  raw_info;
  // raw_message nb等框架标准为string
  constructor(core, group_id, user_id, target_id, raw_message) {
    super(core);
    this.group_id = group_id;
    this.target_id = target_id;
    this.user_id = user_id;
    this.raw_info = raw_message;
  }
}

class OneBotFriendApi {
  obContext;
  core;
  constructor(obContext, core) {
    this.obContext = obContext;
    this.core = core;
  }
  // 使用前预先判断 busiId 1061
  async parsePrivatePokeEvent(grayTipElement, uin) {
    const json = JSON.parse(grayTipElement.jsonGrayTipElement.jsonStr);
    const pokedetail = json.items;
    const poke_uid = pokedetail.filter((item) => item.uid);
    if (poke_uid.length === 2 && poke_uid[0]?.uid && poke_uid[1]?.uid) {
      return new OB11FriendPokeEvent(
        this.core,
        uin,
        parseInt(await this.core.apis.UserApi.getUinByUidV2(poke_uid[0].uid)),
        parseInt(await this.core.apis.UserApi.getUinByUidV2(poke_uid[1].uid)),
        pokedetail
      );
    }
    return void 0;
  }
}

class OB11GroupNoticeEvent extends OB11BaseNoticeEvent {
  group_id;
  user_id;
  constructor(core, group_id, user_id) {
    super(core);
    this.group_id = group_id;
    this.user_id = user_id;
  }
}

class OB11GroupBanEvent extends OB11GroupNoticeEvent {
  notice_type = "group_ban";
  operator_id;
  duration;
  sub_type;
  constructor(core, groupId, userId, operatorId, duration, sub_type) {
    super(core, groupId, userId);
    this.group_id = groupId;
    this.operator_id = operatorId;
    this.user_id = userId;
    this.duration = duration;
    this.sub_type = sub_type;
  }
}

var validator = {};

var util = {};

var hasRequiredUtil;

function requireUtil () {
	if (hasRequiredUtil) return util;
	hasRequiredUtil = 1;
	(function (exports$1) {

		const nameStartChar = ':A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD';
		const nameChar = nameStartChar + '\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040';
		const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*';
		const regexName = new RegExp('^' + nameRegexp + '$');

		const getAllMatches = function(string, regex) {
		  const matches = [];
		  let match = regex.exec(string);
		  while (match) {
		    const allmatches = [];
		    allmatches.startIndex = regex.lastIndex - match[0].length;
		    const len = match.length;
		    for (let index = 0; index < len; index++) {
		      allmatches.push(match[index]);
		    }
		    matches.push(allmatches);
		    match = regex.exec(string);
		  }
		  return matches;
		};

		const isName = function(string) {
		  const match = regexName.exec(string);
		  return !(match === null || typeof match === 'undefined');
		};

		exports$1.isExist = function(v) {
		  return typeof v !== 'undefined';
		};

		exports$1.isEmptyObject = function(obj) {
		  return Object.keys(obj).length === 0;
		};

		/**
		 * Copy all the properties of a into b.
		 * @param {*} target
		 * @param {*} a
		 */
		exports$1.merge = function(target, a, arrayMode) {
		  if (a) {
		    const keys = Object.keys(a); // will return an array of own properties
		    const len = keys.length; //don't make it inline
		    for (let i = 0; i < len; i++) {
		      if (arrayMode === 'strict') {
		        target[keys[i]] = [ a[keys[i]] ];
		      } else {
		        target[keys[i]] = a[keys[i]];
		      }
		    }
		  }
		};
		/* exports.merge =function (b,a){
		  return Object.assign(b,a);
		} */

		exports$1.getValue = function(v) {
		  if (exports$1.isExist(v)) {
		    return v;
		  } else {
		    return '';
		  }
		};

		// const fakeCall = function(a) {return a;};
		// const fakeCallNoReturn = function() {};

		exports$1.isName = isName;
		exports$1.getAllMatches = getAllMatches;
		exports$1.nameRegexp = nameRegexp; 
	} (util));
	return util;
}

var hasRequiredValidator;

function requireValidator () {
	if (hasRequiredValidator) return validator;
	hasRequiredValidator = 1;

	const util = requireUtil();

	const defaultOptions = {
	  allowBooleanAttributes: false, //A tag can have attributes without any value
	  unpairedTags: []
	};

	//const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g");
	validator.validate = function (xmlData, options) {
	  options = Object.assign({}, defaultOptions, options);

	  //xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line
	  //xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag
	  //xmlData = xmlData.replace(/(<!DOCTYPE[\s\w\"\.\/\-\:]+(\[.*\])*\s*>)/g,"");//Remove DOCTYPE
	  const tags = [];
	  let tagFound = false;

	  //indicates that the root tag has been closed (aka. depth 0 has been reached)
	  let reachedRoot = false;

	  if (xmlData[0] === '\ufeff') {
	    // check for byte order mark (BOM)
	    xmlData = xmlData.substr(1);
	  }
	  
	  for (let i = 0; i < xmlData.length; i++) {

	    if (xmlData[i] === '<' && xmlData[i+1] === '?') {
	      i+=2;
	      i = readPI(xmlData,i);
	      if (i.err) return i;
	    }else if (xmlData[i] === '<') {
	      //starting of tag
	      //read until you reach to '>' avoiding any '>' in attribute value
	      let tagStartPos = i;
	      i++;
	      
	      if (xmlData[i] === '!') {
	        i = readCommentAndCDATA(xmlData, i);
	        continue;
	      } else {
	        let closingTag = false;
	        if (xmlData[i] === '/') {
	          //closing tag
	          closingTag = true;
	          i++;
	        }
	        //read tagname
	        let tagName = '';
	        for (; i < xmlData.length &&
	          xmlData[i] !== '>' &&
	          xmlData[i] !== ' ' &&
	          xmlData[i] !== '\t' &&
	          xmlData[i] !== '\n' &&
	          xmlData[i] !== '\r'; i++
	        ) {
	          tagName += xmlData[i];
	        }
	        tagName = tagName.trim();
	        //console.log(tagName);

	        if (tagName[tagName.length - 1] === '/') {
	          //self closing tag without attributes
	          tagName = tagName.substring(0, tagName.length - 1);
	          //continue;
	          i--;
	        }
	        if (!validateTagName(tagName)) {
	          let msg;
	          if (tagName.trim().length === 0) {
	            msg = "Invalid space after '<'.";
	          } else {
	            msg = "Tag '"+tagName+"' is an invalid name.";
	          }
	          return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i));
	        }

	        const result = readAttributeStr(xmlData, i);
	        if (result === false) {
	          return getErrorObject('InvalidAttr', "Attributes for '"+tagName+"' have open quote.", getLineNumberForPosition(xmlData, i));
	        }
	        let attrStr = result.value;
	        i = result.index;

	        if (attrStr[attrStr.length - 1] === '/') {
	          //self closing tag
	          const attrStrStart = i - attrStr.length;
	          attrStr = attrStr.substring(0, attrStr.length - 1);
	          const isValid = validateAttributeString(attrStr, options);
	          if (isValid === true) {
	            tagFound = true;
	            //continue; //text may presents after self closing tag
	          } else {
	            //the result from the nested function returns the position of the error within the attribute
	            //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute
	            //this gives us the absolute index in the entire xml, which we can use to find the line at last
	            return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));
	          }
	        } else if (closingTag) {
	          if (!result.tagClosed) {
	            return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' doesn't have proper closing.", getLineNumberForPosition(xmlData, i));
	          } else if (attrStr.trim().length > 0) {
	            return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
	          } else if (tags.length === 0) {
	            return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
	          } else {
	            const otg = tags.pop();
	            if (tagName !== otg.tagName) {
	              let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
	              return getErrorObject('InvalidTag',
	                "Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.",
	                getLineNumberForPosition(xmlData, tagStartPos));
	            }

	            //when there are no more tags, we reached the root level.
	            if (tags.length == 0) {
	              reachedRoot = true;
	            }
	          }
	        } else {
	          const isValid = validateAttributeString(attrStr, options);
	          if (isValid !== true) {
	            //the result from the nested function returns the position of the error within the attribute
	            //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute
	            //this gives us the absolute index in the entire xml, which we can use to find the line at last
	            return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));
	          }

	          //if the root level has been reached before ...
	          if (reachedRoot === true) {
	            return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));
	          } else if(options.unpairedTags.indexOf(tagName) !== -1); else {
	            tags.push({tagName, tagStartPos});
	          }
	          tagFound = true;
	        }

	        //skip tag text value
	        //It may include comments and CDATA value
	        for (i++; i < xmlData.length; i++) {
	          if (xmlData[i] === '<') {
	            if (xmlData[i + 1] === '!') {
	              //comment or CADATA
	              i++;
	              i = readCommentAndCDATA(xmlData, i);
	              continue;
	            } else if (xmlData[i+1] === '?') {
	              i = readPI(xmlData, ++i);
	              if (i.err) return i;
	            } else {
	              break;
	            }
	          } else if (xmlData[i] === '&') {
	            const afterAmp = validateAmpersand(xmlData, i);
	            if (afterAmp == -1)
	              return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i));
	            i = afterAmp;
	          }else {
	            if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {
	              return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i));
	            }
	          }
	        } //end of reading tag text value
	        if (xmlData[i] === '<') {
	          i--;
	        }
	      }
	    } else {
	      if ( isWhiteSpace(xmlData[i])) {
	        continue;
	      }
	      return getErrorObject('InvalidChar', "char '"+xmlData[i]+"' is not expected.", getLineNumberForPosition(xmlData, i));
	    }
	  }

	  if (!tagFound) {
	    return getErrorObject('InvalidXml', 'Start tag expected.', 1);
	  }else if (tags.length == 1) {
	      return getErrorObject('InvalidTag', "Unclosed tag '"+tags[0].tagName+"'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
	  }else if (tags.length > 0) {
	      return getErrorObject('InvalidXml', "Invalid '"+
	          JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '')+
	          "' found.", {line: 1, col: 1});
	  }

	  return true;
	};

	function isWhiteSpace(char){
	  return char === ' ' || char === '\t' || char === '\n'  || char === '\r';
	}
	/**
	 * Read Processing insstructions and skip
	 * @param {*} xmlData
	 * @param {*} i
	 */
	function readPI(xmlData, i) {
	  const start = i;
	  for (; i < xmlData.length; i++) {
	    if (xmlData[i] == '?' || xmlData[i] == ' ') {
	      //tagname
	      const tagname = xmlData.substr(start, i - start);
	      if (i > 5 && tagname === 'xml') {
	        return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));
	      } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {
	        //check if valid attribut string
	        i++;
	        break;
	      } else {
	        continue;
	      }
	    }
	  }
	  return i;
	}

	function readCommentAndCDATA(xmlData, i) {
	  if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {
	    //comment
	    for (i += 3; i < xmlData.length; i++) {
	      if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {
	        i += 2;
	        break;
	      }
	    }
	  } else if (
	    xmlData.length > i + 8 &&
	    xmlData[i + 1] === 'D' &&
	    xmlData[i + 2] === 'O' &&
	    xmlData[i + 3] === 'C' &&
	    xmlData[i + 4] === 'T' &&
	    xmlData[i + 5] === 'Y' &&
	    xmlData[i + 6] === 'P' &&
	    xmlData[i + 7] === 'E'
	  ) {
	    let angleBracketsCount = 1;
	    for (i += 8; i < xmlData.length; i++) {
	      if (xmlData[i] === '<') {
	        angleBracketsCount++;
	      } else if (xmlData[i] === '>') {
	        angleBracketsCount--;
	        if (angleBracketsCount === 0) {
	          break;
	        }
	      }
	    }
	  } else if (
	    xmlData.length > i + 9 &&
	    xmlData[i + 1] === '[' &&
	    xmlData[i + 2] === 'C' &&
	    xmlData[i + 3] === 'D' &&
	    xmlData[i + 4] === 'A' &&
	    xmlData[i + 5] === 'T' &&
	    xmlData[i + 6] === 'A' &&
	    xmlData[i + 7] === '['
	  ) {
	    for (i += 8; i < xmlData.length; i++) {
	      if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {
	        i += 2;
	        break;
	      }
	    }
	  }

	  return i;
	}

	const doubleQuote = '"';
	const singleQuote = "'";

	/**
	 * Keep reading xmlData until '<' is found outside the attribute value.
	 * @param {string} xmlData
	 * @param {number} i
	 */
	function readAttributeStr(xmlData, i) {
	  let attrStr = '';
	  let startChar = '';
	  let tagClosed = false;
	  for (; i < xmlData.length; i++) {
	    if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {
	      if (startChar === '') {
	        startChar = xmlData[i];
	      } else if (startChar !== xmlData[i]) ; else {
	        startChar = '';
	      }
	    } else if (xmlData[i] === '>') {
	      if (startChar === '') {
	        tagClosed = true;
	        break;
	      }
	    }
	    attrStr += xmlData[i];
	  }
	  if (startChar !== '') {
	    return false;
	  }

	  return {
	    value: attrStr,
	    index: i,
	    tagClosed: tagClosed
	  };
	}

	/**
	 * Select all the attributes whether valid or invalid.
	 */
	const validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g');

	//attr, ="sd", a="amit's", a="sd"b="saf", ab  cd=""

	function validateAttributeString(attrStr, options) {
	  //console.log("start:"+attrStr+":end");

	  //if(attrStr.trim().length === 0) return true; //empty string

	  const matches = util.getAllMatches(attrStr, validAttrStrRegxp);
	  const attrNames = {};

	  for (let i = 0; i < matches.length; i++) {
	    if (matches[i][1].length === 0) {
	      //nospace before attribute name: a="sd"b="saf"
	      return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' has no space in starting.", getPositionFromMatch(matches[i]))
	    } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {
	      return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' is without value.", getPositionFromMatch(matches[i]));
	    } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {
	      //independent attribute: ab
	      return getErrorObject('InvalidAttr', "boolean attribute '"+matches[i][2]+"' is not allowed.", getPositionFromMatch(matches[i]));
	    }
	    /* else if(matches[i][6] === undefined){//attribute without value: ab=
	                    return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}};
	                } */
	    const attrName = matches[i][2];
	    if (!validateAttrName(attrName)) {
	      return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is an invalid name.", getPositionFromMatch(matches[i]));
	    }
	    if (!attrNames.hasOwnProperty(attrName)) {
	      //check for duplicate attribute.
	      attrNames[attrName] = 1;
	    } else {
	      return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is repeated.", getPositionFromMatch(matches[i]));
	    }
	  }

	  return true;
	}

	function validateNumberAmpersand(xmlData, i) {
	  let re = /\d/;
	  if (xmlData[i] === 'x') {
	    i++;
	    re = /[\da-fA-F]/;
	  }
	  for (; i < xmlData.length; i++) {
	    if (xmlData[i] === ';')
	      return i;
	    if (!xmlData[i].match(re))
	      break;
	  }
	  return -1;
	}

	function validateAmpersand(xmlData, i) {
	  // https://www.w3.org/TR/xml/#dt-charref
	  i++;
	  if (xmlData[i] === ';')
	    return -1;
	  if (xmlData[i] === '#') {
	    i++;
	    return validateNumberAmpersand(xmlData, i);
	  }
	  let count = 0;
	  for (; i < xmlData.length; i++, count++) {
	    if (xmlData[i].match(/\w/) && count < 20)
	      continue;
	    if (xmlData[i] === ';')
	      break;
	    return -1;
	  }
	  return i;
	}

	function getErrorObject(code, message, lineNumber) {
	  return {
	    err: {
	      code: code,
	      msg: message,
	      line: lineNumber.line || lineNumber,
	      col: lineNumber.col,
	    },
	  };
	}

	function validateAttrName(attrName) {
	  return util.isName(attrName);
	}

	// const startsWithXML = /^xml/i;

	function validateTagName(tagname) {
	  return util.isName(tagname) /* && !tagname.match(startsWithXML) */;
	}

	//this function returns the line number for the character at the given index
	function getLineNumberForPosition(xmlData, index) {
	  const lines = xmlData.substring(0, index).split(/\r?\n/);
	  return {
	    line: lines.length,

	    // column number is last line's length + 1, because column numbering starts at 1:
	    col: lines[lines.length - 1].length + 1
	  };
	}

	//this function returns the position of the first character of match within attrStr
	function getPositionFromMatch(match) {
	  return match.startIndex + match[1].length;
	}
	return validator;
}

var OptionsBuilder = {};

var hasRequiredOptionsBuilder;

function requireOptionsBuilder () {
	if (hasRequiredOptionsBuilder) return OptionsBuilder;
	hasRequiredOptionsBuilder = 1;
	const defaultOptions = {
	    preserveOrder: false,
	    attributeNamePrefix: '@_',
	    attributesGroupName: false,
	    textNodeName: '#text',
	    ignoreAttributes: true,
	    removeNSPrefix: false, // remove NS from tag name or attribute name if true
	    allowBooleanAttributes: false, //a tag can have attributes without any value
	    //ignoreRootElement : false,
	    parseTagValue: true,
	    parseAttributeValue: false,
	    trimValues: true, //Trim string values of tag and attributes
	    cdataPropName: false,
	    numberParseOptions: {
	      hex: true,
	      leadingZeros: true,
	      eNotation: true
	    },
	    tagValueProcessor: function(tagName, val) {
	      return val;
	    },
	    attributeValueProcessor: function(attrName, val) {
	      return val;
	    },
	    stopNodes: [], //nested tags will not be parsed even for errors
	    alwaysCreateTextNode: false,
	    isArray: () => false,
	    commentPropName: false,
	    unpairedTags: [],
	    processEntities: true,
	    htmlEntities: false,
	    ignoreDeclaration: false,
	    ignorePiTags: false,
	    transformTagName: false,
	    transformAttributeName: false,
	    updateTag: function(tagName, jPath, attrs){
	      return tagName
	    },
	    // skipEmptyListItem: false
	};
	   
	const buildOptions = function(options) {
	    return Object.assign({}, defaultOptions, options);
	};

	OptionsBuilder.buildOptions = buildOptions;
	OptionsBuilder.defaultOptions = defaultOptions;
	return OptionsBuilder;
}

var xmlNode;
var hasRequiredXmlNode;

function requireXmlNode () {
	if (hasRequiredXmlNode) return xmlNode;
	hasRequiredXmlNode = 1;

	class XmlNode{
	  constructor(tagname) {
	    this.tagname = tagname;
	    this.child = []; //nested tags, text, cdata, comments in order
	    this[":@"] = {}; //attributes map
	  }
	  add(key,val){
	    // this.child.push( {name : key, val: val, isCdata: isCdata });
	    if(key === "__proto__") key = "#__proto__";
	    this.child.push( {[key]: val });
	  }
	  addChild(node) {
	    if(node.tagname === "__proto__") node.tagname = "#__proto__";
	    if(node[":@"] && Object.keys(node[":@"]).length > 0){
	      this.child.push( { [node.tagname]: node.child, [":@"]: node[":@"] });
	    }else {
	      this.child.push( { [node.tagname]: node.child });
	    }
	  };
	}

	xmlNode = XmlNode;
	return xmlNode;
}

var DocTypeReader;
var hasRequiredDocTypeReader;

function requireDocTypeReader () {
	if (hasRequiredDocTypeReader) return DocTypeReader;
	hasRequiredDocTypeReader = 1;
	const util = requireUtil();

	//TODO: handle comments
	function readDocType(xmlData, i){
	    
	    const entities = {};
	    if( xmlData[i + 3] === 'O' &&
	         xmlData[i + 4] === 'C' &&
	         xmlData[i + 5] === 'T' &&
	         xmlData[i + 6] === 'Y' &&
	         xmlData[i + 7] === 'P' &&
	         xmlData[i + 8] === 'E')
	    {    
	        i = i+9;
	        let angleBracketsCount = 1;
	        let hasBody = false, comment = false;
	        let exp = "";
	        for(;i<xmlData.length;i++){
	            if (xmlData[i] === '<' && !comment) { //Determine the tag type
	                if( hasBody && isEntity(xmlData, i)){
	                    i += 7; 
	                    let entityName, val;
	                    [entityName, val,i] = readEntityExp(xmlData,i+1);
	                    if(val.indexOf("&") === -1) //Parameter entities are not supported
	                        entities[ validateEntityName(entityName) ] = {
	                            regx : RegExp( `&${entityName};`,"g"),
	                            val: val
	                        };
	                }
	                else if( hasBody && isElement(xmlData, i))  i += 8;//Not supported
	                else if( hasBody && isAttlist(xmlData, i))  i += 8;//Not supported
	                else if( hasBody && isNotation(xmlData, i)) i += 9;//Not supported
	                else if( isComment)                         comment = true;
	                else                                        throw new Error("Invalid DOCTYPE");

	                angleBracketsCount++;
	                exp = "";
	            } else if (xmlData[i] === '>') { //Read tag content
	                if(comment){
	                    if( xmlData[i - 1] === "-" && xmlData[i - 2] === "-"){
	                        comment = false;
	                        angleBracketsCount--;
	                    }
	                }else {
	                    angleBracketsCount--;
	                }
	                if (angleBracketsCount === 0) {
	                  break;
	                }
	            }else if( xmlData[i] === '['){
	                hasBody = true;
	            }else {
	                exp += xmlData[i];
	            }
	        }
	        if(angleBracketsCount !== 0){
	            throw new Error(`Unclosed DOCTYPE`);
	        }
	    }else {
	        throw new Error(`Invalid Tag instead of DOCTYPE`);
	    }
	    return {entities, i};
	}

	function readEntityExp(xmlData,i){
	    //External entities are not supported
	    //    <!ENTITY ext SYSTEM "http://normal-website.com" >

	    //Parameter entities are not supported
	    //    <!ENTITY entityname "&anotherElement;">

	    //Internal entities are supported
	    //    <!ENTITY entityname "replacement text">
	    
	    //read EntityName
	    let entityName = "";
	    for (; i < xmlData.length && (xmlData[i] !== "'" && xmlData[i] !== '"' ); i++) {
	        // if(xmlData[i] === " ") continue;
	        // else 
	        entityName += xmlData[i];
	    }
	    entityName = entityName.trim();
	    if(entityName.indexOf(" ") !== -1) throw new Error("External entites are not supported");

	    //read Entity Value
	    const startChar = xmlData[i++];
	    let val = "";
	    for (; i < xmlData.length && xmlData[i] !== startChar ; i++) {
	        val += xmlData[i];
	    }
	    return [entityName, val, i];
	}

	function isComment(xmlData, i){
	    if(xmlData[i+1] === '!' &&
	    xmlData[i+2] === '-' &&
	    xmlData[i+3] === '-') return true
	    return false
	}
	function isEntity(xmlData, i){
	    if(xmlData[i+1] === '!' &&
	    xmlData[i+2] === 'E' &&
	    xmlData[i+3] === 'N' &&
	    xmlData[i+4] === 'T' &&
	    xmlData[i+5] === 'I' &&
	    xmlData[i+6] === 'T' &&
	    xmlData[i+7] === 'Y') return true
	    return false
	}
	function isElement(xmlData, i){
	    if(xmlData[i+1] === '!' &&
	    xmlData[i+2] === 'E' &&
	    xmlData[i+3] === 'L' &&
	    xmlData[i+4] === 'E' &&
	    xmlData[i+5] === 'M' &&
	    xmlData[i+6] === 'E' &&
	    xmlData[i+7] === 'N' &&
	    xmlData[i+8] === 'T') return true
	    return false
	}

	function isAttlist(xmlData, i){
	    if(xmlData[i+1] === '!' &&
	    xmlData[i+2] === 'A' &&
	    xmlData[i+3] === 'T' &&
	    xmlData[i+4] === 'T' &&
	    xmlData[i+5] === 'L' &&
	    xmlData[i+6] === 'I' &&
	    xmlData[i+7] === 'S' &&
	    xmlData[i+8] === 'T') return true
	    return false
	}
	function isNotation(xmlData, i){
	    if(xmlData[i+1] === '!' &&
	    xmlData[i+2] === 'N' &&
	    xmlData[i+3] === 'O' &&
	    xmlData[i+4] === 'T' &&
	    xmlData[i+5] === 'A' &&
	    xmlData[i+6] === 'T' &&
	    xmlData[i+7] === 'I' &&
	    xmlData[i+8] === 'O' &&
	    xmlData[i+9] === 'N') return true
	    return false
	}

	function validateEntityName(name){
	    if (util.isName(name))
		return name;
	    else
	        throw new Error(`Invalid entity name ${name}`);
	}

	DocTypeReader = readDocType;
	return DocTypeReader;
}

var strnum;
var hasRequiredStrnum;

function requireStrnum () {
	if (hasRequiredStrnum) return strnum;
	hasRequiredStrnum = 1;
	const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;
	const numRegex = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/;
	// const octRegex = /^0x[a-z0-9]+/;
	// const binRegex = /0x[a-z0-9]+/;

	 
	const consider = {
	    hex :  true,
	    // oct: false,
	    leadingZeros: true,
	    decimalPoint: "\.",
	    eNotation: true,
	    //skipLike: /regex/
	};

	function toNumber(str, options = {}){
	    options = Object.assign({}, consider, options );
	    if(!str || typeof str !== "string" ) return str;
	    
	    let trimmedStr  = str.trim();
	    
	    if(options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str;
	    else if(str==="0") return 0;
	    else if (options.hex && hexRegex.test(trimmedStr)) {
	        return parse_int(trimmedStr, 16);
	    // }else if (options.oct && octRegex.test(str)) {
	    //     return Number.parseInt(val, 8);
	    }else if (trimmedStr.search(/[eE]/)!== -1) { //eNotation
	        const notation = trimmedStr.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/); 
	        // +00.123 => [ , '+', '00', '.123', ..
	        if(notation){
	            // console.log(notation)
	            if(options.leadingZeros){ //accept with leading zeros
	                trimmedStr = (notation[1] || "") + notation[3];
	            }else {
	                if(notation[2] === "0" && notation[3][0]=== ".");else {
	                    return str;
	                }
	            }
	            return options.eNotation ? Number(trimmedStr) : str;
	        }else {
	            return str;
	        }
	    // }else if (options.parseBin && binRegex.test(str)) {
	    //     return Number.parseInt(val, 2);
	    }else {
	        //separate negative sign, leading zeros, and rest number
	        const match = numRegex.exec(trimmedStr);
	        // +00.123 => [ , '+', '00', '.123', ..
	        if(match){
	            const sign = match[1];
	            const leadingZeros = match[2];
	            let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros
	            //trim ending zeros for floating number
	            
	            if(!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str; //-0123
	            else if(!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str; //0123
	            else if(options.leadingZeros && leadingZeros===str) return 0; //00
	            
	            else {//no leading zeros or leading zeros are allowed
	                const num = Number(trimmedStr);
	                const numStr = "" + num;

	                if(numStr.search(/[eE]/) !== -1){ //given number is long and parsed to eNotation
	                    if(options.eNotation) return num;
	                    else return str;
	                }else if(trimmedStr.indexOf(".") !== -1){ //floating number
	                    if(numStr === "0" && (numTrimmedByZeros === "") ) return num; //0.0
	                    else if(numStr === numTrimmedByZeros) return num; //0.456. 0.79000
	                    else if( sign && numStr === "-"+numTrimmedByZeros) return num;
	                    else return str;
	                }
	                
	                if(leadingZeros){
	                    return (numTrimmedByZeros === numStr) || (sign+numTrimmedByZeros === numStr) ? num : str
	                }else  {
	                    return (trimmedStr === numStr) || (trimmedStr === sign+numStr) ? num : str
	                }
	            }
	        }else { //non-numeric string
	            return str;
	        }
	    }
	}

	/**
	 * 
	 * @param {string} numStr without leading zeros
	 * @returns 
	 */
	function trimZeros(numStr){
	    if(numStr && numStr.indexOf(".") !== -1){//float
	        numStr = numStr.replace(/0+$/, ""); //remove ending zeros
	        if(numStr === ".")  numStr = "0";
	        else if(numStr[0] === ".")  numStr = "0"+numStr;
	        else if(numStr[numStr.length-1] === ".")  numStr = numStr.substr(0,numStr.length-1);
	        return numStr;
	    }
	    return numStr;
	}

	function parse_int(numStr, base){
	    //polyfill
	    if(parseInt) return parseInt(numStr, base);
	    else if(Number.parseInt) return Number.parseInt(numStr, base);
	    else if(window && window.parseInt) return window.parseInt(numStr, base);
	    else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")
	}

	strnum = toNumber;
	return strnum;
}

var ignoreAttributes;
var hasRequiredIgnoreAttributes;

function requireIgnoreAttributes () {
	if (hasRequiredIgnoreAttributes) return ignoreAttributes;
	hasRequiredIgnoreAttributes = 1;
	function getIgnoreAttributesFn(ignoreAttributes) {
	    if (typeof ignoreAttributes === 'function') {
	        return ignoreAttributes
	    }
	    if (Array.isArray(ignoreAttributes)) {
	        return (attrName) => {
	            for (const pattern of ignoreAttributes) {
	                if (typeof pattern === 'string' && attrName === pattern) {
	                    return true
	                }
	                if (pattern instanceof RegExp && pattern.test(attrName)) {
	                    return true
	                }
	            }
	        }
	    }
	    return () => false
	}

	ignoreAttributes = getIgnoreAttributesFn;
	return ignoreAttributes;
}

var OrderedObjParser_1;
var hasRequiredOrderedObjParser;

function requireOrderedObjParser () {
	if (hasRequiredOrderedObjParser) return OrderedObjParser_1;
	hasRequiredOrderedObjParser = 1;
	///@ts-check

	const util = requireUtil();
	const xmlNode = requireXmlNode();
	const readDocType = requireDocTypeReader();
	const toNumber = requireStrnum();
	const getIgnoreAttributesFn = requireIgnoreAttributes();

	// const regx =
	//   '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)'
	//   .replace(/NAME/g, util.nameRegexp);

	//const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g");
	//const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g");

	class OrderedObjParser{
	  constructor(options){
	    this.options = options;
	    this.currentNode = null;
	    this.tagsNodeStack = [];
	    this.docTypeEntities = {};
	    this.lastEntities = {
	      "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"},
	      "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"},
	      "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"},
	      "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""},
	    };
	    this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"};
	    this.htmlEntities = {
	      "space": { regex: /&(nbsp|#160);/g, val: " " },
	      // "lt" : { regex: /&(lt|#60);/g, val: "<" },
	      // "gt" : { regex: /&(gt|#62);/g, val: ">" },
	      // "amp" : { regex: /&(amp|#38);/g, val: "&" },
	      // "quot" : { regex: /&(quot|#34);/g, val: "\"" },
	      // "apos" : { regex: /&(apos|#39);/g, val: "'" },
	      "cent" : { regex: /&(cent|#162);/g, val: "¢" },
	      "pound" : { regex: /&(pound|#163);/g, val: "£" },
	      "yen" : { regex: /&(yen|#165);/g, val: "¥" },
	      "euro" : { regex: /&(euro|#8364);/g, val: "€" },
	      "copyright" : { regex: /&(copy|#169);/g, val: "©" },
	      "reg" : { regex: /&(reg|#174);/g, val: "®" },
	      "inr" : { regex: /&(inr|#8377);/g, val: "₹" },
	      "num_dec": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) },
	      "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) },
	    };
	    this.addExternalEntities = addExternalEntities;
	    this.parseXml = parseXml;
	    this.parseTextData = parseTextData;
	    this.resolveNameSpace = resolveNameSpace;
	    this.buildAttributesMap = buildAttributesMap;
	    this.isItStopNode = isItStopNode;
	    this.replaceEntitiesValue = replaceEntitiesValue;
	    this.readStopNodeData = readStopNodeData;
	    this.saveTextToParentTag = saveTextToParentTag;
	    this.addChild = addChild;
	    this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes);
	  }

	}

	function addExternalEntities(externalEntities){
	  const entKeys = Object.keys(externalEntities);
	  for (let i = 0; i < entKeys.length; i++) {
	    const ent = entKeys[i];
	    this.lastEntities[ent] = {
	       regex: new RegExp("&"+ent+";","g"),
	       val : externalEntities[ent]
	    };
	  }
	}

	/**
	 * @param {string} val
	 * @param {string} tagName
	 * @param {string} jPath
	 * @param {boolean} dontTrim
	 * @param {boolean} hasAttributes
	 * @param {boolean} isLeafNode
	 * @param {boolean} escapeEntities
	 */
	function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
	  if (val !== undefined) {
	    if (this.options.trimValues && !dontTrim) {
	      val = val.trim();
	    }
	    if(val.length > 0){
	      if(!escapeEntities) val = this.replaceEntitiesValue(val);
	      
	      const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode);
	      if(newval === null || newval === undefined){
	        //don't parse
	        return val;
	      }else if(typeof newval !== typeof val || newval !== val){
	        //overwrite
	        return newval;
	      }else if(this.options.trimValues){
	        return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
	      }else {
	        const trimmedVal = val.trim();
	        if(trimmedVal === val){
	          return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
	        }else {
	          return val;
	        }
	      }
	    }
	  }
	}

	function resolveNameSpace(tagname) {
	  if (this.options.removeNSPrefix) {
	    const tags = tagname.split(':');
	    const prefix = tagname.charAt(0) === '/' ? '/' : '';
	    if (tags[0] === 'xmlns') {
	      return '';
	    }
	    if (tags.length === 2) {
	      tagname = prefix + tags[1];
	    }
	  }
	  return tagname;
	}

	//TODO: change regex to capture NS
	//const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm");
	const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm');

	function buildAttributesMap(attrStr, jPath, tagName) {
	  if (this.options.ignoreAttributes !== true && typeof attrStr === 'string') {
	    // attrStr = attrStr.replace(/\r?\n/g, ' ');
	    //attrStr = attrStr || attrStr.trim();

	    const matches = util.getAllMatches(attrStr, attrsRegx);
	    const len = matches.length; //don't make it inline
	    const attrs = {};
	    for (let i = 0; i < len; i++) {
	      const attrName = this.resolveNameSpace(matches[i][1]);
	      if (this.ignoreAttributesFn(attrName, jPath)) {
	        continue
	      }
	      let oldVal = matches[i][4];
	      let aName = this.options.attributeNamePrefix + attrName;
	      if (attrName.length) {
	        if (this.options.transformAttributeName) {
	          aName = this.options.transformAttributeName(aName);
	        }
	        if(aName === "__proto__") aName  = "#__proto__";
	        if (oldVal !== undefined) {
	          if (this.options.trimValues) {
	            oldVal = oldVal.trim();
	          }
	          oldVal = this.replaceEntitiesValue(oldVal);
	          const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);
	          if(newVal === null || newVal === undefined){
	            //don't parse
	            attrs[aName] = oldVal;
	          }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){
	            //overwrite
	            attrs[aName] = newVal;
	          }else {
	            //parse
	            attrs[aName] = parseValue(
	              oldVal,
	              this.options.parseAttributeValue,
	              this.options.numberParseOptions
	            );
	          }
	        } else if (this.options.allowBooleanAttributes) {
	          attrs[aName] = true;
	        }
	      }
	    }
	    if (!Object.keys(attrs).length) {
	      return;
	    }
	    if (this.options.attributesGroupName) {
	      const attrCollection = {};
	      attrCollection[this.options.attributesGroupName] = attrs;
	      return attrCollection;
	    }
	    return attrs
	  }
	}

	const parseXml = function(xmlData) {
	  xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line
	  const xmlObj = new xmlNode('!xml');
	  let currentNode = xmlObj;
	  let textData = "";
	  let jPath = "";
	  for(let i=0; i< xmlData.length; i++){//for each char in XML data
	    const ch = xmlData[i];
	    if(ch === '<'){
	      // const nextIndex = i+1;
	      // const _2ndChar = xmlData[nextIndex];
	      if( xmlData[i+1] === '/') {//Closing Tag
	        const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.");
	        let tagName = xmlData.substring(i+2,closeIndex).trim();

	        if(this.options.removeNSPrefix){
	          const colonIndex = tagName.indexOf(":");
	          if(colonIndex !== -1){
	            tagName = tagName.substr(colonIndex+1);
	          }
	        }

	        if(this.options.transformTagName) {
	          tagName = this.options.transformTagName(tagName);
	        }

	        if(currentNode){
	          textData = this.saveTextToParentTag(textData, currentNode, jPath);
	        }

	        //check if last tag of nested tag was unpaired tag
	        const lastTagName = jPath.substring(jPath.lastIndexOf(".")+1);
	        if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){
	          throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
	        }
	        let propIndex = 0;
	        if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){
	          propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1);
	          this.tagsNodeStack.pop();
	        }else {
	          propIndex = jPath.lastIndexOf(".");
	        }
	        jPath = jPath.substring(0, propIndex);

	        currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope
	        textData = "";
	        i = closeIndex;
	      } else if( xmlData[i+1] === '?') {

	        let tagData = readTagExp(xmlData,i, false, "?>");
	        if(!tagData) throw new Error("Pi Tag is not closed.");

	        textData = this.saveTextToParentTag(textData, currentNode, jPath);
	        if( (this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags);else {
	  
	          const childNode = new xmlNode(tagData.tagName);
	          childNode.add(this.options.textNodeName, "");
	          
	          if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){
	            childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName);
	          }
	          this.addChild(currentNode, childNode, jPath);

	        }


	        i = tagData.closeIndex + 1;
	      } else if(xmlData.substr(i + 1, 3) === '!--') {
	        const endIndex = findClosingIndex(xmlData, "-->", i+4, "Comment is not closed.");
	        if(this.options.commentPropName){
	          const comment = xmlData.substring(i + 4, endIndex - 2);

	          textData = this.saveTextToParentTag(textData, currentNode, jPath);

	          currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]);
	        }
	        i = endIndex;
	      } else if( xmlData.substr(i + 1, 2) === '!D') {
	        const result = readDocType(xmlData, i);
	        this.docTypeEntities = result.entities;
	        i = result.i;
	      }else if(xmlData.substr(i + 1, 2) === '![') {
	        const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2;
	        const tagExp = xmlData.substring(i + 9,closeIndex);

	        textData = this.saveTextToParentTag(textData, currentNode, jPath);

	        let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);
	        if(val == undefined) val = "";

	        //cdata should be set even if it is 0 length string
	        if(this.options.cdataPropName){
	          currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]);
	        }else {
	          currentNode.add(this.options.textNodeName, val);
	        }
	        
	        i = closeIndex + 2;
	      }else {//Opening tag
	        let result = readTagExp(xmlData,i, this.options.removeNSPrefix);
	        let tagName= result.tagName;
	        const rawTagName = result.rawTagName;
	        let tagExp = result.tagExp;
	        let attrExpPresent = result.attrExpPresent;
	        let closeIndex = result.closeIndex;

	        if (this.options.transformTagName) {
	          tagName = this.options.transformTagName(tagName);
	        }
	        
	        //save text as child node
	        if (currentNode && textData) {
	          if(currentNode.tagname !== '!xml'){
	            //when nested tag is found
	            textData = this.saveTextToParentTag(textData, currentNode, jPath, false);
	          }
	        }

	        //check if last tag was unpaired tag
	        const lastTag = currentNode;
	        if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){
	          currentNode = this.tagsNodeStack.pop();
	          jPath = jPath.substring(0, jPath.lastIndexOf("."));
	        }
	        if(tagName !== xmlObj.tagname){
	          jPath += jPath ? "." + tagName : tagName;
	        }
	        if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) {
	          let tagContent = "";
	          //self-closing tag
	          if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){
	            if(tagName[tagName.length - 1] === "/"){ //remove trailing '/'
	              tagName = tagName.substr(0, tagName.length - 1);
	              jPath = jPath.substr(0, jPath.length - 1);
	              tagExp = tagName;
	            }else {
	              tagExp = tagExp.substr(0, tagExp.length - 1);
	            }
	            i = result.closeIndex;
	          }
	          //unpaired tag
	          else if(this.options.unpairedTags.indexOf(tagName) !== -1){
	            
	            i = result.closeIndex;
	          }
	          //normal tag
	          else {
	            //read until closing tag is found
	            const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
	            if(!result) throw new Error(`Unexpected end of ${rawTagName}`);
	            i = result.i;
	            tagContent = result.tagContent;
	          }

	          const childNode = new xmlNode(tagName);
	          if(tagName !== tagExp && attrExpPresent){
	            childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
	          }
	          if(tagContent) {
	            tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);
	          }
	          
	          jPath = jPath.substr(0, jPath.lastIndexOf("."));
	          childNode.add(this.options.textNodeName, tagContent);
	          
	          this.addChild(currentNode, childNode, jPath);
	        }else {
	  //selfClosing tag
	          if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){
	            if(tagName[tagName.length - 1] === "/"){ //remove trailing '/'
	              tagName = tagName.substr(0, tagName.length - 1);
	              jPath = jPath.substr(0, jPath.length - 1);
	              tagExp = tagName;
	            }else {
	              tagExp = tagExp.substr(0, tagExp.length - 1);
	            }
	            
	            if(this.options.transformTagName) {
	              tagName = this.options.transformTagName(tagName);
	            }

	            const childNode = new xmlNode(tagName);
	            if(tagName !== tagExp && attrExpPresent){
	              childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
	            }
	            this.addChild(currentNode, childNode, jPath);
	            jPath = jPath.substr(0, jPath.lastIndexOf("."));
	          }
	    //opening tag
	          else {
	            const childNode = new xmlNode( tagName);
	            this.tagsNodeStack.push(currentNode);
	            
	            if(tagName !== tagExp && attrExpPresent){
	              childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
	            }
	            this.addChild(currentNode, childNode, jPath);
	            currentNode = childNode;
	          }
	          textData = "";
	          i = closeIndex;
	        }
	      }
	    }else {
	      textData += xmlData[i];
	    }
	  }
	  return xmlObj.child;
	};

	function addChild(currentNode, childNode, jPath){
	  const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]);
	  if(result === false);else if(typeof result === "string"){
	    childNode.tagname = result;
	    currentNode.addChild(childNode);
	  }else {
	    currentNode.addChild(childNode);
	  }
	}

	const replaceEntitiesValue = function(val){

	  if(this.options.processEntities){
	    for(let entityName in this.docTypeEntities){
	      const entity = this.docTypeEntities[entityName];
	      val = val.replace( entity.regx, entity.val);
	    }
	    for(let entityName in this.lastEntities){
	      const entity = this.lastEntities[entityName];
	      val = val.replace( entity.regex, entity.val);
	    }
	    if(this.options.htmlEntities){
	      for(let entityName in this.htmlEntities){
	        const entity = this.htmlEntities[entityName];
	        val = val.replace( entity.regex, entity.val);
	      }
	    }
	    val = val.replace( this.ampEntity.regex, this.ampEntity.val);
	  }
	  return val;
	};
	function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {
	  if (textData) { //store previously collected data as textNode
	    if(isLeafNode === undefined) isLeafNode = currentNode.child.length === 0;
	    
	    textData = this.parseTextData(textData,
	      currentNode.tagname,
	      jPath,
	      false,
	      currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false,
	      isLeafNode);

	    if (textData !== undefined && textData !== "")
	      currentNode.add(this.options.textNodeName, textData);
	    textData = "";
	  }
	  return textData;
	}

	//TODO: use jPath to simplify the logic
	/**
	 * 
	 * @param {string[]} stopNodes 
	 * @param {string} jPath
	 * @param {string} currentTagName 
	 */
	function isItStopNode(stopNodes, jPath, currentTagName){
	  const allNodesExp = "*." + currentTagName;
	  for (const stopNodePath in stopNodes) {
	    const stopNodeExp = stopNodes[stopNodePath];
	    if( allNodesExp === stopNodeExp || jPath === stopNodeExp  ) return true;
	  }
	  return false;
	}

	/**
	 * Returns the tag Expression and where it is ending handling single-double quotes situation
	 * @param {string} xmlData 
	 * @param {number} i starting index
	 * @returns 
	 */
	function tagExpWithClosingIndex(xmlData, i, closingChar = ">"){
	  let attrBoundary;
	  let tagExp = "";
	  for (let index = i; index < xmlData.length; index++) {
	    let ch = xmlData[index];
	    if (attrBoundary) {
	        if (ch === attrBoundary) attrBoundary = "";//reset
	    } else if (ch === '"' || ch === "'") {
	        attrBoundary = ch;
	    } else if (ch === closingChar[0]) {
	      if(closingChar[1]){
	        if(xmlData[index + 1] === closingChar[1]){
	          return {
	            data: tagExp,
	            index: index
	          }
	        }
	      }else {
	        return {
	          data: tagExp,
	          index: index
	        }
	      }
	    } else if (ch === '\t') {
	      ch = " ";
	    }
	    tagExp += ch;
	  }
	}

	function findClosingIndex(xmlData, str, i, errMsg){
	  const closingIndex = xmlData.indexOf(str, i);
	  if(closingIndex === -1){
	    throw new Error(errMsg)
	  }else {
	    return closingIndex + str.length - 1;
	  }
	}

	function readTagExp(xmlData,i, removeNSPrefix, closingChar = ">"){
	  const result = tagExpWithClosingIndex(xmlData, i+1, closingChar);
	  if(!result) return;
	  let tagExp = result.data;
	  const closeIndex = result.index;
	  const separatorIndex = tagExp.search(/\s/);
	  let tagName = tagExp;
	  let attrExpPresent = true;
	  if(separatorIndex !== -1){//separate tag name and attributes expression
	    tagName = tagExp.substring(0, separatorIndex);
	    tagExp = tagExp.substring(separatorIndex + 1).trimStart();
	  }

	  const rawTagName = tagName;
	  if(removeNSPrefix){
	    const colonIndex = tagName.indexOf(":");
	    if(colonIndex !== -1){
	      tagName = tagName.substr(colonIndex+1);
	      attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
	    }
	  }

	  return {
	    tagName: tagName,
	    tagExp: tagExp,
	    closeIndex: closeIndex,
	    attrExpPresent: attrExpPresent,
	    rawTagName: rawTagName,
	  }
	}
	/**
	 * find paired tag for a stop node
	 * @param {string} xmlData 
	 * @param {string} tagName 
	 * @param {number} i 
	 */
	function readStopNodeData(xmlData, tagName, i){
	  const startIndex = i;
	  // Starting at 1 since we already have an open tag
	  let openTagCount = 1;

	  for (; i < xmlData.length; i++) {
	    if( xmlData[i] === "<"){ 
	      if (xmlData[i+1] === "/") {//close tag
	          const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`);
	          let closeTagName = xmlData.substring(i+2,closeIndex).trim();
	          if(closeTagName === tagName){
	            openTagCount--;
	            if (openTagCount === 0) {
	              return {
	                tagContent: xmlData.substring(startIndex, i),
	                i : closeIndex
	              }
	            }
	          }
	          i=closeIndex;
	        } else if(xmlData[i+1] === '?') { 
	          const closeIndex = findClosingIndex(xmlData, "?>", i+1, "StopNode is not closed.");
	          i=closeIndex;
	        } else if(xmlData.substr(i + 1, 3) === '!--') { 
	          const closeIndex = findClosingIndex(xmlData, "-->", i+3, "StopNode is not closed.");
	          i=closeIndex;
	        } else if(xmlData.substr(i + 1, 2) === '![') { 
	          const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2;
	          i=closeIndex;
	        } else {
	          const tagData = readTagExp(xmlData, i, '>');

	          if (tagData) {
	            const openTagName = tagData && tagData.tagName;
	            if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") {
	              openTagCount++;
	            }
	            i=tagData.closeIndex;
	          }
	        }
	      }
	  }//end for loop
	}

	function parseValue(val, shouldParse, options) {
	  if (shouldParse && typeof val === 'string') {
	    //console.log(options)
	    const newval = val.trim();
	    if(newval === 'true' ) return true;
	    else if(newval === 'false' ) return false;
	    else return toNumber(val, options);
	  } else {
	    if (util.isExist(val)) {
	      return val;
	    } else {
	      return '';
	    }
	  }
	}


	OrderedObjParser_1 = OrderedObjParser;
	return OrderedObjParser_1;
}

var node2json = {};

var hasRequiredNode2json;

function requireNode2json () {
	if (hasRequiredNode2json) return node2json;
	hasRequiredNode2json = 1;

	/**
	 * 
	 * @param {array} node 
	 * @param {any} options 
	 * @returns 
	 */
	function prettify(node, options){
	  return compress( node, options);
	}

	/**
	 * 
	 * @param {array} arr 
	 * @param {object} options 
	 * @param {string} jPath 
	 * @returns object
	 */
	function compress(arr, options, jPath){
	  let text;
	  const compressedObj = {};
	  for (let i = 0; i < arr.length; i++) {
	    const tagObj = arr[i];
	    const property = propName(tagObj);
	    let newJpath = "";
	    if(jPath === undefined) newJpath = property;
	    else newJpath = jPath + "." + property;

	    if(property === options.textNodeName){
	      if(text === undefined) text = tagObj[property];
	      else text += "" + tagObj[property];
	    }else if(property === undefined){
	      continue;
	    }else if(tagObj[property]){
	      
	      let val = compress(tagObj[property], options, newJpath);
	      const isLeaf = isLeafTag(val, options);

	      if(tagObj[":@"]){
	        assignAttributes( val, tagObj[":@"], newJpath, options);
	      }else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){
	        val = val[options.textNodeName];
	      }else if(Object.keys(val).length === 0){
	        if(options.alwaysCreateTextNode) val[options.textNodeName] = "";
	        else val = "";
	      }

	      if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) {
	        if(!Array.isArray(compressedObj[property])) {
	            compressedObj[property] = [ compressedObj[property] ];
	        }
	        compressedObj[property].push(val);
	      }else {
	        //TODO: if a node is not an array, then check if it should be an array
	        //also determine if it is a leaf node
	        if (options.isArray(property, newJpath, isLeaf )) {
	          compressedObj[property] = [val];
	        }else {
	          compressedObj[property] = val;
	        }
	      }
	    }
	    
	  }
	  // if(text && text.length > 0) compressedObj[options.textNodeName] = text;
	  if(typeof text === "string"){
	    if(text.length > 0) compressedObj[options.textNodeName] = text;
	  }else if(text !== undefined) compressedObj[options.textNodeName] = text;
	  return compressedObj;
	}

	function propName(obj){
	  const keys = Object.keys(obj);
	  for (let i = 0; i < keys.length; i++) {
	    const key = keys[i];
	    if(key !== ":@") return key;
	  }
	}

	function assignAttributes(obj, attrMap, jpath, options){
	  if (attrMap) {
	    const keys = Object.keys(attrMap);
	    const len = keys.length; //don't make it inline
	    for (let i = 0; i < len; i++) {
	      const atrrName = keys[i];
	      if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) {
	        obj[atrrName] = [ attrMap[atrrName] ];
	      } else {
	        obj[atrrName] = attrMap[atrrName];
	      }
	    }
	  }
	}

	function isLeafTag(obj, options){
	  const { textNodeName } = options;
	  const propCount = Object.keys(obj).length;
	  
	  if (propCount === 0) {
	    return true;
	  }

	  if (
	    propCount === 1 &&
	    (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)
	  ) {
	    return true;
	  }

	  return false;
	}
	node2json.prettify = prettify;
	return node2json;
}

var XMLParser_1;
var hasRequiredXMLParser;

function requireXMLParser () {
	if (hasRequiredXMLParser) return XMLParser_1;
	hasRequiredXMLParser = 1;
	const { buildOptions} = requireOptionsBuilder();
	const OrderedObjParser = requireOrderedObjParser();
	const { prettify} = requireNode2json();
	const validator = requireValidator();

	class XMLParser{
	    
	    constructor(options){
	        this.externalEntities = {};
	        this.options = buildOptions(options);
	        
	    }
	    /**
	     * Parse XML dats to JS object 
	     * @param {string|Buffer} xmlData 
	     * @param {boolean|Object} validationOption 
	     */
	    parse(xmlData,validationOption){
	        if(typeof xmlData === "string");else if( xmlData.toString){
	            xmlData = xmlData.toString();
	        }else {
	            throw new Error("XML data is accepted in String or Bytes[] form.")
	        }
	        if( validationOption){
	            if(validationOption === true) validationOption = {}; //validate with default options
	            
	            const result = validator.validate(xmlData, validationOption);
	            if (result !== true) {
	              throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` )
	            }
	          }
	        const orderedObjParser = new OrderedObjParser(this.options);
	        orderedObjParser.addExternalEntities(this.externalEntities);
	        const orderedResult = orderedObjParser.parseXml(xmlData);
	        if(this.options.preserveOrder || orderedResult === undefined) return orderedResult;
	        else return prettify(orderedResult, this.options);
	    }

	    /**
	     * Add Entity which is not by default supported by this library
	     * @param {string} key 
	     * @param {string} value 
	     */
	    addEntity(key, value){
	        if(value.indexOf("&") !== -1){
	            throw new Error("Entity value can't have '&'")
	        }else if(key.indexOf("&") !== -1 || key.indexOf(";") !== -1){
	            throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'")
	        }else if(value === "&"){
	            throw new Error("An entity with value '&' is not permitted");
	        }else {
	            this.externalEntities[key] = value;
	        }
	    }
	}

	XMLParser_1 = XMLParser;
	return XMLParser_1;
}

var orderedJs2Xml;
var hasRequiredOrderedJs2Xml;

function requireOrderedJs2Xml () {
	if (hasRequiredOrderedJs2Xml) return orderedJs2Xml;
	hasRequiredOrderedJs2Xml = 1;
	const EOL = "\n";

	/**
	 * 
	 * @param {array} jArray 
	 * @param {any} options 
	 * @returns 
	 */
	function toXml(jArray, options) {
	    let indentation = "";
	    if (options.format && options.indentBy.length > 0) {
	        indentation = EOL;
	    }
	    return arrToStr(jArray, options, "", indentation);
	}

	function arrToStr(arr, options, jPath, indentation) {
	    let xmlStr = "";
	    let isPreviousElementTag = false;

	    for (let i = 0; i < arr.length; i++) {
	        const tagObj = arr[i];
	        const tagName = propName(tagObj);
	        if(tagName === undefined) continue;

	        let newJPath = "";
	        if (jPath.length === 0) newJPath = tagName;
	        else newJPath = `${jPath}.${tagName}`;

	        if (tagName === options.textNodeName) {
	            let tagText = tagObj[tagName];
	            if (!isStopNode(newJPath, options)) {
	                tagText = options.tagValueProcessor(tagName, tagText);
	                tagText = replaceEntitiesValue(tagText, options);
	            }
	            if (isPreviousElementTag) {
	                xmlStr += indentation;
	            }
	            xmlStr += tagText;
	            isPreviousElementTag = false;
	            continue;
	        } else if (tagName === options.cdataPropName) {
	            if (isPreviousElementTag) {
	                xmlStr += indentation;
	            }
	            xmlStr += `<![CDATA[${tagObj[tagName][0][options.textNodeName]}]]>`;
	            isPreviousElementTag = false;
	            continue;
	        } else if (tagName === options.commentPropName) {
	            xmlStr += indentation + `<!--${tagObj[tagName][0][options.textNodeName]}-->`;
	            isPreviousElementTag = true;
	            continue;
	        } else if (tagName[0] === "?") {
	            const attStr = attr_to_str(tagObj[":@"], options);
	            const tempInd = tagName === "?xml" ? "" : indentation;
	            let piTextNodeName = tagObj[tagName][0][options.textNodeName];
	            piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; //remove extra spacing
	            xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`;
	            isPreviousElementTag = true;
	            continue;
	        }
	        let newIdentation = indentation;
	        if (newIdentation !== "") {
	            newIdentation += options.indentBy;
	        }
	        const attStr = attr_to_str(tagObj[":@"], options);
	        const tagStart = indentation + `<${tagName}${attStr}`;
	        const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation);
	        if (options.unpairedTags.indexOf(tagName) !== -1) {
	            if (options.suppressUnpairedNode) xmlStr += tagStart + ">";
	            else xmlStr += tagStart + "/>";
	        } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {
	            xmlStr += tagStart + "/>";
	        } else if (tagValue && tagValue.endsWith(">")) {
	            xmlStr += tagStart + `>${tagValue}${indentation}</${tagName}>`;
	        } else {
	            xmlStr += tagStart + ">";
	            if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("</"))) {
	                xmlStr += indentation + options.indentBy + tagValue + indentation;
	            } else {
	                xmlStr += tagValue;
	            }
	            xmlStr += `</${tagName}>`;
	        }
	        isPreviousElementTag = true;
	    }

	    return xmlStr;
	}

	function propName(obj) {
	    const keys = Object.keys(obj);
	    for (let i = 0; i < keys.length; i++) {
	        const key = keys[i];
	        if(!obj.hasOwnProperty(key)) continue;
	        if (key !== ":@") return key;
	    }
	}

	function attr_to_str(attrMap, options) {
	    let attrStr = "";
	    if (attrMap && !options.ignoreAttributes) {
	        for (let attr in attrMap) {
	            if(!attrMap.hasOwnProperty(attr)) continue;
	            let attrVal = options.attributeValueProcessor(attr, attrMap[attr]);
	            attrVal = replaceEntitiesValue(attrVal, options);
	            if (attrVal === true && options.suppressBooleanAttributes) {
	                attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;
	            } else {
	                attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`;
	            }
	        }
	    }
	    return attrStr;
	}

	function isStopNode(jPath, options) {
	    jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1);
	    let tagName = jPath.substr(jPath.lastIndexOf(".") + 1);
	    for (let index in options.stopNodes) {
	        if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true;
	    }
	    return false;
	}

	function replaceEntitiesValue(textValue, options) {
	    if (textValue && textValue.length > 0 && options.processEntities) {
	        for (let i = 0; i < options.entities.length; i++) {
	            const entity = options.entities[i];
	            textValue = textValue.replace(entity.regex, entity.val);
	        }
	    }
	    return textValue;
	}
	orderedJs2Xml = toXml;
	return orderedJs2Xml;
}

var json2xml;
var hasRequiredJson2xml;

function requireJson2xml () {
	if (hasRequiredJson2xml) return json2xml;
	hasRequiredJson2xml = 1;
	//parse Empty Node as self closing node
	const buildFromOrderedJs = requireOrderedJs2Xml();
	const getIgnoreAttributesFn = requireIgnoreAttributes();

	const defaultOptions = {
	  attributeNamePrefix: '@_',
	  attributesGroupName: false,
	  textNodeName: '#text',
	  ignoreAttributes: true,
	  cdataPropName: false,
	  format: false,
	  indentBy: '  ',
	  suppressEmptyNode: false,
	  suppressUnpairedNode: true,
	  suppressBooleanAttributes: true,
	  tagValueProcessor: function(key, a) {
	    return a;
	  },
	  attributeValueProcessor: function(attrName, a) {
	    return a;
	  },
	  preserveOrder: false,
	  commentPropName: false,
	  unpairedTags: [],
	  entities: [
	    { regex: new RegExp("&", "g"), val: "&amp;" },//it must be on top
	    { regex: new RegExp(">", "g"), val: "&gt;" },
	    { regex: new RegExp("<", "g"), val: "&lt;" },
	    { regex: new RegExp("\'", "g"), val: "&apos;" },
	    { regex: new RegExp("\"", "g"), val: "&quot;" }
	  ],
	  processEntities: true,
	  stopNodes: [],
	  // transformTagName: false,
	  // transformAttributeName: false,
	  oneListGroup: false
	};

	function Builder(options) {
	  this.options = Object.assign({}, defaultOptions, options);
	  if (this.options.ignoreAttributes === true || this.options.attributesGroupName) {
	    this.isAttribute = function(/*a*/) {
	      return false;
	    };
	  } else {
	    this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes);
	    this.attrPrefixLen = this.options.attributeNamePrefix.length;
	    this.isAttribute = isAttribute;
	  }

	  this.processTextOrObjNode = processTextOrObjNode;

	  if (this.options.format) {
	    this.indentate = indentate;
	    this.tagEndChar = '>\n';
	    this.newLine = '\n';
	  } else {
	    this.indentate = function() {
	      return '';
	    };
	    this.tagEndChar = '>';
	    this.newLine = '';
	  }
	}

	Builder.prototype.build = function(jObj) {
	  if(this.options.preserveOrder){
	    return buildFromOrderedJs(jObj, this.options);
	  }else {
	    if(Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1){
	      jObj = {
	        [this.options.arrayNodeName] : jObj
	      };
	    }
	    return this.j2x(jObj, 0, []).val;
	  }
	};

	Builder.prototype.j2x = function(jObj, level, ajPath) {
	  let attrStr = '';
	  let val = '';
	  const jPath = ajPath.join('.');
	  for (let key in jObj) {
	    if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue;
	    if (typeof jObj[key] === 'undefined') {
	      // supress undefined node only if it is not an attribute
	      if (this.isAttribute(key)) {
	        val += '';
	      }
	    } else if (jObj[key] === null) {
	      // null attribute should be ignored by the attribute list, but should not cause the tag closing
	      if (this.isAttribute(key)) {
	        val += '';
	      } else if (key === this.options.cdataPropName) {
	        val += '';
	      } else if (key[0] === '?') {
	        val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;
	      } else {
	        val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
	      }
	      // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
	    } else if (jObj[key] instanceof Date) {
	      val += this.buildTextValNode(jObj[key], key, '', level);
	    } else if (typeof jObj[key] !== 'object') {
	      //premitive type
	      const attr = this.isAttribute(key);
	      if (attr && !this.ignoreAttributesFn(attr, jPath)) {
	        attrStr += this.buildAttrPairStr(attr, '' + jObj[key]);
	      } else if (!attr) {
	        //tag value
	        if (key === this.options.textNodeName) {
	          let newval = this.options.tagValueProcessor(key, '' + jObj[key]);
	          val += this.replaceEntitiesValue(newval);
	        } else {
	          val += this.buildTextValNode(jObj[key], key, '', level);
	        }
	      }
	    } else if (Array.isArray(jObj[key])) {
	      //repeated nodes
	      const arrLen = jObj[key].length;
	      let listTagVal = "";
	      let listTagAttr = "";
	      for (let j = 0; j < arrLen; j++) {
	        const item = jObj[key][j];
	        if (typeof item === 'undefined') ; else if (item === null) {
	          if(key[0] === "?") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;
	          else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
	          // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
	        } else if (typeof item === 'object') {
	          if(this.options.oneListGroup){
	            const result = this.j2x(item, level + 1, ajPath.concat(key));
	            listTagVal += result.val;
	            if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) {
	              listTagAttr += result.attrStr;
	            }
	          }else {
	            listTagVal += this.processTextOrObjNode(item, key, level, ajPath);
	          }
	        } else {
	          if (this.options.oneListGroup) {
	            let textValue = this.options.tagValueProcessor(key, item);
	            textValue = this.replaceEntitiesValue(textValue);
	            listTagVal += textValue;
	          } else {
	            listTagVal += this.buildTextValNode(item, key, '', level);
	          }
	        }
	      }
	      if(this.options.oneListGroup){
	        listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level);
	      }
	      val += listTagVal;
	    } else {
	      //nested node
	      if (this.options.attributesGroupName && key === this.options.attributesGroupName) {
	        const Ks = Object.keys(jObj[key]);
	        const L = Ks.length;
	        for (let j = 0; j < L; j++) {
	          attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]);
	        }
	      } else {
	        val += this.processTextOrObjNode(jObj[key], key, level, ajPath);
	      }
	    }
	  }
	  return {attrStr: attrStr, val: val};
	};

	Builder.prototype.buildAttrPairStr = function(attrName, val){
	  val = this.options.attributeValueProcessor(attrName, '' + val);
	  val = this.replaceEntitiesValue(val);
	  if (this.options.suppressBooleanAttributes && val === "true") {
	    return ' ' + attrName;
	  } else return ' ' + attrName + '="' + val + '"';
	};

	function processTextOrObjNode (object, key, level, ajPath) {
	  const result = this.j2x(object, level + 1, ajPath.concat(key));
	  if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) {
	    return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level);
	  } else {
	    return this.buildObjectNode(result.val, key, result.attrStr, level);
	  }
	}

	Builder.prototype.buildObjectNode = function(val, key, attrStr, level) {
	  if(val === ""){
	    if(key[0] === "?") return  this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;
	    else {
	      return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;
	    }
	  }else {

	    let tagEndExp = '</' + key + this.tagEndChar;
	    let piClosingChar = "";
	    
	    if(key[0] === "?") {
	      piClosingChar = "?";
	      tagEndExp = "";
	    }
	  
	    // attrStr is an empty string in case the attribute came as undefined or null
	    if ((attrStr || attrStr === '') && val.indexOf('<') === -1) {
	      return ( this.indentate(level) + '<' +  key + attrStr + piClosingChar + '>' + val + tagEndExp );
	    } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {
	      return this.indentate(level) + `<!--${val}-->` + this.newLine;
	    }else {
	      return (
	        this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar +
	        val +
	        this.indentate(level) + tagEndExp    );
	    }
	  }
	};

	Builder.prototype.closeTag = function(key){
	  let closeTag = "";
	  if(this.options.unpairedTags.indexOf(key) !== -1){ //unpaired
	    if(!this.options.suppressUnpairedNode) closeTag = "/";
	  }else if(this.options.suppressEmptyNode){ //empty
	    closeTag = "/";
	  }else {
	    closeTag = `></${key}`;
	  }
	  return closeTag;
	};

	Builder.prototype.buildTextValNode = function(val, key, attrStr, level) {
	  if (this.options.cdataPropName !== false && key === this.options.cdataPropName) {
	    return this.indentate(level) + `<![CDATA[${val}]]>` +  this.newLine;
	  }else if (this.options.commentPropName !== false && key === this.options.commentPropName) {
	    return this.indentate(level) + `<!--${val}-->` +  this.newLine;
	  }else if(key[0] === "?") {//PI tag
	    return  this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; 
	  }else {
	    let textValue = this.options.tagValueProcessor(key, val);
	    textValue = this.replaceEntitiesValue(textValue);
	  
	    if( textValue === ''){
	      return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;
	    }else {
	      return this.indentate(level) + '<' + key + attrStr + '>' +
	         textValue +
	        '</' + key + this.tagEndChar;
	    }
	  }
	};

	Builder.prototype.replaceEntitiesValue = function(textValue){
	  if(textValue && textValue.length > 0 && this.options.processEntities){
	    for (let i=0; i<this.options.entities.length; i++) {
	      const entity = this.options.entities[i];
	      textValue = textValue.replace(entity.regex, entity.val);
	    }
	  }
	  return textValue;
	};

	function indentate(level) {
	  return this.options.indentBy.repeat(level);
	}

	function isAttribute(name /*, options*/) {
	  if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {
	    return name.substr(this.attrPrefixLen);
	  } else {
	    return false;
	  }
	}

	json2xml = Builder;
	return json2xml;
}

var fxp;
var hasRequiredFxp;

function requireFxp () {
	if (hasRequiredFxp) return fxp;
	hasRequiredFxp = 1;

	const validator = requireValidator();
	const XMLParser = requireXMLParser();
	const XMLBuilder = requireJson2xml();

	fxp = {
	  XMLParser: XMLParser,
	  XMLValidator: validator,
	  XMLBuilder: XMLBuilder
	};
	return fxp;
}

var fxpExports = requireFxp();
const fastXmlParser = /*@__PURE__*/getDefaultExportFromCjs(fxpExports);

class OB11GroupMsgEmojiLikeEvent extends OB11GroupNoticeEvent {
  notice_type = "group_msg_emoji_like";
  message_id;
  likes;
  is_add;
  message_seq;
  constructor(core, groupId, userId, messageId, likes, isAdd, _messageSeq) {
    super(core, groupId, userId);
    this.group_id = groupId;
    this.user_id = userId;
    this.message_id = messageId;
    this.likes = likes;
    this.is_add = isAdd;
  }
}

class OB11GroupCardEvent extends OB11GroupNoticeEvent {
  notice_type = "group_card";
  card_new;
  card_old;
  constructor(core, groupId, userId, cardNew, cardOld) {
    super(core, groupId, userId);
    this.group_id = groupId;
    this.user_id = userId;
    this.card_new = cardNew;
    this.card_old = cardOld;
  }
}

class OB11GroupEssenceEvent extends OB11GroupNoticeEvent {
  notice_type = "essence";
  message_id;
  sender_id;
  operator_id;
  sub_type = "add";
  constructor(core, groupId, message_id, sender_id, operator_id) {
    super(core, groupId, sender_id);
    this.group_id = groupId;
    this.operator_id = operator_id;
    this.message_id = message_id;
    this.sender_id = sender_id;
  }
}

class OB11GroupTitleEvent extends OB11GroupNoticeEvent {
  notice_type = "notify";
  sub_type = "title";
  title;
  constructor(core, groupId, userId, title) {
    super(core, groupId, userId);
    this.group_id = groupId;
    this.user_id = userId;
    this.title = title;
  }
}

class OB11GroupUploadNoticeEvent extends OB11GroupNoticeEvent {
  notice_type = "group_upload";
  file;
  constructor(core, groupId, userId, file) {
    super(core, groupId, userId);
    this.group_id = groupId;
    this.user_id = userId;
    this.file = file;
  }
}

class OB11GroupNameEvent extends OB11GroupNoticeEvent {
  notice_type = "notify";
  sub_type = "group_name";
  name_new;
  constructor(core, groupId, userId, nameNew) {
    super(core, groupId, userId);
    this.name_new = nameNew;
  }
}

class TimeBasedCache {
  constructor(maxCapacity, ttl = 30 * 1e3 * 60, cleanupCount = 10) {
    this.maxCapacity = maxCapacity;
    this.ttl = ttl;
    this.cleanupCount = cleanupCount;
  }
  cache = /* @__PURE__ */ new Map();
  keyList = /* @__PURE__ */ new Set();
  operationCount = 0;
  put(key, value) {
    const timestamp = Date.now();
    const cacheEntry = { value, timestamp, frequency: 1 };
    this.cache.set(key, cacheEntry);
    this.keyList.add(key);
    this.operationCount++;
    if (this.keyList.size > this.maxCapacity) this.evict();
    if (this.operationCount >= this.cleanupCount) this.cleanup(this.cleanupCount);
  }
  get(key) {
    const entry = this.cache.get(key);
    if (entry && Date.now() - entry.timestamp < this.ttl) {
      entry.timestamp = Date.now();
      entry.frequency++;
      this.operationCount++;
      if (this.operationCount >= this.cleanupCount) this.cleanup(this.cleanupCount);
      return entry.value;
    } else {
      this.deleteKey(key);
    }
    return void 0;
  }
  cleanup(count) {
    const currentTime = Date.now();
    let cleaned = 0;
    for (const key of this.keyList) {
      if (cleaned >= count) break;
      const entry = this.cache.get(key);
      if (entry && currentTime - entry.timestamp >= this.ttl) {
        this.deleteKey(key);
        cleaned++;
      }
    }
    this.operationCount = 0;
  }
  deleteKey(key) {
    this.cache.delete(key);
    this.keyList.delete(key);
  }
  evict() {
    while (this.keyList.size > this.maxCapacity) {
      let oldestKey;
      let minFrequency = Infinity;
      for (const key of this.keyList) {
        const entry = this.cache.get(key);
        if (entry && entry.frequency < minFrequency) {
          minFrequency = entry.frequency;
          oldestKey = key;
        }
      }
      if (oldestKey !== void 0) this.deleteKey(oldestKey);
    }
  }
}
class FileUUIDManager {
  cache;
  constructor(ttl) {
    this.cache = new TimeBasedCache(5e3, ttl);
  }
  encode(data, endString = "", customUUID) {
    const uuid = customUUID || randomUUID().replace(/-/g, "") + endString;
    this.cache.put(uuid, data);
    return uuid;
  }
  decode(uuid) {
    return this.cache.get(uuid);
  }
}
class FileNapCatOneBotUUIDWrap {
  manager;
  constructor(ttl = 864e5) {
    this.manager = new FileUUIDManager(ttl);
  }
  encodeModelId(peer, modelId, fileId, fileUUID = "", endString = "", customUUID) {
    return this.manager.encode({ peer, modelId, fileId, fileUUID }, endString, customUUID);
  }
  decodeModelId(uuid) {
    return this.manager.decode(uuid);
  }
  encode(peer, msgId, elementId, fileUUID = "", customUUID) {
    return this.manager.encode({ peer, msgId, elementId, fileUUID }, "", customUUID);
  }
  decode(uuid) {
    return this.manager.decode(uuid);
  }
}
const FileNapCatOneBotUUID = new FileNapCatOneBotUUIDWrap();

class OB11GroupIncreaseEvent extends OB11GroupNoticeEvent {
  notice_type = "group_increase";
  operator_id;
  sub_type;
  constructor(core, groupId, userId, operatorId, subType = "approve") {
    super(core, groupId, userId);
    this.group_id = groupId;
    this.operator_id = operatorId;
    this.user_id = userId;
    this.sub_type = subType;
  }
}

class OneBotGroupApi {
  obContext;
  core;
  constructor(obContext, core) {
    this.obContext = obContext;
    this.core = core;
  }
  async parseGroupBanEvent(GroupCode, grayTipElement) {
    const groupElement = grayTipElement?.groupElement;
    if (!groupElement?.shutUp) return void 0;
    const memberUid = groupElement.shutUp.member.uid;
    const adminUid = groupElement.shutUp.admin.uid;
    let memberUin;
    let duration = parseInt(groupElement.shutUp.duration);
    const subType = duration > 0 ? "ban" : "lift_ban";
    if (memberUid) {
      memberUin = (await this.core.apis.GroupApi.getGroupMember(GroupCode, memberUid))?.uin ?? "";
    } else {
      memberUin = "0";
      if (duration > 0) {
        duration = -1;
      }
    }
    await this.core.apis.GroupApi.refreshGroupMemberCachePartial(GroupCode, memberUid);
    const adminUin = (await this.core.apis.GroupApi.getGroupMember(GroupCode, adminUid))?.uin;
    if (memberUin && adminUin) {
      return new OB11GroupBanEvent(
        this.core,
        parseInt(GroupCode),
        parseInt(memberUin),
        parseInt(adminUin),
        duration,
        subType
      );
    }
    return void 0;
  }
  async parseGroupEmojiLikeEventByGrayTip(groupCode, grayTipElement) {
    if (this.core.apis.PacketApi.packetStatus === true) {
      return;
    }
    const emojiLikeData = new fastXmlParser.XMLParser({
      ignoreAttributes: false,
      attributeNamePrefix: ""
    }).parse(grayTipElement.xmlElement.content);
    this.core.context.logger.logDebug("收到表情回应我的消息", emojiLikeData);
    const senderUin = emojiLikeData.gtip.qq.jp;
    const msgSeq = emojiLikeData.gtip.url.msgseq;
    const emojiId = emojiLikeData.gtip.face.id;
    return await this.createGroupEmojiLikeEvent(groupCode, senderUin, msgSeq, emojiId, true, 1);
  }
  async createGroupEmojiLikeEvent(groupCode, senderUin, msgSeq, emojiId, isAdd = true, count = 1) {
    const peer = {
      chatType: ChatType.KCHATTYPEGROUP,
      guildId: "",
      peerUid: groupCode
    };
    const replyMsgList = (await this.core.apis.MsgApi.queryFirstMsgBySeq(peer, msgSeq)).msgList;
    if (replyMsgList.length < 1) {
      return;
    }
    const replyMsg = replyMsgList[0];
    if (!replyMsg) {
      this.core.context.logger.logError("解析表情回应消息失败: 未找到回应消息");
      return void 0;
    }
    return new OB11GroupMsgEmojiLikeEvent(
      this.core,
      parseInt(groupCode),
      parseInt(senderUin),
      MessageUnique.createUniqueMsgId({ chatType: ChatType.KCHATTYPEGROUP, guildId: "", peerUid: groupCode }, replyMsg.msgId),
      [{
        emoji_id: emojiId,
        count
      }],
      isAdd,
      msgSeq
    );
  }
  async parseCardChangedEvent(msg) {
    if (msg.senderUin && msg.senderUin !== "0") {
      const member = await this.core.apis.GroupApi.getGroupMember(msg.peerUid, msg.senderUin);
      if (member && member.cardName !== msg.sendMemberName) {
        const newCardName = msg.sendMemberName ?? "";
        const event = new OB11GroupCardEvent(this.core, parseInt(msg.peerUid), parseInt(msg.senderUin), newCardName, member.cardName);
        member.cardName = newCardName;
        return event;
      }
      if (member && member.nick !== msg.sendNickName) {
        await this.core.apis.GroupApi.refreshGroupMemberCachePartial(msg.peerUid, msg.senderUid);
      }
    }
    return void 0;
  }
  async registerParseGroupReactEvent() {
    this.obContext.core.context.packetHandler.onCmd("trpc.msg.olpush.OlPushService.MsgPush", async (packet) => {
      const data = new NapProtoMsg(PushMsg).decode(Buffer.from(packet.hex_data, "hex"));
      if (data.message.contentHead.type === 732 && data.message.contentHead.subType === 16) {
        const pbNotify = data.message.body?.msgContent?.slice(7);
        if (!pbNotify) {
          return;
        }
        const notify = new NapProtoMsg(GroupReactNotify).decode(pbNotify);
        if ((notify.field13 ?? 0) === 35) {
          const groupCode = notify.groupUin?.toString() ?? "";
          const operatorUid = notify.groupReactionData?.data?.data?.groupReactionDataContent?.operatorUid ?? "";
          const type = notify.groupReactionData?.data?.data?.groupReactionDataContent?.type ?? 0;
          const seq = notify.groupReactionData?.data?.data?.groupReactionTarget?.seq?.toString() ?? "";
          const code = notify.groupReactionData?.data?.data?.groupReactionDataContent?.code ?? "";
          const senderUin = await this.core.apis.UserApi.getUinByUidV2(operatorUid);
          const event = await this.createGroupEmojiLikeEvent(
            groupCode,
            senderUin,
            seq,
            code,
            type === 1,
            1
          );
          if (event) {
            this.obContext.networkManager.emitEvent(event);
          }
        }
      }
    });
  }
  async registerParseGroupReactEventByCore() {
    this.core.event.on("event:emoji_like", async (data) => {
      const event = await this.createGroupEmojiLikeEvent(
        data.groupId,
        data.senderUin,
        data.msgSeq,
        data.emojiId,
        data.isAdd,
        data.count
      );
      if (event) {
        this.obContext.networkManager.emitEvent(event);
      }
    });
  }
  async parsePaiYiPai(msg, jsonStr) {
    const json = JSON.parse(jsonStr);
    const pokedetail = json.items;
    const poke_uid = pokedetail.filter((item) => item.uid);
    if (poke_uid.length === 2 && poke_uid[0]?.uid && poke_uid[1]?.uid) {
      return new OB11GroupPokeEvent(
        this.core,
        parseInt(msg.peerUid),
        +await this.core.apis.UserApi.getUinByUidV2(poke_uid[0].uid),
        +await this.core.apis.UserApi.getUinByUidV2(poke_uid[1].uid),
        pokedetail
      );
    }
    return void 0;
  }
  async parseOtherJsonEvent(msg, jsonStr, context) {
    const json = JSON.parse(jsonStr);
    const type = json.items[json.items.length - 1]?.txt;
    await this.core.apis.GroupApi.refreshGroupMemberCachePartial(msg.peerUid, msg.senderUid);
    if (type === "头衔") {
      const memberUin = json.items[1].param[0];
      const title = json.items[3].txt;
      context.logger.logDebug("收到群成员新头衔消息", json);
      return new OB11GroupTitleEvent(
        this.core,
        +msg.peerUid,
        +memberUin,
        title
      );
    } else if (type === "移出") {
      context.logger.logDebug("收到机器人被踢消息", json);
    } else {
      context.logger.logWarn("收到未知的灰条消息", json);
    }
    return void 0;
  }
  async parseEssenceMsg(msg, jsonStr) {
    const json = JSON.parse(jsonStr);
    const searchParams = new URL(json.items[0].jp).searchParams;
    const msgSeq = searchParams.get("msgSeq");
    const Group = searchParams.get("groupCode");
    if (!Group) return void 0;
    const Peer = {
      guildId: "",
      chatType: ChatType.KCHATTYPEGROUP,
      peerUid: Group
    };
    const msgData = await this.core.apis.MsgApi.getMsgsBySeqAndCount(Peer, msgSeq.toString(), 1, true, true);
    const msgList = (await this.core.apis.WebApi.getGroupEssenceMsgAll(Group)).flatMap((e) => e.data.msg_list);
    const realMsg = msgList.find((e) => e.msg_seq.toString() === msgSeq);
    if (msgData.msgList[0]) {
      return new OB11GroupEssenceEvent(
        this.core,
        parseInt(msg.peerUid),
        MessageUnique.getShortIdByMsgId(msgData.msgList[0].msgId),
        parseInt(msgData.msgList[0].senderUin ?? await this.core.apis.UserApi.getUinByUidV2(msgData.msgList[0].senderUid)),
        parseInt(realMsg?.add_digest_uin ?? "0")
      );
    }
    return void 0;
  }
  async parseGroupUploadFileEvene(msg, element, elementWrapper) {
    return new OB11GroupUploadNoticeEvent(
      this.core,
      parseInt(msg.peerUid),
      parseInt(msg.senderUin || ""),
      {
        id: FileNapCatOneBotUUID.encode({
          chatType: ChatType.KCHATTYPEGROUP,
          peerUid: msg.peerUid
        }, msg.msgId, elementWrapper.elementId, elementWrapper?.fileElement?.fileUuid, element.fileMd5 ?? element.fileUuid),
        name: element.fileName,
        size: parseInt(element.fileSize),
        busid: element.fileBizId ?? 0
      }
    );
  }
  async parseGroupElement(msg, element, elementWrapper) {
    if (element.type === TipGroupElementType.KGROUPNAMEMODIFIED) {
      this.core.context.logger.logDebug("收到群名称变更事件", element);
      return new OB11GroupNameEvent(
        this.core,
        parseInt(msg.peerUid),
        parseInt(await this.core.apis.UserApi.getUinByUidV2(element.memberUid)),
        element.groupName
      );
    } else if (element.type === TipGroupElementType.KSHUTUP) {
      const event = await this.parseGroupBanEvent(msg.peerUid, elementWrapper);
      return event;
    } else if (element.type === TipGroupElementType.KMEMBERADD) {
      if (element.memberUid === this.core.selfInfo.uid) {
        await this.core.apis.GroupApi.refreshGroupMemberCache(msg.peerUid, true);
        return new OB11GroupIncreaseEvent(
          this.core,
          parseInt(msg.peerUid),
          +this.core.selfInfo.uin,
          element.adminUid ? +await this.core.apis.UserApi.getUinByUidV2(element.adminUid) : 0,
          "approve"
        );
      }
    }
    return void 0;
  }
  async parseSelfInviteEvent(msg, inviterUin, inviteeUin) {
    return new OB11GroupIncreaseEvent(
      this.core,
      parseInt(msg.peerUid),
      +inviteeUin,
      +inviterUin,
      "invite"
    );
  }
  async parse51TypeEvent(msg, grayTipElement) {
    if (grayTipElement.jsonGrayTipElement.jsonStr) {
      const json = JSON.parse(grayTipElement.jsonGrayTipElement.jsonStr);
      if (json.items.length === 1 && json.items[0]?.txt.endsWith("加入群")) {
        const old_members = structuredClone(this.core.apis.GroupApi.groupMemberCache.get(msg.peerUid));
        if (!old_members) return;
        const new_members_map = await this.core.apis.GroupApi.refreshGroupMemberCache(msg.peerUid, true);
        if (!new_members_map) return;
        const new_members = Array.from(new_members_map.values());
        const new_member = new_members.find((member) => old_members.get(member.uid) === void 0);
        if (!new_member) return;
        return new OB11GroupIncreaseEvent(
          this.core,
          +msg.peerUid,
          +new_member.uin,
          0,
          "invite"
        );
      }
    }
    return void 0;
  }
  async parseGrayTipElement(msg, grayTipElement) {
    if (grayTipElement.subElementType === NTGrayTipElementSubTypeV2.GRAYTIP_ELEMENT_SUBTYPE_GROUP) {
      return await this.parseGroupElement(msg, grayTipElement.groupElement, grayTipElement);
    } else if (grayTipElement.subElementType === NTGrayTipElementSubTypeV2.GRAYTIP_ELEMENT_SUBTYPE_XMLMSG) {
      if (grayTipElement.xmlElement?.templId === "10382") {
        return await this.obContext.apis.GroupApi.parseGroupEmojiLikeEventByGrayTip(msg.peerUid, grayTipElement);
      }
    } else if (grayTipElement.subElementType === NTGrayTipElementSubTypeV2.GRAYTIP_ELEMENT_SUBTYPE_JSON) {
      if (grayTipElement.jsonGrayTipElement.busiId === "1061") {
        return await this.parsePaiYiPai(msg, grayTipElement.jsonGrayTipElement.jsonStr);
      } else if (grayTipElement.jsonGrayTipElement.busiId === JsonGrayBusiId.AIO_GROUP_ESSENCE_MSG_TIP.toString()) {
        return await this.parseEssenceMsg(msg, grayTipElement.jsonGrayTipElement.jsonStr);
      } else if (grayTipElement.jsonGrayTipElement.busiId === "51") {
        return await this.parse51TypeEvent(msg, grayTipElement);
      } else {
        console.log("Unknown JSON event:", grayTipElement.jsonGrayTipElement, JSON.stringify(grayTipElement));
        return await this.parseOtherJsonEvent(msg, grayTipElement.jsonGrayTipElement.jsonStr, this.core.context);
      }
    }
    return void 0;
  }
}

class OB11ProfileLikeEvent extends OB11BaseNoticeEvent {
  notice_type = "notify";
  sub_type = "profile_like";
  operator_id;
  operator_nick;
  times;
  time;
  constructor(core, operatorId, operatorNick, times, time) {
    super(core);
    this.operator_id = operatorId;
    this.operator_nick = operatorNick;
    this.times = times;
    this.time = time;
  }
}

const LikeDetail = {
  txt: ProtoField(1, ScalarType.STRING),
  uin: ProtoField(3, ScalarType.INT64),
  nickname: ProtoField(5, ScalarType.STRING)
};
const LikeMsg = {
  times: ProtoField(1, ScalarType.INT32),
  time: ProtoField(2, ScalarType.INT32),
  detail: ProtoField(3, () => LikeDetail)
};
const ProfileLikeSubTip = {
  msg: ProtoField(14, () => LikeMsg)
};
const ProfileLikeTip = {
  msgType: ProtoField(1, ScalarType.INT32),
  subType: ProtoField(2, ScalarType.INT32),
  content: ProtoField(203, () => ProfileLikeSubTip)
};
({
  PeerNumber: ProtoField(1, ScalarType.UINT32),
  PeerString: ProtoField(2, ScalarType.STRING),
  Uin: ProtoField(5, ScalarType.UINT32),
  Uid: ProtoField(6, ScalarType.STRING, true)
});
({
  msgType: ProtoField(1, ScalarType.UINT32),
  subType: ProtoField(2, ScalarType.UINT32),
  subSubType: ProtoField(3, ScalarType.UINT32),
  msgSeq: ProtoField(5, ScalarType.UINT32),
  time: ProtoField(6, ScalarType.UINT32),
  msgId: ProtoField(12, ScalarType.UINT64),
  other: ProtoField(13, ScalarType.UINT32)
});
({
  wrappedBody: ProtoField(2, ScalarType.BYTES)
});
function decodeProfileLikeTip(buffer) {
  const msg = new NapProtoMsg(ProfileLikeTip);
  return msg.decode(buffer);
}

class OneBotUserApi {
  obContext;
  core;
  constructor(obContext, core) {
    this.obContext = obContext;
    this.core = core;
  }
  async parseLikeEvent(wrappedBody) {
    const likeTip = decodeProfileLikeTip(wrappedBody);
    if (likeTip?.msgType !== 0 || likeTip?.subType !== 203) return;
    this.core.context.logger.logDebug("收到点赞通知消息");
    const likeMsg = likeTip.content.msg;
    if (!likeMsg) return;
    const detail = likeMsg.detail;
    if (!detail) return;
    const times = detail.txt.match(/\d+/) ?? "0";
    return new OB11ProfileLikeEvent(
      this.core,
      Number(detail.uin),
      detail.nickname,
      parseInt(times[0], 10),
      likeMsg.time
    );
  }
}

const sysface = /* #__PURE__ */ JSON.parse("[{\"QSid\":\"392\",\"QDes\":\"/龙年快乐\",\"IQLid\":\"392\",\"AQLid\":\"392\",\"EMCode\":\"10392\",\"AniStickerType\":3,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"38\"},{\"QSid\":\"393\",\"QDes\":\"/新年中龙\",\"IQLid\":\"393\",\"AQLid\":\"393\",\"EMCode\":\"10393\",\"QHide\":\"1\",\"AniStickerType\":3,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"39\"},{\"QSid\":\"364\",\"QDes\":\"/超级赞\",\"IQLid\":\"364\",\"AQLid\":\"364\",\"EMCode\":\"10364\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"1\",\"AniStickerPackId\":\"2\",\"AniStickerPackName\":\"汪汪\"},{\"QSid\":\"366\",\"QDes\":\"/芒狗\",\"IQLid\":\"366\",\"AQLid\":\"366\",\"EMCode\":\"10366\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"2\",\"AniStickerPackId\":\"2\",\"AniStickerPackName\":\"汪汪\"},{\"QSid\":\"362\",\"QDes\":\"/好兄弟\",\"IQLid\":\"362\",\"AQLid\":\"362\",\"EMCode\":\"10362\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"3\",\"AniStickerPackId\":\"2\",\"AniStickerPackName\":\"汪汪\"},{\"QSid\":\"397\",\"QDes\":\"/抛媚眼\",\"IQLid\":\"397\",\"AQLid\":\"397\",\"EMCode\":\"10397\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"4\",\"AniStickerPackId\":\"2\",\"AniStickerPackName\":\"汪汪\"},{\"QSid\":\"396\",\"QDes\":\"/狼狗\",\"IQLid\":\"396\",\"AQLid\":\"396\",\"EMCode\":\"10396\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"5\",\"AniStickerPackId\":\"2\",\"AniStickerPackName\":\"汪汪\"},{\"QSid\":\"360\",\"QDes\":\"/亲亲\",\"IQLid\":\"360\",\"AQLid\":\"360\",\"EMCode\":\"10360\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"6\",\"AniStickerPackId\":\"2\",\"AniStickerPackName\":\"汪汪\"},{\"QSid\":\"361\",\"QDes\":\"/狗狗笑哭\",\"IQLid\":\"361\",\"AQLid\":\"361\",\"EMCode\":\"10361\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"7\",\"AniStickerPackId\":\"2\",\"AniStickerPackName\":\"汪汪\"},{\"QSid\":\"363\",\"QDes\":\"/狗狗可怜\",\"IQLid\":\"363\",\"AQLid\":\"363\",\"EMCode\":\"10363\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"8\",\"AniStickerPackId\":\"2\",\"AniStickerPackName\":\"汪汪\"},{\"QSid\":\"365\",\"QDes\":\"/狗狗生气\",\"IQLid\":\"365\",\"AQLid\":\"365\",\"EMCode\":\"10365\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"9\",\"AniStickerPackId\":\"2\",\"AniStickerPackName\":\"汪汪\"},{\"QSid\":\"367\",\"QDes\":\"/狗狗疑问\",\"IQLid\":\"367\",\"AQLid\":\"367\",\"EMCode\":\"10367\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"10\",\"AniStickerPackId\":\"2\",\"AniStickerPackName\":\"汪汪\"},{\"QSid\":\"399\",\"QDes\":\"/tui\",\"IQLid\":\"399\",\"AQLid\":\"399\",\"EMCode\":\"10399\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"1\",\"AniStickerPackId\":\"6\",\"AniStickerPackName\":\"噗噗星人\"},{\"QSid\":\"398\",\"QDes\":\"/超级ok\",\"IQLid\":\"398\",\"AQLid\":\"398\",\"EMCode\":\"10398\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"2\",\"AniStickerPackId\":\"6\",\"AniStickerPackName\":\"噗噗星人\"},{\"QSid\":\"373\",\"QDes\":\"/忙\",\"IQLid\":\"373\",\"AQLid\":\"373\",\"EMCode\":\"10373\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"3\",\"AniStickerPackId\":\"6\",\"AniStickerPackName\":\"噗噗星人\"},{\"QSid\":\"370\",\"QDes\":\"/祝贺\",\"IQLid\":\"370\",\"AQLid\":\"370\",\"EMCode\":\"10370\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"4\",\"AniStickerPackId\":\"6\",\"AniStickerPackName\":\"噗噗星人\"},{\"QSid\":\"375\",\"QDes\":\"/超级鼓掌\",\"IQLid\":\"375\",\"AQLid\":\"375\",\"EMCode\":\"10375\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"5\",\"AniStickerPackId\":\"6\",\"AniStickerPackName\":\"噗噗星人\"},{\"QSid\":\"368\",\"QDes\":\"/奥特笑哭\",\"IQLid\":\"368\",\"AQLid\":\"368\",\"EMCode\":\"10368\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"6\",\"AniStickerPackId\":\"6\",\"AniStickerPackName\":\"噗噗星人\"},{\"QSid\":\"369\",\"QDes\":\"/彩虹\",\"IQLid\":\"369\",\"AQLid\":\"369\",\"EMCode\":\"10369\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"7\",\"AniStickerPackId\":\"6\",\"AniStickerPackName\":\"噗噗星人\"},{\"QSid\":\"371\",\"QDes\":\"/冒泡\",\"IQLid\":\"371\",\"AQLid\":\"371\",\"EMCode\":\"10371\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"8\",\"AniStickerPackId\":\"6\",\"AniStickerPackName\":\"噗噗星人\"},{\"QSid\":\"372\",\"QDes\":\"/气呼呼\",\"IQLid\":\"372\",\"AQLid\":\"372\",\"EMCode\":\"10372\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"9\",\"AniStickerPackId\":\"6\",\"AniStickerPackName\":\"噗噗星人\"},{\"QSid\":\"374\",\"QDes\":\"/波波流泪\",\"IQLid\":\"374\",\"AQLid\":\"374\",\"EMCode\":\"10374\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"10\",\"AniStickerPackId\":\"6\",\"AniStickerPackName\":\"噗噗星人\"},{\"QSid\":\"382\",\"QDes\":\"/emo\",\"IQLid\":\"382\",\"AQLid\":\"382\",\"EMCode\":\"10382\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"1\",\"AniStickerPackId\":\"5\",\"AniStickerPackName\":\"企鹅\"},{\"QSid\":\"383\",\"QDes\":\"/企鹅爱心\",\"IQLid\":\"383\",\"AQLid\":\"383\",\"EMCode\":\"10383\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"2\",\"AniStickerPackId\":\"5\",\"AniStickerPackName\":\"企鹅\"},{\"QSid\":\"401\",\"QDes\":\"/超级转圈\",\"IQLid\":\"401\",\"AQLid\":\"401\",\"EMCode\":\"10401\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"3\",\"AniStickerPackId\":\"5\",\"AniStickerPackName\":\"企鹅\"},{\"QSid\":\"400\",\"QDes\":\"/快乐\",\"IQLid\":\"400\",\"AQLid\":\"400\",\"EMCode\":\"10400\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"4\",\"AniStickerPackId\":\"5\",\"AniStickerPackName\":\"企鹅\"},{\"QSid\":\"380\",\"QDes\":\"/真棒\",\"IQLid\":\"380\",\"AQLid\":\"380\",\"EMCode\":\"10380\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"5\",\"AniStickerPackId\":\"5\",\"AniStickerPackName\":\"企鹅\"},{\"QSid\":\"381\",\"QDes\":\"/路过\",\"IQLid\":\"381\",\"AQLid\":\"381\",\"EMCode\":\"10381\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"6\",\"AniStickerPackId\":\"5\",\"AniStickerPackName\":\"企鹅\"},{\"QSid\":\"379\",\"QDes\":\"/企鹅流泪\",\"IQLid\":\"379\",\"AQLid\":\"379\",\"EMCode\":\"10379\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"7\",\"AniStickerPackId\":\"5\",\"AniStickerPackName\":\"企鹅\"},{\"QSid\":\"376\",\"QDes\":\"/跺脚\",\"IQLid\":\"376\",\"AQLid\":\"376\",\"EMCode\":\"10376\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"8\",\"AniStickerPackId\":\"5\",\"AniStickerPackName\":\"企鹅\"},{\"QSid\":\"378\",\"QDes\":\"/企鹅笑哭\",\"IQLid\":\"378\",\"AQLid\":\"378\",\"EMCode\":\"10378\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"9\",\"AniStickerPackId\":\"5\",\"AniStickerPackName\":\"企鹅\"},{\"QSid\":\"377\",\"QDes\":\"/嗨\",\"IQLid\":\"377\",\"AQLid\":\"377\",\"EMCode\":\"10377\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"10\",\"AniStickerPackId\":\"5\",\"AniStickerPackName\":\"企鹅\"},{\"QSid\":\"403\",\"QDes\":\"/出去玩\",\"IQLid\":\"403\",\"AQLid\":\"403\",\"EMCode\":\"10403\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"1\",\"AniStickerPackId\":\"4\",\"AniStickerPackName\":\"QQ黄脸\"},{\"QSid\":\"402\",\"QDes\":\"/别说话\",\"IQLid\":\"402\",\"AQLid\":\"402\",\"EMCode\":\"10402\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"2\",\"AniStickerPackId\":\"4\",\"AniStickerPackName\":\"QQ黄脸\"},{\"QSid\":\"390\",\"QDes\":\"/太头秃\",\"IQLid\":\"390\",\"AQLid\":\"390\",\"EMCode\":\"10390\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"3\",\"AniStickerPackId\":\"4\",\"AniStickerPackName\":\"QQ黄脸\"},{\"QSid\":\"391\",\"QDes\":\"/太沧桑\",\"IQLid\":\"391\",\"AQLid\":\"391\",\"EMCode\":\"10391\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"4\",\"AniStickerPackId\":\"4\",\"AniStickerPackName\":\"QQ黄脸\"},{\"QSid\":\"388\",\"QDes\":\"/太头疼\",\"IQLid\":\"388\",\"AQLid\":\"388\",\"EMCode\":\"10388\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"5\",\"AniStickerPackId\":\"4\",\"AniStickerPackName\":\"QQ黄脸\"},{\"QSid\":\"389\",\"QDes\":\"/太赞了\",\"IQLid\":\"389\",\"AQLid\":\"389\",\"EMCode\":\"10389\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"6\",\"AniStickerPackId\":\"4\",\"AniStickerPackName\":\"QQ黄脸\"},{\"QSid\":\"386\",\"QDes\":\"/呜呜呜\",\"IQLid\":\"386\",\"AQLid\":\"386\",\"EMCode\":\"10386\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"7\",\"AniStickerPackId\":\"4\",\"AniStickerPackName\":\"QQ黄脸\"},{\"QSid\":\"385\",\"QDes\":\"/太气了\",\"IQLid\":\"385\",\"AQLid\":\"385\",\"EMCode\":\"10385\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"8\",\"AniStickerPackId\":\"4\",\"AniStickerPackName\":\"QQ黄脸\"},{\"QSid\":\"384\",\"QDes\":\"/晚安\",\"IQLid\":\"384\",\"AQLid\":\"384\",\"EMCode\":\"10384\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"9\",\"AniStickerPackId\":\"4\",\"AniStickerPackName\":\"QQ黄脸\"},{\"QSid\":\"387\",\"QDes\":\"/太好笑\",\"IQLid\":\"387\",\"AQLid\":\"387\",\"EMCode\":\"10387\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"10\",\"AniStickerPackId\":\"4\",\"AniStickerPackName\":\"QQ黄脸\"},{\"QSid\":\"413\",\"QDes\":\"/摇起来\",\"IQLid\":\"413\",\"AQLid\":\"413\",\"EMCode\":\"10413\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"1\",\"AniStickerPackId\":\"3\",\"AniStickerPackName\":\"喜花妮\"},{\"QSid\":\"405\",\"QDes\":\"/好运来\",\"IQLid\":\"405\",\"AQLid\":\"405\",\"EMCode\":\"10405\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"2\",\"AniStickerPackId\":\"3\",\"AniStickerPackName\":\"喜花妮\"},{\"QSid\":\"404\",\"QDes\":\"/闪亮登场\",\"IQLid\":\"404\",\"AQLid\":\"404\",\"EMCode\":\"10404\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"3\",\"AniStickerPackId\":\"3\",\"AniStickerPackName\":\"喜花妮\"},{\"QSid\":\"406\",\"QDes\":\"/姐是女王\",\"IQLid\":\"406\",\"AQLid\":\"406\",\"EMCode\":\"10406\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"4\",\"AniStickerPackId\":\"3\",\"AniStickerPackName\":\"喜花妮\"},{\"QSid\":\"410\",\"QDes\":\"/么么哒\",\"IQLid\":\"410\",\"AQLid\":\"410\",\"EMCode\":\"10410\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"5\",\"AniStickerPackId\":\"3\",\"AniStickerPackName\":\"喜花妮\"},{\"QSid\":\"411\",\"QDes\":\"/一起嗨\",\"IQLid\":\"411\",\"AQLid\":\"411\",\"EMCode\":\"10411\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"6\",\"AniStickerPackId\":\"3\",\"AniStickerPackName\":\"喜花妮\"},{\"QSid\":\"407\",\"QDes\":\"/我听听\",\"IQLid\":\"407\",\"AQLid\":\"407\",\"EMCode\":\"10407\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"7\",\"AniStickerPackId\":\"3\",\"AniStickerPackName\":\"喜花妮\"},{\"QSid\":\"408\",\"QDes\":\"/臭美\",\"IQLid\":\"408\",\"AQLid\":\"408\",\"EMCode\":\"10408\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"8\",\"AniStickerPackId\":\"3\",\"AniStickerPackName\":\"喜花妮\"},{\"QSid\":\"412\",\"QDes\":\"/开心\",\"IQLid\":\"412\",\"AQLid\":\"412\",\"EMCode\":\"10412\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"9\",\"AniStickerPackId\":\"3\",\"AniStickerPackName\":\"喜花妮\"},{\"QSid\":\"409\",\"QDes\":\"/送你花花\",\"IQLid\":\"409\",\"AQLid\":\"409\",\"EMCode\":\"10409\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerId\":\"10\",\"AniStickerPackId\":\"3\",\"AniStickerPackName\":\"喜花妮\"},{\"QSid\":\"394\",\"QDes\":\"/新年大龙\",\"IQLid\":\"394\",\"AQLid\":\"394\",\"EMCode\":\"10394\",\"QHide\":\"1\",\"AniStickerType\":3,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"40\"},{\"QSid\":\"14\",\"QDes\":\"/微笑\",\"IQLid\":\"23\",\"AQLid\":\"23\",\"EMCode\":\"100\"},{\"QSid\":\"1\",\"QDes\":\"/撇嘴\",\"IQLid\":\"40\",\"AQLid\":\"40\",\"EMCode\":\"101\"},{\"QSid\":\"2\",\"QDes\":\"/色\",\"IQLid\":\"19\",\"AQLid\":\"19\",\"EMCode\":\"102\"},{\"QSid\":\"3\",\"QDes\":\"/发呆\",\"IQLid\":\"43\",\"AQLid\":\"43\",\"EMCode\":\"103\"},{\"QSid\":\"4\",\"QDes\":\"/得意\",\"IQLid\":\"21\",\"AQLid\":\"21\",\"EMCode\":\"104\"},{\"QSid\":\"6\",\"QDes\":\"/害羞\",\"IQLid\":\"20\",\"AQLid\":\"20\",\"EMCode\":\"106\"},{\"QSid\":\"7\",\"QDes\":\"/闭嘴\",\"IQLid\":\"104\",\"AQLid\":\"106\",\"EMCode\":\"107\"},{\"QSid\":\"8\",\"QDes\":\"/睡\",\"IQLid\":\"35\",\"AQLid\":\"35\",\"EMCode\":\"108\"},{\"QSid\":\"9\",\"QDes\":\"/大哭\",\"IQLid\":\"10\",\"AQLid\":\"10\",\"EMCode\":\"109\"},{\"QSid\":\"5\",\"QDes\":\"/流泪\",\"IQLid\":\"9\",\"AQLid\":\"9\",\"EMCode\":\"105\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"16\"},{\"QSid\":\"10\",\"QDes\":\"/尴尬\",\"IQLid\":\"25\",\"AQLid\":\"25\",\"EMCode\":\"110\"},{\"QSid\":\"11\",\"QDes\":\"/发怒\",\"IQLid\":\"24\",\"AQLid\":\"24\",\"EMCode\":\"111\"},{\"QSid\":\"12\",\"QDes\":\"/调皮\",\"IQLid\":\"1\",\"AQLid\":\"1\",\"EMCode\":\"112\"},{\"QSid\":\"13\",\"QDes\":\"/呲牙\",\"IQLid\":\"0\",\"AQLid\":\"0\",\"EMCode\":\"113\"},{\"QSid\":\"0\",\"QDes\":\"/惊讶\",\"IQLid\":\"33\",\"AQLid\":\"33\",\"EMCode\":\"114\"},{\"QSid\":\"15\",\"QDes\":\"/难过\",\"IQLid\":\"32\",\"AQLid\":\"32\",\"EMCode\":\"115\"},{\"QSid\":\"16\",\"QDes\":\"/酷\",\"IQLid\":\"12\",\"AQLid\":\"12\",\"EMCode\":\"116\"},{\"QSid\":\"96\",\"QDes\":\"/冷汗\",\"IQLid\":\"27\",\"AQLid\":\"27\",\"EMCode\":\"117\"},{\"QSid\":\"18\",\"QDes\":\"/抓狂\",\"IQLid\":\"13\",\"AQLid\":\"13\",\"EMCode\":\"118\"},{\"QSid\":\"19\",\"QDes\":\"/吐\",\"IQLid\":\"22\",\"AQLid\":\"22\",\"EMCode\":\"119\"},{\"QSid\":\"20\",\"QDes\":\"/偷笑\",\"IQLid\":\"3\",\"AQLid\":\"3\",\"EMCode\":\"120\"},{\"QSid\":\"21\",\"QDes\":\"/可爱\",\"IQLid\":\"18\",\"AQLid\":\"18\",\"EMCode\":\"121\"},{\"QSid\":\"22\",\"QDes\":\"/白眼\",\"IQLid\":\"30\",\"AQLid\":\"30\",\"EMCode\":\"122\"},{\"QSid\":\"23\",\"QDes\":\"/傲慢\",\"IQLid\":\"31\",\"AQLid\":\"31\",\"EMCode\":\"123\"},{\"QSid\":\"24\",\"QDes\":\"/饥饿\",\"IQLid\":\"79\",\"AQLid\":\"81\",\"EMCode\":\"124\"},{\"QSid\":\"25\",\"QDes\":\"/困\",\"IQLid\":\"80\",\"AQLid\":\"82\",\"EMCode\":\"125\"},{\"QSid\":\"26\",\"QDes\":\"/惊恐\",\"IQLid\":\"26\",\"AQLid\":\"26\",\"EMCode\":\"126\"},{\"QSid\":\"27\",\"QDes\":\"/流汗\",\"IQLid\":\"2\",\"AQLid\":\"2\",\"EMCode\":\"127\"},{\"QSid\":\"28\",\"QDes\":\"/憨笑\",\"IQLid\":\"37\",\"AQLid\":\"37\",\"EMCode\":\"128\"},{\"QSid\":\"29\",\"QDes\":\"/悠闲\",\"IQLid\":\"50\",\"AQLid\":\"50\",\"EMCode\":\"129\"},{\"QSid\":\"30\",\"QDes\":\"/奋斗\",\"IQLid\":\"42\",\"AQLid\":\"42\",\"EMCode\":\"130\"},{\"QSid\":\"31\",\"QDes\":\"/咒骂\",\"IQLid\":\"81\",\"AQLid\":\"83\",\"EMCode\":\"131\"},{\"QSid\":\"32\",\"QDes\":\"/疑问\",\"IQLid\":\"34\",\"AQLid\":\"34\",\"EMCode\":\"132\"},{\"QSid\":\"33\",\"QDes\":\"/嘘\",\"IQLid\":\"11\",\"AQLid\":\"11\",\"EMCode\":\"133\"},{\"QSid\":\"34\",\"QDes\":\"/晕\",\"IQLid\":\"49\",\"AQLid\":\"49\",\"EMCode\":\"134\"},{\"QSid\":\"35\",\"QDes\":\"/折磨\",\"IQLid\":\"82\",\"AQLid\":\"84\",\"EMCode\":\"135\"},{\"QSid\":\"36\",\"QDes\":\"/衰\",\"IQLid\":\"39\",\"AQLid\":\"39\",\"EMCode\":\"136\"},{\"QSid\":\"37\",\"QDes\":\"/骷髅\",\"isStatic\":\"1\",\"IQLid\":\"76\",\"AQLid\":\"78\",\"EMCode\":\"137\"},{\"QSid\":\"38\",\"QDes\":\"/敲打\",\"IQLid\":\"5\",\"AQLid\":\"5\",\"EMCode\":\"138\"},{\"QSid\":\"39\",\"QDes\":\"/再见\",\"IQLid\":\"4\",\"AQLid\":\"4\",\"EMCode\":\"139\"},{\"QSid\":\"97\",\"QDes\":\"/擦汗\",\"IQLid\":\"6\",\"AQLid\":\"6\",\"EMCode\":\"140\"},{\"QSid\":\"98\",\"QDes\":\"/抠鼻\",\"IQLid\":\"83\",\"AQLid\":\"85\",\"EMCode\":\"141\"},{\"QSid\":\"99\",\"QDes\":\"/鼓掌\",\"IQLid\":\"84\",\"AQLid\":\"86\",\"EMCode\":\"142\"},{\"QSid\":\"100\",\"QDes\":\"/糗大了\",\"IQLid\":\"85\",\"AQLid\":\"87\",\"EMCode\":\"143\"},{\"QSid\":\"101\",\"QDes\":\"/坏笑\",\"IQLid\":\"46\",\"AQLid\":\"46\",\"EMCode\":\"144\"},{\"QSid\":\"102\",\"QDes\":\"/左哼哼\",\"IQLid\":\"86\",\"AQLid\":\"88\",\"EMCode\":\"145\"},{\"QSid\":\"103\",\"QDes\":\"/右哼哼\",\"IQLid\":\"44\",\"AQLid\":\"44\",\"EMCode\":\"146\"},{\"QSid\":\"104\",\"QDes\":\"/哈欠\",\"IQLid\":\"87\",\"AQLid\":\"89\",\"EMCode\":\"147\"},{\"QSid\":\"105\",\"QDes\":\"/鄙视\",\"IQLid\":\"48\",\"AQLid\":\"48\",\"EMCode\":\"148\"},{\"QSid\":\"106\",\"QDes\":\"/委屈\",\"IQLid\":\"14\",\"AQLid\":\"14\",\"EMCode\":\"149\"},{\"QSid\":\"107\",\"QDes\":\"/快哭了\",\"IQLid\":\"88\",\"AQLid\":\"90\",\"EMCode\":\"150\"},{\"QSid\":\"108\",\"QDes\":\"/阴险\",\"IQLid\":\"41\",\"AQLid\":\"41\",\"EMCode\":\"151\"},{\"QSid\":\"305\",\"QDes\":\"/右亲亲\",\"IQLid\":\"305\",\"AQLid\":\"305\",\"EMCode\":\"10305\"},{\"QSid\":\"109\",\"QDes\":\"/左亲亲\",\"IQLid\":\"36\",\"AQLid\":\"36\",\"EMCode\":\"152\"},{\"QSid\":\"110\",\"QDes\":\"/吓\",\"IQLid\":\"89\",\"AQLid\":\"91\",\"EMCode\":\"153\"},{\"QSid\":\"111\",\"QDes\":\"/可怜\",\"IQLid\":\"51\",\"AQLid\":\"51\",\"EMCode\":\"154\"},{\"QSid\":\"172\",\"QDes\":\"/眨眼睛\",\"IQLid\":\"142\",\"AQLid\":\"164\",\"EMCode\":\"242\"},{\"QSid\":\"182\",\"QDes\":\"/笑哭\",\"IQLid\":\"152\",\"AQLid\":\"174\",\"EMCode\":\"252\"},{\"QSid\":\"179\",\"QDes\":\"/doge\",\"IQLid\":\"149\",\"AQLid\":\"171\",\"EMCode\":\"249\"},{\"QSid\":\"173\",\"QDes\":\"/泪奔\",\"IQLid\":\"143\",\"AQLid\":\"165\",\"EMCode\":\"243\"},{\"QSid\":\"174\",\"QDes\":\"/无奈\",\"IQLid\":\"144\",\"AQLid\":\"166\",\"EMCode\":\"244\"},{\"QSid\":\"212\",\"QDes\":\"/托腮\",\"IQLid\":\"182\",\"AQLid\":\"161\",\"EMCode\":\"282\"},{\"QSid\":\"175\",\"QDes\":\"/卖萌\",\"IQLid\":\"145\",\"AQLid\":\"167\",\"EMCode\":\"245\"},{\"QSid\":\"178\",\"QDes\":\"/斜眼笑\",\"IQLid\":\"148\",\"AQLid\":\"170\",\"EMCode\":\"248\"},{\"QSid\":\"177\",\"QDes\":\"/喷血\",\"IQLid\":\"147\",\"AQLid\":\"169\",\"EMCode\":\"247\"},{\"QSid\":\"176\",\"QDes\":\"/小纠结\",\"IQLid\":\"146\",\"AQLid\":\"168\",\"EMCode\":\"246\"},{\"QSid\":\"183\",\"QDes\":\"/我最美\",\"IQLid\":\"153\",\"AQLid\":\"175\",\"EMCode\":\"253\"},{\"QSid\":\"262\",\"QDes\":\"/脑阔疼\",\"IQLid\":\"262\",\"AQLid\":\"262\",\"EMCode\":\"10262\"},{\"QSid\":\"263\",\"QDes\":\"/沧桑\",\"IQLid\":\"263\",\"AQLid\":\"263\",\"EMCode\":\"10263\"},{\"QSid\":\"264\",\"QDes\":\"/捂脸\",\"IQLid\":\"264\",\"AQLid\":\"264\",\"EMCode\":\"10264\"},{\"QSid\":\"265\",\"QDes\":\"/辣眼睛\",\"IQLid\":\"265\",\"AQLid\":\"265\",\"EMCode\":\"10265\"},{\"QSid\":\"266\",\"QDes\":\"/哦哟\",\"IQLid\":\"266\",\"AQLid\":\"266\",\"EMCode\":\"10266\"},{\"QSid\":\"267\",\"QDes\":\"/头秃\",\"IQLid\":\"267\",\"AQLid\":\"267\",\"EMCode\":\"10267\"},{\"QSid\":\"268\",\"QDes\":\"/问号脸\",\"IQLid\":\"268\",\"AQLid\":\"268\",\"EMCode\":\"10268\"},{\"QSid\":\"269\",\"QDes\":\"/暗中观察\",\"IQLid\":\"269\",\"AQLid\":\"269\",\"EMCode\":\"10269\"},{\"QSid\":\"270\",\"QDes\":\"/emm\",\"IQLid\":\"270\",\"AQLid\":\"270\",\"EMCode\":\"10270\"},{\"QSid\":\"271\",\"QDes\":\"/吃瓜\",\"IQLid\":\"271\",\"AQLid\":\"271\",\"EMCode\":\"10271\"},{\"QSid\":\"272\",\"QDes\":\"/呵呵哒\",\"IQLid\":\"272\",\"AQLid\":\"272\",\"EMCode\":\"10272\"},{\"QSid\":\"277\",\"QDes\":\"/汪汪\",\"IQLid\":\"277\",\"AQLid\":\"277\",\"EMCode\":\"10277\"},{\"QSid\":\"307\",\"QDes\":\"/喵喵\",\"IQLid\":\"307\",\"AQLid\":\"307\",\"EMCode\":\"10307\"},{\"QSid\":\"306\",\"QDes\":\"/牛气冲天\",\"isStatic\":\"1\",\"IQLid\":\"306\",\"AQLid\":\"306\",\"EMCode\":\"10306\"},{\"QSid\":\"281\",\"QDes\":\"/无眼笑\",\"IQLid\":\"281\",\"AQLid\":\"281\",\"EMCode\":\"10281\"},{\"QSid\":\"282\",\"QDes\":\"/敬礼\",\"IQLid\":\"282\",\"AQLid\":\"282\",\"EMCode\":\"10282\"},{\"QSid\":\"283\",\"QDes\":\"/狂笑\",\"IQLid\":\"283\",\"AQLid\":\"283\",\"EMCode\":\"10283\"},{\"QSid\":\"284\",\"QDes\":\"/面无表情\",\"IQLid\":\"284\",\"AQLid\":\"284\",\"EMCode\":\"10284\"},{\"QSid\":\"285\",\"QDes\":\"/摸鱼\",\"IQLid\":\"285\",\"AQLid\":\"285\",\"EMCode\":\"10285\"},{\"QSid\":\"293\",\"QDes\":\"/摸锦鲤\",\"IQLid\":\"293\",\"AQLid\":\"293\",\"EMCode\":\"10293\"},{\"QSid\":\"286\",\"QDes\":\"/魔鬼笑\",\"IQLid\":\"286\",\"AQLid\":\"286\",\"EMCode\":\"10286\"},{\"QSid\":\"287\",\"QDes\":\"/哦\",\"IQLid\":\"287\",\"AQLid\":\"287\",\"EMCode\":\"10287\"},{\"QSid\":\"289\",\"QDes\":\"/睁眼\",\"IQLid\":\"289\",\"AQLid\":\"289\",\"EMCode\":\"10289\"},{\"QSid\":\"294\",\"QDes\":\"/期待\",\"IQLid\":\"294\",\"AQLid\":\"294\",\"EMCode\":\"10294\"},{\"QSid\":\"297\",\"QDes\":\"/拜谢\",\"IQLid\":\"297\",\"AQLid\":\"297\",\"EMCode\":\"10297\"},{\"QSid\":\"298\",\"QDes\":\"/元宝\",\"IQLid\":\"298\",\"AQLid\":\"298\",\"EMCode\":\"10298\"},{\"QSid\":\"299\",\"QDes\":\"/牛啊\",\"IQLid\":\"299\",\"AQLid\":\"299\",\"EMCode\":\"10299\"},{\"QSid\":\"300\",\"QDes\":\"/胖三斤\",\"IQLid\":\"300\",\"AQLid\":\"300\",\"EMCode\":\"10300\"},{\"QSid\":\"323\",\"QDes\":\"/嫌弃\",\"IQLid\":\"323\",\"AQLid\":\"323\",\"EMCode\":\"10323\"},{\"QSid\":\"332\",\"QDes\":\"/举牌牌\",\"IQLid\":\"332\",\"AQLid\":\"332\",\"EMCode\":\"10332\"},{\"QSid\":\"336\",\"QDes\":\"/豹富\",\"IQLid\":\"336\",\"AQLid\":\"336\",\"EMCode\":\"10336\"},{\"QSid\":\"353\",\"QDes\":\"/拜托\",\"IQLid\":\"353\",\"AQLid\":\"353\",\"EMCode\":\"10353\"},{\"QSid\":\"355\",\"QDes\":\"/耶\",\"IQLid\":\"355\",\"AQLid\":\"355\",\"EMCode\":\"10355\"},{\"QSid\":\"356\",\"QDes\":\"/666\",\"IQLid\":\"356\",\"AQLid\":\"356\",\"EMCode\":\"10356\"},{\"QSid\":\"354\",\"QDes\":\"/尊嘟假嘟\",\"IQLid\":\"354\",\"AQLid\":\"354\",\"EMCode\":\"10354\"},{\"QSid\":\"352\",\"QDes\":\"/咦\",\"IQLid\":\"352\",\"AQLid\":\"352\",\"EMCode\":\"10352\"},{\"QSid\":\"357\",\"QDes\":\"/裂开\",\"IQLid\":\"357\",\"AQLid\":\"357\",\"EMCode\":\"10357\"},{\"QSid\":\"334\",\"QDes\":\"/虎虎生威\",\"IQLid\":\"334\",\"AQLid\":\"334\",\"EMCode\":\"10334\"},{\"QSid\":\"347\",\"QDes\":\"/大展宏兔\",\"IQLid\":\"347\",\"AQLid\":\"347\",\"EMCode\":\"10347\"},{\"QSid\":\"303\",\"QDes\":\"/右拜年\",\"IQLid\":\"303\",\"AQLid\":\"303\",\"EMCode\":\"10303\"},{\"QSid\":\"302\",\"QDes\":\"/左拜年\",\"IQLid\":\"302\",\"AQLid\":\"302\",\"EMCode\":\"10302\"},{\"QSid\":\"295\",\"QDes\":\"/拿到红包\",\"IQLid\":\"295\",\"AQLid\":\"295\",\"EMCode\":\"10295\"},{\"QSid\":\"311\",\"QDes\":\"/打call\",\"IQLid\":\"311\",\"AQLid\":\"311\",\"EMCode\":\"10311\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"1\"},{\"QSid\":\"312\",\"QDes\":\"/变形\",\"IQLid\":\"312\",\"AQLid\":\"312\",\"EMCode\":\"10312\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"2\"},{\"QSid\":\"314\",\"QDes\":\"/仔细分析\",\"IQLid\":\"314\",\"AQLid\":\"314\",\"EMCode\":\"10314\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"4\"},{\"QSid\":\"317\",\"QDes\":\"/菜汪\",\"IQLid\":\"317\",\"AQLid\":\"317\",\"EMCode\":\"10317\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"7\"},{\"QSid\":\"318\",\"QDes\":\"/崇拜\",\"IQLid\":\"318\",\"AQLid\":\"318\",\"EMCode\":\"10318\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"8\"},{\"QSid\":\"319\",\"QDes\":\"/比心\",\"IQLid\":\"319\",\"AQLid\":\"319\",\"EMCode\":\"10319\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"9\"},{\"QSid\":\"320\",\"QDes\":\"/庆祝\",\"IQLid\":\"320\",\"AQLid\":\"320\",\"EMCode\":\"10320\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"10\"},{\"QSid\":\"324\",\"QDes\":\"/吃糖\",\"IQLid\":\"324\",\"AQLid\":\"324\",\"EMCode\":\"10324\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"12\"},{\"QSid\":\"325\",\"QDes\":\"/惊吓\",\"IQLid\":\"325\",\"AQLid\":\"325\",\"EMCode\":\"10325\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"14\"},{\"QSid\":\"337\",\"QDes\":\"/花朵脸\",\"IQLid\":\"337\",\"AQLid\":\"337\",\"EMCode\":\"10337\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"22\"},{\"QSid\":\"338\",\"QDes\":\"/我想开了\",\"IQLid\":\"338\",\"AQLid\":\"338\",\"EMCode\":\"10338\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"20\"},{\"QSid\":\"339\",\"QDes\":\"/舔屏\",\"IQLid\":\"339\",\"AQLid\":\"339\",\"EMCode\":\"10339\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"21\"},{\"QSid\":\"341\",\"QDes\":\"/打招呼\",\"IQLid\":\"341\",\"AQLid\":\"341\",\"EMCode\":\"10341\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"24\"},{\"QSid\":\"342\",\"QDes\":\"/酸Q\",\"IQLid\":\"342\",\"AQLid\":\"342\",\"EMCode\":\"10342\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"26\"},{\"QSid\":\"343\",\"QDes\":\"/我方了\",\"IQLid\":\"343\",\"AQLid\":\"343\",\"EMCode\":\"10343\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"27\"},{\"QSid\":\"344\",\"QDes\":\"/大怨种\",\"IQLid\":\"344\",\"AQLid\":\"344\",\"EMCode\":\"10344\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"28\"},{\"QSid\":\"345\",\"QDes\":\"/红包多多\",\"IQLid\":\"345\",\"AQLid\":\"345\",\"EMCode\":\"10345\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"29\"},{\"QSid\":\"346\",\"QDes\":\"/你真棒棒\",\"IQLid\":\"346\",\"AQLid\":\"346\",\"EMCode\":\"10346\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"25\"},{\"QSid\":\"181\",\"QDes\":\"/戳一戳\",\"IQLid\":\"151\",\"AQLid\":\"173\",\"EMCode\":\"251\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"37\"},{\"QSid\":\"74\",\"QDes\":\"/太阳\",\"isStatic\":\"1\",\"IQLid\":\"73\",\"AQLid\":\"75\",\"EMCode\":\"176\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"35\"},{\"QSid\":\"75\",\"QDes\":\"/月亮\",\"isStatic\":\"1\",\"IQLid\":\"67\",\"AQLid\":\"68\",\"EMCode\":\"175\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"36\"},{\"QSid\":\"351\",\"QDes\":\"/敲敲\",\"IQLid\":\"351\",\"AQLid\":\"351\",\"EMCode\":\"10351\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"30\"},{\"QSid\":\"349\",\"QDes\":\"/坚强\",\"IQLid\":\"349\",\"AQLid\":\"349\",\"EMCode\":\"10349\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"32\"},{\"QSid\":\"350\",\"QDes\":\"/贴贴\",\"IQLid\":\"350\",\"AQLid\":\"350\",\"EMCode\":\"10350\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"31\"},{\"QSid\":\"395\",\"QDes\":\"/略略略\",\"IQLid\":\"395\",\"AQLid\":\"395\",\"EMCode\":\"10395\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"41\"},{\"QSid\":\"114\",\"QDes\":\"/篮球\",\"IQLid\":\"90\",\"AQLid\":\"92\",\"EMCode\":\"158\",\"AniStickerType\":2,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"13\"},{\"QSid\":\"358\",\"QDes\":\"/骰子\",\"IQLid\":\"358\",\"AQLid\":\"358\",\"QHide\":\"1\",\"EMCode\":\"10358\",\"AniStickerType\":2,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"33\"},{\"QSid\":\"359\",\"QDes\":\"/包剪锤\",\"IQLid\":\"359\",\"AQLid\":\"359\",\"QHide\":\"1\",\"EMCode\":\"10359\",\"AniStickerType\":2,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"34\"},{\"QSid\":\"326\",\"QDes\":\"/生气\",\"IQLid\":\"326\",\"AQLid\":\"326\",\"EMCode\":\"10326\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"15\"},{\"QSid\":\"53\",\"QDes\":\"/蛋糕\",\"IQLid\":\"59\",\"AQLid\":\"59\",\"EMCode\":\"168\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"17\"},{\"QSid\":\"49\",\"QDes\":\"/拥抱\",\"IQLid\":\"45\",\"AQLid\":\"45\",\"EMCode\":\"178\"},{\"QSid\":\"66\",\"QDes\":\"/爱心\",\"IQLid\":\"28\",\"AQLid\":\"28\",\"EMCode\":\"166\"},{\"QSid\":\"63\",\"QDes\":\"/玫瑰\",\"IQLid\":\"8\",\"AQLid\":\"8\",\"EMCode\":\"163\"},{\"QSid\":\"64\",\"QDes\":\"/凋谢\",\"IQLid\":\"57\",\"AQLid\":\"57\",\"EMCode\":\"164\"},{\"QSid\":\"187\",\"QDes\":\"/幽灵\",\"IQLid\":\"157\",\"AQLid\":\"179\",\"EMCode\":\"257\"},{\"QSid\":\"146\",\"QDes\":\"/爆筋\",\"IQLid\":\"116\",\"AQLid\":\"118\",\"EMCode\":\"121011\"},{\"QSid\":\"116\",\"QDes\":\"/示爱\",\"IQLid\":\"29\",\"AQLid\":\"29\",\"EMCode\":\"165\"},{\"QSid\":\"67\",\"QDes\":\"/心碎\",\"IQLid\":\"72\",\"AQLid\":\"74\",\"EMCode\":\"167\"},{\"QSid\":\"60\",\"QDes\":\"/咖啡\",\"IQLid\":\"66\",\"AQLid\":\"66\",\"EMCode\":\"160\"},{\"QSid\":\"185\",\"QDes\":\"/羊驼\",\"IQLid\":\"155\",\"AQLid\":\"177\",\"EMCode\":\"255\"},{\"QSid\":\"137\",\"QDes\":\"/鞭炮\",\"isStatic\":\"1\",\"IQLid\":\"107\",\"AQLid\":\"109\",\"EMCode\":\"121002\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"18\"},{\"QSid\":\"333\",\"QDes\":\"/烟花\",\"isStatic\":\"1\",\"IQLid\":\"333\",\"AQLid\":\"333\",\"EMCode\":\"10333\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"19\"},{\"QSid\":\"76\",\"QDes\":\"/赞\",\"IQLid\":\"52\",\"AQLid\":\"52\",\"EMCode\":\"179\"},{\"QSid\":\"124\",\"QDes\":\"/OK\",\"IQLid\":\"64\",\"AQLid\":\"64\",\"EMCode\":\"189\"},{\"QSid\":\"118\",\"QDes\":\"/抱拳\",\"IQLid\":\"56\",\"AQLid\":\"56\",\"EMCode\":\"183\"},{\"QSid\":\"78\",\"QDes\":\"/握手\",\"IQLid\":\"54\",\"AQLid\":\"54\",\"EMCode\":\"181\"},{\"QSid\":\"119\",\"QDes\":\"/勾引\",\"IQLid\":\"63\",\"AQLid\":\"63\",\"EMCode\":\"184\"},{\"QSid\":\"79\",\"QDes\":\"/胜利\",\"IQLid\":\"55\",\"AQLid\":\"55\",\"EMCode\":\"182\"},{\"QSid\":\"120\",\"QDes\":\"/拳头\",\"IQLid\":\"71\",\"AQLid\":\"73\",\"EMCode\":\"185\"},{\"QSid\":\"121\",\"QDes\":\"/差劲\",\"IQLid\":\"70\",\"AQLid\":\"72\",\"EMCode\":\"186\"},{\"QSid\":\"77\",\"QDes\":\"/踩\",\"IQLid\":\"53\",\"AQLid\":\"53\",\"EMCode\":\"180\"},{\"QSid\":\"123\",\"QDes\":\"/NO\",\"IQLid\":\"92\",\"AQLid\":\"94\",\"EMCode\":\"188\"},{\"QSid\":\"201\",\"QDes\":\"/点赞\",\"IQLid\":\"171\",\"AQLid\":\"150\",\"EMCode\":\"271\"},{\"QSid\":\"273\",\"QDes\":\"/我酸了\",\"isStatic\":\"1\",\"IQLid\":\"273\",\"AQLid\":\"273\",\"EMCode\":\"10273\"},{\"QSid\":\"46\",\"QDes\":\"/猪头\",\"isStatic\":\"1\",\"IQLid\":\"7\",\"AQLid\":\"7\",\"EMCode\":\"162\"},{\"QSid\":\"112\",\"QDes\":\"/菜刀\",\"IQLid\":\"17\",\"AQLid\":\"17\",\"EMCode\":\"155\"},{\"QSid\":\"56\",\"QDes\":\"/刀\",\"IQLid\":\"68\",\"AQLid\":\"70\",\"EMCode\":\"171\"},{\"QSid\":\"169\",\"QDes\":\"/手枪\",\"isStatic\":\"1\",\"IQLid\":\"139\",\"AQLid\":\"141\",\"EMCode\":\"121034\"},{\"QSid\":\"171\",\"QDes\":\"/茶\",\"IQLid\":\"141\",\"AQLid\":\"163\",\"EMCode\":\"241\"},{\"QSid\":\"59\",\"QDes\":\"/便便\",\"IQLid\":\"15\",\"AQLid\":\"15\",\"EMCode\":\"174\"},{\"QSid\":\"144\",\"QDes\":\"/喝彩\",\"isStatic\":\"1\",\"IQLid\":\"114\",\"AQLid\":\"116\",\"EMCode\":\"121009\"},{\"QSid\":\"147\",\"QDes\":\"/棒棒糖\",\"isStatic\":\"1\",\"IQLid\":\"117\",\"AQLid\":\"119\",\"EMCode\":\"121012\"},{\"QSid\":\"89\",\"QDes\":\"/西瓜\",\"isStatic\":\"1\",\"IQLid\":\"60\",\"AQLid\":\"60\",\"EMCode\":\"156\"},{\"QSid\":\"148\",\"QDes\":\"/喝奶\",\"isStatic\":\"1\",\"IQLid\":\"118\",\"AQLid\":\"120\",\"QHide\":\"1\",\"EMCode\":\"121013\"},{\"QSid\":\"55\",\"QDes\":\"/炸弹\",\"isStatic\":\"1\",\"IQLid\":\"16\",\"AQLid\":\"16\",\"QHide\":\"1\",\"EMCode\":\"170\"},{\"QSid\":\"41\",\"QDes\":\"/发抖\",\"isStatic\":\"1\",\"IQLid\":\"69\",\"AQLid\":\"71\",\"EMCode\":\"193\"},{\"QSid\":\"125\",\"QDes\":\"/转圈\",\"IQLid\":\"95\",\"AQLid\":\"97\",\"EMCode\":\"195\"},{\"QSid\":\"42\",\"QDes\":\"/爱情\",\"IQLid\":\"38\",\"AQLid\":\"38\",\"EMCode\":\"190\"},{\"QSid\":\"43\",\"QDes\":\"/跳跳\",\"IQLid\":\"93\",\"AQLid\":\"95\",\"EMCode\":\"192\"},{\"QSid\":\"86\",\"QDes\":\"/怄火\",\"IQLid\":\"94\",\"AQLid\":\"96\",\"EMCode\":\"194\"},{\"QSid\":\"129\",\"QDes\":\"/挥手\",\"IQLid\":\"77\",\"AQLid\":\"79\",\"EMCode\":\"199\"},{\"QSid\":\"226\",\"QDes\":\"/拍桌\",\"IQLid\":\"196\",\"isCMEmoji\":\"1\",\"AQLid\":\"198\",\"QHide\":\"1\",\"EMCode\":\"297\"},{\"QSid\":\"85\",\"QDes\":\"/飞吻\",\"isStatic\":\"1\",\"IQLid\":\"47\",\"AQLid\":\"47\",\"EMCode\":\"191\"},{\"QSid\":\"215\",\"QDes\":\"/糊脸\",\"IQLid\":\"185\",\"isCMEmoji\":\"1\",\"AQLid\":\"187\",\"QHide\":\"1\",\"EMCode\":\"285\"},{\"QSid\":\"214\",\"QDes\":\"/啵啵\",\"IQLid\":\"184\",\"isCMEmoji\":\"1\",\"AQLid\":\"186\",\"QHide\":\"1\",\"EMCode\":\"284\"},{\"QSid\":\"222\",\"QDes\":\"/抱抱\",\"IQLid\":\"192\",\"isCMEmoji\":\"1\",\"AQLid\":\"194\",\"QHide\":\"1\",\"EMCode\":\"292\"},{\"QSid\":\"203\",\"QDes\":\"/托脸\",\"IQLid\":\"173\",\"AQLid\":\"152\",\"QHide\":\"1\",\"EMCode\":\"273\"},{\"QSid\":\"235\",\"QDes\":\"/颤抖\",\"IQLid\":\"205\",\"isCMEmoji\":\"1\",\"AQLid\":\"207\",\"QHide\":\"1\",\"EMCode\":\"305\"},{\"QSid\":\"241\",\"QDes\":\"/生日快乐\",\"IQLid\":\"211\",\"isCMEmoji\":\"1\",\"AQLid\":\"213\",\"QHide\":\"1\",\"EMCode\":\"311\"},{\"QSid\":\"237\",\"QDes\":\"/偷看\",\"IQLid\":\"207\",\"isCMEmoji\":\"1\",\"AQLid\":\"209\",\"QHide\":\"1\",\"EMCode\":\"307\"},{\"QSid\":\"218\",\"QDes\":\"/舔一舔\",\"IQLid\":\"188\",\"isCMEmoji\":\"1\",\"AQLid\":\"190\",\"QHide\":\"1\",\"EMCode\":\"288\"},{\"QSid\":\"233\",\"QDes\":\"/掐一掐\",\"IQLid\":\"203\",\"isCMEmoji\":\"1\",\"AQLid\":\"205\",\"QHide\":\"1\",\"EMCode\":\"303\"},{\"QSid\":\"232\",\"QDes\":\"/佛系\",\"IQLid\":\"202\",\"isCMEmoji\":\"1\",\"AQLid\":\"204\",\"QHide\":\"1\",\"EMCode\":\"302\"},{\"QSid\":\"238\",\"QDes\":\"/扇脸\",\"IQLid\":\"208\",\"isCMEmoji\":\"1\",\"AQLid\":\"210\",\"QHide\":\"1\",\"EMCode\":\"308\"},{\"QSid\":\"217\",\"QDes\":\"/扯一扯\",\"IQLid\":\"187\",\"isCMEmoji\":\"1\",\"AQLid\":\"189\",\"QHide\":\"1\",\"EMCode\":\"287\"},{\"QSid\":\"225\",\"QDes\":\"/撩一撩\",\"IQLid\":\"195\",\"isCMEmoji\":\"1\",\"AQLid\":\"197\",\"QHide\":\"1\",\"EMCode\":\"296\"},{\"QSid\":\"230\",\"QDes\":\"/嘲讽\",\"IQLid\":\"200\",\"isCMEmoji\":\"1\",\"AQLid\":\"202\",\"QHide\":\"1\",\"EMCode\":\"300\"},{\"QSid\":\"194\",\"QDes\":\"/不开心\",\"IQLid\":\"164\",\"AQLid\":\"143\",\"QHide\":\"1\",\"EMCode\":\"264\"},{\"QSid\":\"210\",\"QDes\":\"/飙泪\",\"IQLid\":\"180\",\"AQLid\":\"159\",\"QHide\":\"1\",\"EMCode\":\"280\"},{\"QSid\":\"193\",\"QDes\":\"/大笑\",\"IQLid\":\"163\",\"AQLid\":\"185\",\"QHide\":\"1\",\"EMCode\":\"263\"},{\"QSid\":\"204\",\"QDes\":\"/吃\",\"IQLid\":\"174\",\"AQLid\":\"153\",\"QHide\":\"1\",\"EMCode\":\"274\"},{\"QSid\":\"200\",\"QDes\":\"/求求\",\"IQLid\":\"170\",\"AQLid\":\"149\",\"QHide\":\"1\",\"EMCode\":\"270\"},{\"QSid\":\"290\",\"QDes\":\"/敲开心\",\"IQLid\":\"290\",\"isCMEmoji\":\"1\",\"AQLid\":\"290\",\"QHide\":\"1\",\"EMCode\":\"20240\"},{\"QSid\":\"224\",\"QDes\":\"/开枪\",\"IQLid\":\"194\",\"isCMEmoji\":\"1\",\"AQLid\":\"196\",\"QHide\":\"1\",\"EMCode\":\"295\"},{\"QSid\":\"229\",\"QDes\":\"/干杯\",\"IQLid\":\"199\",\"isCMEmoji\":\"1\",\"AQLid\":\"201\",\"QHide\":\"1\",\"EMCode\":\"299\"},{\"QSid\":\"221\",\"QDes\":\"/顶呱呱\",\"IQLid\":\"191\",\"isCMEmoji\":\"1\",\"AQLid\":\"193\",\"QHide\":\"1\",\"EMCode\":\"291\"},{\"QSid\":\"219\",\"QDes\":\"/蹭一蹭\",\"IQLid\":\"189\",\"isCMEmoji\":\"1\",\"AQLid\":\"191\",\"QHide\":\"1\",\"EMCode\":\"289\"},{\"QSid\":\"227\",\"QDes\":\"/拍手\",\"IQLid\":\"197\",\"isCMEmoji\":\"1\",\"AQLid\":\"199\",\"QHide\":\"1\",\"EMCode\":\"294\"},{\"QSid\":\"216\",\"QDes\":\"/拍头\",\"IQLid\":\"186\",\"isCMEmoji\":\"1\",\"AQLid\":\"188\",\"QHide\":\"1\",\"EMCode\":\"286\"},{\"QSid\":\"231\",\"QDes\":\"/哼\",\"IQLid\":\"201\",\"isCMEmoji\":\"1\",\"AQLid\":\"203\",\"QHide\":\"1\",\"EMCode\":\"301\"},{\"QSid\":\"244\",\"QDes\":\"/扔狗\",\"IQLid\":\"214\",\"isCMEmoji\":\"1\",\"AQLid\":\"216\",\"QHide\":\"1\",\"EMCode\":\"312\"},{\"QSid\":\"223\",\"QDes\":\"/暴击\",\"IQLid\":\"193\",\"isCMEmoji\":\"1\",\"AQLid\":\"195\",\"QHide\":\"1\",\"EMCode\":\"293\"},{\"QSid\":\"243\",\"QDes\":\"/甩头\",\"IQLid\":\"213\",\"isCMEmoji\":\"1\",\"AQLid\":\"215\",\"QHide\":\"1\",\"EMCode\":\"313\"},{\"QSid\":\"211\",\"QDes\":\"/我不看\",\"IQLid\":\"181\",\"AQLid\":\"160\",\"QHide\":\"1\",\"EMCode\":\"281\"},{\"QSid\":\"292\",\"QDes\":\"/让我康康\",\"IQLid\":\"292\",\"isCMEmoji\":\"1\",\"AQLid\":\"292\",\"QHide\":\"1\",\"EMCode\":\"20242\"},{\"QSid\":\"240\",\"QDes\":\"/喷脸\",\"IQLid\":\"210\",\"isCMEmoji\":\"1\",\"AQLid\":\"212\",\"QHide\":\"1\",\"EMCode\":\"310\"},{\"QSid\":\"180\",\"QDes\":\"/惊喜\",\"IQLid\":\"150\",\"AQLid\":\"172\",\"QHide\":\"1\",\"EMCode\":\"250\"},{\"QSid\":\"122\",\"QDes\":\"/爱你\",\"IQLid\":\"65\",\"AQLid\":\"65\",\"QHide\":\"1\",\"EMCode\":\"187\"},{\"QSid\":\"202\",\"QDes\":\"/无聊\",\"IQLid\":\"172\",\"AQLid\":\"151\",\"QHide\":\"1\",\"EMCode\":\"272\"},{\"QSid\":\"278\",\"QDes\":\"/汗\",\"IQLid\":\"278\",\"isCMEmoji\":\"1\",\"AQLid\":\"278\",\"QHide\":\"1\",\"EMCode\":\"20237\"},{\"QSid\":\"301\",\"QDes\":\"/好闪\",\"IQLid\":\"301\",\"AQLid\":\"301\",\"QHide\":\"1\",\"EMCode\":\"10301\"},{\"QSid\":\"288\",\"QDes\":\"/请\",\"IQLid\":\"288\",\"AQLid\":\"288\",\"QHide\":\"1\",\"EMCode\":\"10288\"},{\"QSid\":\"322\",\"QDes\":\"/拒绝\",\"IQLid\":\"322\",\"AQLid\":\"322\",\"QHide\":\"1\",\"EMCode\":\"10322\"},{\"QSid\":\"198\",\"QDes\":\"/呃\",\"IQLid\":\"168\",\"AQLid\":\"147\",\"QHide\":\"1\",\"EMCode\":\"268\"},{\"QSid\":\"348\",\"QDes\":\"/福萝卜\",\"IQLid\":\"348\",\"AQLid\":\"348\",\"QHide\":\"1\",\"EMCode\":\"10348\"},{\"QSid\":\"206\",\"QDes\":\"/害怕\",\"IQLid\":\"176\",\"AQLid\":\"155\",\"QHide\":\"1\",\"EMCode\":\"276\"},{\"QSid\":\"239\",\"QDes\":\"/原谅\",\"IQLid\":\"209\",\"isCMEmoji\":\"1\",\"AQLid\":\"211\",\"QHide\":\"1\",\"EMCode\":\"309\"},{\"QSid\":\"424\",\"QDes\":\"/续标识\",\"IQLid\":\"424\",\"AQLid\":\"424\",\"EMCode\":\"10424\",\"QHide\":\"0\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"52\"},{\"QSid\":\"415\",\"QDes\":\"/划龙舟\",\"IQLid\":\"415\",\"AQLid\":\"415\",\"EMCode\":\"10415\",\"QHide\":\"0\",\"AniStickerType\":3,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"43\"},{\"QSid\":\"416\",\"QDes\":\"/中龙舟\",\"IQLid\":\"416\",\"AQLid\":\"416\",\"EMCode\":\"10416\",\"QHide\":\"1\",\"AniStickerType\":3,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"44\"},{\"QSid\":\"417\",\"QDes\":\"/大龙舟\",\"IQLid\":\"417\",\"AQLid\":\"417\",\"EMCode\":\"10417\",\"QHide\":\"1\",\"AniStickerType\":3,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"45\"},{\"QSid\":\"425\",\"QDes\":\"/求放过\",\"IQLid\":\"425\",\"AQLid\":\"425\",\"EMCode\":\"10425\",\"QHide\":\"0\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"53\"},{\"QSid\":\"427\",\"QDes\":\"/偷感\",\"IQLid\":\"427\",\"AQLid\":\"427\",\"EMCode\":\"10427\",\"QHide\":\"0\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"55\"},{\"QSid\":\"426\",\"QDes\":\"/玩火\",\"IQLid\":\"426\",\"AQLid\":\"426\",\"EMCode\":\"10426\",\"QHide\":\"0\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"54\"},{\"QSid\":\"419\",\"QDes\":\"/火车\",\"IQLid\":\"419\",\"AQLid\":\"419\",\"EMCode\":\"10419\",\"QHide\":\"0\",\"AniStickerType\":3,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"47\"},{\"QSid\":\"420\",\"QDes\":\"/中火车\",\"IQLid\":\"420\",\"AQLid\":\"420\",\"EMCode\":\"10420\",\"QHide\":\"1\",\"AniStickerType\":3,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"48\"},{\"QSid\":\"421\",\"QDes\":\"/大火车\",\"IQLid\":\"421\",\"AQLid\":\"421\",\"EMCode\":\"10421\",\"QHide\":\"1\",\"AniStickerType\":3,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"49\"},{\"QSid\":\"429\",\"QDes\":\"/蛇年快乐\",\"IQLid\":\"429\",\"AQLid\":\"429\",\"EMCode\":\"10429\",\"QHide\":\"0\",\"AniStickerType\":3,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"56\"},{\"QSid\":\"430\",\"QDes\":\"/蛇身\",\"IQLid\":\"430\",\"AQLid\":\"430\",\"EMCode\":\"10430\",\"QHide\":\"1\",\"AniStickerType\":3,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"57\"},{\"QSid\":\"431\",\"QDes\":\"/蛇尾\",\"IQLid\":\"431\",\"AQLid\":\"431\",\"EMCode\":\"10431\",\"QHide\":\"1\",\"AniStickerType\":3,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"56\"},{\"QSid\":\"428\",\"QDes\":\"/收到\",\"IQLid\":\"428\",\"AQLid\":\"428\",\"EMCode\":\"10428\",\"QHide\":\"0\",\"AniStickerType\":0,\"AniStickerPackId\":\"0\",\"AniStickerId\":\"0\"},{\"QSid\":\"422\",\"QDes\":\"/粽于等到你\",\"IQLid\":\"422\",\"AQLid\":\"422\",\"EMCode\":\"10422\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"50\"},{\"QSid\":\"423\",\"QDes\":\"/复兴号\",\"IQLid\":\"423\",\"AQLid\":\"423\",\"EMCode\":\"10423\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"51\"},{\"QSid\":\"432\",\"QDes\":\"/灵蛇献瑞\",\"IQLid\":\"432\",\"AQLid\":\"432\",\"EMCode\":\"10432\",\"QHide\":\"1\",\"AniStickerType\":1,\"AniStickerPackId\":\"1\",\"AniStickerId\":\"59\"}]");
const faceConfig = {
  sysface};

var OB11UserSex = /* @__PURE__ */ ((OB11UserSex2) => {
  OB11UserSex2["male"] = "male";
  OB11UserSex2["female"] = "female";
  OB11UserSex2["unknown"] = "unknown";
  return OB11UserSex2;
})(OB11UserSex || {});
var OB11GroupMemberRole = /* @__PURE__ */ ((OB11GroupMemberRole2) => {
  OB11GroupMemberRole2["owner"] = "owner";
  OB11GroupMemberRole2["admin"] = "admin";
  OB11GroupMemberRole2["member"] = "member";
  return OB11GroupMemberRole2;
})(OB11GroupMemberRole || {});

var OB11MessageDataType = /* @__PURE__ */ ((OB11MessageDataType2) => {
  OB11MessageDataType2["text"] = "text";
  OB11MessageDataType2["image"] = "image";
  OB11MessageDataType2["music"] = "music";
  OB11MessageDataType2["video"] = "video";
  OB11MessageDataType2["voice"] = "record";
  OB11MessageDataType2["file"] = "file";
  OB11MessageDataType2["at"] = "at";
  OB11MessageDataType2["reply"] = "reply";
  OB11MessageDataType2["json"] = "json";
  OB11MessageDataType2["face"] = "face";
  OB11MessageDataType2["mface"] = "mface";
  OB11MessageDataType2["markdown"] = "markdown";
  OB11MessageDataType2["node"] = "node";
  OB11MessageDataType2["forward"] = "forward";
  OB11MessageDataType2["xml"] = "xml";
  OB11MessageDataType2["poke"] = "poke";
  OB11MessageDataType2["dice"] = "dice";
  OB11MessageDataType2["rps"] = "rps";
  OB11MessageDataType2["miniapp"] = "miniapp";
  OB11MessageDataType2["contact"] = "contact";
  OB11MessageDataType2["location"] = "location";
  return OB11MessageDataType2;
})(OB11MessageDataType || {});

class OB11Construct {
  static selfInfo(selfInfo) {
    return {
      user_id: +selfInfo.uin,
      nickname: selfInfo.nick
    };
  }
  static friends(friends) {
    return friends.map((rawFriend) => ({
      birthday_year: rawFriend.baseInfo.birthday_year,
      birthday_month: rawFriend.baseInfo.birthday_month,
      birthday_day: rawFriend.baseInfo.birthday_day,
      user_id: parseInt(rawFriend.coreInfo.uin),
      age: rawFriend.baseInfo.age,
      phone_num: rawFriend.baseInfo.phoneNum,
      email: rawFriend.baseInfo.eMail,
      category_id: rawFriend.baseInfo.categoryId,
      nickname: rawFriend.coreInfo.nick ?? "",
      remark: rawFriend.coreInfo.remark ?? rawFriend.coreInfo.nick,
      sex: this.sex(rawFriend.baseInfo.sex),
      level: rawFriend.qqLevel && calcQQLevel(rawFriend.qqLevel) || 0
    }));
  }
  static friend(friends) {
    return {
      birthday_year: friends.baseInfo.birthday_year,
      birthday_month: friends.baseInfo.birthday_month,
      birthday_day: friends.baseInfo.birthday_day,
      user_id: parseInt(friends.coreInfo.uin),
      age: friends.baseInfo.age,
      phone_num: friends.baseInfo.phoneNum,
      email: friends.baseInfo.eMail,
      category_id: friends.baseInfo.categoryId,
      nickname: friends.coreInfo.nick ?? "",
      remark: friends.coreInfo.remark ?? friends.coreInfo.nick,
      sex: this.sex(friends.baseInfo.sex),
      level: 0
    };
  }
  static groupMemberRole(role) {
    return {
      4: OB11GroupMemberRole.owner,
      3: OB11GroupMemberRole.admin,
      2: OB11GroupMemberRole.member
    }[role];
  }
  static sex(sex) {
    if (!sex) return OB11UserSex.unknown;
    return {
      [NTSex.GENDER_MALE]: OB11UserSex.male,
      [NTSex.GENDER_FEMALE]: OB11UserSex.female,
      [NTSex.GENDER_UNKOWN]: OB11UserSex.unknown,
      [NTSex.GENDER_PRIVACY]: OB11UserSex.unknown
    }[sex] || OB11UserSex.unknown;
  }
  static groupMember(group_id, member) {
    return {
      group_id: +group_id,
      user_id: +member.uin,
      nickname: member.nick,
      card: member.cardName,
      sex: this.sex(member.sex),
      age: member.age ?? 0,
      area: "",
      level: member.memberRealLevel?.toString() ?? "0",
      qq_level: member.qqLevel && calcQQLevel(member.qqLevel) || 0,
      join_time: +member.joinTime,
      last_sent_time: +member.lastSpeakTime,
      title_expire_time: 0,
      unfriendly: false,
      card_changeable: true,
      is_robot: member.isRobot,
      shut_up_timestamp: member.shutUpTime,
      role: this.groupMemberRole(member.role),
      title: member.memberSpecialTitle ?? ""
    };
  }
  static group(group) {
    return {
      group_all_shut: +group.groupShutupExpireTime > 0 ? -1 : 0,
      group_remark: group.remarkName,
      group_id: +group.groupCode,
      group_name: group.groupName,
      member_count: group.memberCount,
      max_member_count: group.maxMember
    };
  }
  static groups(groups) {
    return groups.map(this.group);
  }
  static file(peerId, file) {
    return {
      group_id: +peerId,
      file_id: FileNapCatOneBotUUID.encodeModelId({ chatType: 2, peerUid: peerId }, file.fileModelId, file.fileId, file.fileId ?? ""),
      file_name: file.fileName,
      busid: file.busId,
      size: +file.fileSize,
      file_size: +file.fileSize,
      upload_time: file.uploadTime,
      dead_time: file.deadTime,
      modify_time: file.modifyTime,
      download_times: file.downloadTimes,
      uploader: +file.uploaderUin,
      uploader_name: file.uploaderName
    };
  }
  static folder(peerId, folder) {
    return {
      group_id: +peerId,
      folder_id: folder.folderId,
      folder: folder.folderId,
      folder_name: folder.folderName,
      create_time: folder.createTime,
      creator: +folder.createUin,
      creator_name: folder.creatorName,
      total_file_count: folder.totalFileCount
    };
  }
}

const pattern = /\[CQ:(\w+)((,\w+=[^,\]]*)*)]/;
function unescape$1(source) {
  return String(source).replace(/&#91;/g, "[").replace(/&#93;/g, "]").replace(/&#44;/g, ",").replace(/&amp;/g, "&");
}
function from(source) {
  const capture = pattern.exec(source);
  if (!capture) return null;
  const [, type, attrs] = capture;
  const data = {};
  if (attrs) {
    attrs.slice(1).split(",").forEach((str) => {
      const index = str.indexOf("=");
      data[str.slice(0, index)] = unescape$1(str.slice(index + 1));
    });
  }
  return { type, data, capture };
}
function convert(type, data) {
  return {
    type,
    data
  };
}
function decodeCQCode(source) {
  const elements = [];
  let result;
  while (result = from(source)) {
    const { type, data, capture } = result;
    if (type) {
      if (capture.index) {
        elements.push(convert("text", { text: unescape$1(source.slice(0, capture.index)) }));
      }
      elements.push(convert(type, data));
      source = source.slice(capture.index + capture[0].length);
    }
  }
  if (source) elements.push(convert("text", { text: unescape$1(source) }));
  return elements;
}
function CQCodeEscapeText(text) {
  return text.replace(/&/g, "&amp;").replace(/\[/g, "&#91;").replace(/]/g, "&#93;");
}
function CQCodeEscape(text) {
  return text.replace(/&/g, "&amp;").replace(/\[/g, "&#91;").replace(/]/g, "&#93;").replace(/,/g, "&#44;");
}
function encodeCQCode(data) {
  if (data.type === "text") {
    return CQCodeEscapeText(data.data.text);
  }
  let result = "[CQ:" + data.type;
  for (const name in data.data) {
    const value = data.data[name];
    if (value === void 0) {
      continue;
    }
    try {
      const text = value?.toString();
      if (text) {
        result += `,${name}=${CQCodeEscape(text)}`;
      }
    } catch (error) {
      console.error(`Error encoding CQCode for ${name}:`, error);
    }
  }
  result += "]";
  return result;
}

class OB11FriendAddNoticeEvent extends OB11BaseNoticeEvent {
  notice_type = "friend_add";
  user_id;
  constructor(core, userId) {
    super(core);
    this.user_id = userId;
  }
}

class OB11GroupDecreaseEvent extends OB11GroupNoticeEvent {
  notice_type = "group_decrease";
  sub_type = "leave";
  operator_id;
  constructor(core, groupId, userId, operatorId, subType = "leave") {
    super(core, groupId, userId);
    this.group_id = groupId;
    this.operator_id = operatorId;
    this.user_id = userId;
    this.sub_type = subType;
  }
}

const GroupAdminExtra = {
  adminUid: ProtoField(1, ScalarType.STRING),
  isPromote: ProtoField(2, ScalarType.BOOL)
};
const GroupAdminBody = {
  extraDisable: ProtoField(1, () => GroupAdminExtra),
  extraEnable: ProtoField(2, () => GroupAdminExtra)
};
const GroupAdmin = {
  groupUin: ProtoField(1, ScalarType.UINT32),
  flag: ProtoField(2, ScalarType.UINT32),
  isPromote: ProtoField(3, ScalarType.BOOL),
  body: ProtoField(4, () => GroupAdminBody)
};

class OB11GroupAdminNoticeEvent extends OB11GroupNoticeEvent {
  notice_type = "group_admin";
  sub_type;
  constructor(core, group_id, user_id, sub_type) {
    super(core, group_id, user_id);
    this.sub_type = sub_type;
  }
}

class OB11BaseRequestEvent extends OneBotEvent {
  post_type = EventType.REQUEST;
}

class OB11GroupRequestEvent extends OB11BaseRequestEvent {
  request_type = "group";
  group_id;
  user_id;
  comment;
  flag;
  sub_type;
  constructor(core, groupId, userId, sub_type, comment, flag) {
    super(core);
    this.group_id = groupId;
    this.user_id = userId;
    this.sub_type = sub_type;
    this.comment = comment;
    this.flag = flag;
  }
}

class LRUCache {
  capacity;
  cache;
  constructor(capacity) {
    this.capacity = capacity;
    this.cache = /* @__PURE__ */ new Map();
  }
  get(key) {
    const value = this.cache.get(key);
    if (value !== void 0) {
      this.cache.delete(key);
      this.cache.set(key, value);
    }
    return value;
  }
  put(key, value) {
    if (this.cache.has(key)) {
      this.cache.delete(key);
    } else if (this.cache.size >= this.capacity) {
      const firstKey = this.cache.keys().next().value;
      if (firstKey !== void 0) {
        this.cache.delete(firstKey);
      }
    }
    this.cache.set(key, value);
  }
  resetCapacity(newCapacity) {
    this.capacity = newCapacity;
    while (this.cache.size > this.capacity) {
      const firstKey = this.cache.keys().next().value;
      if (firstKey !== void 0) {
        this.cache.delete(firstKey);
      }
    }
  }
}

class CleanupQueue {
  tasks = /* @__PURE__ */ new Map();
  MAX_RETRIES = 3;
  isProcessing = false;
  pendingOperations = [];
  /**
     * 执行队列中的待处理操作，确保异步安全
     */
  executeNextOperation() {
    if (this.pendingOperations.length === 0) {
      this.isProcessing = false;
      return;
    }
    this.isProcessing = true;
    const operation = this.pendingOperations.shift();
    operation?.();
    setImmediate(() => this.executeNextOperation());
  }
  /**
     * 安全执行操作，防止竞态条件
     * @param operation 要执行的操作
     */
  safeExecute(operation) {
    this.pendingOperations.push(operation);
    if (!this.isProcessing) {
      this.executeNextOperation();
    }
  }
  /**
     * 检查文件是否存在
     * @param filePath 文件路径
     * @returns 文件是否存在
     */
  fileExists(filePath) {
    try {
      return fs__default.existsSync(filePath);
    } catch (_error) {
      return false;
    }
  }
  /**
     * 添加文件到清理队列
     * @param filePath 文件路径
     * @param cleanupDelay 清理延迟时间(毫秒)
     */
  addFile(filePath, cleanupDelay) {
    this.safeExecute(() => {
      if (this.tasks.has(filePath)) {
        this.cancelCleanup(filePath);
      }
      const fileRecord = {
        filePath,
        addedTime: Date.now(),
        retries: 0
      };
      const timer = setTimeout(() => {
        this.cleanupFile(fileRecord, cleanupDelay);
      }, cleanupDelay);
      this.tasks.set(filePath, { fileRecord, timer });
    });
  }
  /**
     * 批量添加文件到清理队列
     * @param filePaths 文件路径数组
     * @param cleanupDelay 清理延迟时间(毫秒)
     */
  addFiles(filePaths, cleanupDelay) {
    this.safeExecute(() => {
      for (const filePath of filePaths) {
        if (this.tasks.has(filePath)) {
          const existingTask = this.tasks.get(filePath);
          if (existingTask) {
            clearTimeout(existingTask.timer);
          }
        }
        const fileRecord = {
          filePath,
          addedTime: Date.now(),
          retries: 0
        };
        const timer = setTimeout(() => {
          this.cleanupFile(fileRecord, cleanupDelay);
        }, cleanupDelay);
        this.tasks.set(filePath, { fileRecord, timer });
      }
    });
  }
  /**
     * 清理文件
     * @param record 文件记录
     * @param delay 延迟时间，用于重试
     */
  cleanupFile(record, delay) {
    this.safeExecute(() => {
      if (!this.fileExists(record.filePath)) {
        this.tasks.delete(record.filePath);
        return;
      }
      try {
        fs__default.unlinkSync(record.filePath);
        this.tasks.delete(record.filePath);
      } catch (error) {
        const err = error;
        if (err.code === "ENOENT") {
          this.tasks.delete(record.filePath);
          return;
        }
        if (err.code === "EACCES" || err.code === "EPERM") ;
        if (record.retries < this.MAX_RETRIES - 1) {
          record.retries++;
          const timer = setTimeout(() => {
            this.cleanupFile(record, delay);
          }, delay);
          this.tasks.set(record.filePath, { fileRecord: record, timer });
        } else {
          this.tasks.delete(record.filePath);
        }
      }
    });
  }
  /**
     * 取消文件的清理任务
     * @param filePath 文件路径
     * @returns 是否成功取消
     */
  cancelCleanup(filePath) {
    let cancelled = false;
    this.safeExecute(() => {
      const task = this.tasks.get(filePath);
      if (task) {
        clearTimeout(task.timer);
        this.tasks.delete(filePath);
        cancelled = true;
      }
    });
    return cancelled;
  }
  /**
     * 获取队列中的文件数量
     * @returns 文件数量
     */
  getQueueSize() {
    return this.tasks.size;
  }
  /**
     * 获取所有待清理的文件
     * @returns 文件路径数组
     */
  getPendingFiles() {
    return Array.from(this.tasks.keys());
  }
  /**
     * 清空所有清理任务
     */
  clearAll() {
    this.safeExecute(() => {
      for (const task of this.tasks.values()) {
        clearTimeout(task.timer);
      }
      this.tasks.clear();
    });
  }
}
const cleanTaskQueue = new CleanupQueue();

class ResourceManager {
  resourceTypes = /* @__PURE__ */ new Map();
  destroyed = false;
  /**
     * 调用资源（自动注册或复用已有配置）
     */
  async callResource(type, config, ...args) {
    if (this.destroyed) {
      throw new Error("ResourceManager has been destroyed");
    }
    let state = this.resourceTypes.get(type);
    if (!state) {
      state = {
        config: {
          resourceFn: config.resourceFn,
          healthCheckFn: config.healthCheckFn,
          disableTime: config.disableTime ?? 3e4,
          maxRetries: config.maxRetries ?? 3,
          healthCheckInterval: config.healthCheckInterval ?? 6e4,
          maxHealthCheckFailures: config.maxHealthCheckFailures ?? 20,
          testArgs: config.testArgs
        },
        isEnabled: true,
        disableUntil: 0,
        currentRetries: 0,
        healthCheckFailureCount: 0,
        isPermanentlyDisabled: false,
        lastHealthCheckTime: 0,
        successCount: 0,
        failureCount: 0
      };
      this.resourceTypes.set(type, state);
    }
    await this.checkAndPerformHealthCheck(state);
    if (state.isPermanentlyDisabled) {
      throw new Error(`Resource type '${type}' is permanently disabled (success: ${state.successCount}, failure: ${state.failureCount})`);
    }
    if (!this.isResourceAvailable(type)) {
      const disableUntilDate = new Date(state.disableUntil).toISOString();
      throw new Error(`Resource type '${type}' is currently disabled until ${disableUntilDate} (success: ${state.successCount}, failure: ${state.failureCount})`);
    }
    try {
      const result = await config.resourceFn(...args);
      this.onResourceSuccess(state);
      return result;
    } catch (error) {
      this.onResourceFailure(state);
      throw error;
    }
  }
  /**
     * 检查资源类型是否可用
     */
  isResourceAvailable(type) {
    const state = this.resourceTypes.get(type);
    if (!state) {
      return true;
    }
    if (state.isPermanentlyDisabled || !state.isEnabled) {
      return false;
    }
    return Date.now() >= state.disableUntil;
  }
  /**
     * 获取资源类型统计信息
     */
  getResourceStats(type) {
    const state = this.resourceTypes.get(type);
    if (!state) {
      return null;
    }
    return {
      successCount: state.successCount,
      failureCount: state.failureCount,
      isEnabled: state.isEnabled,
      isPermanentlyDisabled: state.isPermanentlyDisabled
    };
  }
  /**
     * 获取所有资源类型统计
     */
  getAllResourceStats() {
    const stats = /* @__PURE__ */ new Map();
    for (const [type, state] of this.resourceTypes) {
      stats.set(type, {
        successCount: state.successCount,
        failureCount: state.failureCount,
        isEnabled: state.isEnabled,
        isPermanentlyDisabled: state.isPermanentlyDisabled
      });
    }
    return stats;
  }
  /**
     * 注销资源类型
     */
  unregister(type) {
    return this.resourceTypes.delete(type);
  }
  /**
     * 销毁管理器
     */
  destroy() {
    if (this.destroyed) {
      return;
    }
    this.resourceTypes.clear();
    this.destroyed = true;
  }
  /**
     * 检查并执行健康检查（如果需要）
     */
  async checkAndPerformHealthCheck(state) {
    if (state.isEnabled && Date.now() >= state.disableUntil) {
      return;
    }
    if (state.isPermanentlyDisabled) {
      return;
    }
    const now = Date.now();
    if (now < state.disableUntil) {
      return;
    }
    if (now - state.lastHealthCheckTime < state.config.healthCheckInterval) {
      return;
    }
    await this.performHealthCheck(state);
  }
  async performHealthCheck(state) {
    state.lastHealthCheckTime = Date.now();
    try {
      let healthCheckResult;
      if (state.config.healthCheckFn) {
        const testArgs = state.config.testArgs || [];
        healthCheckResult = await state.config.healthCheckFn(...testArgs);
      } else {
        const testArgs = state.config.testArgs || [];
        await state.config.resourceFn(...testArgs);
        healthCheckResult = true;
      }
      if (healthCheckResult) {
        state.isEnabled = true;
        state.disableUntil = 0;
        state.currentRetries = 0;
        state.healthCheckFailureCount = 0;
      } else {
        throw new Error("Health check function returned false");
      }
    } catch {
      state.healthCheckFailureCount++;
      if (state.healthCheckFailureCount >= state.config.maxHealthCheckFailures) {
        state.isPermanentlyDisabled = true;
        state.disableUntil = 0;
      } else {
        state.disableUntil = Date.now() + state.config.disableTime;
      }
    }
  }
  onResourceSuccess(state) {
    state.currentRetries = 0;
    state.disableUntil = 0;
    state.healthCheckFailureCount = 0;
    state.successCount++;
  }
  onResourceFailure(state) {
    state.currentRetries++;
    state.failureCount++;
    if (state.currentRetries >= state.config.maxRetries) {
      state.disableUntil = Date.now() + state.config.disableTime;
      state.currentRetries = 0;
    }
  }
}
const resourceManager = new ResourceManager();
async function registerResource(type, config, ...args) {
  return resourceManager.callResource(type, config, ...args);
}

function keyCanBeParsed(key, parser) {
  return key in parser;
}
class OneBotMsgApi {
  obContext;
  core;
  notifyGroupInvite = new LRUCache(50);
  // seq -> notify
  rawToOb11Converters = {
    textElement: async (element) => {
      if (element.atType === NTMsgAtType.ATTYPEUNKNOWN) {
        let text = element.content;
        if (text.indexOf("\n") === -1 && text.indexOf("\r\n") === -1) {
          text = text.replace(/\r/g, "\n");
        }
        return {
          type: OB11MessageDataType.text,
          data: { text }
        };
      } else {
        let qq = "all";
        if (element.atType !== NTMsgAtType.ATTYPEALL) {
          const { atNtUid, atUid } = element;
          qq = !atUid || atUid === "0" ? await this.core.apis.UserApi.getUinByUidV2(atNtUid) : String(Number(atUid) >>> 0);
        }
        return {
          type: OB11MessageDataType.at,
          data: {
            qq
            // name: content.slice(1);
          }
        };
      }
    },
    picElement: async (element, msg, elementWrapper, { disableGetUrl }) => {
      try {
        const peer = {
          chatType: msg.chatType,
          peerUid: msg.peerUid,
          guildId: ""
        };
        FileNapCatOneBotUUID.encode(
          peer,
          msg.msgId,
          elementWrapper.elementId,
          element.fileUuid,
          element.fileName
        );
        return {
          type: OB11MessageDataType.image,
          data: {
            summary: element.summary,
            file: element.fileName,
            sub_type: element.picSubType,
            url: disableGetUrl ? element.filePath ?? "" : await this.core.apis.FileApi.getImageUrl(element),
            file_size: element.fileSize
          }
        };
      } catch (e) {
        this.core.context.logger.logError("获取图片url失败", e.stack);
        return null;
      }
    },
    fileElement: async (element, msg, elementWrapper, { disableGetUrl }) => {
      const peer = {
        chatType: msg.chatType,
        peerUid: msg.peerUid,
        guildId: ""
      };
      FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, element.fileUuid, element.fileUuid);
      FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, element.fileUuid, element.fileName);
      if (this.core.apis.PacketApi.packetStatus && !disableGetUrl) {
        let url;
        try {
          url = await registerResource(
            "file-url-get",
            {
              resourceFn: async () => {
                return await this.core.apis.FileApi.getFileUrl(msg.chatType, msg.peerUid, element.fileUuid, element.file10MMd5, 1500);
              },
              healthCheckFn: async () => {
                return await this.core.apis.PacketApi.pkt.operation.FetchRkey().then(() => true).catch(() => false);
              },
              testArgs: [],
              healthCheckInterval: 3e4,
              maxHealthCheckFailures: 3
            }
          );
        } catch (_error) {
          url = "";
        }
        if (url) {
          return {
            type: OB11MessageDataType.file,
            data: {
              file: element.fileName,
              file_id: element.fileUuid,
              file_size: element.fileSize,
              url
            }
          };
        }
      }
      return {
        type: OB11MessageDataType.file,
        data: {
          file: element.fileName,
          file_id: element.fileUuid,
          file_size: element.fileSize
        }
      };
    },
    faceElement: async (element) => {
      const faceIndex = element.faceIndex;
      if (element.faceType === FaceType.Poke) {
        return {
          type: OB11MessageDataType.poke,
          data: {
            type: element?.pokeType?.toString() ?? "0",
            id: faceIndex.toString()
          }
        };
      }
      if (faceIndex === FaceIndex.DICE) {
        return {
          type: OB11MessageDataType.dice,
          data: {
            result: element.resultId
          }
        };
      } else if (faceIndex === FaceIndex.RPS) {
        return {
          type: OB11MessageDataType.rps,
          data: {
            result: element.resultId
          }
        };
      } else {
        return {
          type: OB11MessageDataType.face,
          data: {
            id: element.faceIndex.toString(),
            raw: element,
            resultId: element.resultId,
            chainCount: element.chainCount
          }
        };
      }
    },
    marketFaceElement: async (_, msg, elementWrapper) => {
      const peer = {
        chatType: msg.chatType,
        peerUid: msg.peerUid,
        guildId: ""
      };
      const { emojiId } = _;
      const dir = emojiId.substring(0, 2);
      const url = `https://gxh.vip.qq.com/club/item/parcel/item/${dir}/${emojiId}/raw300.gif`;
      const filename = `${dir}-${emojiId}.gif`;
      FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, "", filename);
      return {
        type: OB11MessageDataType.image,
        data: {
          summary: _.faceName,
          // 商城表情名称
          file: filename,
          url,
          key: _.key,
          emoji_id: _.emojiId,
          emoji_package_id: _.emojiPackageId
        }
      };
    },
    replyElement: async (element, msg, _, quick_reply) => {
      const peer = {
        chatType: msg.chatType,
        peerUid: msg.peerUid,
        guildId: ""
      };
      const createReplyData = (msgId) => ({
        type: OB11MessageDataType.reply,
        data: {
          id: MessageUnique.createUniqueMsgId(peer, msgId).toString()
        }
      });
      const records = msg.records.find((msgRecord) => msgRecord.msgId === element?.sourceMsgIdInRecords);
      if (records && (records.peerUin === "284840486" || records.peerUin === "1094950020")) {
        return createReplyData(records.msgId);
      }
      const tryFetchMethods = async (msgSeq, senderUid, msgTime, msgRandom) => {
        try {
          if (senderUid && msgTime) {
            const replyMsgList2 = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeqV2(
              peer,
              msgSeq,
              msgTime,
              [senderUid]
            )).msgList;
            const replyMsg2 = msgRandom ? replyMsgList2.find((msg2) => msg2.msgRandom === msgRandom) : replyMsgList2.find((msg2) => msg2.msgSeq === msgSeq);
            if (replyMsg2) return replyMsg2;
            if (quick_reply) {
              this.core.context.logger.logWarn(`快速回复，跳过方法1查询，序号: ${msgSeq}, 消息数: ${replyMsgList2.length}`);
              return void 0;
            }
            this.core.context.logger.logWarn(`方法1查询失败，序号: ${msgSeq}, 消息数: ${replyMsgList2.length}`);
          }
          const replyMsgList = (await this.core.apis.MsgApi.getMsgsBySeqAndCount(
            peer,
            msgSeq,
            1,
            true,
            true
          )).msgList;
          const replyMsg = msgRandom ? replyMsgList.find((msg2) => msg2.msgRandom === msgRandom) : replyMsgList.find((msg2) => msg2.msgSeq === msgSeq);
          if (replyMsg) return replyMsg;
          this.core.context.logger.logWarn(`方法2查询失败，序号: ${msgSeq}, 消息数: ${replyMsgList.length}`);
          if (senderUid) {
            const replyMsgList2 = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeqV3(
              peer,
              msgSeq,
              [senderUid]
            )).msgList;
            const replyMsg2 = msgRandom ? replyMsgList2.find((msg2) => msg2.msgRandom === msgRandom) : replyMsgList2.find((msg2) => msg2.msgSeq === msgSeq);
            if (replyMsg2) return replyMsg2;
            this.core.context.logger.logWarn(`方法3查询失败，序号: ${msgSeq}, 消息数: ${replyMsgList2.length}`);
          }
          return void 0;
        } catch (error) {
          this.core.context.logger.logError("查询回复消息出错", error);
          return void 0;
        }
      };
      if (records && element.replyMsgTime && element.senderUidStr) {
        const replyMsg = await tryFetchMethods(
          element.replayMsgSeq,
          element.senderUidStr,
          records.msgTime,
          records.msgRandom
        );
        if (replyMsg) {
          return createReplyData(replyMsg.msgId);
        }
        this.core.context.logger.logError("所有查找方法均失败，获取不到带记录的引用消息", element.replayMsgSeq);
      } else {
        this.core.context.logger.logWarn("似乎是旧版客户端，尝试仅通过序号获取引用消息", element.replayMsgSeq);
        const replyMsg = await tryFetchMethods(element.replayMsgSeq);
        if (replyMsg) {
          return createReplyData(replyMsg.msgId);
        }
        this.core.context.logger.logError("所有查找方法均失败，获取不到旧客户端的引用消息", element.replayMsgSeq);
      }
      return null;
    },
    videoElement: async (element, msg, elementWrapper, { disableGetUrl }) => {
      const peer = {
        chatType: msg.chatType,
        peerUid: msg.peerUid,
        guildId: ""
      };
      let videoUrlWrappers;
      if (msg.peerUin === "284840486" || msg.peerUin === "1094950020") {
        try {
          videoUrlWrappers = await this.core.apis.FileApi.getVideoUrl({
            chatType: msg.chatType,
            peerUid: msg.peerUid,
            guildId: "0"
          }, msg.parentMsgIdList[0] ?? msg.msgId, elementWrapper.elementId);
        } catch {
          this.core.context.logger.logWarn("合并获取视频 URL 失败");
        }
      } else {
        try {
          videoUrlWrappers = await this.core.apis.FileApi.getVideoUrl({
            chatType: msg.chatType,
            peerUid: msg.peerUid,
            guildId: "0"
          }, msg.msgId, elementWrapper.elementId);
        } catch {
          this.core.context.logger.logWarn("获取视频 URL 失败");
        }
      }
      let videoDownUrl;
      if (videoUrlWrappers) {
        const videoDownUrlTemp = videoUrlWrappers.find((urlWrapper) => {
          return !!urlWrapper.url;
        });
        if (videoDownUrlTemp) {
          videoDownUrl = videoDownUrlTemp.url;
        }
      }
      if (!videoDownUrl && !disableGetUrl) {
        if (this.core.apis.PacketApi.packetStatus) {
          try {
            videoDownUrl = await registerResource(
              "video-url-get",
              {
                resourceFn: async () => {
                  return await this.core.apis.FileApi.getVideoUrlPacket(msg.peerUid, element.fileUuid, 1500);
                },
                healthCheckFn: async () => {
                  return await this.core.apis.PacketApi.pkt.operation.FetchRkey().then(() => true).catch(() => false);
                },
                testArgs: [],
                healthCheckInterval: 3e4,
                maxHealthCheckFailures: 3
              }
            );
          } catch (e) {
            this.core.context.logger.logError("获取视频url失败", e.stack);
            videoDownUrl = element.filePath;
          }
        } else {
          videoDownUrl = element.filePath;
        }
      }
      const fileCode = FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, element.fileUuid, element.fileName);
      return {
        type: OB11MessageDataType.video,
        data: {
          file: fileCode,
          url: videoDownUrl,
          file_size: element.fileSize
        }
      };
    },
    pttElement: async (element, msg, elementWrapper, { disableGetUrl }) => {
      const peer = {
        chatType: msg.chatType,
        peerUid: msg.peerUid,
        guildId: ""
      };
      const fileCode = FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, "", element.fileName);
      let pttUrl = "";
      if (this.core.apis.PacketApi.packetStatus && !disableGetUrl) {
        try {
          pttUrl = await registerResource(
            "ptt-url-get",
            {
              resourceFn: async () => {
                return await this.core.apis.FileApi.getPttUrl(msg.peerUid, element.fileUuid, 1500);
              },
              healthCheckFn: async () => {
                return await this.core.apis.PacketApi.pkt.operation.FetchRkey().then(() => true).catch(() => false);
              },
              testArgs: [],
              healthCheckInterval: 3e4,
              maxHealthCheckFailures: 3
            }
          );
        } catch (e) {
          this.core.context.logger.logError("获取语音url失败", e.stack);
          pttUrl = element.filePath;
        }
      } else {
        pttUrl = element.filePath;
      }
      if (pttUrl) {
        return {
          type: OB11MessageDataType.voice,
          data: {
            file: fileCode,
            path: element.filePath,
            url: pttUrl,
            file_size: element.fileSize
          }
        };
      }
      return {
        type: OB11MessageDataType.voice,
        data: {
          file: fileCode,
          file_size: element.fileSize,
          path: element.filePath
        }
      };
    },
    multiForwardMsgElement: async (element, msg, _wrapper, context) => {
      const parentMsgPeer = msg.parentMsgPeer ?? {
        chatType: msg.chatType,
        guildId: "",
        peerUid: msg.peerUid
      };
      let multiMsgs = await this.getMultiMessages(msg, parentMsgPeer);
      if (!multiMsgs || multiMsgs.length === 0) {
        try {
          multiMsgs = await this.core.apis.PacketApi.pkt.operation.FetchForwardMsg(element.resId);
        } catch (e) {
          this.core.context.logger.logError(`Protocol FetchForwardMsg fallback failed! 
                    element = ${JSON.stringify(element)} , error=${e})`);
          return null;
        }
      }
      const forward = {
        type: OB11MessageDataType.forward,
        data: { id: msg.msgId }
      };
      if (!context.parseMultMsg) return forward;
      forward.data.content = await this.parseMultiMessageContent(
        multiMsgs,
        parentMsgPeer,
        msg.parentMsgIdList
      );
      return forward;
    },
    arkElement: async (element) => {
      return {
        type: OB11MessageDataType.json,
        data: {
          data: element.bytesData
        }
      };
    },
    markdownElement: async (element) => {
      return {
        type: OB11MessageDataType.markdown,
        data: {
          content: element.content
        }
      };
    }
  };
  ob11ToRawConverters = {
    [OB11MessageDataType.text]: async ({ data: { text } }) => ({
      elementType: ElementType.TEXT,
      elementId: "",
      textElement: {
        content: text,
        atType: NTMsgAtType.ATTYPEUNKNOWN,
        atUid: "",
        atTinyId: "",
        atNtUid: ""
      }
    }),
    [OB11MessageDataType.at]: async ({ data: { qq: atQQ } }, context) => {
      function at(atUid, atNtUid, atType, atName) {
        return {
          elementType: ElementType.TEXT,
          elementId: "",
          textElement: {
            content: `@${atName}`,
            atType,
            atUid,
            atTinyId: "",
            atNtUid
          }
        };
      }
      if (!context.peer || !atQQ || context.peer.chatType === ChatType.KCHATTYPEC2C) return void 0;
      if (atQQ === "all") return at(atQQ, atQQ, NTMsgAtType.ATTYPEALL, "全体成员");
      const atMember = await this.core.apis.GroupApi.getGroupMember(context.peer.peerUid, atQQ);
      if (atMember) {
        return at(atQQ, atMember.uid, NTMsgAtType.ATTYPEONE, atMember.nick || atMember.cardName);
      }
      const uid = await this.core.apis.UserApi.getUidByUinV2(`${atQQ}`);
      if (!uid) throw new Error("Get Uid Error");
      const info = await this.core.apis.UserApi.getUserDetailInfo(uid);
      return at(atQQ, uid, NTMsgAtType.ATTYPEONE, info.nick || "");
    },
    [OB11MessageDataType.reply]: async ({ data: { id } }) => {
      const replyMsgM = MessageUnique.getMsgIdAndPeerByShortId(parseInt(id));
      if (!replyMsgM) {
        this.core.context.logger.logWarn("回复消息不存在", id);
        return void 0;
      }
      const replyMsg = (await this.core.apis.MsgApi.getMsgsByMsgId(
        replyMsgM.Peer,
        [replyMsgM.MsgId]
      )).msgList[0];
      return replyMsg ? {
        elementType: ElementType.REPLY,
        elementId: "",
        replyElement: {
          replayMsgSeq: replyMsg.msgSeq,
          // raw.msgSeq
          replayMsgId: replyMsg.msgId,
          // raw.msgId
          senderUin: replyMsg.senderUin,
          senderUinStr: replyMsg.senderUin,
          replyMsgClientSeq: replyMsg.clientSeq,
          _replyMsgPeer: replyMsgM.Peer
        }
      } : void 0;
    },
    [OB11MessageDataType.face]: async ({ data: { id, resultId, chainCount } }) => {
      const parsedFaceId = +id;
      const sysFaces = faceConfig.sysface;
      const face = sysFaces.find((systemFace) => systemFace.QSid === parsedFaceId.toString());
      if (!face) {
        this.core.context.logger.logError("不支持的ID", id);
        return void 0;
      }
      let faceType = 1;
      if (parsedFaceId >= 222) {
        faceType = 2;
      }
      if (face.AniStickerType) {
        faceType = 3;
      }
      return {
        elementType: ElementType.FACE,
        elementId: "",
        faceElement: {
          faceIndex: parsedFaceId,
          faceType,
          faceText: face.QDes,
          stickerId: face.AniStickerId,
          stickerType: face.AniStickerType,
          packId: face.AniStickerPackId,
          sourceType: 1,
          resultId: resultId?.toString(),
          chainCount
        }
      };
    },
    [OB11MessageDataType.mface]: async ({
      data: {
        emoji_package_id,
        emoji_id,
        key,
        summary
      }
    }) => ({
      elementType: ElementType.MFACE,
      elementId: "",
      marketFaceElement: {
        emojiPackageId: emoji_package_id,
        emojiId: emoji_id,
        key,
        faceName: summary || "[商城表情]"
      }
    }),
    // File service
    [OB11MessageDataType.image]: async (sendMsg, context) => {
      return await this.obContext.apis.FileApi.createValidSendPicElement(
        context,
        (await this.handleOb11FileLikeMessage(sendMsg, context)).path,
        sendMsg.data.summary,
        sendMsg.data.sub_type
      );
    },
    [OB11MessageDataType.file]: async (sendMsg, context) => {
      const { path, fileName } = await this.handleOb11FileLikeMessage(sendMsg, context);
      return await this.obContext.apis.FileApi.createValidSendFileElement(context, path, fileName);
    },
    [OB11MessageDataType.video]: async (sendMsg, context) => {
      const { path, fileName } = await this.handleOb11FileLikeMessage(sendMsg, context);
      let thumb = sendMsg.data.thumb;
      if (thumb) {
        const uri2LocalRes = await uriToLocalFile(this.core.NapCatTempPath, thumb);
        if (uri2LocalRes.success) {
          thumb = uri2LocalRes.path;
          context.deleteAfterSentFiles.push(thumb);
        }
      }
      return await this.obContext.apis.FileApi.createValidSendVideoElement(context, path, fileName, thumb);
    },
    [OB11MessageDataType.voice]: async (sendMsg, context) => this.obContext.apis.FileApi.createValidSendPttElement(
      context,
      (await this.handleOb11FileLikeMessage(sendMsg, context)).path
    ),
    [OB11MessageDataType.json]: async ({ data: { data } }) => ({
      elementType: ElementType.ARK,
      elementId: "",
      arkElement: {
        bytesData: typeof data === "string" ? data : JSON.stringify(data),
        linkInfo: null,
        subElementType: null
      }
    }),
    [OB11MessageDataType.dice]: async () => ({
      elementType: ElementType.FACE,
      elementId: "",
      faceElement: {
        faceIndex: FaceIndex.DICE,
        faceType: FaceType.AniSticke,
        faceText: "[骰子]",
        packId: "1",
        stickerId: "33",
        sourceType: 1,
        stickerType: 2,
        surpriseId: ""
        // "randomType": 1,
      }
    }),
    [OB11MessageDataType.rps]: async () => ({
      elementType: ElementType.FACE,
      elementId: "",
      faceElement: {
        faceIndex: FaceIndex.RPS,
        faceText: "[包剪锤]",
        faceType: FaceType.AniSticke,
        packId: "1",
        stickerId: "34",
        sourceType: 1,
        stickerType: 2,
        surpriseId: ""
        // "randomType": 1,
      }
    }),
    // Need signing
    [OB11MessageDataType.markdown]: async ({ data: { content } }) => ({
      elementType: ElementType.MARKDOWN,
      elementId: "",
      markdownElement: { content }
    }),
    [OB11MessageDataType.music]: async ({ data }, context) => {
      const supportedPlatforms = ["qq", "163", "kugou", "kuwo", "migu"];
      const supportedPlatformsWithCustom = [...supportedPlatforms, "custom"];
      if (data.id !== void 0) {
        if (!supportedPlatforms.includes(data.type)) {
          this.core.context.logger.logError(`[音乐卡片] type参数错误: "${data.type}"，仅支持: ${supportedPlatforms.join("、")}`);
          return void 0;
        }
      } else {
        if (!supportedPlatformsWithCustom.includes(data.type)) {
          this.core.context.logger.logError(`[音乐卡片] type参数错误: "${data.type}"，仅支持: ${supportedPlatformsWithCustom.join("、")}`);
          return void 0;
        }
        if (!data.url) {
          this.core.context.logger.logError("[音乐卡片] 自定义音乐卡片缺少必需参数: url");
          return void 0;
        }
        if (!data.image) {
          this.core.context.logger.logError("[音乐卡片] 自定义音乐卡片缺少必需参数: image");
          return void 0;
        }
      }
      let postData;
      if (data.id === void 0 && data.content) {
        const { content, ...others } = data;
        postData = { singer: content, ...others };
      } else {
        postData = data;
      }
      let signUrl = this.obContext.configLoader.configData.musicSignUrl;
      if (!signUrl) {
        signUrl = "https://ss.xingzhige.com/music_card/card";
      }
      try {
        const musicJson = await RequestUtil.HttpGetJson(signUrl, "POST", postData);
        return this.ob11ToRawConverters.json({
          data: { data: musicJson },
          type: OB11MessageDataType.json
        }, context);
      } catch (e) {
        const errorMessage = e instanceof Error ? e.message : String(e);
        this.core.context.logger.logError(
          `[音乐卡片签名失败] 签名服务请求出错!
  ├─ 音乐类型: ${data.type}
  ├─ 音乐ID: ${data.id ?? "自定义"}
  ├─ 错误信息: ${errorMessage}
  └─ 提示: 请检查网络连接，或尝试在配置中更换其他音乐签名服务地址(musicSignUrl)`
        );
        return void 0;
      }
    },
    [OB11MessageDataType.node]: async () => void 0,
    [OB11MessageDataType.forward]: async ({ data }, context) => {
      const jsonData = ForwardMsgBuilder.fromResId(data.id);
      return this.ob11ToRawConverters.json({
        data: { data: JSON.stringify(jsonData) },
        type: OB11MessageDataType.json
      }, context);
    },
    [OB11MessageDataType.xml]: async () => void 0,
    [OB11MessageDataType.poke]: async () => void 0,
    [OB11MessageDataType.location]: async () => ({
      elementType: ElementType.SHARELOCATION,
      elementId: "",
      shareLocationElement: {
        text: "测试",
        ext: ""
      }
    }),
    [OB11MessageDataType.miniapp]: async () => void 0,
    [OB11MessageDataType.contact]: async ({ data: { type = "qq", id } }, context) => {
      if (type === "qq") {
        const arkJson = await this.core.apis.UserApi.getBuddyRecommendContactArkJson(id.toString(), "");
        return this.ob11ToRawConverters.json({
          data: { data: arkJson.arkMsg },
          type: OB11MessageDataType.json
        }, context);
      } else if (type === "group") {
        const arkJson = await this.core.apis.GroupApi.getGroupRecommendContactArkJson(id.toString());
        return this.ob11ToRawConverters.json({
          data: { data: arkJson.arkJson },
          type: OB11MessageDataType.json
        }, context);
      }
      return void 0;
    }
  };
  constructor(obContext, core) {
    this.obContext = obContext;
    this.core = core;
  }
  /**
     * 解析带有JSON标记的文本
     * @param text 要解析的文本
     * @returns 解析后的结果数组，每个元素包含类型(text或json)和内容
     */
  parseTextWithJson(text) {
    const regex = /<(\{.*?\})>/g;
    const parts = [];
    let lastIndex = 0;
    let match;
    while ((match = regex.exec(text)) !== null) {
      if (match.index > lastIndex) {
        parts.push({
          type: "text",
          content: text.substring(lastIndex, match.index)
        });
      }
      try {
        const jsonContent = JSON.parse(match[1] ?? "");
        parts.push({
          type: "json",
          content: jsonContent
        });
      } catch (_e) {
        parts.push({
          type: "text",
          content: match[0]
        });
      }
      lastIndex = regex.lastIndex;
    }
    if (lastIndex < text.length) {
      parts.push({
        type: "text",
        content: text.substring(lastIndex)
      });
    }
    return parts;
  }
  async parsePrivateMsgEvent(msg, grayTipElement) {
    if (grayTipElement.subElementType === NTGrayTipElementSubTypeV2.GRAYTIP_ELEMENT_SUBTYPE_JSON) {
      if (grayTipElement.jsonGrayTipElement.busiId.toString() === "1061") {
        const PokeEvent = await this.obContext.apis.FriendApi.parsePrivatePokeEvent(grayTipElement, Number(await this.core.apis.UserApi.getUinByUidV2(msg.peerUid)));
        if (PokeEvent) {
          return PokeEvent;
        }
      } else if (grayTipElement.jsonGrayTipElement.busiId.toString() === "19324" && msg.peerUid !== "") {
        return new OB11FriendAddNoticeEvent(this.core, Number(await this.core.apis.UserApi.getUinByUidV2(msg.peerUid)));
      }
    }
    return void 0;
  }
  async getMultiMessages(msg, parentMsgPeer) {
    msg.parentMsgIdList = msg.parentMsgIdList ?? [];
    msg.parentMsgIdList.push(msg.msgId);
    if (msg.parentMsgIdList[0]) {
      return (await this.core.apis.MsgApi.getMultiMsg(
        parentMsgPeer,
        msg.parentMsgIdList[0],
        msg.msgId
      ))?.msgList;
    }
    return void 0;
  }
  async parseMultiMessageContent(multiMsgs, parentMsgPeer, parentMsgIdList) {
    const parsed = await Promise.all(multiMsgs.map(async (msg) => {
      msg.parentMsgPeer = parentMsgPeer;
      msg.parentMsgIdList = parentMsgIdList;
      msg.id = MessageUnique.createUniqueMsgId(parentMsgPeer, msg.msgId);
      return await this.parseMessage(msg, "array", true);
    }));
    return parsed.filter((item) => item !== void 0);
  }
  async parseMessage(msg, messagePostFormat, parseMultMsg = true, disableGetUrl = false, quick_reply = false) {
    if (messagePostFormat === "string") {
      return (await this.parseMessageV2(msg, parseMultMsg, disableGetUrl, quick_reply))?.stringMsg;
    }
    return (await this.parseMessageV2(msg, parseMultMsg, disableGetUrl, quick_reply))?.arrayMsg;
  }
  async parseMessageV2(msg, parseMultMsg = true, disableGetUrl = false, quick_reply = false) {
    if (msg.senderUin === "0" || msg.senderUin === "") return;
    if (msg.peerUin === "0" || msg.peerUin === "") return;
    const resMsg = this.initializeMessage(msg);
    if (this.core.selfInfo.uin === msg.senderUin) {
      resMsg.message_sent_type = "self";
    }
    if (msg.chatType === ChatType.KCHATTYPEGROUP) {
      await this.handleGroupMessage(resMsg, msg);
    } else if (msg.chatType === ChatType.KCHATTYPEC2C) {
      await this.handlePrivateMessage(resMsg, msg);
    } else if (msg.chatType === ChatType.KCHATTYPETEMPC2CFROMGROUP) {
      await this.handleTempGroupMessage(resMsg, msg);
    } else {
      return void 0;
    }
    const validSegments = await this.parseMessageSegments(msg, parseMultMsg, disableGetUrl, quick_reply);
    resMsg.message = validSegments;
    resMsg.raw_message = validSegments.map((msg2) => encodeCQCode(msg2)).join("").trim();
    const stringMsg = await this.convertArrayToStringMessage(resMsg);
    return { stringMsg, arrayMsg: resMsg };
  }
  initializeMessage(msg) {
    return {
      self_id: parseInt(this.core.selfInfo.uin),
      user_id: parseInt(msg.senderUin),
      time: parseInt(msg.msgTime) || Date.now(),
      message_id: msg.id,
      message_seq: msg.id,
      real_id: msg.id,
      real_seq: msg.msgSeq,
      message_type: msg.chatType === ChatType.KCHATTYPEGROUP ? "group" : "private",
      sender: {
        user_id: +(msg.senderUin ?? 0),
        nickname: msg.sendNickName,
        card: msg.sendMemberName ?? ""
      },
      raw_message: "",
      font: 14,
      sub_type: "friend",
      message: [],
      message_format: "array",
      post_type: this.core.selfInfo.uin === msg.senderUin ? EventType.MESSAGE_SENT : EventType.MESSAGE
    };
  }
  async handleGroupMessage(resMsg, msg) {
    resMsg.sub_type = "normal";
    resMsg.group_id = parseInt(msg.peerUin);
    resMsg.group_name = msg.peerName;
    let member = await this.core.apis.GroupApi.getGroupMember(msg.peerUin, msg.senderUin);
    if (!member) member = await this.core.apis.GroupApi.getGroupMember(msg.peerUin, msg.senderUin);
    if (member) {
      resMsg.sender.role = OB11Construct.groupMemberRole(member.role);
      resMsg.sender.nickname = member.nick;
    }
  }
  async handlePrivateMessage(resMsg, msg) {
    resMsg.sub_type = "friend";
    if (await this.core.apis.FriendApi.isBuddy(msg.senderUid)) {
      const nickname = (await this.core.apis.UserApi.getCoreAndBaseInfo([msg.senderUid])).get(msg.senderUid)?.coreInfo.nick;
      if (nickname) {
        resMsg.sender.nickname = nickname;
        return;
      }
    }
    resMsg.sender.nickname = (await this.core.apis.UserApi.getUserDetailInfo(msg.senderUid)).nick;
  }
  async handleTempGroupMessage(resMsg, msg) {
    resMsg.sub_type = "group";
    const ret = await this.core.apis.MsgApi.getTempChatInfo(ChatType.KCHATTYPETEMPC2CFROMGROUP, msg.senderUid);
    if (ret.result === 0) {
      const member = await this.core.apis.GroupApi.getGroupMember(msg.peerUin, msg.senderUin);
      resMsg.group_id = parseInt(ret.tmpChatInfo.groupCode);
      resMsg.sender.nickname = member?.nick ?? member?.cardName ?? "临时会话";
      resMsg.temp_source = 0;
    } else {
      resMsg.group_id = 284840486;
      resMsg.temp_source = 0;
      resMsg.sender.nickname = "临时会话";
    }
  }
  async parseMessageSegments(msg, parseMultMsg, disableGetUrl = false, quick_reply = false) {
    const msgSegments = await Promise.allSettled(msg.elements.map(
      async (element) => {
        for (const key in element) {
          if (keyCanBeParsed(key, this.rawToOb11Converters) && element[key]) {
            const converters = this.rawToOb11Converters[key];
            const parsedElement = await converters?.(
              element[key],
              msg,
              element,
              { parseMultMsg, disableGetUrl, quick_reply }
            );
            if (key === "faceElement" && !parsedElement) {
              return null;
            }
            return parsedElement;
          }
        }
        return null;
      }
    ));
    return msgSegments.filter((entry) => {
      if (entry.status === "fulfilled") {
        return !!entry.value;
      } else {
        this.core.context.logger.logError("消息段解析失败", entry.reason);
        return false;
      }
    }).map((entry) => entry.value).filter((value) => value != null);
  }
  async convertArrayToStringMessage(originMsg) {
    const msg = structuredClone(originMsg);
    msg.message_format = "string";
    msg.message = msg.raw_message;
    return msg;
  }
  async importArrayTostringMsg(originMsg) {
    const msg = structuredClone(originMsg);
    msg.message_format = "string";
    msg.message = msg.raw_message;
    return msg;
  }
  async createSendElements(messageData, peer, ignoreTypes = []) {
    const deleteAfterSentFiles = [];
    const callResultList = [];
    for (const sendMsg of messageData) {
      if (ignoreTypes.includes(sendMsg.type)) {
        continue;
      }
      const converter = this.ob11ToRawConverters[sendMsg.type];
      if (converter === void 0) {
        throw new Error("未知的消息类型：" + sendMsg.type);
      }
      const callResult = converter(
        sendMsg,
        { peer, deleteAfterSentFiles }
      )?.catch(void 0);
      callResultList.push(callResult);
    }
    const ret = await Promise.all(callResultList);
    const sendElements = ret.filter((ele) => !!ele);
    return { sendElements, deleteAfterSentFiles };
  }
  async sendMsgWithOb11UniqueId(peer, sendElements, deleteAfterSentFiles) {
    if (!sendElements.length) {
      throw new Error("消息体无法解析, 请检查是否发送了不支持的消息类型");
    }
    const calculateTotalSize = async (elements) => {
      const sizePromises = elements.map(async (element) => {
        switch (element.elementType) {
          case ElementType.PTT:
            return (await fs$1.stat(element.pttElement.filePath)).size;
          case ElementType.FILE:
            return (await fs$1.stat(element.fileElement.filePath)).size;
          case ElementType.VIDEO:
            return (await fs$1.stat(element.videoElement.filePath)).size;
          case ElementType.PIC:
            return (await fs$1.stat(element.picElement.sourcePath)).size;
          default:
            return 0;
        }
      });
      const sizes = await Promise.all(sizePromises);
      return sizes.reduce((total, size) => total + size, 0);
    };
    const totalSize = await calculateTotalSize(sendElements).catch((e) => {
      this.core.context.logger.logError("发送消息计算预计时间异常", e);
      return 0;
    });
    const timeout = 1e4 + totalSize / 1024 / 256 * 1e3;
    try {
      const returnMsg = await this.core.apis.MsgApi.sendMsg(peer, sendElements, timeout);
      if (!returnMsg) throw new Error("发送消息失败");
      returnMsg.id = MessageUnique.createUniqueMsgId({
        chatType: peer.chatType,
        guildId: "",
        peerUid: peer.peerUid
      }, returnMsg.msgId);
      return returnMsg;
    } finally {
      cleanTaskQueue.addFiles(deleteAfterSentFiles, timeout);
    }
  }
  async handleOb11FileLikeMessage({ data: inputdata }, { deleteAfterSentFiles }) {
    let realUri = [inputdata.url, inputdata.file, inputdata.path].find((uri) => uri && uri.trim()) ?? "";
    if (!realUri) {
      this.core.context.logger.logError("文件消息缺少参数", inputdata);
      throw new Error("文件消息缺少参数");
    }
    realUri = await this.handleObfuckName(realUri) ?? realUri;
    try {
      const { path, fileName, errMsg, success } = await uriToLocalFile(this.core.NapCatTempPath, realUri);
      if (!success) {
        this.core.context.logger.logError("文件处理失败", errMsg);
        throw new Error("文件处理失败: " + errMsg);
      }
      deleteAfterSentFiles.push(path);
      return { path, fileName: inputdata.name ?? fileName };
    } catch (e) {
      throw new Error(e.message);
    }
  }
  async handleObfuckName(name) {
    const contextMsgFile = FileNapCatOneBotUUID.decode(name);
    if (contextMsgFile && contextMsgFile.msgId && contextMsgFile.elementId) {
      const { peer, msgId, elementId } = contextMsgFile;
      const rawMessage = (await this.core.apis.MsgApi.getMsgsByMsgId(peer, [msgId]))?.msgList.find((msg) => msg.msgId === msgId);
      const mixElement = rawMessage?.elements.find((e) => e.elementId === elementId);
      const mixElementInner = mixElement?.videoElement ?? mixElement?.fileElement ?? mixElement?.pttElement ?? mixElement?.picElement;
      if (!mixElementInner) throw new Error("element not found");
      let url = "";
      if (mixElement?.picElement && rawMessage) {
        const tempData = await this.obContext.apis.MsgApi.rawToOb11Converters.picElement?.(mixElement?.picElement, rawMessage, mixElement, { parseMultMsg: false, disableGetUrl: false, quick_reply: false });
        url = tempData?.data.url ?? "";
      }
      if (mixElement?.videoElement && rawMessage) {
        const tempData = await this.obContext.apis.MsgApi.rawToOb11Converters.videoElement?.(mixElement?.videoElement, rawMessage, mixElement, { parseMultMsg: false, disableGetUrl: false, quick_reply: false });
        url = tempData?.data.url ?? "";
      }
      return url !== "" ? url : await this.core.apis.FileApi.downloadMedia(msgId, peer.chatType, peer.peerUid, elementId, "", "");
    }
    return void 0;
  }
  groupChangDecreseType2String(type) {
    switch (type) {
      case 130:
        return "leave";
      case 131:
        return "kick";
      case 3:
        return "kick_me";
      case 129:
        return "disband";
      default:
        return "kick";
    }
  }
  async waitGroupNotify(groupUin, memberUid, operatorUid) {
    const groupRole = this.core.apis.GroupApi.groupMemberCache.get(groupUin)?.get(this.core.selfInfo.uid.toString())?.role;
    const isAdminOrOwner = groupRole === 3 || groupRole === 4;
    if (isAdminOrOwner && !operatorUid) {
      let dataNotify;
      await this.core.eventWrapper.registerListen(
        "NodeIKernelGroupListener/onGroupNotifiesUpdated",
        (_doubt, notifies) => {
          for (const notify of notifies) {
            if (notify.group.groupCode === groupUin && notify.user1.uid === memberUid) {
              dataNotify = notify;
              return true;
            }
          }
          return false;
        },
        1,
        1e3
      ).catch(() => void 0);
      if (dataNotify) {
        return !dataNotify.actionUser.uid ? dataNotify.user2.uid : dataNotify.actionUser.uid;
      }
    }
    return operatorUid;
  }
  async parseSysMessage(msg) {
    const SysMessage = new NapProtoMsg(PushMsgBody).decode(Uint8Array.from(msg));
    if (SysMessage.contentHead.type === 33 && SysMessage.body?.msgContent) {
      const groupChange = new NapProtoMsg(GroupChange).decode(SysMessage.body.msgContent);
      await this.core.apis.GroupApi.refreshGroupMemberCache(groupChange.groupUin.toString(), true);
      const operatorUid = await this.waitGroupNotify(
        groupChange.groupUin.toString(),
        groupChange.memberUid,
        groupChange.operatorInfo ? new TextDecoder("utf-8").decode(groupChange.operatorInfo) : void 0
      );
      return new OB11GroupIncreaseEvent(
        this.core,
        groupChange.groupUin,
        groupChange.memberUid ? +await this.core.apis.UserApi.getUinByUidV2(groupChange.memberUid) : 0,
        operatorUid ? +await this.core.apis.UserApi.getUinByUidV2(operatorUid) : 0,
        groupChange.decreaseType === 131 ? "invite" : "approve"
      );
    } else if (SysMessage.contentHead.type === 34 && SysMessage.body?.msgContent) {
      const groupChange = new NapProtoMsg(GroupChange).decode(SysMessage.body.msgContent);
      let operator_uid_parse;
      if (groupChange.operatorInfo) {
        if (groupChange.decreaseType === 3 || Buffer.from(groupChange.operatorInfo).toString("hex").startsWith("0a")) {
          try {
            operator_uid_parse = new NapProtoMsg(GroupChangeInfo).decode(groupChange.operatorInfo).operator?.operatorUid;
          } catch (_error) {
            try {
              const decoded = new TextDecoder("utf-8").decode(groupChange.operatorInfo);
              const isAsciiOnly = [...decoded].every((char) => char.charCodeAt(0) >= 32 && char.charCodeAt(0) <= 126);
              operator_uid_parse = isAsciiOnly ? decoded : "";
            } catch (_e2) {
              operator_uid_parse = "";
            }
          }
        } else {
          try {
            const decoded = new TextDecoder("utf-8").decode(groupChange.operatorInfo);
            const isAsciiOnly = [...decoded].every((char) => char.charCodeAt(0) >= 32 && char.charCodeAt(0) <= 126);
            operator_uid_parse = isAsciiOnly ? decoded : "";
          } catch (_e) {
            operator_uid_parse = "";
          }
        }
      }
      const operatorUid = await this.waitGroupNotify(
        groupChange.groupUin.toString(),
        groupChange.memberUid,
        operator_uid_parse
      );
      if (groupChange.memberUid === this.core.selfInfo.uid) {
        setTimeout(() => {
          this.core.apis.GroupApi.groupMemberCache.delete(groupChange.groupUin.toString());
        }, 5e3);
      } else {
        await this.core.apis.GroupApi.refreshGroupMemberCache(groupChange.groupUin.toString(), true);
      }
      return new OB11GroupDecreaseEvent(
        this.core,
        groupChange.groupUin,
        groupChange.memberUid ? +await this.core.apis.UserApi.getUinByUidV2(groupChange.memberUid) : 0,
        operatorUid ? +await this.core.apis.UserApi.getUinByUidV2(operatorUid) : 0,
        this.groupChangDecreseType2String(groupChange.decreaseType)
      );
    } else if (SysMessage.contentHead.type === 44 && SysMessage.body?.msgContent) {
      const groupAmin = new NapProtoMsg(GroupAdmin).decode(SysMessage.body.msgContent);
      await this.core.apis.GroupApi.refreshGroupMemberCache(groupAmin.groupUin.toString(), true);
      let enabled = false;
      let uid = "";
      if (groupAmin.body.extraEnable != null) {
        uid = groupAmin.body.extraEnable.adminUid;
        enabled = true;
      } else if (groupAmin.body.extraDisable != null) {
        uid = groupAmin.body.extraDisable.adminUid;
        enabled = false;
      }
      return new OB11GroupAdminNoticeEvent(
        this.core,
        groupAmin.groupUin,
        +await this.core.apis.UserApi.getUinByUidV2(uid),
        enabled ? "set" : "unset"
      );
    } else if (SysMessage.contentHead.type === 87 && SysMessage.body?.msgContent) {
      const groupInvite = new NapProtoMsg(GroupInvite).decode(SysMessage.body.msgContent);
      let request_seq = "";
      try {
        await this.core.eventWrapper.registerListen("NodeIKernelMsgListener/onRecvMsg", (msgs) => {
          for (const msg2 of msgs) {
            if (msg2.senderUid === groupInvite.invitorUid && msg2.msgType === 11) {
              const jumpUrl = JSON.parse(msg2.elements.find((e) => e.elementType === 10)?.arkElement?.bytesData ?? "").meta?.news?.jumpUrl;
              const jumpUrlParams = new URLSearchParams(jumpUrl);
              const groupcode = jumpUrlParams.get("groupcode");
              const receiveruin = jumpUrlParams.get("receiveruin");
              const msgseq = jumpUrlParams.get("msgseq");
              request_seq = msgseq ?? "";
              if (groupcode === groupInvite.groupUin.toString() && receiveruin === this.core.selfInfo.uin) {
                return true;
              }
            }
          }
          return false;
        }, 1, 1e3);
      } catch {
        request_seq = "";
      }
      if (request_seq === "") {
        return;
      }
      this.notifyGroupInvite.put(request_seq, {
        seq: request_seq,
        type: 1,
        group: {
          groupCode: groupInvite.groupUin.toString(),
          groupName: ""
        },
        user1: {
          uid: groupInvite.invitorUid,
          nickName: ""
        },
        user2: {
          uid: this.core.selfInfo.uid,
          nickName: ""
        },
        actionUser: {
          uid: groupInvite.invitorUid,
          nickName: ""
        },
        actionTime: Date.now().toString(),
        postscript: "",
        repeatSeqs: [],
        warningTips: "",
        invitationExt: {
          srcType: 1,
          groupCode: groupInvite.groupUin.toString(),
          waitStatus: 1
        },
        status: 1
      });
      return new OB11GroupRequestEvent(
        this.core,
        +groupInvite.groupUin,
        +await this.core.apis.UserApi.getUinByUidV2(groupInvite.invitorUid),
        "invite",
        "",
        request_seq
      );
    } else if (SysMessage.contentHead.type === 528 && SysMessage.contentHead.subType === 39 && SysMessage.body?.msgContent) {
      return await this.obContext.apis.UserApi.parseLikeEvent(SysMessage.body?.msgContent);
    }
    return void 0;
  }
}

var ContextMode = /* @__PURE__ */ ((ContextMode2) => {
  ContextMode2[ContextMode2["Normal"] = 0] = "Normal";
  ContextMode2[ContextMode2["Private"] = 1] = "Private";
  ContextMode2[ContextMode2["Group"] = 2] = "Group";
  return ContextMode2;
})(ContextMode || {});
function normalize(message, autoEscape = false) {
  return typeof message === "string" ? autoEscape ? [{ type: OB11MessageDataType.text, data: { text: message } }] : decodeCQCode(message) : Array.isArray(message) ? message : [message];
}
async function createContext(core, payload, contextMode = 0 /* Normal */) {
  if (!payload) {
    throw new Error("请传递请求内容");
  }
  if ((contextMode === 2 /* Group */ || contextMode === 0 /* Normal */) && payload.group_id) {
    return {
      chatType: ChatType.KCHATTYPEGROUP,
      peerUid: payload.group_id.toString()
    };
  }
  if ((contextMode === 1 /* Private */ || contextMode === 0 /* Normal */) && payload.user_id) {
    const Uid = await core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
    if (!Uid) {
      if (payload.group_id) {
        return {
          chatType: ChatType.KCHATTYPEGROUP,
          peerUid: payload.group_id.toString(),
          guildId: ""
        };
      }
      throw new Error("无法获取用户信息");
    }
    const isBuddy = await core.apis.FriendApi.isBuddy(Uid);
    if (!isBuddy) {
      const ret = await core.apis.MsgApi.getTempChatInfo(ChatType.KCHATTYPETEMPC2CFROMGROUP, Uid);
      if (ret.tmpChatInfo?.groupCode) {
        return {
          chatType: ChatType.KCHATTYPETEMPC2CFROMGROUP,
          peerUid: Uid,
          guildId: ""
        };
      }
      if (payload.group_id) {
        return {
          chatType: ChatType.KCHATTYPETEMPC2CFROMGROUP,
          peerUid: Uid,
          guildId: payload.group_id.toString()
        };
      }
      return {
        chatType: ChatType.KCHATTYPEC2C,
        peerUid: Uid,
        guildId: ""
      };
    }
    return {
      chatType: ChatType.KCHATTYPEC2C,
      peerUid: Uid,
      guildId: ""
    };
  }
  if (contextMode === 1 /* Private */ && payload.group_id) {
    throw new Error("当前私聊发送,请指定 user_id 而不是 group_id");
  }
  if (contextMode === 2 /* Group */ && payload.user_id) {
    throw new Error("当前群聊发送,请指定 group_id 而不是 user_id");
  }
  throw new Error("请指定正确的 group_id 或 user_id");
}
function getSpecialMsgNum(payload, msgType) {
  if (Array.isArray(payload.message)) {
    return payload.message.filter((msg) => msg.type === msgType).length;
  }
  return 0;
}
class SendMsgBase extends OneBotAction {
  async check(payload) {
    const messages = normalize(payload.message);
    const nodeElementLength = getSpecialMsgNum(payload, OB11MessageDataType.node);
    if (nodeElementLength > 0 && nodeElementLength !== messages.length) {
      return {
        valid: false,
        message: "转发消息不能和普通消息混在一起发送,转发需要保证message只有type为node的元素"
      };
    }
    return { valid: true };
  }
  async _handle(payload) {
    return this.base_handle(payload);
  }
  async base_handle(payload, contextMode = 0 /* Normal */) {
    if (payload.message_type === "group") contextMode = 2 /* Group */;
    if (payload.message_type === "private") contextMode = 1 /* Private */;
    const peer = await createContext(this.core, payload, contextMode);
    const messages = normalize(
      payload.message,
      typeof payload.auto_escape === "string" ? payload.auto_escape === "true" : !!payload.auto_escape
    );
    if (getSpecialMsgNum(payload, OB11MessageDataType.node)) {
      const packetMode = this.core.apis.PacketApi.packetStatus;
      let returnMsgAndResId;
      try {
        returnMsgAndResId = packetMode ? await this.handleForwardedNodesPacket(peer, messages, payload.source, payload.news, payload.summary, payload.prompt) : await this.handleForwardedNodes(peer, messages);
      } catch (e) {
        throw Error(packetMode ? `发送伪造合并转发消息失败: ${e?.stack}` : `发送合并转发消息失败: ${e?.stack}`);
      }
      if (!returnMsgAndResId) {
        throw Error("发送合并转发消息失败：returnMsgAndResId 为空！");
      }
      if (returnMsgAndResId.message) {
        const msgShortId = MessageUnique.createUniqueMsgId({
          guildId: "",
          peerUid: peer.peerUid,
          chatType: peer.chatType
        }, returnMsgAndResId.message.msgId);
        const resId = returnMsgAndResId.res_id;
        return { message_id: msgShortId, res_id: resId, forward_id: resId };
      } else if (returnMsgAndResId.res_id && !returnMsgAndResId.message) {
        throw Error(`发送转发消息（res_id：${returnMsgAndResId.res_id} 失败`);
      }
    }
    const { sendElements, deleteAfterSentFiles } = await this.obContext.apis.MsgApi.createSendElements(messages, peer);
    const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(peer, sendElements, deleteAfterSentFiles);
    return { message_id: returnMsg.id };
  }
  async uploadForwardedNodesPacket(msgPeer, messageNodes, source, news, summary, prompt, parentMeta, dp = 0) {
    const packetMsg = [];
    const delFiles = [];
    for (const node of messageNodes) {
      if (dp >= 3) {
        this.core.context.logger.logWarn("转发消息深度超过3层，将停止解析！");
        break;
      }
      if (!node.data.id) {
        const OB11Data = normalize(node.type === OB11MessageDataType.node ? node.data.content : node);
        let sendElements;
        if (getSpecialMsgNum({ message: OB11Data }, OB11MessageDataType.node)) {
          const uploadReturnData = await this.uploadForwardedNodesPacket(msgPeer, OB11Data, node.data.source, node.data.news, node.data.summary, node.data.prompt, {
            user_id: (node.data.user_id ?? node.data.uin)?.toString() ?? parentMeta?.user_id ?? this.core.selfInfo.uin,
            nickname: (node.data.nickname || node.data.name) ?? parentMeta?.nickname ?? "QQ用户"
          }, dp + 1);
          sendElements = uploadReturnData?.finallySendElements ? [uploadReturnData.finallySendElements] : [];
          delFiles.push(...uploadReturnData?.deleteAfterSentFiles || []);
        } else {
          const sendElementsCreateReturn = await this.obContext.apis.MsgApi.createSendElements(OB11Data, msgPeer);
          sendElements = sendElementsCreateReturn.sendElements;
          delFiles.push(...sendElementsCreateReturn.deleteAfterSentFiles);
        }
        const packetMsgElements = {
          senderUin: Number(node.data.user_id ?? node.data.uin ?? parentMeta?.user_id) || +this.core.selfInfo.uin,
          senderName: (node.data.nickname || node.data.name) ?? parentMeta?.nickname ?? "QQ用户",
          groupId: msgPeer.chatType === ChatType.KCHATTYPEGROUP ? +msgPeer.peerUid : 0,
          time: Number(node.data.time) || Date.now(),
          msg: sendElements
        };
        this.core.context.logger.logDebug(`handleForwardedNodesPacket[SendRaw] 开始转换 ${stringifyWithBigInt(packetMsgElements)}`);
        const transformedMsg = this.core.apis.PacketApi.pkt.msgConverter.rawMsgWithSendMsgToPacketMsg(packetMsgElements);
        this.core.context.logger.logDebug(`handleForwardedNodesPacket[SendRaw] 转换为 ${stringifyWithBigInt(transformedMsg)}`);
        packetMsg.push(transformedMsg);
      } else if (node.data.id) {
        const id = node.data.id;
        const nodeMsg = MessageUnique.getMsgIdAndPeerByShortId(+id) || MessageUnique.getPeerByMsgId(id);
        if (!nodeMsg) {
          this.core.context.logger.logError("转发消息失败，未找到消息", id);
          continue;
        }
        const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(nodeMsg.Peer, [nodeMsg.MsgId])).msgList[0];
        this.core.context.logger.logDebug(`handleForwardedNodesPacket[PureRaw] 开始转换 ${stringifyWithBigInt(msg)}`);
        if (msg) {
          const msgCache = await this.core.apis.FileApi.downloadRawMsgMedia([msg]);
          delFiles.push(...msgCache);
          const transformedMsg = this.core.apis.PacketApi.pkt.msgConverter.rawMsgToPacketMsg(msg, msgPeer);
          this.core.context.logger.logDebug(`handleForwardedNodesPacket[PureRaw] 转换为 ${stringifyWithBigInt(transformedMsg)}`);
          packetMsg.push(transformedMsg);
        }
      } else {
        this.core.context.logger.logDebug(`handleForwardedNodesPacket 跳过元素 ${stringifyWithBigInt(node)}`);
      }
    }
    if (packetMsg.length === 0) {
      this.core.context.logger.logWarn("handleForwardedNodesPacket 元素为空！");
      return null;
    }
    const resid = await this.core.apis.PacketApi.pkt.operation.UploadForwardMsg(packetMsg, msgPeer.chatType === ChatType.KCHATTYPEGROUP ? +msgPeer.peerUid : 0);
    const forwardJson = ForwardMsgBuilder.fromPacketMsg(resid, packetMsg, source, news, summary, prompt);
    return {
      deleteAfterSentFiles: delFiles,
      finallySendElements: {
        elementType: ElementType.ARK,
        elementId: "",
        arkElement: {
          bytesData: JSON.stringify(forwardJson)
        }
      },
      res_id: resid
    };
  }
  async handleForwardedNodesPacket(msgPeer, messageNodes, source, news, summary, prompt) {
    const uploadReturnData = await this.uploadForwardedNodesPacket(msgPeer, messageNodes, source, news, summary, prompt);
    const res_id = uploadReturnData?.res_id;
    const finallySendElements = uploadReturnData?.finallySendElements;
    if (!finallySendElements) throw Error("转发消息失败，生成节点为空");
    const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(msgPeer, [finallySendElements], uploadReturnData.deleteAfterSentFiles || []).catch(() => void 0);
    return { message: returnMsg ?? null, res_id };
  }
  async handleForwardedNodes(destPeer, messageNodes) {
    const selfPeer = {
      chatType: ChatType.KCHATTYPEC2C,
      peerUid: this.core.selfInfo.uid
    };
    let nodeMsgIds = [];
    for (const messageNode of messageNodes) {
      const nodeId = messageNode.data.id;
      if (nodeId) {
        const nodeMsg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(nodeId)) || MessageUnique.getPeerByMsgId(nodeId);
        if (!nodeMsg) {
          this.core.context.logger.logError("转发消息失败，未找到消息", nodeId);
          continue;
        }
        nodeMsgIds.push(nodeMsg.MsgId);
      } else {
        try {
          const OB11Data = normalize(messageNode.data.content);
          const isNodeMsg = OB11Data.filter((e) => e.type === OB11MessageDataType.node).length;
          if (isNodeMsg !== 0) {
            if (isNodeMsg !== OB11Data.length) {
              this.core.context.logger.logError("子消息中包含非node消息 跳过不合法部分");
              continue;
            }
            const nodeMsg = await this.handleForwardedNodes(selfPeer, OB11Data.filter((e) => e.type === OB11MessageDataType.node));
            if (nodeMsg) {
              nodeMsgIds.push(nodeMsg.message.msgId);
              MessageUnique.createUniqueMsgId(selfPeer, nodeMsg.message.msgId);
            }
            continue;
          }
          const { sendElements } = await this.obContext.apis.MsgApi.createSendElements(OB11Data, destPeer);
          const MixElement = sendElements.filter(
            (element) => element.elementType !== ElementType.FILE && element.elementType !== ElementType.VIDEO && element.elementType !== ElementType.ARK
          );
          const SingleElement = sendElements.filter(
            (element) => element.elementType === ElementType.FILE || element.elementType === ElementType.VIDEO || element.elementType === ElementType.ARK
          ).map((e) => [e]);
          const AllElement = [MixElement, ...SingleElement].filter((e) => e !== void 0 && e.length !== 0);
          const MsgNodeList = [];
          for (const sendElementsSplitElement of AllElement) {
            MsgNodeList.push(this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(selfPeer, sendElementsSplitElement, []).catch(() => void 0));
          }
          (await Promise.allSettled(MsgNodeList)).map((result) => {
            if (result.status === "fulfilled" && result.value) {
              nodeMsgIds.push(result.value.msgId);
              MessageUnique.createUniqueMsgId(selfPeer, result.value.msgId);
            }
            return result;
          });
        } catch (e) {
          this.core.context.logger.logDebug("生成转发消息节点失败", e.stack);
        }
      }
    }
    const nodeMsgArray = [];
    let srcPeer;
    let needSendSelf = false;
    for (const msgId of nodeMsgIds) {
      const nodeMsgPeer = MessageUnique.getPeerByMsgId(msgId);
      if (!nodeMsgPeer) {
        this.core.context.logger.logError("转发消息失败，未找到消息", msgId);
        continue;
      }
      const nodeMsg = (await this.core.apis.MsgApi.getMsgsByMsgId(nodeMsgPeer.Peer, [msgId])).msgList[0];
      if (nodeMsg) {
        srcPeer = srcPeer ?? { chatType: nodeMsg.chatType, peerUid: nodeMsg.peerUid };
        if (srcPeer.peerUid !== nodeMsg.peerUid) {
          needSendSelf = true;
        }
        nodeMsgArray.push(nodeMsg);
      }
    }
    nodeMsgIds = nodeMsgArray.map((msg) => msg.msgId);
    let retMsgIds = [];
    if (needSendSelf) {
      for (const [, msg] of nodeMsgArray.entries()) {
        if (msg.peerUid === this.core.selfInfo.uid) {
          retMsgIds.push(msg.msgId);
          continue;
        }
        const ClonedMsg = await this.cloneMsg(msg);
        if (ClonedMsg) retMsgIds.push(ClonedMsg.msgId);
      }
    } else {
      retMsgIds = nodeMsgIds;
    }
    if (retMsgIds.length === 0) throw Error("转发消息失败，生成节点为空");
    try {
      this.core.context.logger.logDebug("开发转发", srcPeer, destPeer, retMsgIds);
      return {
        message: await this.core.apis.MsgApi.multiForwardMsg(srcPeer, destPeer, retMsgIds)
      };
    } catch (e) {
      this.core.context.logger.logError("forward failed", e?.stack);
      return {
        message: null
      };
    }
  }
  async cloneMsg(msg) {
    const selfPeer = {
      chatType: ChatType.KCHATTYPEC2C,
      peerUid: this.core.selfInfo.uid
    };
    const sendElements = [];
    for (const element of msg.elements) {
      sendElements.push(element);
    }
    if (sendElements.length === 0) {
      this.core.context.logger.logDebug("需要clone的消息无法解析，将会忽略掉", msg);
    }
    try {
      return await this.core.apis.MsgApi.sendMsg(selfPeer, sendElements);
    } catch (e) {
      this.core.context.logger.logError(e?.stack, "克隆转发消息失败,将忽略本条消息", msg);
      return void 0;
    }
  }
}
class SendMsg extends SendMsgBase {
  actionName = ActionName.SendMsg;
}

class OneBotQuickActionApi {
  obContext;
  core;
  constructor(obContext, core) {
    this.obContext = obContext;
    this.core = core;
  }
  async handleQuickOperation(eventContext, quickAction) {
    if (eventContext.post_type === "message") {
      await this.handleMsg(eventContext, quickAction).catch((e) => this.core.context.logger.logError(e));
    }
    if (eventContext.post_type === "request") {
      const friendRequest = eventContext;
      const groupRequest = eventContext;
      if (friendRequest.request_type === "friend") {
        await this.handleFriendRequest(friendRequest, quickAction).catch((e) => this.core.context.logger.logError(e));
      } else if (groupRequest.request_type === "group") {
        await this.handleGroupRequest(groupRequest, quickAction).catch((e) => this.core.context.logger.logError(e));
      }
    }
  }
  async handleMsg(msg, quickAction) {
    const reply = quickAction.reply;
    const peerContextMode = msg.message_type === "private" ? ContextMode.Private : ContextMode.Group;
    const peer = await createContext(this.core, {
      group_id: msg.group_id?.toString(),
      user_id: msg.user_id?.toString()
    }, peerContextMode);
    if (reply) {
      let replyMessage = [];
      if (msg.message_type === "group") {
        replyMessage.push({
          type: "reply",
          data: {
            id: msg.message_id.toString()
          }
        });
        if (quickAction.at_sender) {
          replyMessage.push({
            type: "at",
            data: {
              qq: msg.user_id.toString()
            }
          });
        }
      }
      replyMessage = replyMessage.concat(normalize(reply, quickAction.auto_escape));
      const {
        sendElements,
        deleteAfterSentFiles
      } = await this.obContext.apis.MsgApi.createSendElements(replyMessage, peer);
      this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(peer, sendElements, deleteAfterSentFiles).then().catch((e) => this.core.context.logger.logError(e));
    }
  }
  async findNotify(flag) {
    let notify = (await this.core.apis.GroupApi.getSingleScreenNotifies(false, 100)).find((e) => e.seq === flag);
    if (!notify) {
      notify = (await this.core.apis.GroupApi.getSingleScreenNotifies(true, 100)).find((e) => e.seq === flag);
      return { doubt: true, notify };
    }
    return { doubt: false, notify };
  }
  async handleGroupRequest(request, quickAction) {
    const invite_notify = this.obContext.apis.MsgApi.notifyGroupInvite.get(request.flag);
    const { doubt, notify } = invite_notify ? { doubt: false, notify: invite_notify } : await this.findNotify(request.flag);
    if (!isNull(quickAction.approve) && notify) {
      this.core.apis.GroupApi.handleGroupRequest(
        doubt,
        notify,
        quickAction.approve ? NTGroupRequestOperateTypes.KAGREE : NTGroupRequestOperateTypes.KREFUSE,
        quickAction.reason
      ).catch((e) => this.core.context.logger.logError(e));
    }
  }
  async handleFriendRequest(request, quickAction) {
    const notify = (await this.core.apis.FriendApi.getBuddyReq()).buddyReqs.find((e) => e.reqTime === request.flag.toString());
    if (!isNull(quickAction.approve) && notify) {
      this.core.apis.FriendApi.handleFriendRequest(notify, !!quickAction.approve).then().catch((e) => this.core.context.logger.logError(e));
    }
  }
}

const SchemaData$1A = Type.Object({
  message_id: Type.Union([Type.Number(), Type.String()])
});
class GetMsg extends OneBotAction {
  actionName = ActionName.GetMsg;
  payloadSchema = SchemaData$1A;
  async _handle(payload, _adapter, config) {
    if (!payload.message_id) {
      throw Error("参数message_id不能为空");
    }
    const MsgShortId = MessageUnique.getShortIdByMsgId(payload.message_id.toString());
    const msgIdWithPeer = MessageUnique.getMsgIdAndPeerByShortId(MsgShortId ?? +payload.message_id);
    if (!msgIdWithPeer) {
      throw new Error("消息不存在");
    }
    const peer = { guildId: "", peerUid: msgIdWithPeer?.Peer.peerUid, chatType: msgIdWithPeer.Peer.chatType };
    const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(peer, [msgIdWithPeer?.MsgId || payload.message_id.toString()])).msgList[0];
    if (!msg) throw Error("消息不存在");
    const retMsg = await this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat);
    if (!retMsg) throw Error("消息为空");
    try {
      retMsg.message_id = MessageUnique.createUniqueMsgId(peer, msg.msgId);
      retMsg.message_seq = retMsg.message_id;
      retMsg.real_id = retMsg.message_id;
    } catch {
    }
    return retMsg;
  }
}

class GetLoginInfo extends OneBotAction {
  actionName = ActionName.GetLoginInfo;
  async _handle() {
    return OB11Construct.selfInfo(this.core.selfInfo);
  }
}

const SchemaData$1z = Type.Object({
  no_cache: Type.Optional(Type.Union([Type.Boolean(), Type.String()]))
});
class GetFriendList extends OneBotAction {
  actionName = ActionName.GetFriendList;
  payloadSchema = SchemaData$1z;
  async _handle(_payload) {
    const buddyMap = await this.core.apis.FriendApi.getBuddyV2SimpleInfoMap();
    const isNocache = typeof _payload.no_cache === "string" ? _payload.no_cache === "true" : !!_payload.no_cache;
    await Promise.all(
      Array.from(buddyMap.values()).map(async (buddyInfo) => {
        try {
          const userDetail = await this.core.apis.UserApi.getUserDetailInfo(buddyInfo.coreInfo.uid, isNocache);
          const data = buddyMap.get(buddyInfo.coreInfo.uid);
          if (data) {
            data.qqLevel = userDetail.qqLevel;
          }
        } catch (error) {
          this.core.context.logger.logError("获取好友详细信息失败", error);
        }
      })
    );
    return OB11Construct.friends(Array.from(buddyMap.values()));
  }
}

const SchemaData$1y = Type.Object({
  no_cache: Type.Optional(Type.Union([Type.Boolean(), Type.String()]))
});
class GetGroupList extends OneBotAction {
  actionName = ActionName.GetGroupList;
  payloadSchema = SchemaData$1y;
  async _handle(payload) {
    return OB11Construct.groups(
      await this.core.apis.GroupApi.getGroups(
        typeof payload.no_cache === "string" ? payload.no_cache === "true" : !!payload.no_cache
      )
    );
  }
}

const SchemaData$1x = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()])
});
class GetGroupInfo extends OneBotAction {
  actionName = ActionName.GetGroupInfo;
  payloadSchema = SchemaData$1x;
  async _handle(payload) {
    const group = (await this.core.apis.GroupApi.getGroups()).find((e) => e.groupCode === payload.group_id.toString());
    if (!group) {
      const data = await this.core.apis.GroupApi.fetchGroupDetail(payload.group_id.toString());
      if (data.ownerUid && data.ownerUin === "0") {
        data.ownerUin = await this.core.apis.UserApi.getUinByUidV2(data.ownerUid);
      }
      return {
        ...data,
        group_all_shut: data.shutUpAllTimestamp > 0 ? -1 : 0,
        group_remark: "",
        group_id: +payload.group_id,
        group_name: data.groupName,
        member_count: data.memberNum,
        max_member_count: data.maxMemberNum
      };
    }
    return OB11Construct.group(group);
  }
}

const SchemaData$1w = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  user_id: Type.Union([Type.Number(), Type.String()]),
  no_cache: Type.Optional(Type.Union([Type.Boolean(), Type.String()]))
});
class GetGroupMemberInfo extends OneBotAction {
  actionName = ActionName.GetGroupMemberInfo;
  payloadSchema = SchemaData$1w;
  parseBoolean(value) {
    return typeof value === "string" ? value === "true" : value;
  }
  async getUid(userId) {
    const uid = await this.core.apis.UserApi.getUidByUinV2(userId.toString());
    if (!uid) throw new Error(`Uin2Uid Error: 用户ID ${userId} 不存在`);
    return uid;
  }
  async getGroupMemberInfo(payload, uid, isNocache) {
    const groupMemberCache = this.core.apis.GroupApi.groupMemberCache.get(payload.group_id.toString());
    const groupMember = groupMemberCache?.get(uid);
    const [member, info] = await Promise.all([
      this.core.apis.GroupApi.getGroupMemberEx(payload.group_id.toString(), uid, isNocache),
      this.core.apis.UserApi.getUserDetailInfo(uid, isNocache)
    ]);
    if (!member || !groupMember) throw new Error(`群(${payload.group_id})成员${payload.user_id}不存在`);
    return info ? { ...groupMember, ...member, ...info } : member;
  }
  async _handle(payload) {
    const isNocache = this.parseBoolean(payload.no_cache ?? true);
    const uid = await this.getUid(payload.user_id);
    const member = await this.getGroupMemberInfo(payload, uid, isNocache);
    if (!member) {
      this.core.context.logger.logDebug("获取群成员详细信息失败, 只能返回基础信息");
    }
    return OB11Construct.groupMember(payload.group_id.toString(), member);
  }
}

class SendGroupMsg extends SendMsgBase {
  actionName = ActionName.SendGroupMsg;
  async check(payload) {
    delete payload.user_id;
    payload.message_type = "group";
    return super.check(payload);
  }
  async _handle(payload) {
    return this.base_handle(payload, ContextMode.Group);
  }
}

class SendPrivateMsg extends SendMsgBase {
  actionName = ActionName.SendPrivateMsg;
  async check(payload) {
    payload.message_type = "private";
    return super.check(payload);
  }
  async _handle(payload) {
    return this.base_handle(payload, ContextMode.Private);
  }
}

const SchemaData$1v = Type.Object({
  message_id: Type.Union([Type.Number(), Type.String()])
});
class DeleteMsg extends OneBotAction {
  actionName = ActionName.DeleteMsg;
  payloadSchema = SchemaData$1v;
  async _handle(payload) {
    const msg = MessageUnique.getMsgIdAndPeerByShortId(Number(payload.message_id));
    if (msg) {
      this.obContext.recallEventCache.set(msg.MsgId, setTimeout(() => {
        this.obContext.recallEventCache.delete(msg.MsgId);
      }, 5e3));
      await this.core.apis.MsgApi.recallMsg(msg.Peer, msg.MsgId);
    } else {
      throw new Error("Recall failed");
    }
  }
}

class GetVersionInfo extends OneBotAction {
  actionName = ActionName.GetVersionInfo;
  async _handle() {
    return {
      app_name: "NapCat.Onebot",
      protocol_version: "v11",
      app_version: napCatVersion
    };
  }
}

class CanSend extends OneBotAction {
  async _handle() {
    return {
      yes: true
    };
  }
}
class CanSendRecord extends CanSend {
  actionName = ActionName.CanSendRecord;
}

class CanSendImage extends CanSend {
  actionName = ActionName.CanSendImage;
}

class GetStatus extends OneBotAction {
  actionName = ActionName.GetStatus;
  async _handle() {
    return {
      online: !!this.core.selfInfo.online,
      good: true,
      stat: {}
    };
  }
}

class GoCQHTTPSendForwardMsgBase extends SendMsgBase {
  async check(payload) {
    if (payload.messages) payload.message = normalize(payload.messages);
    return super.check(payload);
  }
}
class GoCQHTTPSendForwardMsg extends GoCQHTTPSendForwardMsgBase {
  actionName = ActionName.GoCQHTTP_SendForwardMsg;
  async check(payload) {
    if (payload.messages) payload.message = normalize(payload.messages);
    return super.check(payload);
  }
}
class GoCQHTTPSendPrivateForwardMsg extends GoCQHTTPSendForwardMsgBase {
  actionName = ActionName.GoCQHTTP_SendPrivateForwardMsg;
  async _handle(payload) {
    return this.base_handle(payload, ContextMode.Private);
  }
}
class GoCQHTTPSendGroupForwardMsg extends GoCQHTTPSendForwardMsgBase {
  actionName = ActionName.GoCQHTTP_SendGroupForwardMsg;
  async _handle(payload) {
    return this.base_handle(payload, ContextMode.Group);
  }
}

const SchemaData$1u = Type.Object({
  user_id: Type.Union([Type.Number(), Type.String()]),
  no_cache: Type.Union([Type.Boolean(), Type.String()], { default: false })
});
class GoCQHTTPGetStrangerInfo extends OneBotAction {
  actionName = ActionName.GoCQHTTP_GetStrangerInfo;
  payloadSchema = SchemaData$1u;
  async _handle(payload) {
    const user_id = payload.user_id.toString();
    const isNocache = typeof payload.no_cache === "string" ? payload.no_cache === "true" : !!payload.no_cache;
    const extendData = await this.core.apis.UserApi.getUserDetailInfoByUin(user_id);
    let uid = await this.core.apis.UserApi.getUidByUinV2(user_id);
    if (!uid) uid = extendData.detail.uid;
    const info = await this.core.apis.UserApi.getUserDetailInfo(uid, isNocache);
    return {
      ...extendData.detail.simpleInfo.coreInfo,
      ...extendData.detail.commonExt ?? {},
      ...extendData.detail.simpleInfo.baseInfo,
      ...extendData.detail.simpleInfo.relationFlags ?? {},
      ...extendData.detail.simpleInfo.status ?? {},
      user_id: parseInt(extendData.detail.uin) ?? 0,
      uid: info.uid ?? uid,
      nickname: extendData.detail.simpleInfo.coreInfo.nick ?? "",
      age: extendData.detail.simpleInfo.baseInfo.age ?? info.age,
      qid: extendData.detail.simpleInfo.baseInfo.qid,
      qqLevel: calcQQLevel(extendData.detail.commonExt?.qqLevel ?? info.qqLevel),
      sex: OB11Construct.sex(extendData.detail.simpleInfo.baseInfo.sex) ?? OB11UserSex.unknown,
      long_nick: extendData.detail.simpleInfo.baseInfo.longNick ?? info.longNick,
      reg_time: extendData.detail.commonExt?.regTime ?? info.regTime,
      is_vip: extendData.detail.simpleInfo.vasInfo?.svipFlag,
      is_years_vip: extendData.detail.simpleInfo.vasInfo?.yearVipFlag,
      vip_level: extendData.detail.simpleInfo.vasInfo?.vipLevel,
      remark: extendData.detail.simpleInfo.coreInfo.remark ?? info.remark,
      status: extendData.detail.simpleInfo.status?.status ?? info.status,
      login_days: 0
      // 失效
    };
  }
}

const SchemaData$1t = Type.Object({
  times: Type.Union([Type.Number(), Type.String()], { default: 1 }),
  user_id: Type.Union([Type.Number(), Type.String()])
});
class SendLike extends OneBotAction {
  actionName = ActionName.SendLike;
  payloadSchema = SchemaData$1t;
  async _handle(payload) {
    const qq = payload.user_id.toString();
    const uid = await this.core.apis.UserApi.getUidByUinV2(qq) ?? "";
    const result = await this.core.apis.UserApi.like(uid, +payload.times);
    if (result.result !== 0) {
      throw new Error(`点赞失败 ${result.errMsg}`);
    }
    return null;
  }
}

const SchemaData$1s = Type.Object({
  flag: Type.Union([Type.String(), Type.Number()]),
  approve: Type.Optional(Type.Union([Type.Boolean(), Type.String()])),
  reason: Type.Optional(Type.Union([Type.String({ default: " " }), Type.Null()])),
  count: Type.Optional(Type.Number({ default: 100 }))
});
class SetGroupAddRequest extends OneBotAction {
  actionName = ActionName.SetGroupAddRequest;
  payloadSchema = SchemaData$1s;
  async _handle(payload) {
    const flag = payload.flag.toString();
    const approve = payload.approve?.toString() !== "false";
    const reason = payload.reason ?? " ";
    const count = payload.count;
    const invite_notify = this.obContext.apis.MsgApi.notifyGroupInvite.get(flag);
    const { doubt, notify } = invite_notify ? {
      doubt: false,
      notify: invite_notify
    } : await this.findNotify(flag, count);
    if (!notify) {
      throw new Error("No such request");
    }
    await this.core.apis.GroupApi.handleGroupRequest(
      doubt,
      notify,
      approve ? NTGroupRequestOperateTypes.KAGREE : NTGroupRequestOperateTypes.KREFUSE,
      reason
    );
    return null;
  }
  async findNotify(flag, count = 100) {
    let notify = (await this.core.apis.GroupApi.getSingleScreenNotifies(false, count)).find((e) => e.seq === flag);
    if (!notify) {
      notify = (await this.core.apis.GroupApi.getSingleScreenNotifies(true, count)).find((e) => e.seq === flag);
      return { doubt: true, notify };
    }
    return { doubt: false, notify };
  }
}

const SchemaData$1r = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  is_dismiss: Type.Optional(Type.Union([Type.Boolean(), Type.String()]))
});
class SetGroupLeave extends OneBotAction {
  actionName = ActionName.SetGroupLeave;
  payloadSchema = SchemaData$1r;
  async _handle(payload) {
    await this.core.apis.GroupApi.quitGroup(payload.group_id.toString());
  }
}

const SchemaData$1q = Type.Object({
  flag: Type.Union([Type.String(), Type.Number()]),
  approve: Type.Optional(Type.Union([Type.String(), Type.Boolean()])),
  remark: Type.Optional(Type.String())
});
class SetFriendAddRequest extends OneBotAction {
  actionName = ActionName.SetFriendAddRequest;
  payloadSchema = SchemaData$1q;
  async _handle(payload) {
    const approve = payload.approve?.toString() !== "false";
    const notify = (await this.core.apis.FriendApi.getBuddyReq()).buddyReqs.find((e) => e.reqTime === payload.flag.toString());
    if (!notify) {
      throw new Error("No such request");
    }
    await this.core.apis.FriendApi.handleFriendRequest(notify, approve);
    if (payload.remark) {
      await this.core.apis.FriendApi.setBuddyRemark(notify.friendUid, payload.remark);
    }
    return null;
  }
}

const SchemaData$1p = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  enable: Type.Optional(Type.Union([Type.Boolean(), Type.String()]))
});
class SetGroupWholeBan extends OneBotAction {
  actionName = ActionName.SetGroupWholeBan;
  payloadSchema = SchemaData$1p;
  async _handle(payload) {
    const enable = payload.enable?.toString() !== "false";
    const res = await this.core.apis.GroupApi.banGroup(payload.group_id.toString(), enable);
    if (res.result !== 0) {
      throw new Error(`SetGroupWholeBan failed: ${res.errMsg} ${res.result}`);
    }
    return null;
  }
}

const SchemaData$1o = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  group_name: Type.String()
});
class SetGroupName extends OneBotAction {
  actionName = ActionName.SetGroupName;
  payloadSchema = SchemaData$1o;
  async _handle(payload) {
    const ret = await this.core.apis.GroupApi.setGroupName(payload.group_id.toString(), payload.group_name);
    if (ret.result !== 0) {
      throw new Error(`设置群名称失败 ErrCode: ${ret.result} ErrMsg: ${ret.errMsg}`);
    }
    return null;
  }
}

const SchemaData$1n = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  user_id: Type.Union([Type.Number(), Type.String()]),
  duration: Type.Union([Type.Number(), Type.String()], { default: 0 })
});
class SetGroupBan extends OneBotAction {
  actionName = ActionName.SetGroupBan;
  payloadSchema = SchemaData$1n;
  async _handle(payload) {
    const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
    if (!uid) throw new Error("uid error");
    const member_role = (await this.core.apis.GroupApi.getGroupMemberEx(payload.group_id.toString(), uid, true))?.role;
    if (member_role === 4) throw new Error("cannot ban owner");
    const ret = await this.core.apis.GroupApi.banMember(
      payload.group_id.toString(),
      [{ uid, timeStamp: +payload.duration }]
    );
    if (ret.result !== 0) throw new Error(ret.errMsg);
    return null;
  }
}

const SchemaData$1m = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  user_id: Type.Union([Type.Number(), Type.String()]),
  reject_add_request: Type.Optional(Type.Union([Type.Boolean(), Type.String()]))
});
class SetGroupKick extends OneBotAction {
  actionName = ActionName.SetGroupKick;
  payloadSchema = SchemaData$1m;
  async _handle(payload) {
    const rejectReq = payload.reject_add_request?.toString() === "true";
    const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
    if (!uid) throw new Error("get Uid Error");
    await this.core.apis.GroupApi.kickMember(payload.group_id.toString(), [uid], rejectReq);
    return null;
  }
}

const SchemaData$1l = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  user_id: Type.Union([Type.Number(), Type.String()]),
  enable: Type.Optional(Type.Union([Type.Boolean(), Type.String()]))
});
class SetGroupAdmin extends OneBotAction {
  actionName = ActionName.SetGroupAdmin;
  payloadSchema = SchemaData$1l;
  async _handle(payload) {
    const enable = typeof payload.enable === "string" ? payload.enable === "true" : !!payload.enable;
    const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
    if (!uid) throw new Error("get Uid Error");
    await this.core.apis.GroupApi.setMemberRole(payload.group_id.toString(), uid, enable ? NTGroupMemberRole.KADMIN : NTGroupMemberRole.KMEMBER);
    return null;
  }
}

const SchemaData$1k = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  user_id: Type.Union([Type.Number(), Type.String()]),
  card: Type.Optional(Type.String())
});
class SetGroupCard extends OneBotAction {
  actionName = ActionName.SetGroupCard;
  payloadSchema = SchemaData$1k;
  async _handle(payload) {
    const member = await this.core.apis.GroupApi.getGroupMember(payload.group_id.toString(), payload.user_id.toString());
    if (member) await this.core.apis.GroupApi.setMemberCard(payload.group_id.toString(), member.uid, payload.card || "");
    return null;
  }
}

const GetFileBase_PayloadSchema = Type.Object({
  file: Type.Optional(Type.String()),
  file_id: Type.Optional(Type.String())
});
class GetFileBase extends OneBotAction {
  payloadSchema = GetFileBase_PayloadSchema;
  async _handle(payload) {
    payload.file ||= payload.file_id || "";
    const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file);
    if (contextMsgFile && contextMsgFile.msgId && contextMsgFile.elementId) {
      const { peer, msgId, elementId } = contextMsgFile;
      const downloadPath = await this.core.apis.FileApi.downloadMedia(msgId, peer.chatType, peer.peerUid, elementId, "", "");
      const rawMessage = (await this.core.apis.MsgApi.getMsgsByMsgId(peer, [msgId]))?.msgList.find((msg) => msg.msgId === msgId);
      const mixElement = rawMessage?.elements.find((e) => e.elementId === elementId);
      const mixElementInner = mixElement?.videoElement ?? mixElement?.fileElement ?? mixElement?.pttElement ?? mixElement?.picElement;
      if (!mixElementInner) throw new Error("element not found");
      const fileSize = mixElementInner.fileSize?.toString() ?? "";
      const fileName = mixElementInner.fileName ?? "";
      let url = "";
      if (mixElement?.picElement && rawMessage) {
        const tempData = await this.obContext.apis.MsgApi.rawToOb11Converters.picElement?.(mixElement?.picElement, rawMessage, mixElement, { parseMultMsg: false, disableGetUrl: false, quick_reply: true });
        url = tempData?.data.url ?? "";
      }
      if (mixElement?.videoElement && rawMessage) {
        const tempData = await this.obContext.apis.MsgApi.rawToOb11Converters.videoElement?.(mixElement?.videoElement, rawMessage, mixElement, { parseMultMsg: false, disableGetUrl: false, quick_reply: true });
        url = tempData?.data.url ?? "";
      }
      const res = {
        file: downloadPath,
        url: url !== "" ? url : downloadPath,
        file_size: fileSize,
        file_name: fileName
      };
      if (this.obContext.configLoader.configData.enableLocalFile2Url && downloadPath) {
        try {
          res.base64 = await fsProm.readFile(downloadPath, "base64");
        } catch (e) {
          throw new Error("文件下载失败. " + e);
        }
      }
      return res;
    }
    const contextModelIdFile = FileNapCatOneBotUUID.decodeModelId(payload.file);
    if (contextModelIdFile && contextModelIdFile.modelId) {
      const { peer, modelId } = contextModelIdFile;
      const downloadPath = await this.core.apis.FileApi.downloadFileForModelId(peer, modelId, "");
      const res = {
        file: downloadPath,
        url: downloadPath,
        file_size: "",
        file_name: ""
      };
      if (this.obContext.configLoader.configData.enableLocalFile2Url && downloadPath) {
        try {
          res.base64 = await fsProm.readFile(downloadPath, "base64");
        } catch (e) {
          throw new Error("文件下载失败. " + e);
        }
      }
      return res;
    }
    const searchResult = await this.core.apis.FileApi.searchForFile([payload.file]);
    if (searchResult) {
      const downloadPath = await this.core.apis.FileApi.downloadFileById(searchResult.id, parseInt(searchResult.fileSize));
      const res = {
        file: downloadPath,
        url: downloadPath,
        file_size: searchResult.fileSize.toString(),
        file_name: searchResult.fileName
      };
      if (this.obContext.configLoader.configData.enableLocalFile2Url && downloadPath) {
        try {
          res.base64 = await fsProm.readFile(downloadPath, "base64");
        } catch (e) {
          throw new Error("文件下载失败. " + e);
        }
      }
      return res;
    }
    throw new Error("file not found");
  }
}
class GetFile extends GetFileBase {
  actionName = ActionName.GetFile;
}

class GetImage extends GetFileBase {
  actionName = ActionName.GetImage;
}

const out_format$1 = ["mp3", "amr", "wma", "m4a", "spx", "ogg", "wav", "flac"];
class GetRecord extends GetFileBase {
  actionName = ActionName.GetRecord;
  async _handle(payload) {
    const res = await super._handle(payload);
    if (payload.out_format && typeof payload.out_format === "string") {
      const inputFile = res.file;
      if (!inputFile) throw new Error("file not found");
      if (!out_format$1.includes(payload.out_format)) {
        throw new Error("转换失败 out_format 字段可能格式不正确");
      }
      const pcmFile = `${inputFile}.pcm`;
      const outputFile = `${inputFile}.${payload.out_format}`;
      try {
        await promises.access(inputFile);
        try {
          await promises.access(outputFile);
        } catch {
          if (FFmpegService.getAdapterName() === "FFmpegAddon") {
            await FFmpegService.convertFile(inputFile, outputFile, payload.out_format);
          } else {
            await this.decodeFile(inputFile, pcmFile);
            await FFmpegService.convertFile(pcmFile, outputFile, payload.out_format);
          }
        }
        const base64Data = await promises.readFile(outputFile, { encoding: "base64" });
        res.file = outputFile;
        res.url = outputFile;
        res.base64 = base64Data;
      } catch (error) {
        console.error("Error processing file:", error);
        throw error;
      }
    }
    return res;
  }
  async decodeFile(inputFile, outputFile) {
    try {
      const inputData = await promises.readFile(inputFile);
      const decodedData = await decode(inputData, 24e3);
      await promises.writeFile(outputFile, Buffer.from(decodedData.data));
    } catch (error) {
      console.error("Error decoding file:", error);
      throw error;
    }
  }
}

const SchemaData$1j = Type.Object({
  user_id: Type.Optional(Type.Union([Type.String(), Type.Number()])),
  group_id: Type.Optional(Type.Union([Type.String(), Type.Number()])),
  message_id: Type.Optional(Type.Union([Type.String(), Type.Number()]))
});
class MarkMsgAsRead extends OneBotAction {
  async getPeer(payload) {
    if (payload.message_id) {
      const s_peer = MessageUnique.getMsgIdAndPeerByShortId(+payload.message_id)?.Peer;
      if (s_peer) {
        return s_peer;
      }
      const l_peer = MessageUnique.getPeerByMsgId(payload.message_id.toString())?.Peer;
      if (l_peer) {
        return l_peer;
      }
    }
    if (payload.user_id) {
      const peerUid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
      if (!peerUid) {
        throw new Error(`私聊${payload.user_id}不存在`);
      }
      const isBuddy = await this.core.apis.FriendApi.isBuddy(peerUid);
      return { chatType: isBuddy ? ChatType.KCHATTYPEC2C : ChatType.KCHATTYPETEMPC2CFROMGROUP, peerUid };
    }
    if (!payload.group_id) {
      throw new Error("缺少参数 group_id 或 user_id");
    }
    return { chatType: ChatType.KCHATTYPEGROUP, peerUid: payload.group_id.toString() };
  }
  async _handle(payload) {
    const ret = await this.core.apis.MsgApi.setMsgRead(await this.getPeer(payload));
    if (ret.result !== 0) {
      throw new Error("设置已读失败," + ret.errMsg);
    }
    return null;
  }
}
class MarkPrivateMsgAsRead extends MarkMsgAsRead {
  payloadSchema = SchemaData$1j;
  actionName = ActionName.MarkPrivateMsgAsRead;
}
class MarkGroupMsgAsRead extends MarkMsgAsRead {
  payloadSchema = SchemaData$1j;
  actionName = ActionName.MarkGroupMsgAsRead;
}
class GoCQHTTPMarkMsgAsRead extends MarkMsgAsRead {
  actionName = ActionName.GoCQHTTP_MarkMsgAsRead;
}
class MarkAllMsgAsRead extends OneBotAction {
  actionName = ActionName._MarkAllMsgAsRead;
  async _handle() {
    await this.core.apis.MsgApi.markAllMsgAsRead();
    return null;
  }
}

const SchemaData$1i = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  file: Type.String(),
  name: Type.String(),
  folder: Type.Optional(Type.String()),
  folder_id: Type.Optional(Type.String())
  // 临时扩展
});
class GoCQHTTPUploadGroupFile extends OneBotAction {
  actionName = ActionName.GoCQHTTP_UploadGroupFile;
  payloadSchema = SchemaData$1i;
  async _handle(payload) {
    let file = payload.file;
    if (fs__default.existsSync(file)) {
      file = `file://${file}`;
    }
    const downloadResult = await uriToLocalFile(this.core.NapCatTempPath, file);
    const peer = {
      chatType: ChatType.KCHATTYPEGROUP,
      peerUid: payload.group_id.toString()
    };
    if (!downloadResult.success) {
      throw new Error(downloadResult.errMsg);
    }
    const msgContext = {
      peer,
      deleteAfterSentFiles: []
    };
    const sendFileEle = await this.obContext.apis.FileApi.createValidSendFileElement(msgContext, downloadResult.path, payload.name, payload.folder ?? payload.folder_id);
    msgContext.deleteAfterSentFiles.push(downloadResult.path);
    const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(peer, [sendFileEle], msgContext.deleteAfterSentFiles);
    const fileElement = returnMsg.elements.find((ele) => ele.elementType === ElementType.FILE);
    return {
      file_id: fileElement?.fileElement?.fileUuid || null
    };
  }
}

const SchemaData$1h = Type.Object({
  file: Type.String()
});
class SetAvatar extends OneBotAction {
  actionName = ActionName.SetQQAvatar;
  payloadSchema = SchemaData$1h;
  async _handle(payload) {
    const { path, success } = await uriToLocalFile(this.core.NapCatTempPath, payload.file);
    if (!success) {
      throw new Error(`头像${payload.file}设置失败,file字段可能格式不正确`);
    }
    if (path) {
      await checkFileExist(path, 5e3);
      const ret = await this.core.apis.UserApi.setQQAvatar(path);
      fs$1.unlink(path).catch(() => {
      });
      if (!ret) {
        throw new Error(`头像${payload.file}设置失败,api无返回`);
      }
      if (ret.result === 1004022) {
        throw new Error(`头像${payload.file}设置失败，文件可能不是图片格式`);
      } else if (ret.result !== 0) {
        throw new Error(`头像${payload.file}设置失败,未知的错误,${ret.result}:${ret.errMsg}`);
      }
    } else {
      fs$1.unlink(path).catch(() => {
      });
      throw new Error(`头像${payload.file}设置失败,无法获取头像,文件可能不存在`);
    }
    return null;
  }
}

const SchemaData$1g = Type.Object({
  url: Type.Optional(Type.String()),
  base64: Type.Optional(Type.String()),
  name: Type.Optional(Type.String()),
  headers: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())]))
});
class GoCQHTTPDownloadFile extends OneBotAction {
  actionName = ActionName.GoCQHTTP_DownloadFile;
  payloadSchema = SchemaData$1g;
  async _handle(payload) {
    const isRandomName = !payload.name;
    const name = payload.name || randomUUID();
    let result;
    if (payload.base64) {
      result = await uriToLocalFile(this.core.NapCatTempPath, `base64://${payload.base64}`, name);
    } else if (payload.url) {
      const headers = this.getHeaders(payload.headers);
      result = await uriToLocalFile(this.core.NapCatTempPath, payload.url, name, headers);
    } else {
      throw new Error("不存在任何文件, 无法下载");
    }
    if (!result.success) {
      throw new Error(result.errMsg);
    }
    const filePath = result.path;
    if (fs__default.existsSync(filePath)) {
      if (isRandomName) {
        const md5 = await calculateFileMD5(filePath);
        const newPath = join$1(this.core.NapCatTempPath, md5);
        fs__default.renameSync(filePath, newPath);
        return { file: newPath };
      }
      return { file: filePath };
    } else {
      throw new Error("文件写入失败, 检查权限");
    }
  }
  getHeaders(headersIn) {
    const headers = {};
    if (typeof headersIn === "string") {
      headersIn = headersIn.split("[\\r\\n]");
    }
    if (Array.isArray(headersIn)) {
      for (const headerItem of headersIn) {
        const spilt = headerItem.indexOf("=");
        if (spilt < 0) {
          headers[headerItem] = "";
        } else {
          const key = headerItem.substring(0, spilt);
          headers[key] = headerItem.substring(spilt + 1);
        }
      }
    }
    if (!headers["Content-Type"]) {
      headers["Content-Type"] = "application/octet-stream";
    }
    return headers;
  }
}

const SchemaData$1f = Type.Object({
  group_id: Type.String(),
  message_seq: Type.Optional(Type.String()),
  count: Type.Number({ default: 20 }),
  reverse_order: Type.Boolean({ default: false }),
  disable_get_url: Type.Boolean({ default: false }),
  parse_mult_msg: Type.Boolean({ default: true }),
  quick_reply: Type.Boolean({ default: false }),
  reverseOrder: Type.Boolean({ default: false })
  // @deprecated 兼容旧版本
});
class GoCQHTTPGetGroupMsgHistory extends OneBotAction {
  actionName = ActionName.GoCQHTTP_GetGroupMsgHistory;
  payloadSchema = SchemaData$1f;
  async _handle(payload, _adapter, config) {
    const peer = { chatType: ChatType.KCHATTYPEGROUP, peerUid: payload.group_id.toString() };
    const hasMessageSeq = !payload.message_seq ? !!payload.message_seq : !(payload.message_seq?.toString() === "" || payload.message_seq?.toString() === "0");
    const startMsgId = hasMessageSeq ? MessageUnique.getMsgIdAndPeerByShortId(+payload.message_seq)?.MsgId ?? payload.message_seq.toString() : "0";
    const msgList = hasMessageSeq ? (await this.core.apis.MsgApi.getMsgHistory(peer, startMsgId, +payload.count, payload.reverse_order || payload.reverseOrder)).msgList : (await this.core.apis.MsgApi.getAioFirstViewLatestMsgs(peer, +payload.count)).msgList;
    if (msgList.length === 0) throw new Error(`消息${payload.message_seq}不存在`);
    await Promise.all(msgList.map(async (msg) => {
      msg.id = MessageUnique.createUniqueMsgId({ guildId: "", chatType: msg.chatType, peerUid: msg.peerUid }, msg.msgId);
    }));
    const ob11MsgList = (await Promise.all(
      msgList.map((msg) => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, payload.parse_mult_msg, payload.disable_get_url, payload.quick_reply))
    )).filter((msg) => msg !== void 0);
    return { messages: ob11MsgList };
  }
}

const SchemaData$1e = Type.Object({
  message_id: Type.Optional(Type.String()),
  id: Type.Optional(Type.String())
});
class GoCQHTTPGetForwardMsgAction extends OneBotAction {
  actionName = ActionName.GoCQHTTP_GetForwardMsg;
  payloadSchema = SchemaData$1e;
  createTemplateNode(message) {
    return {
      type: OB11MessageDataType.node,
      data: {
        user_id: message.user_id,
        nickname: message.sender.nickname,
        message: [],
        content: []
      }
    };
  }
  async parseForward(messages) {
    const retMsg = [];
    for (const message of messages) {
      const templateNode = this.createTemplateNode(message);
      for (const msgdata of message.message) {
        if (msgdata.type === OB11MessageDataType.forward) {
          const newNode = this.createTemplateNode(message);
          newNode.data.message = await this.parseForward(msgdata.data.content ?? []);
          templateNode.data.message.push(newNode);
        } else {
          templateNode.data.message.push(msgdata);
        }
      }
      retMsg.push(templateNode);
    }
    return retMsg;
  }
  async _handle(payload) {
    const msgId = payload.message_id || payload.id;
    if (!msgId) {
      throw new Error("message_id is required");
    }
    const createFakeForwardMsg = (resId) => {
      return {
        chatType: ChatType.KCHATTYPEGROUP,
        elements: [{
          elementType: ElementType.MULTIFORWARD,
          elementId: "",
          multiForwardMsgElement: {
            resId,
            fileName: "",
            xmlContent: ""
          }
        }],
        guildId: "",
        isOnlineMsg: false,
        msgId: "",
        // TODO: no necessary
        msgRandom: "0",
        msgSeq: "",
        msgTime: "",
        msgType: NTMsgType.KMSGTYPEMIX,
        parentMsgIdList: [],
        parentMsgPeer: {
          chatType: ChatType.KCHATTYPEGROUP,
          peerUid: ""
        },
        peerName: "",
        peerUid: "284840486",
        peerUin: "284840486",
        recallTime: "0",
        records: [],
        sendNickName: "",
        sendRemarkName: "",
        senderUid: "",
        senderUin: "1094950020",
        sourceType: MsgSourceType.K_DOWN_SOURCETYPE_UNKNOWN,
        subMsgType: 1
      };
    };
    const protocolFallbackLogic = async (resId) => {
      const ob = (await this.obContext.apis.MsgApi.parseMessageV2(createFakeForwardMsg(resId)))?.arrayMsg;
      if (ob) {
        return {
          messages: ob?.message?.[0]?.data?.content
        };
      }
      throw new Error("protocolFallbackLogic: 找不到相关的聊天记录");
    };
    if (!isNumeric(msgId)) {
      const ret = await protocolFallbackLogic(msgId);
      if (ret.messages) {
        return ret;
      }
      throw new Error("ResId无效: 找不到相关的聊天记录");
    }
    const rootMsgId = MessageUnique.getShortIdByMsgId(msgId.toString());
    const rootMsg = MessageUnique.getMsgIdAndPeerByShortId(rootMsgId ?? +msgId);
    if (rootMsg) {
      const data = await this.core.apis.MsgApi.getMsgsByMsgId(rootMsg.Peer, [rootMsg.MsgId]);
      if (data && data.result === 0 && data.msgList.length > 0) {
        const singleMsg = data.msgList[0];
        if (!singleMsg) {
          throw new Error("消息不存在或已过期");
        }
        const resMsg = await this.obContext.apis.MsgApi.parseMessage(singleMsg, "array", true);
        const forwardContent = resMsg?.message?.[0]?.data?.content;
        if (forwardContent) {
          return { messages: forwardContent };
        }
      }
    }
    throw new Error("消息已过期或者为内层消息，无法获取转发消息");
  }
}

const SchemaData$1d = Type.Object({
  user_id: Type.String(),
  message_seq: Type.Optional(Type.String()),
  count: Type.Number({ default: 20 }),
  reverse_order: Type.Boolean({ default: false }),
  disable_get_url: Type.Boolean({ default: false }),
  parse_mult_msg: Type.Boolean({ default: true }),
  quick_reply: Type.Boolean({ default: false }),
  reverseOrder: Type.Boolean({ default: false })
  // @deprecated 兼容旧版本
});
class GetFriendMsgHistory extends OneBotAction {
  actionName = ActionName.GetFriendMsgHistory;
  payloadSchema = SchemaData$1d;
  async _handle(payload, _adapter, config) {
    const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
    if (!uid) throw new Error(`记录${payload.user_id}不存在`);
    const friend = await this.core.apis.FriendApi.isBuddy(uid);
    const peer = { chatType: friend ? ChatType.KCHATTYPEC2C : ChatType.KCHATTYPETEMPC2CFROMGROUP, peerUid: uid };
    const hasMessageSeq = !payload.message_seq ? !!payload.message_seq : !(payload.message_seq?.toString() === "" || payload.message_seq?.toString() === "0");
    const startMsgId = hasMessageSeq ? MessageUnique.getMsgIdAndPeerByShortId(+payload.message_seq)?.MsgId ?? payload.message_seq.toString() : "0";
    const msgList = hasMessageSeq ? (await this.core.apis.MsgApi.getMsgHistory(peer, startMsgId, +payload.count, payload.reverse_order || payload.reverseOrder)).msgList : (await this.core.apis.MsgApi.getAioFirstViewLatestMsgs(peer, +payload.count)).msgList;
    if (msgList.length === 0) throw new Error(`消息${payload.message_seq}不存在`);
    await Promise.all(msgList.map(async (msg) => {
      msg.id = MessageUnique.createUniqueMsgId({ guildId: "", chatType: msg.chatType, peerUid: msg.peerUid }, msg.msgId);
    }));
    const ob11MsgList = (await Promise.all(
      msgList.map((msg) => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, payload.parse_mult_msg, payload.disable_get_url))
    )).filter((msg) => msg !== void 0);
    return { messages: ob11MsgList };
  }
}

const SchemaData$1c = Type.Object({
  domain: Type.String()
});
class GetCookies extends OneBotAction {
  actionName = ActionName.GetCookies;
  payloadSchema = SchemaData$1c;
  async _handle(payload) {
    const cookiesObject = await this.core.apis.UserApi.getCookies(payload.domain);
    const cookies = Object.entries(cookiesObject).map(([key, value]) => `${key}=${value}`).join("; ");
    const bkn = cookiesObject?.["skey"] ? this.core.apis.WebApi.getBknFromCookie(cookiesObject) : "";
    return { cookies, bkn };
  }
}

const SchemaData$1b = Type.Object({
  message_id: Type.Union([Type.Number(), Type.String()]),
  emoji_id: Type.Union([Type.Number(), Type.String()]),
  set: Type.Optional(Type.Union([Type.Boolean(), Type.String()]))
});
class SetMsgEmojiLike extends OneBotAction {
  actionName = ActionName.SetMsgEmojiLike;
  payloadSchema = SchemaData$1b;
  async _handle(payload) {
    const msg = MessageUnique.getMsgIdAndPeerByShortId(+payload.message_id);
    if (!msg) {
      throw new Error("msg not found");
    }
    if (!payload.emoji_id) {
      throw new Error("emojiId not found");
    }
    payload.set = payload.set ?? true;
    const msgData = (await this.core.apis.MsgApi.getMsgsByMsgId(msg.Peer, [msg.MsgId])).msgList;
    if (!msgData || msgData.length === 0 || !msgData[0]?.msgSeq) {
      throw new Error("find msg by msgid error");
    }
    return await this.core.apis.MsgApi.setEmojiLike(
      msg.Peer,
      msgData[0].msgSeq,
      payload.emoji_id.toString(),
      typeof payload.set === "string" ? payload.set === "true" : !!payload.set
    );
  }
}

class GetRobotUinRange extends OneBotAction {
  actionName = ActionName.GetRobotUinRange;
  async _handle() {
    return await this.core.apis.UserApi.getRobotUinRange();
  }
}

const SchemaData$1a = Type.Object({
  status: Type.Union([Type.Number(), Type.String()]),
  ext_status: Type.Union([Type.Number(), Type.String()]),
  battery_status: Type.Union([Type.Number(), Type.String()])
});
class SetOnlineStatus extends OneBotAction {
  actionName = ActionName.SetOnlineStatus;
  payloadSchema = SchemaData$1a;
  async _handle(payload) {
    const ret = await this.core.apis.UserApi.setSelfOnlineStatus(
      +payload.status,
      +payload.ext_status,
      +payload.battery_status
    );
    if (ret.result !== 0) {
      throw new Error("设置在线状态失败");
    }
    return null;
  }
}

const SchemaData$19 = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()])
});
class GetGroupNotice extends OneBotAction {
  actionName = ActionName.GoCQHTTP_GetGroupNotice;
  payloadSchema = SchemaData$19;
  async _handle(payload) {
    const group = payload.group_id.toString();
    const ret = await this.core.apis.WebApi.getGroupNotice(group);
    if (!ret) {
      throw new Error("获取公告失败");
    }
    const retNotices = new Array();
    for (const key in ret.feeds) {
      if (!ret.feeds[key]) {
        continue;
      }
      const retApiNotice = ret.feeds[key];
      const image = retApiNotice.msg.pics?.map((pic) => {
        return { id: pic.id, height: pic.h, width: pic.w };
      }) || [];
      const retNotice = {
        notice_id: retApiNotice.fid,
        sender_id: retApiNotice.u,
        publish_time: retApiNotice.pubt,
        message: {
          text: retApiNotice.msg.text,
          image,
          images: image
        }
      };
      retNotices.push(retNotice);
    }
    return retNotices;
  }
}

const SchemaData$18 = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()])
});
class GetGroupEssence extends OneBotAction {
  actionName = ActionName.GoCQHTTP_GetEssenceMsg;
  payloadSchema = SchemaData$18;
  async msgSeqToMsgId(peer, msgSeq, msgRandom) {
    const replyMsgList = (await this.core.apis.MsgApi.getMsgsBySeqAndCount(peer, msgSeq, 1, true, true)).msgList.find((msg) => msg.msgSeq === msgSeq && msg.msgRandom === msgRandom);
    if (!replyMsgList) {
      return void 0;
    }
    return {
      id: MessageUnique.createUniqueMsgId(peer, replyMsgList.msgId),
      msg: replyMsgList
    };
  }
  async _handle(payload, _adapter, config) {
    const msglist = (await this.core.apis.WebApi.getGroupEssenceMsgAll(payload.group_id.toString())).flatMap((e) => e?.data?.msg_list).filter(Boolean);
    if (!msglist) {
      throw new Error("获取失败");
    }
    return await Promise.all(msglist.map(async (msg) => {
      const msgOriginData = await this.msgSeqToMsgId({
        chatType: ChatType.KCHATTYPEGROUP,
        peerUid: payload.group_id.toString()
      }, msg.msg_seq.toString(), msg.msg_random.toString());
      if (msgOriginData) {
        const { id: message_id, msg: rawMessage } = msgOriginData;
        return {
          msg_seq: msg.msg_seq,
          msg_random: msg.msg_random,
          sender_id: +msg.sender_uin,
          sender_nick: msg.sender_nick,
          operator_id: +msg.add_digest_uin,
          operator_nick: msg.add_digest_nick,
          message_id,
          operator_time: msg.add_digest_time,
          content: (await this.obContext.apis.MsgApi.parseMessage(rawMessage, config.messagePostFormat))?.message
        };
      }
      const msgTempData = JSON.stringify({
        msg_seq: msg.msg_seq.toString(),
        msg_random: msg.msg_random.toString(),
        group_id: payload.group_id.toString()
      });
      const hash = crypto__default.createHash("md5").update(msgTempData).digest();
      if (hash[0]) {
        hash[0] &= 127;
      }
      const shortId = hash.readInt32BE(0);
      this.core.apis.GroupApi.essenceLRU.set(shortId, msgTempData);
      return {
        msg_seq: msg.msg_seq,
        msg_random: msg.msg_random,
        sender_id: +msg.sender_uin,
        sender_nick: msg.sender_nick,
        operator_id: +msg.add_digest_uin,
        operator_nick: msg.add_digest_nick,
        message_id: shortId,
        operator_time: msg.add_digest_time,
        content: msg.msg_content.map((msg2) => {
          if (msg2.msg_type === 1) {
            return {
              type: "text",
              data: {
                text: msg2?.text
              }
            };
          } else if (msg2.msg_type === 3) {
            return {
              type: "image",
              data: {
                url: msg2?.image_url
              }
            };
          }
          return void 0;
        }).filter((e) => e !== void 0)
      };
    }));
  }
}

const SchemaData$17 = Type.Object({
  message_id: Type.Union([Type.Number(), Type.String()]),
  group_id: Type.Optional(Type.Union([Type.Number(), Type.String()])),
  user_id: Type.Optional(Type.Union([Type.Number(), Type.String()]))
});
class ForwardSingleMsg extends OneBotAction {
  async getTargetPeer(payload) {
    if (payload.user_id) {
      const peerUid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
      if (!peerUid) {
        throw new Error(`无法找到私聊对象${payload.user_id}`);
      }
      return { chatType: ChatType.KCHATTYPEC2C, peerUid };
    }
    return { chatType: ChatType.KCHATTYPEGROUP, peerUid: payload.group_id.toString() };
  }
  async _handle(payload) {
    const msg = MessageUnique.getMsgIdAndPeerByShortId(+payload.message_id);
    if (!msg) {
      throw new Error(`无法找到消息${payload.message_id}`);
    }
    const peer = await this.getTargetPeer(payload);
    const ret = await this.core.apis.MsgApi.forwardMsg(
      msg.Peer,
      peer,
      [msg.MsgId]
    );
    if (ret.result !== 0) {
      throw new Error(`转发消息失败 ${ret.errMsg}`);
    }
    return null;
  }
}
class ForwardFriendSingleMsg extends ForwardSingleMsg {
  payloadSchema = SchemaData$17;
  actionName = ActionName.ForwardFriendSingleMsg;
}
class ForwardGroupSingleMsg extends ForwardSingleMsg {
  payloadSchema = SchemaData$17;
  actionName = ActionName.ForwardGroupSingleMsg;
}

class GetFriendWithCategory extends OneBotAction {
  actionName = ActionName.GetFriendsWithCategory;
  async _handle() {
    return (await this.core.apis.FriendApi.getBuddyV2ExWithCate()).map((category) => ({
      ...category,
      buddyList: OB11Construct.friends(category.buddyList)
    }));
  }
}

const SchemaData$16 = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  content: Type.String(),
  image: Type.Optional(Type.String()),
  pinned: Type.Union([Type.Number(), Type.String()], { default: 0 }),
  type: Type.Union([Type.Number(), Type.String()], { default: 1 }),
  confirm_required: Type.Union([Type.Number(), Type.String()], { default: 1 }),
  is_show_edit_card: Type.Union([Type.Number(), Type.String()], { default: 0 }),
  tip_window_type: Type.Union([Type.Number(), Type.String()], { default: 0 })
});
class SendGroupNotice extends OneBotAction {
  actionName = ActionName.GoCQHTTP_SendGroupNotice;
  payloadSchema = SchemaData$16;
  async _handle(payload) {
    let UploadImage;
    if (payload.image) {
      const {
        path,
        success
      } = await uriToLocalFile(this.core.NapCatTempPath, payload.image);
      if (!success) {
        throw new Error(`群公告${payload.image}设置失败,image字段可能格式不正确`);
      }
      if (!path) {
        throw new Error(`群公告${payload.image}设置失败,获取资源失败`);
      }
      await checkFileExist(path, 5e3);
      const ImageUploadResult = await this.core.apis.GroupApi.uploadGroupBulletinPic(payload.group_id.toString(), path);
      if (ImageUploadResult.errCode !== 0) {
        throw new Error(`群公告${payload.image}设置失败,图片上传失败 ， 错误信息:${ImageUploadResult.errMsg}`);
      }
      unlink(path).catch(() => {
      });
      UploadImage = ImageUploadResult.picInfo;
    }
    const publishGroupBulletinResult = await this.core.apis.WebApi.setGroupNotice(
      payload.group_id.toString(),
      payload.content,
      +payload.pinned,
      +payload.type,
      +payload.is_show_edit_card,
      +payload.tip_window_type,
      +payload.confirm_required,
      UploadImage?.id,
      UploadImage?.width,
      UploadImage?.height
    );
    if (!publishGroupBulletinResult || publishGroupBulletinResult.ec !== 0) {
      throw new Error(`设置群公告失败,错误信息:${publishGroupBulletinResult?.em}`);
    }
    return null;
  }
}

const SchemaData$15 = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  type: Type.Optional(Type.Enum(WebHonorType))
});
class GetGroupHonorInfo extends OneBotAction {
  actionName = ActionName.GetGroupHonorInfo;
  payloadSchema = SchemaData$15;
  async _handle(payload) {
    if (!payload.type) {
      payload.type = WebHonorType.ALL;
    }
    return await this.core.apis.WebApi.getGroupHonorInfo(payload.group_id.toString(), payload.type);
  }
}

class GoCQHTTPHandleQuickAction extends OneBotAction {
  actionName = ActionName.GoCQHTTP_HandleQuickAction;
  async _handle(payload) {
    this.obContext.apis.QuickActionApi.handleQuickOperation(payload.context, payload.operation).catch((e) => this.core.context.logger.logError(e));
    return null;
  }
}

class GetGroupIgnoredNotifies extends OneBotAction {
  actionName = ActionName.GetGroupIgnoredNotifies;
  async _handle() {
    const SingleScreenNotifies = await this.core.apis.GroupApi.getSingleScreenNotifies(false, 50);
    const retData = { invited_requests: [], InvitedRequest: [], join_requests: [] };
    const notifyPromises = SingleScreenNotifies.map(async (SSNotify) => {
      const invitorUin = SSNotify.user1?.uid ? +await this.core.apis.UserApi.getUinByUidV2(SSNotify.user1.uid) : 0;
      const actorUin = SSNotify.user2?.uid ? +await this.core.apis.UserApi.getUinByUidV2(SSNotify.user2.uid) : 0;
      const commonData = {
        request_id: +SSNotify.seq,
        invitor_uin: invitorUin,
        invitor_nick: SSNotify.user1?.nickName,
        group_id: +SSNotify.group?.groupCode,
        message: SSNotify?.postscript,
        group_name: SSNotify.group?.groupName,
        checked: SSNotify.status !== GroupNotifyMsgStatus.KUNHANDLE,
        actor: actorUin,
        requester_nick: SSNotify.user1?.nickName
      };
      if (SSNotify.type === 1) {
        retData.InvitedRequest.push(commonData);
      } else if (SSNotify.type === 7) {
        retData.join_requests.push(commonData);
      }
    });
    await Promise.all(notifyPromises);
    retData.invited_requests = retData.InvitedRequest;
    return retData;
  }
}

class GetOnlineClient extends OneBotAction {
  actionName = ActionName.GetOnlineClient;
  async _handle() {
    this.core.apis.SystemApi.getOnlineDev();
    await sleep(500);
    return [];
  }
}

const SchemaData$14 = Type.Object({
  image: Type.String()
});
class OCRImageBase extends OneBotAction {
  payloadSchema = SchemaData$14;
  async _handle(payload) {
    const { path, success } = await uriToLocalFile(this.core.NapCatTempPath, payload.image);
    if (!success) {
      throw new Error(`OCR ${payload.image}失败, image字段可能格式不正确`);
    }
    if (path) {
      try {
        await checkFileExist(path, 5e3);
        const ret = await this.core.apis.SystemApi.ocrImage(path);
        if (!ret) {
          throw new Error(`OCR ${payload.image}失败`);
        }
        return ret.result;
      } finally {
        fs__default.unlink(path, () => {
        });
      }
    }
    throw new Error(`OCR ${payload.image}失败, 文件可能不存在`);
  }
}
class OCRImage extends OCRImageBase {
  actionName = ActionName.OCRImage;
}
class IOCRImage extends OCRImageBase {
  actionName = ActionName.IOCRImage;
}

const SchemaData$13 = Type.Object({
  words: Type.Array(Type.String())
});
class TranslateEnWordToZn extends OneBotAction {
  actionName = ActionName.TranslateEnWordToZn;
  payloadSchema = SchemaData$13;
  async _handle(payload) {
    const ret = await this.core.apis.SystemApi.translateEnWordToZn(payload.words);
    if (ret.result !== 0) {
      throw new Error("翻译失败");
    }
    return ret.words;
  }
}

const SchemaData$12 = Type.Object({
  nickname: Type.String(),
  personal_note: Type.Optional(Type.String()),
  sex: Type.Optional(Type.Union([Type.Number(), Type.String()]))
  // 传Sex值？建议传0
});
class SetQQProfile extends OneBotAction {
  actionName = ActionName.SetQQProfile;
  payloadSchema = SchemaData$12;
  async _handle(payload) {
    const self = this.core.selfInfo;
    const OldProfile = await this.core.apis.UserApi.getUserDetailInfo(self.uid);
    return await this.core.apis.UserApi.modifySelfProfile({
      nick: payload.nickname,
      longNick: (payload?.personal_note ?? OldProfile?.longNick) || "",
      sex: parseInt(payload?.sex ? payload?.sex.toString() : OldProfile?.sex.toString()),
      birthday: {
        birthday_year: OldProfile?.birthday_year.toString(),
        birthday_month: OldProfile?.birthday_month.toString(),
        birthday_day: OldProfile?.birthday_day.toString()
      },
      location: void 0
    });
  }
}

const SchemaData$11 = Type.Object({
  user_id: Type.Optional(Type.Union([Type.Number(), Type.String()])),
  group_id: Type.Optional(Type.Union([Type.Number(), Type.String()])),
  phone_number: Type.String({ default: "" })
});
class SharePeerBase extends OneBotAction {
  payloadSchema = SchemaData$11;
  async _handle(payload) {
    if (payload.group_id) {
      return await this.core.apis.GroupApi.getGroupRecommendContactArkJson(payload.group_id.toString());
    } else if (payload.user_id) {
      return await this.core.apis.UserApi.getBuddyRecommendContactArkJson(payload.user_id.toString(), payload.phone_number);
    }
    throw new Error("group_id or user_id is required");
  }
}
const SchemaDataGroupEx = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()])
});
class SharePeer extends SharePeerBase {
  actionName = ActionName.SharePeer;
}
class ShareGroupExBase extends OneBotAction {
  payloadSchema = SchemaDataGroupEx;
  async _handle(payload) {
    return await this.core.apis.GroupApi.getArkJsonGroupShare(payload.group_id.toString());
  }
}
class ShareGroupEx extends ShareGroupExBase {
  actionName = ActionName.ShareGroupEx;
}
class SendGroupArkShare extends ShareGroupExBase {
  actionName = ActionName.SendGroupArkShare;
}
class SendArkShare extends SharePeerBase {
  actionName = ActionName.SendArkShare;
}

const SchemaData$10 = Type.Object({
  rawData: Type.String(),
  brief: Type.String()
});
class CreateCollection extends OneBotAction {
  actionName = ActionName.CreateCollection;
  payloadSchema = SchemaData$10;
  async _handle(payload) {
    return await this.core.apis.CollectionApi.createCollection(
      this.core.selfInfo.uin,
      this.core.selfInfo.uid,
      this.core.selfInfo.nick,
      payload.brief,
      payload.rawData
    );
  }
}

const SchemaData$$ = Type.Object({
  longNick: Type.String()
});
class SetLongNick extends OneBotAction {
  actionName = ActionName.SetLongNick;
  payloadSchema = SchemaData$$;
  async _handle(payload) {
    return await this.core.apis.UserApi.setLongNick(payload.longNick);
  }
}

const SchemaData$_ = Type.Object({
  message_id: Type.Optional(Type.Union([Type.Number(), Type.String()])),
  msg_seq: Type.Optional(Type.String()),
  msg_random: Type.Optional(Type.String()),
  group_id: Type.Optional(Type.String())
});
class DelEssenceMsg extends OneBotAction {
  actionName = ActionName.DelEssenceMsg;
  payloadSchema = SchemaData$_;
  async _handle(payload) {
    if (payload.msg_seq && payload.msg_random && payload.group_id) {
      return await this.core.apis.GroupApi.removeGroupEssenceBySeq(
        payload.group_id,
        payload.msg_random,
        payload.msg_seq
      );
    }
    if (!payload.message_id) {
      throw new Error("必须提供 message_id 或者同时提供 msg_seq, msg_random, group_id");
    }
    const msg = MessageUnique.getMsgIdAndPeerByShortId(+payload.message_id);
    if (!msg) {
      const data = this.core.apis.GroupApi.essenceLRU.getValue(+payload.message_id);
      if (!data) throw new Error("消息不存在");
      const { msg_seq, msg_random, group_id } = JSON.parse(data);
      return await this.core.apis.GroupApi.removeGroupEssenceBySeq(group_id, msg_seq, msg_random);
    }
    return await this.core.apis.GroupApi.removeGroupEssence(
      msg.Peer.peerUid,
      msg.MsgId
    );
  }
}

const SchemaData$Z = Type.Object({
  message_id: Type.Union([Type.Number(), Type.String()])
});
class SetEssenceMsg extends OneBotAction {
  actionName = ActionName.SetEssenceMsg;
  payloadSchema = SchemaData$Z;
  async _handle(payload) {
    const msg = MessageUnique.getMsgIdAndPeerByShortId(+payload.message_id);
    if (!msg) {
      throw new Error("msg not found");
    }
    return await this.core.apis.GroupApi.addGroupEssence(
      msg.Peer.peerUid,
      msg.MsgId
    );
  }
}

const SchemaData$Y = Type.Object({
  count: Type.Union([Type.Number(), Type.String()], { default: 10 })
});
class GetRecentContact extends OneBotAction {
  actionName = ActionName.GetRecentContact;
  payloadSchema = SchemaData$Y;
  async _handle(payload, _adapter, config) {
    const ret = await this.core.apis.UserApi.getRecentContactListSnapShot(+payload.count);
    return await Promise.all(ret.info.changedList.map(async (t) => {
      const FastMsg = await this.core.apis.MsgApi.getMsgsByMsgId({ chatType: t.chatType, peerUid: t.peerUid }, [t.msgId]);
      if (FastMsg.msgList.length > 0 && FastMsg.msgList[0]) {
        const lastestMsg = await this.obContext.apis.MsgApi.parseMessage(FastMsg.msgList[0], config.messagePostFormat);
        return {
          lastestMsg,
          peerUin: t.peerUin,
          remark: t.remark,
          msgTime: t.msgTime,
          chatType: t.chatType,
          msgId: t.msgId,
          sendNickName: t.sendNickName,
          sendMemberName: t.sendMemberName,
          peerName: t.peerName
        };
      }
      return {
        peerUin: t.peerUin,
        remark: t.remark,
        msgTime: t.msgTime,
        chatType: t.chatType,
        msgId: t.msgId,
        sendNickName: t.sendNickName,
        sendMemberName: t.sendMemberName,
        peerName: t.peerName
      };
    }));
  }
}

const SchemaData$X = Type.Object({
  user_id: Type.Optional(Type.Union([Type.Number(), Type.String()])),
  start: Type.Union([Type.Number(), Type.String()], { default: 0 }),
  count: Type.Union([Type.Number(), Type.String()], { default: 10 })
});
class GetProfileLike extends OneBotAction {
  actionName = ActionName.GetProfileLike;
  payloadSchema = SchemaData$X;
  async _handle(payload) {
    const isSelf = this.core.selfInfo.uin === payload.user_id || !payload.user_id;
    const userUid = isSelf || !payload.user_id ? this.core.selfInfo.uid : await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
    const type = isSelf ? 2 : 1;
    const ret = await this.core.apis.UserApi.getProfileLike(userUid ?? this.core.selfInfo.uid, +payload.start, +payload.count, type);
    const data = ret.info.userLikeInfos[0];
    if (!data) {
      throw new Error("get info error");
    }
    for (const item of data.voteInfo.userInfos) {
      item.uin = +(await this.core.apis.UserApi.getUinByUidV2(item.uid) ?? "");
    }
    for (const item of data.favoriteInfo.userInfos) {
      item.uin = +(await this.core.apis.UserApi.getUinByUidV2(item.uid) ?? "");
    }
    return data;
  }
}

const SchemaData$W = Type.Object({
  file: Type.String(),
  group_id: Type.Union([Type.Number(), Type.String()])
});
class SetGroupPortrait extends OneBotAction {
  actionName = ActionName.SetGroupPortrait;
  payloadSchema = SchemaData$W;
  async _handle(payload) {
    const { path, success } = await uriToLocalFile(this.core.NapCatTempPath, payload.file);
    if (!success) {
      throw new Error(`头像${payload.file}设置失败,file字段可能格式不正确`);
    }
    if (path) {
      await checkFileExistV2(path, 5e3);
      const ret = await this.core.apis.GroupApi.setGroupAvatar(payload.group_id.toString(), path);
      fs$1.unlink(path).catch(() => {
      });
      if (!ret) {
        throw new Error(`头像${payload.file}设置失败,api无返回`);
      }
      if (ret.result === 1004022) {
        throw new Error(`头像${payload.file}设置失败，文件可能不是图片格式或权限不足`);
      } else if (ret.result !== 0) {
        throw new Error(`头像${payload.file}设置失败,未知的错误,${ret.result}:${ret.errMsg}`);
      }
      return ret;
    } else {
      fs$1.unlink(path).catch(() => {
      });
      throw new Error(`头像${payload.file}设置失败,无法获取头像,文件可能不存在`);
    }
  }
}

const SchemaData$V = Type.Object({
  count: Type.Union([Type.Number(), Type.String()], { default: 48 })
});
class FetchCustomFace extends OneBotAction {
  actionName = ActionName.FetchCustomFace;
  payloadSchema = SchemaData$V;
  async _handle(payload) {
    const ret = await this.core.apis.MsgApi.fetchFavEmojiList(+payload.count);
    return ret.emojiInfoList.map((e) => e.url);
  }
}

const SchemaData$U = Type.Object({
  user_id: Type.Union([Type.Number(), Type.String()]),
  file: Type.String(),
  name: Type.String()
});
class GoCQHTTPUploadPrivateFile extends OneBotAction {
  actionName = ActionName.GOCQHTTP_UploadPrivateFile;
  payloadSchema = SchemaData$U;
  async getPeer(payload) {
    if (payload.user_id) {
      const peerUid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
      if (!peerUid) {
        throw new Error(`私聊${payload.user_id}不存在`);
      }
      const isBuddy = await this.core.apis.FriendApi.isBuddy(peerUid);
      return { chatType: isBuddy ? ChatType.KCHATTYPEC2C : ChatType.KCHATTYPETEMPC2CFROMGROUP, peerUid };
    }
    throw new Error("缺少参数 user_id");
  }
  async _handle(payload) {
    let file = payload.file;
    if (fs__default.existsSync(file)) {
      file = `file://${file}`;
    }
    const downloadResult = await uriToLocalFile(this.core.NapCatTempPath, file);
    if (!downloadResult.success) {
      throw new Error(downloadResult.errMsg);
    }
    const msgContext = {
      peer: await createContext(this.core, {
        user_id: payload.user_id.toString()
      }, ContextMode.Private),
      deleteAfterSentFiles: []
    };
    const sendFileEle = await this.obContext.apis.FileApi.createValidSendFileElement(msgContext, downloadResult.path, payload.name);
    msgContext.deleteAfterSentFiles.push(downloadResult.path);
    const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(await this.getPeer(payload), [sendFileEle], msgContext.deleteAfterSentFiles);
    const fileElement = returnMsg.elements.find((ele) => ele.elementType === ElementType.FILE);
    return {
      file_id: fileElement?.fileElement?.fileUuid || null
    };
  }
}

const SchemaData$T = Type.Object({
  message_id: Type.Union([Type.Number(), Type.String()]),
  emojiId: Type.Union([Type.Number(), Type.String()]),
  emojiType: Type.Union([Type.Number(), Type.String()]),
  count: Type.Union([Type.Number(), Type.String()], { default: 20 })
});
class FetchEmojiLike extends OneBotAction {
  actionName = ActionName.FetchEmojiLike;
  payloadSchema = SchemaData$T;
  async _handle(payload) {
    const msgIdPeer = MessageUnique.getMsgIdAndPeerByShortId(+payload.message_id);
    if (!msgIdPeer) throw new Error("消息不存在");
    const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(msgIdPeer.Peer, [msgIdPeer.MsgId])).msgList[0];
    if (!msg) throw new Error("消息不存在");
    return await this.core.apis.MsgApi.getMsgEmojiLikesList(
      msgIdPeer.Peer,
      msg.msgSeq,
      payload.emojiId.toString(),
      payload.emojiType.toString(),
      +payload.count
    );
  }
}

const SchemaData$S = Type.Object({
  user_id: Type.Union([Type.Number(), Type.String()]),
  event_type: Type.Number()
});
class SetInputStatus extends OneBotAction {
  actionName = ActionName.SetInputStatus;
  payloadSchema = SchemaData$S;
  async _handle(payload) {
    const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
    if (!uid) throw new Error("uid is empty");
    const peer = {
      chatType: ChatType.KCHATTYPEC2C,
      peerUid: uid
    };
    return await this.core.apis.MsgApi.sendShowInputStatusReq(peer, payload.event_type);
  }
}

class GetCSRF extends OneBotAction {
  actionName = ActionName.GetCSRF;
  async _handle() {
    const sKey = await this.core.apis.UserApi.getSKey();
    if (!sKey) {
      throw new Error("SKey is undefined");
    }
    return {
      token: +this.core.apis.WebApi.getBknFromSKey(sKey)
    };
  }
}

const SchemaData$R = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  notice_id: Type.String()
});
class DelGroupNotice extends OneBotAction {
  actionName = ActionName.DelGroupNotice;
  payloadSchema = SchemaData$R;
  async _handle(payload) {
    const group = payload.group_id.toString();
    const noticeId = payload.notice_id;
    return await this.core.apis.GroupApi.deleteGroupBulletin(group, noticeId);
  }
}

const SchemaData$Q = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()])
});
class GetGroupInfoEx extends OneBotAction {
  actionName = ActionName.GetGroupInfoEx;
  payloadSchema = SchemaData$Q;
  async _handle(payload) {
    return (await this.core.apis.GroupApi.getGroupExtFE0Info([payload.group_id.toString()])).result.groupExtInfos.get(payload.group_id.toString());
  }
}

const SchemaData$P = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  file_id: Type.String()
});
class DeleteGroupFile extends OneBotAction {
  actionName = ActionName.GOCQHTTP_DeleteGroupFile;
  payloadSchema = SchemaData$P;
  async _handle(payload) {
    const data = FileNapCatOneBotUUID.decodeModelId(payload.file_id);
    if (!data || !data.fileId) throw new Error("Invalid file_id");
    return await this.core.apis.GroupApi.delGroupFile(payload.group_id.toString(), [data.fileId]);
  }
}

const SchemaData$O = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  // 兼容gocq 与name二选一
  folder_name: Type.Optional(Type.String()),
  // 兼容gocq 与folder_name二选一
  name: Type.Optional(Type.String())
});
class CreateGroupFileFolder extends OneBotAction {
  actionName = ActionName.GoCQHTTP_CreateGroupFileFolder;
  payloadSchema = SchemaData$O;
  async _handle(payload) {
    const folderName = payload.folder_name || payload.name;
    return (await this.core.apis.GroupApi.creatGroupFileFolder(payload.group_id.toString(), folderName)).resultWithGroupItem;
  }
}

const SchemaData$N = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  folder_id: Type.Optional(Type.String()),
  folder: Type.Optional(Type.String())
});
class DeleteGroupFileFolder extends OneBotAction {
  actionName = ActionName.GoCQHTTP_DeleteGroupFileFolder;
  payloadSchema = SchemaData$N;
  async _handle(payload) {
    return (await this.core.apis.GroupApi.delGroupFileFolder(
      payload.group_id.toString(),
      payload.folder ?? payload.folder_id ?? ""
    )).groupFileCommonResult;
  }
}

const SchemaData$M = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()])
});
class GetGroupFileSystemInfo extends OneBotAction {
  actionName = ActionName.GoCQHTTP_GetGroupFileSystemInfo;
  payloadSchema = SchemaData$M;
  async _handle(payload) {
    const groupFileCount = (await this.core.apis.GroupApi.getGroupFileCount([payload.group_id.toString()])).groupFileCounts[0];
    if (!groupFileCount) {
      throw new Error("Group not found");
    }
    return {
      file_count: groupFileCount,
      limit_count: 1e4,
      used_space: 0,
      total_space: 10 * 1024 * 1024 * 1024
    };
  }
}

const SchemaData$L = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  file_count: Type.Union([Type.Number(), Type.String()], { default: 50 })
});
class GetGroupRootFiles extends OneBotAction {
  actionName = ActionName.GoCQHTTP_GetGroupRootFiles;
  payloadSchema = SchemaData$L;
  async _handle(payload) {
    const ret = await this.core.apis.MsgApi.getGroupFileList(payload.group_id.toString(), {
      sortType: 1,
      fileCount: +payload.file_count,
      startIndex: 0,
      sortOrder: 2,
      showOnlinedocFolder: 0
    });
    return {
      files: ret.filter((item) => item.fileInfo).map((item) => OB11Construct.file(item.peerId, item.fileInfo)),
      folders: ret.filter((item) => item.folderInfo).map((item) => OB11Construct.folder(item.peerId, item.folderInfo))
    };
  }
}

const SchemaData$K = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  folder_id: Type.Optional(Type.String()),
  folder: Type.Optional(Type.String()),
  file_count: Type.Union([Type.Number(), Type.String()], { default: 50 })
});
class GetGroupFilesByFolder extends OneBotAction {
  actionName = ActionName.GoCQHTTP_GetGroupFilesByFolder;
  payloadSchema = SchemaData$K;
  async _handle(payload) {
    const ret = await this.core.apis.MsgApi.getGroupFileList(payload.group_id.toString(), {
      sortType: 1,
      fileCount: +payload.file_count,
      startIndex: 0,
      sortOrder: 2,
      showOnlinedocFolder: 0,
      folderId: payload.folder ?? payload.folder_id ?? ""
    }).catch(() => []);
    return {
      files: ret.filter((item) => item.fileInfo).map((item) => OB11Construct.file(item.peerId, item.fileInfo)),
      folders: []
    };
  }
}

const SchemaData$J = Type.Object({
  count: Type.Union([Type.Number(), Type.String()], { default: 50 })
});
class GetGroupSystemMsg extends OneBotAction {
  actionName = ActionName.GetGroupSystemMsg;
  payloadSchema = SchemaData$J;
  async _handle(params) {
    const SingleScreenNotifies = await this.core.apis.GroupApi.getSingleScreenNotifies(false, +params.count);
    const retData = { invited_requests: [], InvitedRequest: [], join_requests: [] };
    const notifyPromises = SingleScreenNotifies.map(async (SSNotify) => {
      const invitorUin = SSNotify.user1?.uid ? +await this.core.apis.UserApi.getUinByUidV2(SSNotify.user1.uid) : 0;
      const actorUin = SSNotify.user2?.uid ? +await this.core.apis.UserApi.getUinByUidV2(SSNotify.user2.uid) : 0;
      const commonData = {
        request_id: +SSNotify.seq,
        invitor_uin: invitorUin,
        invitor_nick: SSNotify.user1?.nickName,
        group_id: +SSNotify.group?.groupCode,
        message: SSNotify?.postscript,
        group_name: SSNotify.group?.groupName,
        checked: SSNotify.status !== GroupNotifyMsgStatus.KUNHANDLE,
        actor: actorUin,
        requester_nick: SSNotify.user1?.nickName
      };
      if (SSNotify.type === 1) {
        retData.InvitedRequest.push(commonData);
      } else if (SSNotify.type === 7) {
        retData.join_requests.push(commonData);
      }
    });
    await Promise.all(notifyPromises);
    retData.invited_requests = retData.InvitedRequest;
    return retData;
  }
}

class GetPacketStatusDepends extends OneBotAction {
  async check(payload) {
    if (!this.core.apis.PacketApi.packetStatus) {
      return {
        valid: false,
        message: "packetBackend不可用，请参照文档 https://napneko.github.io/config/advanced 和启动日志检查packetBackend状态或进行配置！错误堆栈信息：" + this.core.apis.PacketApi.clientLogStack
      };
    }
    return await super.check(payload);
  }
}
class GetPacketStatus extends GetPacketStatusDepends {
  actionName = ActionName.GetPacketStatus;
  async _handle() {
  }
}

const SchemaData$I = Type.Object({
  user_id: Type.Union([Type.Number(), Type.String()])
});
class GetUserStatus extends GetPacketStatusDepends {
  actionName = ActionName.GetUserStatus;
  payloadSchema = SchemaData$I;
  async _handle(payload) {
    return await this.core.apis.PacketApi.pkt.operation.GetStrangerStatus(+payload.user_id);
  }
}

class GetRkey extends GetPacketStatusDepends {
  actionName = ActionName.GetRkey;
  async _handle() {
    return await this.core.apis.PacketApi.pkt.operation.FetchRkey();
  }
}

const SchemaData$H = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  user_id: Type.Union([Type.Number(), Type.String()]),
  special_title: Type.String({ default: "" })
});
class SetSpecialTitle extends GetPacketStatusDepends {
  actionName = ActionName.SetSpecialTitle;
  payloadSchema = SchemaData$H;
  async _handle(payload) {
    const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
    if (!uid) throw new Error("User not found");
    await this.core.apis.PacketApi.pkt.operation.SetGroupSpecialTitle(+payload.group_id, uid, payload.special_title);
  }
}

const SchemaData$G = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()])
});
class GetGroupShutList extends OneBotAction {
  actionName = ActionName.GetGroupShutList;
  payloadSchema = SchemaData$G;
  async _handle(payload) {
    return await this.core.apis.GroupApi.getGroupShutUpMemberList(payload.group_id.toString());
  }
}

const SchemaData$F = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  no_cache: Type.Optional(Type.Union([Type.Boolean(), Type.String()]))
});
class GetGroupMemberList extends OneBotAction {
  actionName = ActionName.GetGroupMemberList;
  payloadSchema = SchemaData$F;
  async _handle(payload) {
    const groupIdStr = payload.group_id.toString();
    const noCache = this.parseBoolean(payload.no_cache ?? false);
    const groupMembers = await this.getGroupMembers(groupIdStr, noCache);
    const _groupMembers = await Promise.all(
      Array.from(groupMembers.values()).map(
        (item) => OB11Construct.groupMember(groupIdStr, item)
      )
    );
    return Array.from(new Map(_groupMembers.map((member) => [member.user_id, member])).values());
  }
  parseBoolean(value) {
    return typeof value === "string" ? value === "true" : value;
  }
  async getGroupMembers(groupIdStr, noCache) {
    const memberCache = this.core.apis.GroupApi.groupMemberCache;
    let groupMembers = memberCache.get(groupIdStr);
    if (noCache || !groupMembers) {
      const data = this.core.apis.GroupApi.refreshGroupMemberCache(groupIdStr, true).then().catch();
      groupMembers = memberCache.get(groupIdStr) || await data;
      if (!groupMembers) {
        throw new Error(`Failed to get group member list for group ${groupIdStr}`);
      }
    }
    return groupMembers;
  }
}

const SchemaData$E = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  file_id: Type.String()
});
class GetGroupFileUrl extends GetPacketStatusDepends {
  actionName = ActionName.GOCQHTTP_GetGroupFileUrl;
  payloadSchema = SchemaData$E;
  async _handle(payload) {
    const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file_id) || FileNapCatOneBotUUID.decodeModelId(payload.file_id);
    if (contextMsgFile?.fileUUID) {
      return {
        url: await this.core.apis.PacketApi.pkt.operation.GetGroupFileUrl(+payload.group_id, contextMsgFile.fileUUID)
      };
    }
    throw new Error("real fileUUID not found!");
  }
}

const SchemaData$D = Type.Object({
  domain: Type.String()
});
class GetCredentials extends OneBotAction {
  actionName = ActionName.GetCredentials;
  payloadSchema = SchemaData$D;
  async _handle(payload) {
    const cookiesObject = await this.core.apis.UserApi.getCookies(payload.domain);
    const cookies = Object.entries(cookiesObject).map(([key, value]) => `${key}=${value}`).join("; ");
    const bkn = cookiesObject?.["skey"] ? this.core.apis.WebApi.getBknFromCookie(cookiesObject) : "";
    return { cookies, token: +bkn };
  }
}

const SchemaData$C = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()])
});
class SetGroupSignBase extends GetPacketStatusDepends {
  payloadSchema = SchemaData$C;
  async _handle(payload) {
    return await this.core.apis.PacketApi.pkt.operation.GroupSign(+payload.group_id);
  }
}
class SetGroupSign extends SetGroupSignBase {
  actionName = ActionName.SetGroupSign;
}
class SendGroupSign extends SetGroupSignBase {
  actionName = ActionName.SendGroupSign;
}

const SchemaData$B = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()])
});
class GoCQHTTPGetGroupAtAllRemain extends OneBotAction {
  actionName = ActionName.GoCQHTTP_GetGroupAtAllRemain;
  payloadSchema = SchemaData$B;
  async _handle(payload) {
    const ret = await this.core.apis.GroupApi.getGroupRemainAtTimes(payload.group_id.toString());
    const data = {
      can_at_all: ret.atInfo.canAtAll,
      remain_at_all_count_for_group: ret.atInfo.RemainAtAllCountForGroup,
      remain_at_all_count_for_uin: ret.atInfo.RemainAtAllCountForUin
    };
    return data;
  }
}

const SchemaData$A = Type.Object({
  url: Type.String()
});
class GoCQHTTPCheckUrlSafely extends OneBotAction {
  actionName = ActionName.GoCQHTTP_CheckUrlSafely;
  payloadSchema = SchemaData$A;
  async _handle() {
    return { level: 1 };
  }
}

const SchemaData$z = Type.Object({
  model: Type.Optional(Type.String())
});
class GoCQHTTPGetModelShow extends OneBotAction {
  actionName = ActionName.GoCQHTTP_GetModelShow;
  payloadSchema = SchemaData$z;
  async _handle(payload) {
    if (!payload.model) {
      payload.model = "napcat";
    }
    return [{
      variants: {
        model_show: "napcat",
        need_pay: false
      }
    }];
  }
}

class GoCQHTTPSetModelShow extends OneBotAction {
  actionName = ActionName.GoCQHTTP_SetModelShow;
  async _handle() {
  }
}

const SchemaData$y = Type.Object({
  friend_id: Type.Optional(Type.Union([Type.String(), Type.Number()])),
  user_id: Type.Optional(Type.Union([Type.String(), Type.Number()])),
  temp_block: Type.Optional(Type.Boolean()),
  temp_both_del: Type.Optional(Type.Boolean())
});
class GoCQHTTPDeleteFriend extends OneBotAction {
  actionName = ActionName.GoCQHTTP_DeleteFriend;
  payloadSchema = SchemaData$y;
  async _handle(payload) {
    const uin = payload.friend_id ?? payload.user_id ?? "";
    const uid = await this.core.apis.UserApi.getUidByUinV2(uin.toString());
    if (!uid) {
      return {
        valid: false,
        message: "好友不存在"
      };
    }
    const isBuddy = await this.core.apis.FriendApi.isBuddy(uid);
    if (!isBuddy) {
      return {
        valid: false,
        message: "不是好友"
      };
    }
    return await this.core.apis.FriendApi.delBuudy(uid, payload.temp_block, payload.temp_both_del);
  }
}

class MiniAppInfo {
  static sdkId = "V1_PC_MINISDK_99.99.99_1_APP_A";
  template;
  static appMap = /* @__PURE__ */ new Map();
  constructor(template) {
    this.template = template;
  }
  static get(name) {
    return this.appMap.get(name);
  }
  static Bili = new class extends MiniAppInfo {
    constructor() {
      super({
        sdkId: MiniAppInfo.sdkId,
        appId: "1109937557",
        scene: 1,
        templateType: 1,
        businessType: 0,
        verType: 3,
        shareType: 0,
        versionId: "cfc5f7b05b44b5956502edaecf9d2240",
        withShareTicket: 0,
        iconUrl: "https://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg"
      });
      MiniAppInfo.appMap.set("bili", this);
    }
  }();
  static WeiBo = new class extends MiniAppInfo {
    constructor() {
      super({
        sdkId: MiniAppInfo.sdkId,
        appId: "1109224783",
        scene: 1,
        templateType: 1,
        businessType: 0,
        verType: 3,
        shareType: 0,
        versionId: "e482a3cc4e574d9b772e96ba6eec9ba2",
        withShareTicket: 0,
        iconUrl: "https://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg"
      });
      MiniAppInfo.appMap.set("weibo", this);
    }
  }();
}
class MiniAppInfoHelper {
  static generateReq(custom, template) {
    return {
      ...custom,
      ...template
    };
  }
  static RawToSend(rawData) {
    return {
      ver: rawData.ver,
      prompt: rawData.prompt,
      config: rawData.config,
      app: rawData.appName,
      view: rawData.appView,
      meta: rawData.metaData,
      miniappShareOrigin: 3,
      miniappOpenRefer: "10002"
    };
  }
  static SendToRaw(data) {
    return {
      appName: data.app,
      appView: data.view,
      ver: data.ver,
      desc: data.meta.detail_1.desc,
      prompt: data.prompt,
      metaData: data.meta,
      config: data.config
    };
  }
}

const SchemaData$x = Type.Union([
  Type.Object({
    type: Type.Union([Type.Literal("bili"), Type.Literal("weibo")]),
    title: Type.String(),
    desc: Type.String(),
    picUrl: Type.String(),
    jumpUrl: Type.String(),
    webUrl: Type.Optional(Type.String()),
    rawArkData: Type.Optional(Type.Union([Type.String()]))
  }),
  Type.Object({
    title: Type.String(),
    desc: Type.String(),
    picUrl: Type.String(),
    jumpUrl: Type.String(),
    iconUrl: Type.String(),
    webUrl: Type.Optional(Type.String()),
    appId: Type.String(),
    scene: Type.Union([Type.Number(), Type.String()]),
    templateType: Type.Union([Type.Number(), Type.String()]),
    businessType: Type.Union([Type.Number(), Type.String()]),
    verType: Type.Union([Type.Number(), Type.String()]),
    shareType: Type.Union([Type.Number(), Type.String()]),
    versionId: Type.String(),
    sdkId: Type.String(),
    withShareTicket: Type.Union([Type.Number(), Type.String()]),
    rawArkData: Type.Optional(Type.Union([Type.String()]))
  })
]);
class GetMiniAppArk extends GetPacketStatusDepends {
  actionName = ActionName.GetMiniAppArk;
  payloadSchema = SchemaData$x;
  async _handle(payload) {
    let reqParam;
    const customParams = {
      title: payload.title,
      desc: payload.desc,
      picUrl: payload.picUrl,
      jumpUrl: payload.jumpUrl,
      webUrl: payload.webUrl
    };
    if ("type" in payload) {
      reqParam = MiniAppInfoHelper.generateReq(customParams, MiniAppInfo.get(payload.type).template);
    } else {
      const { appId, scene, iconUrl, templateType, businessType, verType, shareType, versionId, withShareTicket } = payload;
      reqParam = MiniAppInfoHelper.generateReq(
        customParams,
        {
          sdkId: payload.sdkId ?? MiniAppInfo.sdkId,
          appId,
          scene: +scene,
          iconUrl,
          templateType: +templateType,
          businessType: +businessType,
          verType: +verType,
          shareType: +shareType,
          versionId,
          withShareTicket: +withShareTicket
        }
      );
    }
    const arkData = await this.core.apis.PacketApi.pkt.operation.GetMiniAppAdaptShareInfo(reqParam);
    return {
      data: payload.rawArkData === "true" ? arkData : MiniAppInfoHelper.RawToSend(arkData)
    };
  }
}

var AIVoiceChatType = /* @__PURE__ */ ((AIVoiceChatType2) => {
  AIVoiceChatType2[AIVoiceChatType2["Unknown"] = 0] = "Unknown";
  AIVoiceChatType2[AIVoiceChatType2["Sound"] = 1] = "Sound";
  AIVoiceChatType2[AIVoiceChatType2["Sing"] = 2] = "Sing";
  return AIVoiceChatType2;
})(AIVoiceChatType || {});

const SchemaData$w = Type.Object({
  character: Type.String(),
  group_id: Type.Union([Type.Number(), Type.String()]),
  text: Type.String()
});
class GetAiRecord extends GetPacketStatusDepends {
  actionName = ActionName.GetAiRecord;
  payloadSchema = SchemaData$w;
  async _handle(payload) {
    const rawRsp = await this.core.apis.PacketApi.pkt.operation.GetAiVoice(+payload.group_id, payload.character, payload.text, AIVoiceChatType.Sound);
    if (!rawRsp.msgInfoBody[0]) {
      throw new Error("No voice data");
    }
    return await this.core.apis.PacketApi.pkt.operation.GetGroupPttUrl(+payload.group_id, rawRsp.msgInfoBody[0].index);
  }
}

const SchemaData$v = Type.Object({
  character: Type.String(),
  group_id: Type.Union([Type.Number(), Type.String()]),
  text: Type.String()
});
class SendGroupAiRecord extends GetPacketStatusDepends {
  actionName = ActionName.SendGroupAiRecord;
  payloadSchema = SchemaData$v;
  async _handle(payload) {
    await this.core.apis.PacketApi.pkt.operation.GetAiVoice(+payload.group_id, payload.character, payload.text, AIVoiceChatType.Sound);
    return {
      message_id: 0
      // can't get message_id from GetAiVoice
    };
  }
}

const SchemaData$u = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  chat_type: Type.Union([Type.Union([Type.Number(), Type.String()])], { default: 1 })
});
class GetAiCharacters extends GetPacketStatusDepends {
  actionName = ActionName.GetAiCharacters;
  payloadSchema = SchemaData$u;
  async _handle(payload) {
    const rawList = await this.core.apis.PacketApi.pkt.operation.FetchAiVoiceList(+payload.group_id, +payload.chat_type);
    return rawList?.map((item) => ({
      type: item.category,
      characters: item.voices.map((voice) => ({
        character_id: voice.voiceId,
        character_name: voice.voiceDisplayName,
        preview_url: voice.voiceExampleUrl
      }))
    })) ?? [];
  }
}

class GetGuildList extends OneBotAction {
  actionName = ActionName.GetGuildList;
  async _handle() {
  }
}

class GetGuildProfile extends OneBotAction {
  actionName = ActionName.GetGuildProfile;
  async _handle() {
  }
}

class GetClientkey extends OneBotAction {
  actionName = ActionName.GetClientkey;
  async _handle() {
    return { clientkey: (await this.core.apis.UserApi.forceFetchClientKey()).clientKey };
  }
}

const SchemaData$t = Type.Object({
  cmd: Type.String(),
  data: Type.String(),
  rsp: Type.Union([Type.String(), Type.Boolean()], { default: true })
});
class SendPacket extends GetPacketStatusDepends {
  payloadSchema = SchemaData$t;
  actionName = ActionName.SendPacket;
  async _handle(payload) {
    const rsp = typeof payload.rsp === "boolean" ? payload.rsp : payload.rsp === "true";
    const data = await this.core.apis.PacketApi.pkt.operation.sendPacket({ cmd: payload.cmd, data: Buffer.from(payload.data, "hex") }, rsp);
    return typeof data === "object" ? data.toString("hex") : void 0;
  }
}

const SchemaData$s = Type.Object({
  group_id: Type.Optional(Type.String()),
  user_id: Type.Optional(Type.String()),
  target_id: Type.Optional(Type.String())
});
class SendPokeBase extends GetPacketStatusDepends {
  payloadSchema = SchemaData$s;
  async _handle(payload) {
    const target_id = payload.target_id ? payload.target_id : payload.user_id;
    const peer_id = payload.group_id ? payload.group_id : payload.user_id;
    const is_group = !!payload.group_id;
    if (!target_id || !peer_id) {
      throw new Error("请检查参数，缺少 user_id 或 group_id");
    }
    await this.core.apis.PacketApi.pkt.operation.SendPoke(is_group, +peer_id, +target_id);
  }
}
class SendPoke extends SendPokeBase {
  actionName = ActionName.SendPoke;
}
class GroupPoke extends SendPokeBase {
  actionName = ActionName.GroupPoke;
}
class FriendPoke extends SendPokeBase {
  actionName = ActionName.FriendPoke;
}

const SchemaData$r = Type.Object({
  face_id: Type.Union([Type.Number(), Type.String()]),
  // 参考 face_config.json 的 QSid
  face_type: Type.Union([Type.Number(), Type.String()], { default: "1" }),
  wording: Type.String({ default: " " })
});
class SetDiyOnlineStatus extends OneBotAction {
  actionName = ActionName.SetDiyOnlineStatus;
  payloadSchema = SchemaData$r;
  async _handle(payload) {
    const ret = await this.core.apis.UserApi.setDiySelfOnlineStatus(
      payload.face_id.toString(),
      payload.wording,
      payload.face_type.toString()
    );
    if (ret.result !== 0) {
      throw new Error("设置在线状态失败");
    }
    return ret.errMsg;
  }
}

class BotExit extends OneBotAction {
  actionName = ActionName.Exit;
  async _handle() {
    process.exit(0);
  }
}

const SchemaData$q = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  bot_appid: Type.String(),
  button_id: Type.String({ default: "" }),
  callback_data: Type.String({ default: "" }),
  msg_seq: Type.String({ default: "10086" })
});
class ClickInlineKeyboardButton extends OneBotAction {
  actionName = ActionName.ClickInlineKeyboardButton;
  payloadSchema = SchemaData$q;
  async _handle(payload) {
    return await this.core.apis.MsgApi.clickInlineKeyboardButton({
      buttonId: payload.button_id,
      peerId: payload.group_id.toString(),
      botAppid: payload.bot_appid,
      msgSeq: payload.msg_seq,
      callback_data: payload.callback_data,
      dmFlag: 0,
      chatType: 2
    });
  }
}

const SchemaData$p = Type.Object({
  file_id: Type.String()
});
class GetPrivateFileUrl extends GetPacketStatusDepends {
  actionName = ActionName.NapCat_GetPrivateFileUrl;
  payloadSchema = SchemaData$p;
  async _handle(payload) {
    const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file_id);
    if (contextMsgFile?.fileUUID && contextMsgFile.msgId) {
      const msg = await this.core.apis.MsgApi.getMsgsByMsgId(contextMsgFile.peer, [contextMsgFile.msgId]);
      const self_id = this.core.selfInfo.uid;
      const file_hash = msg.msgList[0]?.elements.map((ele) => ele.fileElement?.file10MMd5)[0];
      if (file_hash) {
        return {
          url: await this.core.apis.PacketApi.pkt.operation.GetPrivateFileUrl(self_id, contextMsgFile.fileUUID, file_hash)
        };
      }
    }
    throw new Error("real fileUUID not found!");
  }
}

var A = Object.defineProperty;
var j = (r, e, t) => e in r ? A(r, e, { enumerable: true, configurable: true, writable: true, value: t }) : r[e] = t;
var W = (r, e, t) => j(r, typeof e != "symbol" ? e + "" : e, t);
class s {
  constructor(e, t, a, p) {
    W(this, "_value");
    W(this, "_fieldId");
    W(this, "_opt");
    W(this, "_callback");
    this._value = t, this._fieldId = e, this._opt = a, this._callback = p;
  }
  get value() {
    return this._value;
  }
  set value(e) {
    this._value = e;
  }
  getTypeName() {
    return this.constructor.name;
  }
  getFieldId() {
    return this._fieldId;
  }
  getField(e) {
    return L(e, this);
  }
}
class T extends s {
  getTypeName() {
    return "StringWrapper";
  }
}
class S extends s {
  getTypeName() {
    return "UInt32Wrapper";
  }
}
const n = {
  UInt32Wrapper: "UInt32Wrapper",
  Int32Wrapper: "Int32Wrapper",
  Int64Wrapper: "Int64Wrapper",
  UInt64Wrapper: "UInt64Wrapper",
  StringWrapper: "StringWrapper",
  ArrayWrapper: "ArrayWrapper",
  BoolWrapper: "BoolWrapper",
  BytesWrapper: "BytesWrapper",
  DoubleWrapper: "DoubleWrapper",
  FloatWrapper: "FloatWrapper",
  Fixed64Wrapper: "Fixed64Wrapper",
  Fixed32Wrapper: "Fixed32Wrapper",
  SFixed32Wrapper: "SFixed32Wrapper",
  SFixed64Wrapper: "SFixed64Wrapper",
  SInt32Wrapper: "SInt32Wrapper",
  SInt64Wrapper: "SInt64Wrapper",
  UnknownWrapper: "UnknownWrapper"
}, M = {
  [n.UInt32Wrapper]: ScalarType.UINT32,
  [n.Int32Wrapper]: ScalarType.INT32,
  [n.Int64Wrapper]: ScalarType.INT64,
  [n.UInt64Wrapper]: ScalarType.UINT64,
  [n.StringWrapper]: ScalarType.STRING,
  [n.BytesWrapper]: ScalarType.BYTES,
  [n.BoolWrapper]: ScalarType.BOOL,
  [n.DoubleWrapper]: ScalarType.DOUBLE,
  [n.FloatWrapper]: ScalarType.FLOAT,
  [n.Fixed64Wrapper]: ScalarType.FIXED64,
  [n.Fixed32Wrapper]: ScalarType.FIXED32,
  [n.SFixed32Wrapper]: ScalarType.SFIXED32,
  [n.SFixed64Wrapper]: ScalarType.SFIXED64,
  [n.SInt32Wrapper]: ScalarType.SINT32,
  [n.SInt64Wrapper]: ScalarType.SINT64,
  [n.UnknownWrapper]: ScalarType.BYTES
};
function x(r) {
  return M[r] || ScalarType.BYTES;
}
function Z(r = 0, e = false, t = "") {
  return new T(r, t, e);
}
function ee(r = 0, e = false, t = 0) {
  return new S(r, t, e);
}
function L(r, e) {
  var c;
  const t = e.getTypeName(), a = e.getFieldId(), p = e._opt;
  if (t === n.ArrayWrapper) {
    const i = (c = e._callback) == null ? void 0 : c.call(e);
    if (i instanceof l)
      return {
        no: a,
        name: r,
        kind: "message",
        T: () => new MessageType(r, i.generateFields()),
        opt: p || false,
        repeat: RepeatType.PACKED
      };
    if (i instanceof s) {
      const u = i.getTypeName();
      return {
        no: a,
        name: r,
        kind: "scalar",
        T: x(u),
        opt: p || false,
        repeat: u === n.StringWrapper || u === n.BytesWrapper ? RepeatType.UNPACKED : RepeatType.PACKED
      };
    }
    throw new Error("ArrayWrapper item type error");
  }
  return {
    no: a,
    name: r,
    kind: "scalar",
    T: x(t),
    opt: p || false,
    repeat: RepeatType.NO
  };
}
class l {
  constructor() {
    W(this, "_fieldId", 0);
  }
  //默认标记类
  generateFields() {
    const e = [];
    for (const t of Object.keys(this)) {
      const a = "_" + t, p = this[a];
      p instanceof s && e.push(p.getField(t)), p instanceof l && e.push({
        no: p._fieldId,
        name: t,
        kind: "message",
        T: () => new MessageType(a, p.generateFields()),
        repeat: RepeatType.NO,
        opt: false
      });
    }
    return e;
  }
  assignFields(e) {
    for (const t of Object.keys(this)) {
      const a = "_" + t;
      let p = this[a];
      if (p instanceof s) {
        const c = e[t];
        c !== void 0 && (p.value = c);
      } else if (p instanceof l) {
        const c = e[t];
        c !== void 0 && p.assignFields(c);
      } else {
        const c = e[t];
        c !== void 0 && (this[a] = c);
      }
    }
  }
  toObject() {
    const e = {};
    for (const t of Object.keys(this)) {
      const a = "_" + t, p = this[a];
      p && (p instanceof s && (e[t] = p.value), p instanceof l && (e[t] = p.toObject()));
    }
    return e;
  }
  encode() {
    return new MessageType("message", this.generateFields()).toBinary(this.toObject());
  }
  decode(e) {
    const t = new MessageType("message", this.generateFields()).fromBinary(e);
    return this.assignFields(t), this;
  }
  then(e) {
    e(this);
  }
}
function g(r) {
  return new Proxy(r, {
    set(e, t, a) {
      return e[t] instanceof s ? (e[t].value = a, true) : (e[t] = a, true);
    },
    get(e, t) {
      if (typeof t == "string" && t.startsWith("_")) {
        const p = t.slice(1);
        if (e[p])
          return e[p];
      }
      const a = e[t];
      return a instanceof s ? a.value : a;
    }
  });
}
function X(r, e) {
  const t = g(new r());
  return t._fieldId = typeof r == "number" ? r : 0, t;
}

class GetUnidirectionalFriendList extends OneBotAction {
  actionName = ActionName.GetUnidirectionalFriendList;
  async pack_data(data) {
    return X(class extends l {
      type = ee(2, false, 0);
      data = Z(3, false, data);
    }).encode();
  }
  async _handle() {
    const self_id = this.core.selfInfo.uin;
    const req_json = {
      uint64_uin: self_id,
      uint64_top: 0,
      uint32_req_num: 99,
      bytes_cookies: ""
    };
    const packed_data = await this.pack_data(JSON.stringify(req_json));
    const data = Buffer.from(packed_data);
    const rsq = { cmd: "MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0", data };
    const rsp_data = await this.core.apis.PacketApi.pkt.operation.sendPacket(rsq, true);
    const block_json = X(class extends l {
      data = Z(4);
    }).decode(rsp_data);
    const block_list = JSON.parse(block_json.data).rpt_block_list;
    return block_list.map((block) => ({
      uin: block.uint64_uin,
      uid: block.str_uid,
      nick_name: Buffer.from(block.bytes_nick, "base64").toString(),
      age: block.uint32_age,
      source: Buffer.from(block.bytes_source, "base64").toString()
    }));
  }
}

const SchemaData$o = Type.Object({
  group_id: Type.String(),
  remark: Type.String()
});
class SetGroupRemark extends OneBotAction {
  actionName = ActionName.SetGroupRemark;
  payloadSchema = SchemaData$o;
  async _handle(payload) {
    const ret = await this.core.apis.GroupApi.setGroupRemark(payload.group_id, payload.remark);
    if (ret.result !== 0) {
      throw new Error(`设置群备注失败, ${ret.result}:${ret.errMsg}`);
    }
    return null;
  }
}

const SchemaData$n = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  file_id: Type.String(),
  current_parent_directory: Type.String(),
  target_parent_directory: Type.String()
});
class MoveGroupFile extends GetPacketStatusDepends {
  actionName = ActionName.MoveGroupFile;
  payloadSchema = SchemaData$n;
  async _handle(payload) {
    const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file_id) || FileNapCatOneBotUUID.decodeModelId(payload.file_id);
    if (contextMsgFile?.fileUUID) {
      await this.core.apis.PacketApi.pkt.operation.MoveGroupFile(+payload.group_id, contextMsgFile.fileUUID, payload.current_parent_directory, payload.target_parent_directory);
      return {
        ok: true
      };
    }
    throw new Error("real fileUUID not found!");
  }
}

const SchemaData$m = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  file_id: Type.String()
});
class TransGroupFile extends GetPacketStatusDepends {
  actionName = ActionName.TransGroupFile;
  payloadSchema = SchemaData$m;
  async _handle(payload) {
    const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file_id) || FileNapCatOneBotUUID.decodeModelId(payload.file_id);
    if (contextMsgFile?.fileUUID) {
      const result = await this.core.apis.GroupApi.transGroupFile(payload.group_id.toString(), contextMsgFile.fileUUID);
      if (result.transGroupFileResult.result.retCode === 0) {
        return {
          ok: true
        };
      }
      throw new Error(result.transGroupFileResult.result.retMsg);
    }
    throw new Error("real fileUUID not found!");
  }
}

const SchemaData$l = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  file_id: Type.String(),
  current_parent_directory: Type.String(),
  new_name: Type.String()
});
class RenameGroupFile extends GetPacketStatusDepends {
  actionName = ActionName.RenameGroupFile;
  payloadSchema = SchemaData$l;
  async _handle(payload) {
    const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file_id) || FileNapCatOneBotUUID.decodeModelId(payload.file_id);
    if (contextMsgFile?.fileUUID) {
      await this.core.apis.PacketApi.pkt.operation.RenameGroupFile(+payload.group_id, contextMsgFile.fileUUID, payload.current_parent_directory, payload.new_name);
      return {
        ok: true
      };
    }
    throw new Error("real fileUUID not found!");
  }
}

class GetRkeyServer extends GetPacketStatusDepends {
  actionName = ActionName.GetRkeyServer;
  rkeyCache = null;
  expiryTime = null;
  async _handle() {
    if (this.expiryTime && this.expiryTime > Math.floor(Date.now() / 1e3) && this.rkeyCache) {
      return this.rkeyCache;
    }
    const rkeys = await this.core.apis.PacketApi.pkt.operation.FetchRkey();
    const privateRkeyItem = rkeys.filter((rkey) => rkey.type === 10)[0];
    const groupRkeyItem = rkeys.filter((rkey) => rkey.type === 20)[0];
    this.expiryTime = Math.floor(Date.now() / 1e3) + Math.min(+groupRkeyItem.ttl.toString(), +privateRkeyItem.ttl.toString());
    this.rkeyCache = {
      private_rkey: privateRkeyItem ? privateRkeyItem.rkey : void 0,
      group_rkey: groupRkeyItem ? groupRkeyItem.rkey : void 0,
      expired_time: this.expiryTime,
      name: "NapCat 4"
    };
    return this.rkeyCache;
  }
}

class GetRkeyEx extends GetPacketStatusDepends {
  actionName = ActionName.GetRkeyEx;
  async _handle() {
    const rkeys = await this.core.apis.PacketApi.pkt.operation.FetchRkey();
    return rkeys.map((rkey) => {
      return {
        type: rkey.type === 10 ? "private" : "group",
        rkey: rkey.rkey,
        created_at: rkey.time,
        ttl: rkey.ttl
      };
    });
  }
}

class CleanCache extends OneBotAction {
  actionName = ActionName.CleanCache;
  async _handle() {
    try {
      const tempPath = this.core.NapCatTempPath;
      const files = await readdir(tempPath);
      const deletePromises = files.map(async (file) => {
        const filePath = join(tempPath, file);
        try {
          await unlink$1(filePath);
          this.core.context.logger.log(`已删除文件: ${filePath}`);
        } catch (err) {
          this.core.context.logger.log(`删除文件 ${filePath} 失败: ${err.message}`);
        }
      });
      await Promise.all(deletePromises);
      const basic_path = path__default.join(this.core.dataPath, this.core.selfInfo.uin || "10001", "nt_qq", "nt_data");
      const dirsToClean = ["Pic", "Ptt", "Video", "File", "log"];
      for (const dir of dirsToClean) {
        const dirPath = path__default.join(basic_path, dir);
        try {
          const files2 = await readdir(dirPath).catch(() => null);
          if (files2) {
            const dirDeletePromises = files2.map(async (file) => {
              const filePath = path__default.join(dirPath, file);
              try {
                await unlink$1(filePath);
                this.core.context.logger.log(`已删除文件: ${filePath}`);
              } catch (err) {
                this.core.context.logger.log(`删除文件 ${filePath} 失败: ${err.message}`);
              }
            });
            await Promise.all(dirDeletePromises);
            this.core.context.logger.log(`目录清理完成: ${dirPath}`);
          }
        } catch (err) {
          this.core.context.logger.log(`清理目录 ${dirPath} 失败: ${err.message}`);
        }
      }
      this.core.context.logger.log(`临时文件夹清理完成: ${tempPath}`);
    } catch (err) {
      this.core.context.logger.log(`清理缓存失败: ${err.message}`);
      throw err;
    }
  }
}

const SchemaData$k = Type.Object({
  user_id: Type.String(),
  remark: Type.String()
});
class SetFriendRemark extends OneBotAction {
  actionName = ActionName.SetFriendRemark;
  payloadSchema = SchemaData$k;
  async _handle(payload) {
    const friendUid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id);
    const is_friend = await this.core.apis.FriendApi.isBuddy(friendUid);
    if (!is_friend) {
      throw new Error(`用户 ${payload.user_id} 不是好友`);
    }
    await this.core.apis.FriendApi.setBuddyRemark(friendUid, payload.remark);
    return null;
  }
}

const SchemaData$j = Type.Object({
  flag: Type.String(),
  // 注意强制String 非isNumeric 不遵守则不符合设计
  approve: Type.Boolean({ default: true })
  // 该字段没有语义 仅做保留 强制为True
});
class SetDoubtFriendsAddRequest extends OneBotAction {
  actionName = ActionName.SetDoubtFriendsAddRequest;
  payloadSchema = SchemaData$j;
  async _handle(payload) {
    return await this.core.apis.FriendApi.handleDoubtFriendRequest(payload.flag);
  }
}

const SchemaData$i = Type.Object({
  count: Type.Number({ default: 50 })
});
class GetDoubtFriendsAddRequest extends OneBotAction {
  actionName = ActionName.GetDoubtFriendsAddRequest;
  payloadSchema = SchemaData$i;
  async _handle(payload) {
    return await this.core.apis.FriendApi.getDoubtFriendRequest(payload.count);
  }
}

const SchemaData$h = Type.Object({
  group_id: Type.String(),
  add_type: Type.Number(),
  group_question: Type.Optional(Type.String()),
  group_answer: Type.Optional(Type.String())
});
class SetGroupAddOption extends OneBotAction {
  actionName = ActionName.SetGroupAddOption;
  payloadSchema = SchemaData$h;
  async _handle(payload) {
    const ret = await this.core.apis.GroupApi.setGroupAddOption(payload.group_id, {
      addOption: payload.add_type,
      groupQuestion: payload.group_question,
      groupAnswer: payload.group_answer
    });
    if (ret.result !== 0) {
      throw new Error(`设置群添加选项失败, ${ret.result}:${ret.errMsg}`);
    }
    return null;
  }
}

const SchemaData$g = Type.Object({
  group_id: Type.String(),
  no_code_finger_open: Type.Optional(Type.Number()),
  no_finger_open: Type.Optional(Type.Number())
});
class SetGroupSearch extends OneBotAction {
  actionName = ActionName.SetGroupSearch;
  payloadSchema = SchemaData$g;
  async _handle(payload) {
    const ret = await this.core.apis.GroupApi.setGroupSearch(payload.group_id, {
      noCodeFingerOpenFlag: payload.no_code_finger_open,
      noFingerOpenFlag: payload.no_finger_open
    });
    if (ret.result !== 0) {
      throw new Error(`设置群搜索失败, ${ret.result}:${ret.errMsg}`);
    }
    return null;
  }
}

const SchemaData$f = Type.Object({
  group_id: Type.String(),
  robot_member_switch: Type.Optional(Type.Number()),
  robot_member_examine: Type.Optional(Type.Number())
});
class SetGroupRobotAddOption extends OneBotAction {
  actionName = ActionName.SetGroupRobotAddOption;
  payloadSchema = SchemaData$f;
  async _handle(payload) {
    const ret = await this.core.apis.GroupApi.setGroupRobotAddOption(
      payload.group_id,
      payload.robot_member_switch,
      payload.robot_member_examine
    );
    if (ret.result !== 0) {
      throw new Error(`设置群机器人添加选项失败, ${ret.result}:${ret.errMsg}`);
    }
    return null;
  }
}

const SchemaData$e = Type.Object({
  group_id: Type.String(),
  user_id: Type.Array(Type.String()),
  reject_add_request: Type.Optional(Type.Union([Type.Boolean(), Type.String()]))
});
class SetGroupKickMembers extends OneBotAction {
  actionName = ActionName.SetGroupKickMembers;
  payloadSchema = SchemaData$e;
  async _handle(payload) {
    const rejectReq = payload.reject_add_request?.toString() === "true";
    const uids = await Promise.all(payload.user_id.map(async (uin) => await this.core.apis.UserApi.getUidByUinV2(uin)));
    await this.core.apis.GroupApi.kickMember(payload.group_id.toString(), uids.filter((uid) => !!uid), rejectReq);
    return null;
  }
}

const SchemaData$d = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()])
});
class GetGroupDetailInfo extends OneBotAction {
  actionName = ActionName.GetGroupDetailInfo;
  payloadSchema = SchemaData$d;
  async _handle(payload) {
    const data = await this.core.apis.GroupApi.fetchGroupDetail(payload.group_id.toString());
    return {
      ...data,
      group_all_shut: data.shutUpAllTimestamp > 0 ? -1 : 0,
      group_remark: "",
      group_id: +payload.group_id,
      group_name: data.groupName,
      member_count: data.memberNum,
      max_member_count: data.maxMemberNum
    };
  }
}

class GetGroupAddRequest extends OneBotAction {
  actionName = ActionName.GetGroupIgnoreAddRequest;
  async _handle() {
    const NTQQUserApi = this.core.apis.UserApi;
    const NTQQGroupApi = this.core.apis.GroupApi;
    const ignoredNotifies = await NTQQGroupApi.getSingleScreenNotifies(true, 10);
    const retData = [];
    const notifyPromises = ignoredNotifies.filter((notify) => notify.type === 7).map(async (SSNotify) => {
      const invitorUin = SSNotify.user1?.uid ? +await NTQQUserApi.getUinByUidV2(SSNotify.user1.uid) : 0;
      const actorUin = SSNotify.user2?.uid ? +await NTQQUserApi.getUinByUidV2(SSNotify.user2.uid) : 0;
      retData.push({
        request_id: +SSNotify.seq,
        invitor_uin: invitorUin,
        invitor_nick: SSNotify.user1?.nickName,
        group_id: +SSNotify.group?.groupCode,
        message: SSNotify?.postscript,
        group_name: SSNotify.group?.groupName,
        checked: SSNotify.status !== GroupNotifyMsgStatus.KUNHANDLE,
        actor: actorUin,
        requester_nick: SSNotify.user1?.nickName
      });
    });
    await Promise.all(notifyPromises);
    return retData;
  }
}

const SchemaData$c = Type.Object({
  category: Type.Union([Type.Number(), Type.String()]),
  count: Type.Union([Type.Union([Type.Number(), Type.String()])], { default: 1 })
});
class GetCollectionList extends OneBotAction {
  actionName = ActionName.GetCollectionList;
  payloadSchema = SchemaData$c;
  async _handle(payload) {
    return await this.core.apis.CollectionApi.getAllCollection(+payload.category, +payload.count);
  }
}

const SchemaData$b = Type.Object({
  group_id: Type.String(),
  message_id: Type.String(),
  message_seq: Type.Optional(Type.String())
});
class SetGroupTodo extends GetPacketStatusDepends {
  payloadSchema = SchemaData$b;
  actionName = ActionName.SetGroupTodo;
  async _handle(payload) {
    if (payload.message_seq) {
      return await this.core.apis.PacketApi.pkt.operation.SetGroupTodo(+payload.group_id, payload.message_seq);
    }
    const peer = {
      chatType: ChatType.KCHATTYPEGROUP,
      peerUid: payload.group_id
    };
    const { MsgId, Peer: Peer2 } = MessageUnique.getMsgIdAndPeerByShortId(+payload.message_id) ?? { Peer: peer, MsgId: payload.message_id };
    const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(Peer2, [MsgId])).msgList[0];
    if (!msg) throw new Error("消息不存在");
    await this.core.apis.PacketApi.pkt.operation.SetGroupTodo(+payload.group_id, msg.msgSeq);
  }
}

const SchemaData$a = Type.Object({
  group_id: Type.String()
});
class GetQunAlbumList extends OneBotAction {
  actionName = ActionName.GetQunAlbumList;
  payloadSchema = SchemaData$a;
  async _handle(payload) {
    return (await this.core.apis.WebApi.getAlbumListByNTQQ(payload.group_id)).response.album_list;
  }
}

const SchemaData$9 = Type.Object({
  group_id: Type.String(),
  album_id: Type.String(),
  album_name: Type.String(),
  file: Type.String()
});
class UploadImageToQunAlbum extends OneBotAction {
  actionName = ActionName.UploadImageToQunAlbum;
  payloadSchema = SchemaData$9;
  async _handle(payload) {
    const downloadResult = await uriToLocalFile(this.core.NapCatTempPath, payload.file);
    try {
      return await this.core.apis.WebApi.uploadImageToQunAlbum(payload.group_id, payload.album_id, payload.album_name, downloadResult.path);
    } finally {
      if (downloadResult.path && existsSync(downloadResult.path)) {
        await unlink(downloadResult.path);
      }
    }
  }
}

const SchemaData$8 = Type.Object({
  group_id: Type.String(),
  album_id: Type.String(),
  lloc: Type.String(),
  content: Type.String()
});
class DoGroupAlbumComment extends OneBotAction {
  actionName = ActionName.DoGroupAlbumComment;
  payloadSchema = SchemaData$8;
  async _handle(payload) {
    return await this.core.apis.WebApi.doAlbumMediaPlainCommentByNTQQ(
      payload.group_id,
      payload.album_id,
      payload.lloc,
      payload.content
    );
  }
}

const SchemaData$7 = Type.Object({
  group_id: Type.String(),
  album_id: Type.String(),
  attach_info: Type.String({ default: "" })
});
class GetGroupAlbumMediaList extends OneBotAction {
  actionName = ActionName.GetGroupAlbumMediaList;
  payloadSchema = SchemaData$7;
  async _handle(payload) {
    return await this.core.apis.WebApi.getAlbumMediaListByNTQQ(
      payload.group_id,
      payload.album_id,
      payload.attach_info
    );
  }
}

const SchemaData$6 = Type.Object({
  group_id: Type.String(),
  album_id: Type.String(),
  lloc: Type.String(),
  id: Type.String(),
  // 421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|V5bCgAxMDEyOTU5MjU3.PyqaPndPxg!^||^421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|17560363448^||^1
  set: Type.Boolean({ default: true })
  // true=点赞 false=取消点赞 未实现
});
class SetGroupAlbumMediaLike extends OneBotAction {
  actionName = ActionName.SetGroupAlbumMediaLike;
  payloadSchema = SchemaData$6;
  async _handle(payload) {
    return await this.core.apis.WebApi.doAlbumMediaLikeByNTQQ(
      payload.group_id,
      payload.album_id,
      payload.lloc,
      payload.id
    );
  }
}

const SchemaData$5 = Type.Object({
  group_id: Type.String(),
  album_id: Type.String(),
  lloc: Type.String()
});
class DelGroupAlbumMedia extends OneBotAction {
  actionName = ActionName.DelGroupAlbumMedia;
  payloadSchema = SchemaData$5;
  async _handle(payload) {
    return await this.core.apis.WebApi.deleteAlbumMediaByNTQQ(
      payload.group_id,
      payload.album_id,
      payload.lloc
    );
  }
}

class CleanStreamTempFile extends OneBotAction {
  actionName = ActionName.CleanStreamTempFile;
  async _handle(_payload) {
    try {
      const tempPath = this.core.NapCatTempPath;
      const files = await readdir$1(tempPath);
      const deletePromises = files.map(async (file) => {
        const filePath = join$1(tempPath, file);
        try {
          await unlink(filePath);
          this.core.context.logger.log(`已删除文件: ${filePath}`);
        } catch (err) {
          this.core.context.logger.log(`删除文件 ${filePath} 失败: ${err.message}`);
        }
      });
      await Promise.all(deletePromises);
    } catch (err) {
      this.core.context.logger.log(`清理流临时文件失败: ${err.message}`);
    }
  }
}

class BaseDownloadStream extends OneBotAction {
  async resolveDownload(file) {
    const target = file || "";
    let downloadPath = "";
    let fileName = "";
    let fileSize = 0;
    const contextMsgFile = FileNapCatOneBotUUID.decode(target);
    if (contextMsgFile && contextMsgFile.msgId && contextMsgFile.elementId) {
      const { peer, msgId, elementId } = contextMsgFile;
      downloadPath = await this.core.apis.FileApi.downloadMedia(msgId, peer.chatType, peer.peerUid, elementId, "", "");
      const rawMessage = (await this.core.apis.MsgApi.getMsgsByMsgId(peer, [msgId]))?.msgList.find((msg) => msg.msgId === msgId);
      const mixElement = rawMessage?.elements.find((e) => e.elementId === elementId);
      const mixElementInner = mixElement?.videoElement ?? mixElement?.fileElement ?? mixElement?.pttElement ?? mixElement?.picElement;
      if (!mixElementInner) throw new Error("element not found");
      fileSize = parseInt(mixElementInner.fileSize?.toString() ?? "0");
      fileName = mixElementInner.fileName ?? "";
      return { downloadPath, fileName, fileSize };
    }
    const contextModelIdFile = FileNapCatOneBotUUID.decodeModelId(target);
    if (contextModelIdFile && contextModelIdFile.modelId) {
      const { peer, modelId } = contextModelIdFile;
      downloadPath = await this.core.apis.FileApi.downloadFileForModelId(peer, modelId, "");
      return { downloadPath, fileName, fileSize };
    }
    const searchResult = await this.core.apis.FileApi.searchForFile([target]);
    if (searchResult) {
      downloadPath = await this.core.apis.FileApi.downloadFileById(searchResult.id, parseInt(searchResult.fileSize));
      fileSize = parseInt(searchResult.fileSize);
      fileName = searchResult.fileName;
      return { downloadPath, fileName, fileSize };
    }
    throw new Error("file not found");
  }
  async streamFileChunks(req, streamPath, chunkSize, chunkDataType) {
    const stats = await fs__default.promises.stat(streamPath);
    const totalSize = stats.size;
    const readStream = fs__default.createReadStream(streamPath, { highWaterMark: chunkSize });
    let chunkIndex = 0;
    let bytesRead = 0;
    for await (const chunk of readStream) {
      const base64Chunk = chunk.toString("base64");
      bytesRead += chunk.length;
      await req.send({
        type: StreamStatus.Stream,
        data_type: chunkDataType,
        index: chunkIndex,
        data: base64Chunk,
        size: chunk.length,
        progress: Math.round(bytesRead / totalSize * 100),
        base64_size: base64Chunk.length
      });
      chunkIndex++;
    }
    return { totalChunks: chunkIndex, totalBytes: bytesRead };
  }
}

const SchemaData$4 = Type.Object({
  file: Type.Optional(Type.String()),
  file_id: Type.Optional(Type.String()),
  chunk_size: Type.Optional(Type.Number({ default: 64 * 1024 }))
  // 默认64KB分块
});
class DownloadFileStream extends BaseDownloadStream {
  actionName = ActionName.DownloadFileStream;
  payloadSchema = SchemaData$4;
  useStream = true;
  async _handle(payload, _adaptername, _config, req) {
    try {
      payload.file ||= payload.file_id || "";
      const chunkSize = payload.chunk_size || 64 * 1024;
      const { downloadPath, fileName, fileSize } = await this.resolveDownload(payload.file);
      const stats = await fs__default.promises.stat(downloadPath);
      const totalSize = fileSize || stats.size;
      await req.send({
        type: StreamStatus.Stream,
        data_type: "file_info",
        file_name: fileName,
        file_size: totalSize,
        chunk_size: chunkSize
      });
      const { totalChunks, totalBytes } = await this.streamFileChunks(req, downloadPath, chunkSize, "file_chunk");
      return {
        type: StreamStatus.Response,
        data_type: "file_complete",
        total_chunks: totalChunks,
        total_bytes: totalBytes,
        message: "Download completed"
      };
    } catch (error) {
      throw new Error(`Download failed: ${error.message}`);
    }
  }
}

const out_format = ["mp3", "amr", "wma", "m4a", "spx", "ogg", "wav", "flac"];
const SchemaData$3 = Type.Object({
  file: Type.Optional(Type.String()),
  file_id: Type.Optional(Type.String()),
  chunk_size: Type.Optional(Type.Number({ default: 64 * 1024 })),
  // 默认64KB分块
  out_format: Type.Optional(Type.String())
});
class DownloadFileRecordStream extends BaseDownloadStream {
  actionName = ActionName.DownloadFileRecordStream;
  payloadSchema = SchemaData$3;
  useStream = true;
  async _handle(payload, _adaptername, _config, req) {
    try {
      payload.file ||= payload.file_id || "";
      const chunkSize = payload.chunk_size || 64 * 1024;
      const { downloadPath, fileName, fileSize } = await this.resolveDownload(payload.file);
      let streamPath = downloadPath;
      if (payload.out_format && typeof payload.out_format === "string") {
        if (!out_format.includes(payload.out_format)) {
          throw new Error("转换失败 out_format 字段可能格式不正确");
        }
        const pcmFile = `${downloadPath}.pcm`;
        const outputFile = `${downloadPath}.${payload.out_format}`;
        try {
          await fs__default.promises.access(outputFile);
          streamPath = outputFile;
        } catch {
          if (FFmpegService.getAdapterName() === "FFmpegAddon") {
            await FFmpegService.convertFile(downloadPath, outputFile, payload.out_format);
          } else {
            await this.decodeFile(downloadPath, pcmFile);
            await FFmpegService.convertFile(pcmFile, outputFile, payload.out_format);
          }
          streamPath = outputFile;
        }
      }
      const stats = await fs__default.promises.stat(streamPath);
      const totalSize = fileSize || stats.size;
      await req.send({
        type: StreamStatus.Stream,
        data_type: "file_info",
        file_name: fileName,
        file_size: totalSize,
        chunk_size: chunkSize,
        out_format: payload.out_format
      });
      const { totalChunks, totalBytes } = await this.streamFileChunks(req, streamPath, chunkSize, "file_chunk");
      return {
        type: StreamStatus.Response,
        data_type: "file_complete",
        total_chunks: totalChunks,
        total_bytes: totalBytes,
        message: "Download completed"
      };
    } catch (error) {
      throw new Error(`Download failed: ${error.message}`);
    }
  }
  async decodeFile(inputFile, outputFile) {
    try {
      const inputData = await fs__default.promises.readFile(inputFile);
      const decodedData = await decode(inputData, 24e3);
      await fs__default.promises.writeFile(outputFile, Buffer.from(decodedData.data));
    } catch (error) {
      console.error("Error decoding file:", error);
      throw error;
    }
  }
}

const SchemaData$2 = Type.Object({
  file: Type.Optional(Type.String()),
  file_id: Type.Optional(Type.String()),
  chunk_size: Type.Optional(Type.Number({ default: 64 * 1024 }))
  // 默认64KB分块
});
class DownloadFileImageStream extends BaseDownloadStream {
  actionName = ActionName.DownloadFileImageStream;
  payloadSchema = SchemaData$2;
  useStream = true;
  async _handle(payload, _adaptername, _config, req) {
    try {
      payload.file ||= payload.file_id || "";
      const chunkSize = payload.chunk_size || 64 * 1024;
      const { downloadPath, fileName, fileSize } = await this.resolveDownload(payload.file);
      const stats = await fs__default.promises.stat(downloadPath);
      const totalSize = fileSize || stats.size;
      const { width, height } = await imageSizeFallBack(downloadPath);
      await req.send({
        type: StreamStatus.Stream,
        data_type: "file_info",
        file_name: fileName,
        file_size: totalSize,
        chunk_size: chunkSize,
        width,
        height
      });
      const { totalChunks, totalBytes } = await this.streamFileChunks(req, downloadPath, chunkSize, "file_chunk");
      return {
        type: StreamStatus.Response,
        data_type: "file_complete",
        total_chunks: totalChunks,
        total_bytes: totalBytes,
        message: "Download completed"
      };
    } catch (error) {
      throw new Error(`Download failed: ${error.message}`);
    }
  }
}

const SchemaData$1 = Type.Object({
  error: Type.Optional(Type.Boolean({ default: false }))
});
class TestDownloadStream extends OneBotAction {
  actionName = ActionName.TestDownloadStream;
  payloadSchema = SchemaData$1;
  useStream = true;
  async _handle(_payload, _adaptername, _config, req) {
    for (let i = 0; i < 10; i++) {
      await req.send({ type: StreamStatus.Stream, data: `Index-> ${i + 1}`, data_type: "data_chunk" });
      await new Promise((resolve) => setTimeout(resolve, 100));
    }
    if (_payload.error) {
      throw new Error("This is a test error");
    }
    return {
      type: StreamStatus.Response,
      data_type: "data_complete",
      data: "Stream transmission complete"
    };
  }
}

const CONFIG = {
  TIMEOUT: 10 * 60 * 1e3,
  // 10分钟超时
  MEMORY_THRESHOLD: 10 * 1024 * 1024,
  // 10MB，超过使用磁盘
  MEMORY_LIMIT: 100 * 1024 * 1024
  // 100MB内存总限制
};
const SchemaData = Type.Object({
  stream_id: Type.String(),
  chunk_data: Type.Optional(Type.String()),
  chunk_index: Type.Optional(Type.Number()),
  total_chunks: Type.Optional(Type.Number()),
  file_size: Type.Optional(Type.Number()),
  expected_sha256: Type.Optional(Type.String()),
  is_complete: Type.Optional(Type.Boolean()),
  filename: Type.Optional(Type.String()),
  reset: Type.Optional(Type.Boolean()),
  verify_only: Type.Optional(Type.Boolean()),
  file_retention: Type.Number({ default: 5 * 60 * 1e3 })
  // 默认5分钟 回收 不设置或0为不回收
});
class UploadFileStream extends OneBotAction {
  actionName = ActionName.UploadFileStream;
  payloadSchema = SchemaData;
  useStream = true;
  static streams = /* @__PURE__ */ new Map();
  static memoryUsage = 0;
  async _handle(payload, _adaptername, _config) {
    const { stream_id, reset, verify_only } = payload;
    if (reset) {
      this.cleanupStream(stream_id);
      throw new Error("Stream reset completed");
    }
    if (verify_only) {
      const stream2 = UploadFileStream.streams.get(stream_id);
      if (!stream2) throw new Error("Stream not found");
      return this.getStreamStatus(stream2);
    }
    const stream = this.getOrCreateStream(payload);
    if (payload.chunk_data && payload.chunk_index !== void 0) {
      return await this.processChunk(stream, payload.chunk_data, payload.chunk_index);
    }
    if (payload.is_complete || stream.receivedChunks === stream.totalChunks) {
      return await this.completeStream(stream);
    }
    return this.getStreamStatus(stream);
  }
  getOrCreateStream(payload) {
    let stream = UploadFileStream.streams.get(payload.stream_id);
    if (!stream) {
      if (!payload.total_chunks) {
        throw new Error("total_chunks required for new stream");
      }
      stream = this.createStream(payload);
    }
    return stream;
  }
  createStream(payload) {
    const { stream_id, total_chunks, file_size, filename, expected_sha256 } = payload;
    const useMemory = this.shouldUseMemory(file_size);
    if (useMemory && file_size && UploadFileStream.memoryUsage + file_size > CONFIG.MEMORY_LIMIT) {
      throw new Error("Memory limit exceeded");
    }
    const stream = {
      id: stream_id,
      filename: filename || `upload_${randomUUID()}`,
      totalChunks: total_chunks,
      receivedChunks: 0,
      missingChunks: new Set(Array.from({ length: total_chunks }, (_, i) => i)),
      fileSize: file_size,
      expectedSha256: expected_sha256,
      useMemory,
      createdAt: Date.now(),
      timeoutId: this.setupTimeout(stream_id),
      fileRetention: payload.file_retention
    };
    try {
      if (useMemory) {
        stream.memoryChunks = /* @__PURE__ */ new Map();
        if (file_size) UploadFileStream.memoryUsage += file_size;
      } else {
        this.setupDiskStorage(stream);
      }
      UploadFileStream.streams.set(stream_id, stream);
      return stream;
    } catch (error) {
      clearTimeout(stream.timeoutId);
      if (stream.tempDir && fs__default.existsSync(stream.tempDir)) {
        try {
          fs__default.rmSync(stream.tempDir, { recursive: true, force: true });
        } catch (cleanupError) {
          console.error("Failed to cleanup temp dir during creation error:", cleanupError);
        }
      }
      throw error;
    }
  }
  shouldUseMemory(fileSize) {
    return fileSize !== void 0 && fileSize <= CONFIG.MEMORY_THRESHOLD;
  }
  setupDiskStorage(stream) {
    const tempDir = join$1(this.core.NapCatTempPath, `upload_${stream.id}`);
    const finalPath = join$1(this.core.NapCatTempPath, stream.filename);
    fs__default.mkdirSync(tempDir, { recursive: true });
    stream.tempDir = tempDir;
    stream.finalPath = finalPath;
  }
  setupTimeout(streamId) {
    return setTimeout(() => {
      console.log(`Stream ${streamId} timeout`);
      this.cleanupStream(streamId);
    }, CONFIG.TIMEOUT);
  }
  async processChunk(stream, chunkData, chunkIndex) {
    if (chunkIndex < 0 || chunkIndex >= stream.totalChunks) {
      throw new Error(`Invalid chunk index: ${chunkIndex}`);
    }
    if (!stream.missingChunks.has(chunkIndex)) {
      return this.getStreamStatus(stream);
    }
    const buffer = Buffer.from(chunkData, "base64");
    if (stream.useMemory) {
      stream.memoryChunks.set(chunkIndex, buffer);
    } else {
      const chunkPath = join$1(stream.tempDir, `${chunkIndex}.chunk`);
      await fs__default.promises.writeFile(chunkPath, buffer);
    }
    stream.missingChunks.delete(chunkIndex);
    stream.receivedChunks++;
    this.refreshTimeout(stream);
    return {
      type: StreamStatus.Stream,
      stream_id: stream.id,
      status: "chunk_received",
      received_chunks: stream.receivedChunks,
      total_chunks: stream.totalChunks
    };
  }
  refreshTimeout(stream) {
    clearTimeout(stream.timeoutId);
    stream.timeoutId = this.setupTimeout(stream.id);
  }
  getStreamStatus(stream) {
    return {
      type: StreamStatus.Stream,
      stream_id: stream.id,
      status: "file_created",
      received_chunks: stream.receivedChunks,
      total_chunks: stream.totalChunks
    };
  }
  async completeStream(stream) {
    const finalBuffer = stream.useMemory ? await this.mergeMemoryChunks(stream) : await this.mergeDiskChunks(stream);
    const sha256 = this.validateSha256(stream, finalBuffer);
    const finalPath = stream.finalPath || join$1(this.core.NapCatTempPath, stream.filename);
    await fs__default.promises.writeFile(finalPath, finalBuffer);
    this.cleanupStream(stream.id, false);
    if (stream.fileRetention && stream.fileRetention > 0) {
      setTimeout(() => {
        unlink$2(finalPath, (err) => {
          if (err) this.core.context.logger.logError(`Failed to delete retained file ${finalPath}:`, err);
        });
      }, stream.fileRetention);
    }
    return {
      type: StreamStatus.Response,
      stream_id: stream.id,
      status: "file_complete",
      received_chunks: stream.receivedChunks,
      total_chunks: stream.totalChunks,
      file_path: finalPath,
      file_size: finalBuffer.length,
      sha256
    };
  }
  async mergeMemoryChunks(stream) {
    const chunks = [];
    for (let i = 0; i < stream.totalChunks; i++) {
      const chunk = stream.memoryChunks.get(i);
      if (!chunk) throw new Error(`Missing memory chunk ${i}`);
      chunks.push(chunk);
    }
    return Buffer.concat(chunks);
  }
  async mergeDiskChunks(stream) {
    const chunks = [];
    for (let i = 0; i < stream.totalChunks; i++) {
      const chunkPath = join$1(stream.tempDir, `${i}.chunk`);
      if (!fs__default.existsSync(chunkPath)) throw new Error(`Missing chunk file ${i}`);
      chunks.push(await fs__default.promises.readFile(chunkPath));
    }
    return Buffer.concat(chunks);
  }
  validateSha256(stream, buffer) {
    if (!stream.expectedSha256) return void 0;
    const actualSha256 = createHash$1("sha256").update(buffer).digest("hex");
    if (actualSha256 !== stream.expectedSha256) {
      throw new Error(`SHA256 mismatch. Expected: ${stream.expectedSha256}, Got: ${actualSha256}`);
    }
    return actualSha256;
  }
  cleanupStream(streamId, deleteFinalFile = true) {
    const stream = UploadFileStream.streams.get(streamId);
    if (!stream) return;
    try {
      clearTimeout(stream.timeoutId);
      if (stream.useMemory) {
        if (stream.fileSize) {
          UploadFileStream.memoryUsage = Math.max(0, UploadFileStream.memoryUsage - stream.fileSize);
        }
        stream.memoryChunks?.clear();
      }
      if (stream.tempDir) {
        try {
          if (fs__default.existsSync(stream.tempDir)) {
            fs__default.rmSync(stream.tempDir, { recursive: true, force: true });
            console.log(`Cleaned up temp directory: ${stream.tempDir}`);
          }
        } catch (error) {
          console.error(`Failed to cleanup temp directory ${stream.tempDir}:`, error);
        }
      }
      if (deleteFinalFile && stream.finalPath) {
        try {
          if (fs__default.existsSync(stream.finalPath)) {
            fs__default.unlinkSync(stream.finalPath);
            console.log(`Deleted final file: ${stream.finalPath}`);
          }
        } catch (error) {
          console.error(`Failed to delete final file ${stream.finalPath}:`, error);
        }
      }
    } catch (error) {
      console.error(`Cleanup error for stream ${streamId}:`, error);
    } finally {
      UploadFileStream.streams.delete(streamId);
      console.log(`Stream ${streamId} cleaned up`);
    }
  }
}

function createActionMap(obContext, core) {
  const actionHandlers = [
    new CleanStreamTempFile(obContext, core),
    new DownloadFileStream(obContext, core),
    new DownloadFileRecordStream(obContext, core),
    new DownloadFileImageStream(obContext, core),
    new TestDownloadStream(obContext, core),
    new UploadFileStream(obContext, core),
    new DelGroupAlbumMedia(obContext, core),
    new SetGroupAlbumMediaLike(obContext, core),
    new DoGroupAlbumComment(obContext, core),
    new GetGroupAlbumMediaList(obContext, core),
    new GetQunAlbumList(obContext, core),
    new UploadImageToQunAlbum(obContext, core),
    new SetGroupTodo(obContext, core),
    new GetGroupDetailInfo(obContext, core),
    new SetGroupKickMembers(obContext, core),
    new SetGroupAddOption(obContext, core),
    new SetGroupRobotAddOption(obContext, core),
    new SetGroupSearch(obContext, core),
    new SetDoubtFriendsAddRequest(obContext, core),
    new GetDoubtFriendsAddRequest(obContext, core),
    new SetFriendRemark(obContext, core),
    new GetRkeyEx(obContext, core),
    new GetRkeyServer(obContext, core),
    new SetGroupRemark(obContext, core),
    new GetGroupInfoEx(obContext, core),
    new FetchEmojiLike(obContext, core),
    new GetFile(obContext, core),
    new SetQQProfile(obContext, core),
    new ShareGroupEx(obContext, core),
    new SharePeer(obContext, core),
    new SendGroupArkShare(obContext, core),
    new SendArkShare(obContext, core),
    new CreateCollection(obContext, core),
    new SetLongNick(obContext, core),
    new ForwardFriendSingleMsg(obContext, core),
    new ForwardGroupSingleMsg(obContext, core),
    new MarkGroupMsgAsRead(obContext, core),
    new MarkPrivateMsgAsRead(obContext, core),
    new SetAvatar(obContext, core),
    new TranslateEnWordToZn(obContext, core),
    new GetGroupRootFiles(obContext, core),
    new SetGroupSign(obContext, core),
    new SendGroupSign(obContext, core),
    new GetClientkey(obContext, core),
    new MoveGroupFile(obContext, core),
    new RenameGroupFile(obContext, core),
    new TransGroupFile(obContext, core),
    // onebot11
    new SendLike(obContext, core),
    new GetMsg(obContext, core),
    new GetLoginInfo(obContext, core),
    new GetFriendList(obContext, core),
    new GetGroupList(obContext, core),
    new GetGroupInfo(obContext, core),
    new GetGroupMemberList(obContext, core),
    new GetGroupMemberInfo(obContext, core),
    new SendGroupMsg(obContext, core),
    new SendPrivateMsg(obContext, core),
    new SendMsg(obContext, core),
    new DeleteMsg(obContext, core),
    new SetGroupAddRequest(obContext, core),
    new SetFriendAddRequest(obContext, core),
    new SetGroupLeave(obContext, core),
    new GetVersionInfo(obContext, core),
    new CanSendRecord(obContext, core),
    new CanSendImage(obContext, core),
    new GetStatus(obContext, core),
    new SetGroupWholeBan(obContext, core),
    new SetGroupBan(obContext, core),
    new SetGroupKick(obContext, core),
    new SetGroupAdmin(obContext, core),
    new SetGroupName(obContext, core),
    new SetGroupCard(obContext, core),
    new GetImage(obContext, core),
    new GetRecord(obContext, core),
    new SetMsgEmojiLike(obContext, core),
    new GetCookies(obContext, core),
    new SetOnlineStatus(obContext, core),
    new GetRobotUinRange(obContext, core),
    new GetFriendWithCategory(obContext, core),
    // 以下为go-cqhttp api
    new GoCQHTTPDeleteFriend(obContext, core),
    new GoCQHTTPCheckUrlSafely(obContext, core),
    new GetOnlineClient(obContext, core),
    new OCRImage(obContext, core),
    new IOCRImage(obContext, core),
    new GetGroupHonorInfo(obContext, core),
    new SendGroupNotice(obContext, core),
    new GetGroupNotice(obContext, core),
    new GetGroupEssence(obContext, core),
    new GoCQHTTPGetGroupAtAllRemain(obContext, core),
    new GoCQHTTPSendForwardMsg(obContext, core),
    new GoCQHTTPSendGroupForwardMsg(obContext, core),
    new GoCQHTTPSendPrivateForwardMsg(obContext, core),
    new GoCQHTTPGetStrangerInfo(obContext, core),
    new GoCQHTTPDownloadFile(obContext, core),
    new GetGuildList(obContext, core),
    new GoCQHTTPMarkMsgAsRead(obContext, core),
    new GoCQHTTPUploadGroupFile(obContext, core),
    new GoCQHTTPGetGroupMsgHistory(obContext, core),
    new GoCQHTTPGetForwardMsgAction(obContext, core),
    new GetFriendMsgHistory(obContext, core),
    new GoCQHTTPHandleQuickAction(obContext, core),
    new GetGroupIgnoredNotifies(obContext, core),
    new DelEssenceMsg(obContext, core),
    new SetEssenceMsg(obContext, core),
    new GetRecentContact(obContext, core),
    new MarkAllMsgAsRead(obContext, core),
    new GetProfileLike(obContext, core),
    new SetGroupPortrait(obContext, core),
    new FetchCustomFace(obContext, core),
    new GoCQHTTPUploadPrivateFile(obContext, core),
    new GetGuildProfile(obContext, core),
    new GoCQHTTPGetModelShow(obContext, core),
    new GoCQHTTPSetModelShow(obContext, core),
    new GoCQHTTPCheckUrlSafely(obContext, core),
    new SetInputStatus(obContext, core),
    new GetCSRF(obContext, core),
    new GetCredentials(obContext, core),
    new DelGroupNotice(obContext, core),
    new DeleteGroupFile(obContext, core),
    new CreateGroupFileFolder(obContext, core),
    new DeleteGroupFileFolder(obContext, core),
    new GetGroupFileSystemInfo(obContext, core),
    new GetGroupFilesByFolder(obContext, core),
    new GetPacketStatus(obContext, core),
    new GroupPoke(obContext, core),
    new FriendPoke(obContext, core),
    new GetUserStatus(obContext, core),
    new GetRkey(obContext, core),
    new SetSpecialTitle(obContext, core),
    new SetDiyOnlineStatus(obContext, core),
    // new UploadForwardMsg(obContext, core),
    new GetGroupShutList(obContext, core),
    new GetGroupFileUrl(obContext, core),
    new GetMiniAppArk(obContext, core),
    new GetAiRecord(obContext, core),
    new SendGroupAiRecord(obContext, core),
    new GetAiCharacters(obContext, core),
    new SendPacket(obContext, core),
    new SendPoke(obContext, core),
    new GetGroupSystemMsg(obContext, core),
    new BotExit(obContext, core),
    new ClickInlineKeyboardButton(obContext, core),
    new GetPrivateFileUrl(obContext, core),
    new GetUnidirectionalFriendList(obContext, core),
    new CleanCache(obContext, core),
    new GetGroupAddRequest(obContext, core),
    new GetCollectionList(obContext, core)
  ];
  const _map = /* @__PURE__ */ new Map();
  actionHandlers.forEach((h) => {
    _map.set(h.actionName, h);
    _map.set(`${h.actionName}_async`, h);
    _map.set(`${h.actionName}_rate_limited`, h);
  });
  AutoRegisterRouter.forEach((ActionClass) => {
    const handlerInstance = new ActionClass(obContext, core);
    const actionName = handlerInstance.actionName;
    _map.set(actionName, handlerInstance);
    _map.set(`${actionName}_async`, handlerInstance);
    _map.set(`${actionName}_rate_limited`, handlerInstance);
  });
  function get(key) {
    return _map.get(key);
  }
  return { get };
}

class OB11InputStatusEvent extends OB11BaseNoticeEvent {
  notice_type = "notify";
  sub_type = "input_status";
  status_text = "对方正在输入...";
  event_type = 1;
  user_id = 0;
  group_id = 0;
  constructor(core, user_id, eventType, status_text) {
    super(core);
    this.user_id = user_id;
    this.event_type = eventType;
    this.status_text = status_text;
  }
}

class OB11FriendRequestEvent extends OB11BaseRequestEvent {
  request_type = "friend";
  user_id;
  comment;
  flag;
  constructor(core, user_id, comment, flag) {
    super(core);
    this.user_id = user_id;
    this.comment = comment;
    this.flag = flag;
  }
}

class OB11FriendRecallNoticeEvent extends OB11BaseNoticeEvent {
  notice_type = "friend_recall";
  user_id;
  message_id;
  constructor(core, userId, messageId) {
    super(core);
    this.user_id = userId;
    this.message_id = messageId;
  }
}

class OB11GroupRecallNoticeEvent extends OB11GroupNoticeEvent {
  notice_type = "group_recall";
  operator_id;
  message_id;
  constructor(core, groupId, userId, operatorId, messageId) {
    super(core, groupId, userId);
    this.group_id = groupId;
    this.user_id = userId;
    this.operator_id = operatorId;
    this.message_id = messageId;
  }
}

class BotOfflineEvent extends OB11BaseNoticeEvent {
  notice_type = "bot_offline";
  user_id;
  tag = "BotOfflineEvent";
  message = "BotOfflineEvent";
  constructor(core, tag, message) {
    super(core);
    this.user_id = +core.selfInfo.uin;
    this.tag = tag;
    this.message = message;
  }
}

const HttpServerConfigSchema = Type.Object({
  name: Type.String({ default: "http-server" }),
  enable: Type.Boolean({ default: false }),
  port: Type.Number({ default: 3e3 }),
  host: Type.String({ default: "127.0.0.1" }),
  enableCors: Type.Boolean({ default: true }),
  enableWebsocket: Type.Boolean({ default: true }),
  messagePostFormat: Type.String({ default: "array" }),
  token: Type.String({ default: "" }),
  debug: Type.Boolean({ default: false })
});
const HttpSseServerConfigSchema = Type.Object({
  name: Type.String({ default: "http-sse-server" }),
  enable: Type.Boolean({ default: false }),
  port: Type.Number({ default: 3e3 }),
  host: Type.String({ default: "127.0.0.1" }),
  enableCors: Type.Boolean({ default: true }),
  enableWebsocket: Type.Boolean({ default: true }),
  messagePostFormat: Type.String({ default: "array" }),
  token: Type.String({ default: "" }),
  debug: Type.Boolean({ default: false }),
  reportSelfMessage: Type.Boolean({ default: false })
});
const HttpClientConfigSchema = Type.Object({
  name: Type.String({ default: "http-client" }),
  enable: Type.Boolean({ default: false }),
  url: Type.String({ default: "http://localhost:8080" }),
  messagePostFormat: Type.String({ default: "array" }),
  reportSelfMessage: Type.Boolean({ default: false }),
  token: Type.String({ default: "" }),
  debug: Type.Boolean({ default: false })
});
const WebsocketServerConfigSchema = Type.Object({
  name: Type.String({ default: "websocket-server" }),
  enable: Type.Boolean({ default: false }),
  host: Type.String({ default: "127.0.0.1" }),
  port: Type.Number({ default: 3001 }),
  messagePostFormat: Type.String({ default: "array" }),
  reportSelfMessage: Type.Boolean({ default: false }),
  token: Type.String({ default: "" }),
  enableForcePushEvent: Type.Boolean({ default: true }),
  debug: Type.Boolean({ default: false }),
  heartInterval: Type.Number({ default: 3e4 })
});
const WebsocketClientConfigSchema = Type.Object({
  name: Type.String({ default: "websocket-client" }),
  enable: Type.Boolean({ default: false }),
  url: Type.String({ default: "ws://localhost:8082" }),
  messagePostFormat: Type.String({ default: "array" }),
  reportSelfMessage: Type.Boolean({ default: false }),
  reconnectInterval: Type.Number({ default: 5e3 }),
  token: Type.String({ default: "" }),
  debug: Type.Boolean({ default: false }),
  heartInterval: Type.Number({ default: 3e4 })
});
const PluginConfigSchema = Type.Object({
  name: Type.String({ default: "plugin" }),
  enable: Type.Boolean({ default: false }),
  messagePostFormat: Type.String({ default: "array" }),
  reportSelfMessage: Type.Boolean({ default: false }),
  debug: Type.Boolean({ default: false })
});
const NetworkConfigSchema = Type.Object({
  httpServers: Type.Array(HttpServerConfigSchema, { default: [] }),
  httpSseServers: Type.Array(HttpSseServerConfigSchema, { default: [] }),
  httpClients: Type.Array(HttpClientConfigSchema, { default: [] }),
  websocketServers: Type.Array(WebsocketServerConfigSchema, { default: [] }),
  websocketClients: Type.Array(WebsocketClientConfigSchema, { default: [] }),
  plugins: Type.Array(PluginConfigSchema, { default: [] })
}, { default: {} });
const OneBotConfigSchema = Type.Object({
  network: NetworkConfigSchema,
  musicSignUrl: Type.String({ default: "" }),
  enableLocalFile2Url: Type.Boolean({ default: false }),
  parseMultMsg: Type.Boolean({ default: false })
});

class OB11HttpSSEServerAdapter extends OB11HttpServerAdapter {
  sseClients = [];
  async handleRequest(req, res) {
    if (req.path === "/_events") {
      this.createSseSupport(req, res);
    } else {
      super.httpApiRequest(req, res, true);
    }
  }
  async createSseSupport(req, res) {
    res.setHeader("Content-Type", "text/event-stream");
    res.setHeader("Cache-Control", "no-cache");
    res.setHeader("Connection", "keep-alive");
    res.flushHeaders();
    this.sseClients.push(res);
    req.on("close", () => {
      this.sseClients = this.sseClients.filter((client) => client !== res);
    });
  }
  async onEvent(event) {
    const promises = [];
    this.sseClients.forEach((res) => {
      promises.push(new Promise((resolve, reject) => {
        res.write(`data: ${JSON.stringify(event)}

`, (err) => {
          if (err) {
            reject(err);
          } else {
            resolve();
          }
        });
      }));
    });
    await Promise.allSettled(promises);
  }
}

class OB11PluginMangerAdapter extends IOB11NetworkAdapter {
  pluginPath;
  loadedPlugins = /* @__PURE__ */ new Map();
  constructor(name, core, obContext, actions) {
    const config = {
      name,
      messagePostFormat: "array",
      reportSelfMessage: true,
      enable: true,
      debug: true
    };
    super(name, config, core, obContext, actions);
    this.pluginPath = this.core.context.pathWrapper.pluginPath;
  }
  /**
     * 扫描并加载插件
     */
  async loadPlugins() {
    try {
      if (!fs__default.existsSync(this.pluginPath)) {
        this.logger.logWarn(`[Plugin Adapter] Plugin directory does not exist: ${this.pluginPath}`);
        fs__default.mkdirSync(this.pluginPath, { recursive: true });
        return;
      }
      const items = fs__default.readdirSync(this.pluginPath, { withFileTypes: true });
      for (const item of items) {
        if (item.isFile()) {
          await this.loadFilePlugin(item.name);
        } else if (item.isDirectory()) {
          await this.loadDirectoryPlugin(item.name);
        }
      }
      this.logger.log(`[Plugin Adapter] Loaded ${this.loadedPlugins.size} plugins`);
    } catch (error) {
      this.logger.logError("[Plugin Adapter] Error loading plugins:", error);
    }
  }
  /**
     * 加载单文件插件 (.mjs, .js)
     */
  async loadFilePlugin(filename) {
    if (!this.isSupportedFile(filename)) {
      return;
    }
    const filePath = path__default.join(this.pluginPath, filename);
    const pluginName = path__default.parse(filename).name;
    try {
      const module = await this.importModule(filePath);
      if (!this.isValidPluginModule(module)) {
        this.logger.logWarn(`[Plugin Adapter] File ${filename} is not a valid plugin (missing plugin methods)`);
        return;
      }
      const plugin = {
        name: pluginName,
        pluginPath: this.pluginPath,
        entryPath: filePath,
        module
      };
      await this.registerPlugin(plugin);
    } catch (error) {
      this.logger.logError(`[Plugin Adapter] Error loading file plugin ${filename}:`, error);
    }
  }
  /**
     * 加载目录插件
     */
  async loadDirectoryPlugin(dirname) {
    const pluginDir = path__default.join(this.pluginPath, dirname);
    try {
      let packageJson;
      const packageJsonPath = path__default.join(pluginDir, "package.json");
      if (fs__default.existsSync(packageJsonPath)) {
        try {
          const packageContent = fs__default.readFileSync(packageJsonPath, "utf-8");
          packageJson = JSON.parse(packageContent);
        } catch (error) {
          this.logger.logWarn(`[Plugin Adapter] Invalid package.json in ${dirname}:`, error);
        }
      }
      const entryFile = this.findEntryFile(pluginDir, packageJson);
      if (!entryFile) {
        this.logger.logWarn(`[Plugin Adapter] No valid entry file found for plugin directory: ${dirname}`);
        return;
      }
      const entryPath = path__default.join(pluginDir, entryFile);
      const module = await this.importModule(entryPath);
      if (!this.isValidPluginModule(module)) {
        this.logger.logWarn(`[Plugin Adapter] Directory ${dirname} does not contain a valid plugin`);
        return;
      }
      const plugin = {
        name: packageJson?.name || dirname,
        version: packageJson?.version,
        pluginPath: pluginDir,
        entryPath,
        packageJson,
        module
      };
      await this.registerPlugin(plugin);
    } catch (error) {
      this.logger.logError(`[Plugin Adapter] Error loading directory plugin ${dirname}:`, error);
    }
  }
  /**
     * 查找插件目录的入口文件
     */
  findEntryFile(pluginDir, packageJson) {
    const possibleEntries = [
      packageJson?.main,
      "index.mjs",
      "index.js",
      "main.mjs",
      "main.js"
    ].filter(Boolean);
    for (const entry of possibleEntries) {
      const entryPath = path__default.join(pluginDir, entry);
      if (fs__default.existsSync(entryPath) && fs__default.statSync(entryPath).isFile()) {
        return entry;
      }
    }
    return null;
  }
  /**
     * 检查是否为支持的文件类型
     */
  isSupportedFile(filename) {
    const ext = path__default.extname(filename).toLowerCase();
    return [".mjs", ".js"].includes(ext);
  }
  /**
     * 动态导入模块
     */
  async importModule(filePath) {
    const fileUrl = `file://${filePath.replace(/\\/g, "/")}`;
    return await import(fileUrl);
  }
  /**
     * 检查模块是否为有效的插件模块
     */
  isValidPluginModule(module) {
    return module && typeof module.plugin_init === "function";
  }
  /**
     * 注册插件
     */
  async registerPlugin(plugin) {
    if (this.loadedPlugins.has(plugin.name)) {
      this.logger.logWarn(`[Plugin Adapter] Plugin name conflict: ${plugin.name}, skipping...`);
      return;
    }
    this.loadedPlugins.set(plugin.name, plugin);
    this.logger.log(`[Plugin Adapter] Registered plugin: ${plugin.name}${plugin.version ? ` v${plugin.version}` : ""}`);
    try {
      await plugin.module.plugin_init(this.core, this.obContext, this.actions, this);
      this.logger.log(`[Plugin Adapter] Initialized plugin: ${plugin.name}`);
    } catch (error) {
      this.logger.logError(`[Plugin Adapter] Error initializing plugin ${plugin.name}:`, error);
    }
  }
  /**
     * 卸载插件
     */
  async unloadPlugin(pluginName) {
    const plugin = this.loadedPlugins.get(pluginName);
    if (!plugin) {
      return;
    }
    if (typeof plugin.module.plugin_cleanup === "function") {
      try {
        await plugin.module.plugin_cleanup(this.core, this.obContext, this.actions, this);
        this.logger.log(`[Plugin Adapter] Cleaned up plugin: ${pluginName}`);
      } catch (error) {
        this.logger.logError(`[Plugin Adapter] Error cleaning up plugin ${pluginName}:`, error);
      }
    }
    this.loadedPlugins.delete(pluginName);
    this.logger.log(`[Plugin Adapter] Unloaded plugin: ${pluginName}`);
  }
  async onEvent(event) {
    if (!this.isEnable) {
      return;
    }
    try {
      await Promise.allSettled(
        Array.from(this.loadedPlugins.values()).map(
          (plugin) => this.callPluginEventHandler(plugin, event)
        )
      );
    } catch (error) {
      this.logger.logError("[Plugin Adapter] Error handling event:", error);
    }
  }
  /**
     * 调用插件的事件处理方法
     */
  async callPluginEventHandler(plugin, event) {
    try {
      if (typeof plugin.module.plugin_onevent === "function") {
        await plugin.module.plugin_onevent(this.name, this.core, this.obContext, event, this.actions, this);
      }
      if (event.message_type && typeof plugin.module.plugin_onmessage === "function") {
        await plugin.module.plugin_onmessage(this.name, this.core, this.obContext, event, this.actions, this);
      }
    } catch (error) {
      this.logger.logError(`[Plugin Adapter] Error calling plugin ${plugin.name} event handler:`, error);
    }
  }
  async open() {
    if (this.isEnable) {
      return;
    }
    this.logger.log("[Plugin Adapter] Opening plugin adapter...");
    this.isEnable = true;
    await this.loadPlugins();
    this.logger.log(`[Plugin Adapter] Plugin adapter opened with ${this.loadedPlugins.size} plugins loaded`);
  }
  async close() {
    if (!this.isEnable) {
      return;
    }
    this.logger.log("[Plugin Adapter] Closing plugin adapter...");
    this.isEnable = false;
    const pluginNames = Array.from(this.loadedPlugins.keys());
    for (const pluginName of pluginNames) {
      await this.unloadPlugin(pluginName);
    }
    this.logger.log("[Plugin Adapter] Plugin adapter closed");
  }
  async reload() {
    this.logger.log("[Plugin Adapter] Reloading plugin adapter...");
    await this.close();
    await this.open();
    this.logger.log("[Plugin Adapter] Plugin adapter reloaded");
    return OB11NetworkReloadType.Normal;
  }
  /**
     * 获取已加载的插件列表
     */
  getLoadedPlugins() {
    return Array.from(this.loadedPlugins.values());
  }
  /**
     * 获取插件信息
     */
  getPluginInfo(pluginName) {
    return this.loadedPlugins.get(pluginName);
  }
  /**
     * 重载指定插件
     */
  async reloadPlugin(pluginName) {
    const plugin = this.loadedPlugins.get(pluginName);
    if (!plugin) {
      this.logger.logWarn(`[Plugin Adapter] Plugin ${pluginName} not found`);
      return false;
    }
    try {
      await this.unloadPlugin(pluginName);
      const isDirectory = fs__default.statSync(plugin.pluginPath).isDirectory() && plugin.pluginPath !== this.pluginPath;
      if (isDirectory) {
        const dirname = path__default.basename(plugin.pluginPath);
        await this.loadDirectoryPlugin(dirname);
      } else {
        const filename = path__default.basename(plugin.entryPath);
        await this.loadFilePlugin(filename);
      }
      this.logger.log(`[Plugin Adapter] Plugin ${pluginName} reloaded successfully`);
      return true;
    } catch (error) {
      this.logger.logError(`[Plugin Adapter] Error reloading plugin ${pluginName}:`, error);
      return false;
    }
  }
}

async function runTask(workerScript, taskData) {
  const worker = new Worker$1(workerScript);
  try {
    return await new Promise((resolve, reject) => {
      worker.on("message", (result) => {
        if (result?.log) {
          console.error("Worker Log--->:", result.log);
        }
        if (result?.error) {
          reject(new Error("Worker error: " + result.error));
        }
        resolve(result);
      });
      worker.on("error", (error) => {
        reject(new Error(`Worker error: ${error.message}`));
      });
      worker.on("exit", (code) => {
        if (code !== 0) {
          reject(new Error(`Worker stopped with exit code ${code}`));
        }
      });
      worker.postMessage(taskData);
    });
  } catch (error) {
    throw new Error(`Failed to run task: ${error.message}`);
  } finally {
    worker.terminate();
  }
}

const ALLOW_SAMPLE_RATE = [8e3, 12e3, 16e3, 24e3, 32e3, 44100, 48e3];
function getWorkerPath() {
  return path$1.join(path$1.dirname(fileURLToPath$1(import.meta.url)), "audio-worker.mjs");
}
async function guessDuration(pttPath, logger) {
  const pttFileInfo = await fsProm.stat(pttPath);
  const duration = Math.max(1, Math.floor(pttFileInfo.size / 1024 / 3));
  logger.log("通过文件大小估算语音的时长:", duration);
  return duration;
}
async function handleWavFile(file, filePath, pcmPath) {
  const { fmt } = getWavFileInfo(file);
  if (!ALLOW_SAMPLE_RATE.includes(fmt.sampleRate)) {
    const result = await FFmpegService.convert(filePath, pcmPath);
    return { input: await fsProm.readFile(pcmPath), sampleRate: result.sampleRate };
  }
  return { input: file, sampleRate: fmt.sampleRate };
}
async function encodeSilk(filePath, TEMP_DIR, logger) {
  try {
    const file = await fsProm.readFile(filePath);
    const pttPath = path$1.join(TEMP_DIR, randomUUID());
    if (!isSilk(file)) {
      logger.log(`语音文件${filePath}需要转换成silk`);
      const pcmPath = `${pttPath}.pcm`;
      let input;
      let sampleRate;
      if (isWav(file)) {
        const result = await handleWavFile(file, filePath, pcmPath);
        input = result.input;
        sampleRate = result.sampleRate;
      } else {
        const result = await FFmpegService.convert(filePath, pcmPath);
        input = await fsProm.readFile(pcmPath);
        sampleRate = result.sampleRate;
      }
      const silk = await runTask(getWorkerPath(), { input, sampleRate });
      fsProm.unlink(pcmPath).catch((e) => logger.logError("删除临时文件失败", pcmPath, e));
      await fsProm.writeFile(pttPath, Buffer.from(silk.data));
      logger.log(`语音文件${filePath}转换成功!`, pttPath, "时长:", silk.duration);
      return {
        converted: true,
        path: pttPath,
        duration: silk.duration / 1e3
      };
    } else {
      let duration = 0;
      try {
        duration = getDuration(file) / 1e3;
      } catch (e) {
        logger.log("获取语音文件时长失败, 使用文件大小推测时长", filePath, e.stack);
        duration = await guessDuration(filePath, logger);
      }
      return {
        converted: false,
        path: filePath,
        duration
      };
    }
  } catch (error) {
    logger.logError("convert silk failed", error);
    return {};
  }
}

async function getFileTypeForSendType(picPath) {
  const fileTypeResult = (await fileTypeFromFile(picPath))?.ext ?? "jpg";
  const picTypeMap = {
    // 'webp': PicType.NEWPIC_WEBP,
    gif: PicType.NEWPIC_GIF
    // 'png': PicType.NEWPIC_APNG,
    // 'jpg': PicType.NEWPIC_JPEG,
    // 'jpeg': PicType.NEWPIC_JPEG,
    // 'bmp': PicType.NEWPIC_BMP,
  };
  return picTypeMap[fileTypeResult] ?? PicType.NEWPIC_JPEG;
}

class OneBotFileApi {
  obContext;
  core;
  constructor(obContext, core) {
    this.obContext = obContext;
    this.core = core;
  }
  async createValidSendFileElement(context, filePath, fileName = "", folderId = "") {
    const {
      fileName: _fileName,
      path,
      fileSize
    } = await this.core.apis.FileApi.uploadFile(filePath, ElementType.FILE);
    if (fileSize === 0) {
      throw new Error("文件异常，大小为0");
    }
    context.deleteAfterSentFiles.push(path);
    return {
      elementType: ElementType.FILE,
      elementId: "",
      fileElement: {
        fileName: fileName || _fileName,
        folderId,
        filePath: path,
        fileSize: fileSize.toString()
      }
    };
  }
  async createValidSendPicElement(context, picPath, summary = "", subType = 0) {
    const { md5, fileName, path, fileSize } = await this.core.apis.FileApi.uploadFile(picPath, ElementType.PIC, subType);
    if (fileSize === 0) {
      throw new Error("文件异常，大小为0");
    }
    const imageSize = await imageSizeFallBack(picPath);
    context.deleteAfterSentFiles.push(path);
    return {
      elementType: ElementType.PIC,
      elementId: "",
      picElement: {
        md5HexStr: md5,
        fileSize: fileSize.toString(),
        picWidth: imageSize.width,
        picHeight: imageSize.height,
        fileName,
        sourcePath: path,
        original: true,
        picType: await getFileTypeForSendType(picPath),
        picSubType: subType,
        fileUuid: "",
        fileSubId: "",
        thumbFileSize: 0,
        summary
      }
    };
  }
  async createValidSendVideoElement(context, filePath, fileName = "", _diyThumbPath = "") {
    let videoInfo = {
      width: 1920,
      height: 1080,
      time: 15,
      format: "mp4",
      size: 0,
      filePath
    };
    let fileExt = "mp4";
    try {
      const tempExt = (await fileTypeFromFile(filePath))?.ext;
      if (tempExt) fileExt = tempExt;
    } catch (e) {
      this.core.context.logger.logError("获取文件类型失败", e);
    }
    const newFilePath = `${filePath}.${fileExt}`;
    fs__default.copyFileSync(filePath, newFilePath);
    context.deleteAfterSentFiles.push(newFilePath);
    filePath = newFilePath;
    const { fileName: _fileName, path, fileSize, md5 } = await this.core.apis.FileApi.uploadFile(filePath, ElementType.VIDEO);
    context.deleteAfterSentFiles.push(path);
    if (fileSize === 0) {
      throw new Error("文件异常，大小为0");
    }
    const thumbDir = path.replace(`${path$1.sep}Ori${path$1.sep}`, `${path$1.sep}Thumb${path$1.sep}`);
    fs__default.mkdirSync(path$1.dirname(thumbDir), { recursive: true });
    const thumbPath = path$1.join(path$1.dirname(thumbDir), `${md5}_0.png`);
    try {
      videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
      if (!fs__default.existsSync(thumbPath)) {
        this.core.context.logger.logError("获取视频缩略图失败", new Error("缩略图不存在"));
        throw new Error("获取视频缩略图失败");
      }
    } catch (e) {
      this.core.context.logger.logError("获取视频信息失败", e);
      fs__default.writeFileSync(thumbPath, Buffer.from(defaultVideoThumbB64, "base64"));
    }
    if (_diyThumbPath) {
      try {
        await this.core.apis.FileApi.copyFile(_diyThumbPath, thumbPath);
      } catch (e) {
        this.core.context.logger.logError("复制自定义缩略图失败", e);
      }
    }
    context.deleteAfterSentFiles.push(thumbPath);
    const thumbSize = (await fsProm.stat(thumbPath)).size;
    const thumbMd5 = await calculateFileMD5(thumbPath);
    context.deleteAfterSentFiles.push(thumbPath);
    const uploadName = (fileName || _fileName).toLocaleLowerCase().endsWith(`.${fileExt.toLocaleLowerCase()}`) ? fileName || _fileName : `${fileName || _fileName}.${fileExt}`;
    return {
      elementType: ElementType.VIDEO,
      elementId: "",
      videoElement: {
        fileName: uploadName,
        filePath: path,
        videoMd5: md5,
        thumbMd5,
        fileTime: videoInfo.time,
        thumbPath: /* @__PURE__ */ new Map([[0, thumbPath]]),
        thumbSize,
        thumbWidth: videoInfo.width,
        thumbHeight: videoInfo.height,
        fileSize: fileSize.toString()
      }
    };
  }
  async createValidSendPttElement(_context, pttPath) {
    const { converted, path: silkPath, duration } = await encodeSilk(pttPath, this.core.NapCatTempPath, this.core.context.logger);
    if (!silkPath) {
      throw new Error("语音转换失败, 请检查语音文件是否正常");
    }
    const { md5, fileName, path, fileSize } = await this.core.apis.FileApi.uploadFile(silkPath, ElementType.PTT);
    if (fileSize === 0) {
      throw new Error("文件异常，大小为0");
    }
    if (converted) {
      fsProm.unlink(silkPath).then().catch((e) => this.core.context.logger.logError("删除临时文件失败", e));
    }
    return {
      elementType: ElementType.PTT,
      elementId: "",
      pttElement: {
        fileName,
        filePath: path,
        md5HexStr: md5,
        fileSize: fileSize.toString(),
        duration: duration ?? 1,
        formatType: 1,
        voiceType: 1,
        voiceChangeType: 0,
        canConvert2Text: true,
        waveAmplitudes: [
          0,
          18,
          9,
          23,
          16,
          17,
          16,
          15,
          44,
          17,
          24,
          20,
          14,
          15,
          17
        ],
        fileSubId: "",
        playState: 1,
        autoConvertText: 0,
        storeID: 0,
        otherBusinessInfo: {
          aiVoiceType: 0
        }
      }
    };
  }
}

class NapCatOneBot11Adapter {
  core;
  context;
  configLoader;
  apis;
  networkManager;
  actions;
  bootTime = Date.now() / 1e3;
  recallEventCache = /* @__PURE__ */ new Map();
  constructor(core, context, pathWrapper) {
    this.core = core;
    this.context = context;
    this.configLoader = new OB11ConfigLoader(core, pathWrapper.configPath, OneBotConfigSchema);
    this.apis = {
      GroupApi: new OneBotGroupApi(this, core),
      UserApi: new OneBotUserApi(this, core),
      FriendApi: new OneBotFriendApi(this, core),
      MsgApi: new OneBotMsgApi(this, core),
      QuickActionApi: new OneBotQuickActionApi(this, core),
      FileApi: new OneBotFileApi(this, core)
    };
    this.actions = createActionMap(this, core);
    this.networkManager = new OB11NetworkManager();
  }
  async creatOneBotLog(ob11Config) {
    let log = "[network] 配置加载\n";
    for (const key of ob11Config.network.httpServers) {
      log += `HTTP服务: ${key.host}:${key.port}, : ${key.enable ? "已启动" : "未启动"}
`;
    }
    for (const key of ob11Config.network.httpSseServers) {
      log += `HTTP-SSE服务: ${key.host}:${key.port}, : ${key.enable ? "已启动" : "未启动"}
`;
    }
    for (const key of ob11Config.network.httpClients) {
      log += `HTTP上报服务: ${key.url}, : ${key.enable ? "已启动" : "未启动"}
`;
    }
    for (const key of ob11Config.network.websocketServers) {
      log += `WebSocket服务: ${key.host}:${key.port}, : ${key.enable ? "已启动" : "未启动"}
`;
    }
    for (const key of ob11Config.network.websocketClients) {
      log += `WebSocket反向服务: ${key.url}, : ${key.enable ? "已启动" : "未启动"}
`;
    }
    return log;
  }
  async InitOneBot() {
    const selfInfo = this.core.selfInfo;
    const ob11Config = this.configLoader.configData;
    this.core.apis.UserApi.getUserDetailInfo(selfInfo.uid, false).then(async (user) => {
      selfInfo.nick = user.nick;
      this.context.logger.setLogSelfInfo(selfInfo);
      if (pendingTokenToSend) {
        this.context.logger.log("[NapCat] [OneBot] 🔐 检测到待发送的WebUI Token，开始发送");
        try {
          await this.core.apis.MsgApi.sendMsg(
            { chatType: ChatType.KCHATTYPEC2C, peerUid: selfInfo.uid, guildId: "" },
            [{
              elementType: ElementType.TEXT,
              elementId: "",
              textElement: {
                content: "[NapCat] 温馨提示:\nWebUI密码为默认密码，已进行强制修改\n新密码: " + pendingTokenToSend,
                atType: NTMsgAtType.ATTYPEUNKNOWN,
                atUid: "",
                atTinyId: "",
                atNtUid: ""
              }
            }],
            5e3
          );
          this.context.logger.log("[NapCat] [OneBot] ✅ WebUI Token 消息发送成功");
        } catch (error) {
          this.context.logger.logError("[NapCat] [OneBot] ❌ WebUI Token 消息发送失败:", error);
        }
      }
      WebUiDataRuntime.getQQLoginCallback()(true);
    }).catch((e) => this.context.logger.logError(e));
    const serviceInfo = await this.creatOneBotLog(ob11Config);
    this.context.logger.log(`[Notice] [OneBot11] ${serviceInfo}`);
    if (existsSync(this.context.pathWrapper.pluginPath)) {
      this.context.logger.log("[Plugins] 插件目录存在，开始加载插件");
      this.networkManager.registerAdapter(
        new OB11PluginMangerAdapter("plugin_manager", this.core, this, this.actions)
      );
    }
    for (const key of ob11Config.network.httpServers) {
      if (key.enable) {
        this.networkManager.registerAdapter(
          new OB11HttpServerAdapter(key.name, key, this.core, this, this.actions)
        );
      }
    }
    for (const key of ob11Config.network.httpSseServers) {
      if (key.enable) {
        this.networkManager.registerAdapter(
          new OB11HttpSSEServerAdapter(key.name, key, this.core, this, this.actions)
        );
      }
    }
    for (const key of ob11Config.network.httpClients) {
      if (key.enable) {
        this.networkManager.registerAdapter(
          new OB11HttpClientAdapter(key.name, key, this.core, this, this.actions)
        );
      }
    }
    for (const key of ob11Config.network.websocketServers) {
      if (key.enable) {
        this.networkManager.registerAdapter(
          new OB11WebSocketServerAdapter(
            key.name,
            key,
            this.core,
            this,
            this.actions
          )
        );
      }
    }
    for (const key of ob11Config.network.websocketClients) {
      if (key.enable) {
        this.networkManager.registerAdapter(
          new OB11WebSocketClientAdapter(
            key.name,
            key,
            this.core,
            this,
            this.actions
          )
        );
      }
    }
    await this.networkManager.openAllAdapters();
    this.initMsgListener();
    this.initBuddyListener();
    this.initGroupListener();
    WebUiDataRuntime.setQQVersion(this.core.context.basicInfoWrapper.getFullQQVersion());
    WebUiDataRuntime.setQQLoginInfo(selfInfo);
    WebUiDataRuntime.setQQLoginStatus(true);
    WebUiDataRuntime.setOnOB11ConfigChanged(async (newConfig) => {
      const prev = this.configLoader.configData;
      this.configLoader.save(newConfig);
      await this.reloadNetwork(prev, newConfig);
    });
    this.apis.GroupApi.registerParseGroupReactEventByCore().catch(
      (e) => this.context.logger.logError("注册群消息反应表情失败", e)
    );
  }
  async reloadNetwork(prev, now) {
    const prevLog = await this.creatOneBotLog(prev);
    const newLog = await this.creatOneBotLog(now);
    this.context.logger.log(`[Notice] [OneBot11] 配置变更前:
${prevLog}`);
    this.context.logger.log(`[Notice] [OneBot11] 配置变更后:
${newLog}`);
    await this.handleConfigChange(prev.network.httpServers, now.network.httpServers, OB11HttpServerAdapter);
    await this.handleConfigChange(prev.network.httpClients, now.network.httpClients, OB11HttpClientAdapter);
    await this.handleConfigChange(prev.network.httpSseServers, now.network.httpSseServers, OB11HttpSSEServerAdapter);
    await this.handleConfigChange(prev.network.websocketServers, now.network.websocketServers, OB11WebSocketServerAdapter);
    await this.handleConfigChange(prev.network.websocketClients, now.network.websocketClients, OB11WebSocketClientAdapter);
  }
  async handleConfigChange(prevConfig, nowConfig, adapterClass) {
    for (const adapterConfig of prevConfig) {
      const existingAdapter = nowConfig.find((e) => e.name === adapterConfig.name);
      if (!existingAdapter) {
        const existingAdapter2 = this.networkManager.findSomeAdapter(adapterConfig.name);
        if (existingAdapter2) {
          await this.networkManager.closeSomeAdaterWhenOpen([existingAdapter2]);
        }
      }
    }
    for (const adapterConfig of nowConfig) {
      const existingAdapter = this.networkManager.findSomeAdapter(adapterConfig.name);
      if (existingAdapter) {
        const networkChange = await existingAdapter.reload(adapterConfig);
        if (networkChange === OB11NetworkReloadType.NetWorkClose) {
          await this.networkManager.closeSomeAdaterWhenOpen([existingAdapter]);
        }
      } else if (adapterConfig.enable) {
        const newAdapter = new adapterClass(adapterConfig.name, adapterConfig, this.core, this, this.actions);
        await this.networkManager.registerAdapterAndOpen(newAdapter);
      }
    }
  }
  initMsgListener() {
    const msgListener = new NodeIKernelMsgListener();
    msgListener.onRecvSysMsg = (msg) => {
      this.apis.MsgApi.parseSysMessage(msg).then((event) => {
        if (event) this.networkManager.emitEvent(event);
      }).catch(
        (e) => this.context.logger.logError(
          "constructSysMessage error: ",
          e,
          "\n Parse Hex:",
          Buffer.from(msg).toString("hex")
        )
      );
    };
    msgListener.onInputStatusPush = async (data) => {
      const uin = await this.core.apis.UserApi.getUinByUidV2(data.fromUin);
      this.context.logger.log(`[Notice] [输入状态] ${uin} ${data.statusText}`);
      await this.networkManager.emitEvent(
        new OB11InputStatusEvent(this.core, parseInt(uin), data.eventType, data.statusText)
      );
    };
    msgListener.onRecvMsg = async (msg) => {
      for (const m of msg) {
        if (this.bootTime > parseInt(m.msgTime)) {
          this.context.logger.logDebug(`消息时间${m.msgTime}早于启动时间${this.bootTime}，忽略上报`);
          continue;
        }
        m.id = MessageUnique.createUniqueMsgId(
          {
            chatType: m.chatType,
            peerUid: m.peerUid,
            guildId: ""
          },
          m.msgId
        );
        await this.emitMsg(m).catch(
          (e) => this.context.logger.logError("处理消息失败", e)
        );
      }
    };
    msgListener.onAddSendMsg = async (msg) => {
      try {
        if (msg.sendStatus === SendStatusType.KSEND_STATUS_SENDING) {
          const [updatemsgs] = await this.core.eventWrapper.registerListen("NodeIKernelMsgListener/onMsgInfoListUpdate", (msgList) => {
            const report = msgList.find(
              (e) => e.senderUin === this.core.selfInfo.uin && e.sendStatus !== SendStatusType.KSEND_STATUS_SENDING && e.msgId === msg.msgId
            );
            return !!report;
          }, 1, 10 * 60 * 1e3);
          const updatemsg = updatemsgs.find((e) => e.msgId === msg.msgId);
          if (updatemsg?.sendStatus === SendStatusType.KSEND_STATUS_SUCCESS) {
            updatemsg.id = MessageUnique.createUniqueMsgId(
              {
                chatType: updatemsg.chatType,
                peerUid: updatemsg.peerUid,
                guildId: ""
              },
              updatemsg.msgId
            );
            this.emitMsg(updatemsg);
          }
        }
      } catch (error) {
        this.context.logger.logError("处理发送消息失败", error);
      }
    };
    msgListener.onMsgRecall = async (chatType, uid, msgSeq) => {
      const peer = {
        chatType,
        peerUid: uid,
        guildId: ""
      };
      let msg = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeq(peer, msgSeq)).msgList.find((e) => e.msgType === NTMsgType.KMSGTYPEGRAYTIPS);
      const element = msg?.elements.find((e) => !!e.grayTipElement?.revokeElement);
      if (msg && element?.grayTipElement?.revokeElement.isSelfOperate) {
        const isSelfDevice = this.recallEventCache.has(msg.msgId);
        if (isSelfDevice) {
          await this.core.eventWrapper.registerListen(
            "NodeIKernelMsgListener/onMsgRecall",
            (chatType2, uid2, msgSeq2) => {
              return chatType2 === msg?.chatType && uid2 === msg?.peerUid && msgSeq2 === msg?.msgSeq;
            }
          ).catch(() => {
            msg = void 0;
            this.context.logger.logDebug("自操作消息撤回事件");
          });
        }
      }
      if (msg && element) {
        const recallEvent = await this.emitRecallMsg(msg, element);
        try {
          if (recallEvent) {
            await this.networkManager.emitEvent(recallEvent);
          }
        } catch (e) {
          this.context.logger.logError("处理消息撤回失败", e);
        }
      }
    };
    msgListener.onKickedOffLine = async (kick) => {
      const event = new BotOfflineEvent(this.core, kick.tipsTitle, kick.tipsDesc);
      this.networkManager.emitEvent(event).catch((e) => this.context.logger.logError("处理Bot掉线失败", e));
    };
    this.context.session.getMsgService().addKernelMsgListener(proxiedListenerOf(msgListener, this.context.logger));
  }
  initBuddyListener() {
    const buddyListener = new NodeIKernelBuddyListener();
    buddyListener.onBuddyReqChange = async (reqs) => {
      this.core.apis.FriendApi.clearBuddyReqUnreadCnt();
      for (let i = 0; i < reqs.unreadNums; i++) {
        const req = reqs.buddyReqs[i];
        if (!req) continue;
        if (!!req.isInitiator || req.isDecide && req.reqType !== BuddyReqType.KMEINITIATORWAITPEERCONFIRM || !req.isUnread) {
          continue;
        }
        try {
          const requesterUin = await this.core.apis.UserApi.getUinByUidV2(req.friendUid);
          await this.networkManager.emitEvent(
            new OB11FriendRequestEvent(
              this.core,
              +requesterUin,
              req.extWords,
              req.reqTime
            )
          );
        } catch (e) {
          this.context.logger.logDebug("获取加好友者QQ号失败", e);
        }
      }
    };
    this.context.session.getBuddyService().addKernelBuddyListener(proxiedListenerOf(buddyListener, this.context.logger));
  }
  initGroupListener() {
    const groupListener = new NodeIKernelGroupListener();
    groupListener.onGroupNotifiesUpdated = async (_, notifies) => {
      await this.core.apis.GroupApi.clearGroupNotifiesUnreadCount(false);
      if (!notifies[0]?.type) return;
      if (![
        GroupNotifyMsgType.SET_ADMIN,
        GroupNotifyMsgType.CANCEL_ADMIN_NOTIFY_CANCELED,
        GroupNotifyMsgType.CANCEL_ADMIN_NOTIFY_ADMIN
      ].includes(notifies[0]?.type)) {
        for (const notify of notifies) {
          const notifyTime = parseInt(notify.seq) / 1e3 / 1e3;
          if (notifyTime < this.bootTime) {
            continue;
          }
          const flag = notify.seq;
          this.context.logger.logDebug("收到群通知", notify);
          if ([GroupNotifyMsgType.REQUEST_JOIN_NEED_ADMINI_STRATOR_PASS].includes(notify.type) && notify.status === GroupNotifyMsgStatus.KUNHANDLE) {
            this.context.logger.logDebug("有加群请求");
            try {
              const requestUin = await this.core.apis.UserApi.getUinByUidV2(notify.user1.uid);
              const groupRequestEvent = new OB11GroupRequestEvent(
                this.core,
                parseInt(notify.group.groupCode),
                parseInt(requestUin),
                "add",
                notify.postscript,
                flag
              );
              this.networkManager.emitEvent(groupRequestEvent).catch(
                (e) => this.context.logger.logError("处理加群请求失败", e)
              );
            } catch (e) {
              this.context.logger.logError(
                "获取加群人QQ号失败 Uid:",
                notify.user1.uid,
                e
              );
            }
          } else if (notify.type === GroupNotifyMsgType.INVITED_BY_MEMBER && notify.status === GroupNotifyMsgStatus.KUNHANDLE) {
            this.context.logger.logDebug(`收到邀请我加群通知:${notify}`);
            const groupInviteEvent = new OB11GroupRequestEvent(
              this.core,
              +notify.group.groupCode,
              +await this.core.apis.UserApi.getUinByUidV2(notify.user2.uid),
              "invite",
              notify.postscript,
              flag
            );
            this.networkManager.emitEvent(groupInviteEvent).catch(
              (e) => this.context.logger.logError("处理邀请本人加群失败", e)
            );
          } else if (notify.type === GroupNotifyMsgType.INVITED_NEED_ADMINI_STRATOR_PASS && notify.status === GroupNotifyMsgStatus.KUNHANDLE) {
            this.context.logger.logDebug(`收到群员邀请加群通知:${notify}`);
            const groupInviteEvent = new OB11GroupRequestEvent(
              this.core,
              +notify.group.groupCode,
              +await this.core.apis.UserApi.getUinByUidV2(notify.user1.uid),
              "add",
              notify.postscript,
              flag
            );
            this.networkManager.emitEvent(groupInviteEvent).catch(
              (e) => this.context.logger.logError("处理邀请本人加群失败", e)
            );
          }
        }
      }
    };
    this.context.session.getGroupService().addKernelGroupListener(proxiedListenerOf(groupListener, this.context.logger));
  }
  async emitMsg(message) {
    const network = await this.networkManager.getAllConfig();
    this.context.logger.logDebug("收到新消息 RawMessage", message);
    await Promise.allSettled([
      this.handleMsg(message, network),
      message.chatType === ChatType.KCHATTYPEGROUP ? this.handleGroupEvent(message) : this.handlePrivateMsgEvent(message)
    ]);
  }
  async handleMsg(message, network) {
    if (message.msgType === NTMsgType.KMSGTYPENULL) {
      return;
    }
    try {
      const ob11Msg = await this.apis.MsgApi.parseMessageV2(message, this.configLoader.configData.parseMultMsg);
      if (ob11Msg) {
        const isSelfMsg = this.isSelfMessage(ob11Msg);
        this.context.logger.logDebug("转化为 OB11Message", ob11Msg);
        const msgMap = this.createMsgMap(network, ob11Msg, isSelfMsg, message);
        this.handleDebugNetwork(network, msgMap, message);
        this.handleNotReportSelfNetwork(network, msgMap, isSelfMsg);
        this.networkManager.emitEventByNames(msgMap);
      }
    } catch (e) {
      this.context.logger.logError("constructMessage error: ", e);
    }
  }
  isSelfMessage(ob11Msg) {
    return ob11Msg.stringMsg.user_id.toString() === this.core.selfInfo.uin || ob11Msg.arrayMsg.user_id.toString() === this.core.selfInfo.uin;
  }
  createMsgMap(network, ob11Msg, isSelfMsg, message) {
    const msgMap = /* @__PURE__ */ new Map();
    network.filter((e) => e.enable).forEach((e) => {
      if (isSelfMsg || message.chatType !== ChatType.KCHATTYPEGROUP) {
        ob11Msg.stringMsg.target_id = parseInt(message.peerUin);
        ob11Msg.arrayMsg.target_id = parseInt(message.peerUin);
      }
      if ("messagePostFormat" in e && e.messagePostFormat === "string") {
        msgMap.set(e.name, structuredClone(ob11Msg.stringMsg));
      } else {
        msgMap.set(e.name, structuredClone(ob11Msg.arrayMsg));
      }
    });
    return msgMap;
  }
  handleDebugNetwork(network, msgMap, message) {
    const debugNetwork = network.filter((e) => e.enable && e.debug);
    if (debugNetwork.length > 0) {
      debugNetwork.forEach((adapter) => {
        const msg = msgMap.get(adapter.name);
        if (msg) {
          msg.raw = message;
        }
      });
    } else if (msgMap.size === 0) {
      this.context.logger.logDebug("没有可用的网络适配器发送消息，消息内容:", message);
    }
  }
  handleNotReportSelfNetwork(network, msgMap, isSelfMsg) {
    if (isSelfMsg) {
      const notReportSelfNetwork = network.filter((e) => e.enable && ("reportSelfMessage" in e && !e.reportSelfMessage || !("reportSelfMessage" in e)));
      notReportSelfNetwork.forEach((adapter) => {
        msgMap.delete(adapter.name);
      });
    }
  }
  async handleGroupEvent(message) {
    try {
      if (message.senderUin && message.senderUin !== "0") {
        const cardChangedEvent = await this.apis.GroupApi.parseCardChangedEvent(message);
        if (cardChangedEvent) {
          await this.networkManager.emitEvent(cardChangedEvent);
        }
      }
      if (message.msgType === NTMsgType.KMSGTYPEFILE) {
        const elementWrapper = message.elements.find((e) => !!e.fileElement);
        if (elementWrapper?.fileElement) {
          const uploadGroupFileEvent = await this.apis.GroupApi.parseGroupUploadFileEvene(message, elementWrapper.fileElement, elementWrapper);
          if (uploadGroupFileEvent) {
            await this.networkManager.emitEvent(uploadGroupFileEvent);
          }
        }
      } else if (message.msgType === NTMsgType.KMSGTYPEGRAYTIPS) {
        const grayTipElement = message.elements[0]?.grayTipElement;
        if (grayTipElement) {
          const event = await this.apis.GroupApi.parseGrayTipElement(message, grayTipElement);
          if (event) {
            await this.networkManager.emitEvent(event);
          }
        }
      }
    } catch (e) {
      this.context.logger.logError("constructGroupEvent error: ", e);
    }
  }
  async handlePrivateMsgEvent(message) {
    try {
      if (message.msgType === NTMsgType.KMSGTYPEGRAYTIPS) {
        const grayTipElement = message.elements[0]?.grayTipElement;
        if (grayTipElement) {
          const event = await this.apis.MsgApi.parsePrivateMsgEvent(message, grayTipElement);
          if (event) {
            await this.networkManager.emitEvent(event);
          }
        }
      }
    } catch (e) {
      this.context.logger.logError("constructPrivateEvent error: ", e);
    }
  }
  async emitRecallMsg(message, element) {
    const peer = { chatType: message.chatType, peerUid: message.peerUid, guildId: "" };
    const oriMessageId = MessageUnique.getShortIdByMsgId(message.msgId) ?? MessageUnique.createUniqueMsgId(peer, message.msgId);
    if (message.chatType === ChatType.KCHATTYPEC2C) {
      return await this.emitFriendRecallMsg(message, oriMessageId, element);
    } else if (message.chatType === ChatType.KCHATTYPEGROUP) {
      return await this.emitGroupRecallMsg(message, oriMessageId, element);
    }
    return void 0;
  }
  async emitFriendRecallMsg(message, oriMessageId, element) {
    const operatorUid = element.grayTipElement?.revokeElement.operatorUid;
    if (!operatorUid) return void 0;
    return new OB11FriendRecallNoticeEvent(
      this.core,
      +message.senderUin,
      oriMessageId
    );
  }
  async emitGroupRecallMsg(message, oriMessageId, element) {
    const operatorUid = element.grayTipElement?.revokeElement.operatorUid;
    if (!operatorUid) return void 0;
    const operatorId = await this.core.apis.UserApi.getUinByUidV2(operatorUid);
    return new OB11GroupRecallNoticeEvent(
      this.core,
      +message.peerUin,
      +message.senderUin,
      +operatorId,
      oriMessageId
    );
  }
}

class NodeIO3MiscListener {
  getOnAmgomDataPiece(..._arg) {
  }
}

function connectToNamedPipe(logger, timeoutMs = 5e3) {
  return new Promise((resolve, reject) => {
    if (process$1.platform !== "win32") {
      return resolve({ disconnect: () => {
      } });
    }
    const pid = process$1.pid;
    const pipePath = `\\\\.\\pipe\\NapCat_${pid}`;
    const timeoutId = setTimeout(() => {
      reject(new Error(`连接命名管道超时: ${pipePath}`));
    }, timeoutMs);
    try {
      const originalStdoutWrite = process$1.stdout.write.bind(process$1.stdout);
      const pipeSocket = net$1.connect(pipePath, () => {
        clearTimeout(timeoutId);
        pipeSocket.setNoDelay(true);
        logger.log(`[StdOut] 已重定向到命名管道: ${pipePath}`);
        const pipeWritable = new Writable({
          highWaterMark: 1024 * 64,
          // 64KB 高水位线
          write(chunk, encoding, callback) {
            if (!pipeSocket.writable) {
              logger.log("[StdOut] 管道不可写，回退到控制台输出");
              return originalStdoutWrite(chunk, encoding, callback);
            }
            const canContinue = pipeSocket.write(chunk, encoding, () => {
            });
            if (canContinue) {
              process$1.nextTick(callback);
            } else {
              pipeSocket.once("drain", () => {
                callback();
              });
            }
            return true;
          }
        });
        process$1.stdout.write = (chunk, encoding, cb) => {
          if (typeof encoding === "function") {
            cb = encoding;
            encoding = void 0;
          }
          return pipeWritable.write(chunk, encoding, cb);
        };
        const disconnect = () => {
          process$1.stdout.write = originalStdoutWrite;
          pipeSocket.end();
          logger.log(`已手动断开命名管道连接: ${pipePath}`);
        };
        resolve({ disconnect });
      });
      pipeSocket.on("error", (err) => {
        clearTimeout(timeoutId);
        process$1.stdout.write = originalStdoutWrite;
        logger.log(`连接命名管道 ${pipePath} 时出错:`, err);
        reject(err);
      });
      pipeSocket.on("end", () => {
        process$1.stdout.write = originalStdoutWrite;
        logger.log("命名管道连接已关闭");
      });
      pipeSocket.on("close", () => {
        process$1.stdout.write = originalStdoutWrite;
        logger.log("命名管道连接已关闭");
      });
    } catch (error) {
      clearTimeout(timeoutId);
      logger.log(`尝试连接命名管道 ${pipePath} 时发生异常:`, error);
      reject(error);
    }
  });
}

const offset = {
  "3.2.12-28418-x64": {"recv":"A0723E0","send":"A06EAE0"},
  "9.9.15-28418-x64": {"recv":"37A9004","send":"37A4BD0"},
  "6.9.56-28418-x64": {"send":"4471360","recv":"4473BCC"},
  "6.9.56-28418-arm64": {"send":"3FBDBF8","recv":"3FC0410"},
  "9.9.15-28498-x64": {"recv":"37A9004","send":"37A4BD0"},
  "9.9.16-28788-x64": {"send":"38076D0","recv":"380BB04"},
  "3.2.13-28788-x64": {"send":"A0CEC20","recv":"A0D2520"},
  "3.2.13-28788-arm64": {"send":"6E91018","recv":"6E94850"},
  "9.9.16-28971-x64": {"send":"38079F0","recv":"380BE24"},
  "3.2.13-28971-x64": {"send":"A0CEF60","recv":"A0D2860"},
  "3.2.12-28971-arm64": {"send":"6E91318","recv":"6E94B50"},
  "6.9.58-28971-x64": {"send":"449ACA0","recv":"449D50C"},
  "6.9.58-28971-arm64": {"send":"3FE0DB0","recv":"3FE35C8"},
  "9.9.16-29271-x64": {"send":"3833510","recv":"3837944"},
  "3.2.13-29271-x64": {"send":"A11E680","recv":"A121F80"},
  "3.2.13-29271-arm64": {"send":"6ECA098","recv":"6ECD8D0"},
  "9.9.16-29456-x64": {"send":"3835CD0","recv":"383A104"},
  "3.2.13-29456-x64": {"send":"A11E820","recv":"A122120"},
  "3.2.13-29456-arm64": {"send":"6ECA130","recv":"6ECD968"},
  "6.9.59-29456-x64": {"send":"44C57A0","recv":"44C800C"},
  "6.9.59-29456-arm64": {"send":"4005FE8","recv":"4008800"},
  "9.9.16-29927-x64": {"send":"3869C50","recv":"386E084"},
  "3.2.13-29927-x64": {"send":"A1913A0","recv":"A194CA0"},
  "3.2.13-29927-arm64": {"send":"6F1C7E0","recv":"6F20018"},
  "6.9.61-29927-x64": {"send":"44FCC60","recv":"44FF4CC"},
  "6.9.61-29927-arm64": {"send":"4038740","recv":"403AF58"},
  "9.9.17-30366-x64": {"send":"39AB0B0","recv":"39AF4E4"},
  "3.2.15-30366-x64": {"send":"A402380","recv":"A405C80"},
  "3.2.15-30366-arm64": {"send":"70C3FA8","recv":"70C77E0"},
  "6.9.62-30366-x64": {"send":"4669760","recv":"466BFCC"},
  "6.9.62-30366-arm64": {"send":"4189770","recv":"418BF88"},
  "9.9.17-30483-x64": {"send":"39AC1B0","recv":"39B05E4"},
  "6.9.62-30483-arm64": {"send":"41896B0","recv":"418bec8"},
  "6.9.62-30483-x64": {"send":"4669460","recv":"466BCCC"},
  "3.2.15-30483-x64": {"send":"A402540","recv":"A405E40"},
  "3.2.15-30483-arm64": {"send":"70C40E8","recv":"70C7920"},
  "9.9.17-30594-x64": {"send":"39AC1B0","recv":"39B05E4"},
  "6.9.62-30594-arm64": {"send":"41896B0","recv":"418bec8"},
  "6.9.62-30594-x64": {"send":"4669460","recv":"466BCCC"},
  "3.2.15-30594-x64": {"send":"A402540","recv":"A405E40"},
  "3.2.15-30594-arm64": {"send":"70C40E8","recv":"70C7920"},
  "9.9.17-30851-x64": {"send":"395C150","recv":"3960584"},
  "3.2.15-30851-x64": {"send":"A4A03E0","recv":"A4A3CE0"},
  "3.2.15-30851-arm64": {"send":"713A318","recv":"713DB50"},
  "6.9.63-30851-x64": {"send":"46C8040","recv":"46CA8AC"},
  "6.9.63-30851-arm64": {"send":"41DCBD8","recv":"41DF3F0"},
  "9.9.17-30899-x64": {"send":"395C150","recv":"3960584"},
  "3.2.15-30899-x64": {"send":"A4A03E0","recv":"A4A3CE0"},
  "3.2.15-30899-arm64": {"send":"713A318","recv":"713DB50"},
  "6.9.63-30899-x64": {"send":"46C8040","recv":"46CA8AC"},
  "6.9.63-30899-arm64": {"send":"41DCBD8","recv":"41DF3F0"},
  "9.9.17-31219-x64": {"send":"39C1350","recv":"39C5784"},
  "9.9.17-31245-x64": {"send":"39C1350","recv":"39C5784"},
  "6.9.63-31245-x64": {"send":"4720A40","recv":"47232AC"},
  "6.9.63-31245-arm64": {"send":"41DCBD8","recv":"422D4E8"},
  "3.2.15-31245-x64": {"send":"A550F80","recv":"A554880"},
  "3.2.15-31245-arm64": {"send":"71BEBB8","recv":"71C23F0"},
  "9.9.17-31363-x64": {"send":"39C1910","recv":"39C5d44"},
  "3.2.15-31363-x64": {"send":"A554500","recv":"A557E00"},
  "3.2.15-31363-arm64": {"send":"71BFD48","recv":"71C3580"},
  "6.9.65-31363-x64": {"send":"4720E80","recv":"47236EC"},
  "6.9.65-31363-arm64": {"send":"422CEF8","recv":"422F710"},
  "9.9.18-32690-x64": {"send":"39F9630","recv":"39FDE30"},
  "3.2.16-32690-x64": {"send":"A5E24C0","recv":"A5E5EE0"},
  "3.2.16-32690-arm64": {"send":"7226630","recv":"7229F60"},
  "3.2.16-32721-x64": {"send":"A5E24C0","recv":"A5E5EE0"},
  "3.2.16-32721-arm64": {"send":"7226630","recv":"7229F60"},
  "9.9.18-32793-x64": {"send":"39F9A30","recv":"39FE230"},
  "3.2.16-32793-x64": {"send":"A5E24C0","recv":"A5E5EE0"},
  "3.2.16-32793-arm64": {"send":"7226630","recv":"7229F60"},
  "9.9.18-32869-x64": {"send":"39F9A30","recv":"39FE230"},
  "3.2.16-32869-x64": {"send":"A5E24C0","recv":"A5E5EE0"},
  "3.2.16-32869-arm64": {"send":"7226630","recv":"7229F60"},
  "9.9.18-33139-x64": {"send":"39F5870","recv":"39FA070"},
  "3.2.16-33139-x64": {"send":"A634F60","recv":"A638980"},
  "3.2.16-33139-arm64": {"send":"7262BB0","recv":"72664E0"},
  "9.9.18-33800-x64": {"send":"39F5870","recv":"39FA070"},
  "3.2.16-33800-x64": {"send":"A634F60","recv":"A638980"},
  "3.2.16-33800-arm64": {"send":"7262BB0","recv":"72664E0"},
  "9.9.19-34231-x64": {"send":"3BD73D0","recv":"3BDBBD0"},
  "3.2.17-34231-x64": {"send":"AD787E0","recv":"AD7C200"},
  "3.2.17-34231-arm64": {"send":"770CDC0","recv":"77106F0"},
  "9.9.19-34362-x64": {"send":"3BD80D0","recv":"3BDC8D0"},
  "9.9.19-34467-x64": {"send":"3BD8690","recv":"3BDCE90"},
  "9.9.19-34566-x64": {"send":"3BDA110","recv":"3BDE910"},
  "9.9.19-34606-x64": {"send":"3BDA110","recv":"3BDE910"},
  "3.2.17-34606-x64": {"send":"AD7DC60","recv":"AD81680"},
  "3.2.17-34606-arm64": {"send":"7711270","recv":"7714BA0"},
  "9.9.19-34740-x64": {"send":"3BDD8D0","recv":"3BE20D0"},
  "3.2.17-34740-x64": {"send":"ADDF0A0","recv":"ADE2AC0"},
  "3.2.17-34740-arm64": {"send":"7753BB8","recv":"77574E8"},
  "9.9.19-34958-x64": {"send":"3BDD8D0","recv":"3BE20D0"},
  "3.2.17-35184-x64": {"send":"AE0DDE0","recv":"AE11800"},
  "3.2.17-35184-arm64": {"send":"7776028","recv":"7779958"},
  "9.9.19-35184-x64": {"send":"3BE5A10","recv":"3BEA210"},
  "9.9.19-35341-x64": {"send":"3BF1D50","recv":"3BF6550"},
  "9.9.19-35469-x64": {"send":"3BF1D50","recv":"3BF6550"},
  "3.2.17-35341-x64": {"send":"AE2F700","recv":"AE33120"},
  "3.2.17-35341-arm64": {"send":"778D840","recv":"7791170"},
  "9.9.20-35951-x64": {"send":"3034BAC","recv":"3038354"},
  "3.2.18-35951-x64": {"send":"AFBBB00","recv":"AFBF520"},
  "9.9.20-36580-x64": {"send":"30824B8","recv":"3085C5C"},
  "3.2.18-36580-x64": {"send":"B0853E0","recv":"B088E60"},
  "3.2.18-36580-arm64": {"send":"793DAC8","recv":"7941458"},
  "3.2.18-37012-x64": {"send":"B20F960","recv":"B2133E0"},
  "3.2.18-37012-arm64": {"send":"7A19E00","recv":"7A1D790"},
  "9.9.20-37012-x64": {"send":"30CC958","recv":"30D00FC"},
  "3.2.18-37051-x64": {"send":"B20F960","recv":"B2133E0"},
  "3.2.18-37051-arm64": {"send":"7A19E00","recv":"7A1D790"},
  "9.9.20-37051-x64": {"send":"30CC958","recv":"30D00FC"},
  "9.9.20-37475-x64": {"send":"30D30D8","recv":"30D687C"},
  "3.2.18-37475-x64": {"send":"B238EC0","recv":"B23C940"},
  "3.2.18-37475-arm64": {"send":"7A34B38","recv":"7A384C8"},
  "9.9.20-37625-x64": {"send":"30D39D8","recv":"30D717C"},
  "3.2.18-37625-x64": {"send":"B2397E0","recv":"B23D260"},
  "3.2.18-37625-arm64": {"send":"7A350D8","recv":"7A38A68"},
  "9.9.21-38503-x64": {"send":"3105F38","recv":"31096DC"},
  "3.2.19-38503-x64": {"send":"B2C1A60","recv":"B2C54E0"},
  "3.2.19-38626-x64": {"send":"B2C1BE0","recv":"B2C5660"},
  "9.9.21-38626-x64": {"send":"310A758","recv":"310DEFC"},
  "3.2.19-38626-arm64": {"send":"7A8A490","recv":"7A8DE20"},
  "9.9.21-38711-x64": {"send":"310A758","recv":"310DEFC"},
  "3.2.19-38960-x64": {"send":"B3740E0","recv":"B377B60"},
  "9.9.21-38960-x64": {"send":"313F7D8","recv":"3142F7C"},
  "3.2.19-38960-arm64": {"send":"7B01D98","recv":"7B05728"},
  "3.2.19-39038-x64": {"send":"B3759E0","recv":"B379460"},
  "3.2.19-39038-arm64": {"send":"7B025C8","recv":"7B05F58"},
  "9.9.21-39038-x64": {"send":"313FB58","recv":"31432FC"},
  "9.9.22-40362-x64": {"send":"31C0EB8","recv":"31C465C"},
  "3.2.20-40768-x64": {"send":"B69CFE0","recv":"B6A0A60"},
  "9.9.22-40768-x64": {"send":"31C1838","recv":"31C4FDC"},
  "3.2.20-40768-arm64": {"send":"7D49B18","recv":"7D4D4A8"},
  "6.9.82-40768-arm64": {"send":"202A198","recv":"202B718"},
  "9.9.22-40824-x64": {"send":"31C1838","recv":"31C4FDC"},
  "3.2.20-40824-arm64": {"send":"7D49B18","recv":"7D4D4A8"},
  "6.9.82-40824-arm64": {"send":"202A198","recv":"202B718"},
  "3.2.20-40990-x64": {"send":"B69CFE0","recv":"B6A0A60"},
  "3.2.20-40990-arm64": {"send":"7D49B18","recv":"7D4D4A8"},
  "9.9.22-40990-x64": {"send":"31C1838","recv":"31C4FDC"},
  "6.9.82-40990-arm64": {"send":"202A198","recv":"202B718"},
  "9.9.23-41679-x64": {"send":"2C94520","recv":"2C97AA0"},
  "6.9.83-41679-arm64": {"send":"3D718F8","recv":"3D74208"},
  "9.9.23-41785-x64": {"send":"2C944A0","recv":"2C97A20"},
  "6.9.83-41785-arm64": {"send":"3D6DA28","recv":"3D70338"},
  "6.9.83-41857-arm64": {"send":"3D74610","recv":"3D76F20"},
  "3.2.21-41857-x64": {"send":"A7B40A0","recv":"A7B7B20"},
  "9.9.23-41857-x64": {"send":"2C98F00","recv":"2C9C480"},
  "3.2.21-41857-arm64": {"send":"6B159F8","recv":"6B19388"},
  "9.9.23-42086-x64": {"send":"2C99800","recv":"2C9CD80"},
  "3.2.21-42086-x64": {"send":"A7B1060","recv":"A7B4AE0"},
  "3.2.21-42086-arm64": {"send":"6B13038","recv":"6B169C8"},
  "9.9.23-42430-x64": {"send":"2C9A4A0","recv":"2C9DA20"},
  "9.9.25-42744-x64": {"send":"2CD8E40","recv":"2CDC3C0"},
  "6.9.86-42744-arm64": {"send":"3DCC840","recv":"3DCF150"},
  "9.9.25-42905-x64": {"send":"2CE46A0","recv":"2CE7C20"},
  "6.9.86-42905-arm64": {"send":"3DD6098","recv":"3DD89A8"},
  "3.2.22-42941-x64": {"send":"A8AD8A0","recv":"A8B1320"},
  "9.9.25-42941-x64": {"send":"2CE4DA0","recv":"2CE8320"},
  "3.2.22-42941-arm64": {"send":"6BC95E8","recv":"6BCCF78"},
  "6.9.86-42941-arm64": {"send":"3DDDAD0","recv":"3DE03E0"},
  "9.9.26-44175-x64": {"send":"2CD84A0","recv":"2CDBA20"},
};

const typedOffset = offset;
class NativePacketHandler {
  supportedPlatforms = ["win32.x64", "linux.x64", "linux.arm64", "darwin.x64", "darwin.arm64"];
  MoeHooExport = { exports: {} };
  logger;
  loaded = false;
  // 统一的监听器存储 - key: 'all' | 'type:0' | 'type:1' | 'cmd:xxx' | 'exact:type:cmd'
  listeners = /* @__PURE__ */ new Map();
  constructor({ logger }) {
    this.logger = logger;
    try {
      const platform = process.platform + "." + process.arch;
      const moehoo_path = path__default.join(dirname(fileURLToPath(import.meta.url)), "./native/packet/MoeHoo." + platform + ".node");
      if (!fs__default.existsSync(moehoo_path)) {
        this.logger.logWarn(`NativePacketClient: 缺失运行时文件: ${moehoo_path}`);
        this.loaded = false;
      }
      process.dlopen(this.MoeHooExport, moehoo_path, constants.dlopen.RTLD_LAZY);
      this.loaded = true;
      this.logger.log("[PacketHandler] 加载成功");
    } catch (error) {
      this.logger.logError("NativePacketClient 加载出错:", error);
      this.loaded = false;
    }
  }
  /**
     * 添加监听器的通用方法
     */
  addListener(key, callback, once = false) {
    if (!this.listeners.has(key)) {
      this.listeners.set(key, /* @__PURE__ */ new Set());
    }
    const entry = { callback, once };
    this.listeners.get(key).add(entry);
    return () => this.removeListener(key, callback);
  }
  /**
     * 移除监听器的通用方法
     */
  removeListener(key, callback) {
    const entries = this.listeners.get(key);
    if (!entries) return false;
    for (const entry of entries) {
      if (entry.callback === callback) {
        return entries.delete(entry);
      }
    }
    return false;
  }
  // ===== 永久监听器 =====
  /** 监听所有数据包 */
  onAll(callback) {
    return this.addListener("all", callback);
  }
  /** 监听特定类型的数据包 (0: send, 1: recv) */
  onType(type, callback) {
    return this.addListener(`type:${type}`, callback);
  }
  /** 监听所有发送的数据包 */
  onSend(callback) {
    return this.onType(0, callback);
  }
  /** 监听所有接收的数据包 */
  onRecv(callback) {
    return this.onType(1, callback);
  }
  /** 监听特定cmd的数据包(不限type) */
  onCmd(cmd, callback) {
    return this.addListener(`cmd:${cmd}`, callback);
  }
  /** 监听特定type和cmd的数据包(精确匹配) */
  onExact(type, cmd, callback) {
    return this.addListener(`exact:${type}:${cmd}`, callback);
  }
  // ===== 一次性监听器 =====
  /** 一次性监听所有数据包 */
  onceAll(callback) {
    return this.addListener("all", callback, true);
  }
  /** 一次性监听特定类型的数据包 */
  onceType(type, callback) {
    return this.addListener(`type:${type}`, callback, true);
  }
  /** 一次性监听所有发送的数据包 */
  onceSend(callback) {
    return this.onceType(0, callback);
  }
  /** 一次性监听所有接收的数据包 */
  onceRecv(callback) {
    return this.onceType(1, callback);
  }
  /** 一次性监听特定cmd的数据包 */
  onceCmd(cmd, callback) {
    return this.addListener(`cmd:${cmd}`, callback, true);
  }
  /** 一次性监听特定type和cmd的数据包 */
  onceExact(type, cmd, callback) {
    return this.addListener(`exact:${type}:${cmd}`, callback, true);
  }
  // ===== 移除监听器 =====
  /** 移除特定的全局监听器 */
  off(key, callback) {
    return this.removeListener(key, callback);
  }
  /** 移除特定key下的所有监听器 */
  offAll(key) {
    this.listeners.delete(key);
  }
  /** 移除所有监听器 */
  removeAllListeners() {
    this.listeners.clear();
  }
  /**
     * 触发监听器 - 按优先级触发: 精确匹配 > cmd匹配 > type匹配 > 全局
     */
  emitPacket(type, uin, cmd, seq, hex_data) {
    const keys = [
      `exact:${type}:${cmd}`,
      // 精确匹配
      `cmd:${cmd}`,
      // cmd匹配
      `type:${type}`,
      // type匹配
      "all"
      // 全局
    ];
    for (const key of keys) {
      const entries = this.listeners.get(key);
      if (!entries) continue;
      const toRemove = [];
      for (const entry of entries) {
        try {
          entry.callback({ type, uin, cmd, seq, hex_data });
          if (entry.once) {
            toRemove.push(entry);
          }
        } catch (error) {
          this.logger.logError("监听器回调执行出错:", error);
        }
      }
      for (const entry of toRemove) {
        entries.delete(entry);
      }
    }
  }
  async init(version) {
    const version_arch = version + "-" + process.arch;
    try {
      if (!this.loaded) {
        this.logger.logWarn("NativePacketClient 未成功加载，无法初始化");
        return false;
      }
      const send = typedOffset[version_arch]?.send;
      const recv = typedOffset[version_arch]?.recv;
      if (!send || !recv) {
        this.logger.logWarn(`NativePacketClient: 未找到对应版本的偏移数据: ${version_arch}`);
        return false;
      }
      const platform = process.platform + "." + process.arch;
      if (!this.supportedPlatforms.includes(platform)) {
        this.logger.logWarn(`NativePacketClient: 不支持的平台: ${platform}`);
        return false;
      }
      this.MoeHooExport.exports.initHook?.(send, recv, (type, uin, cmd, seq, hex_data) => {
        this.emitPacket(type, uin, cmd, seq, hex_data);
      }, true);
      this.logger.log("[PacketHandler] 初始化成功");
      return true;
    } catch (error) {
      this.logger.logError("NativePacketClient 初始化出错:", error);
      return false;
    }
  }
}

const AppidTable = {
  "9.9.15-28060": {"appid":537246092,"qua":"V1_WIN_NQ_9.9.15_28060_GW_B"},
  "9.9.15-28131": {"appid":537246092,"qua":"V1_WIN_NQ_9.9.15_28131_GW_B"},
  "3.2.12-28060": {"appid":537246140,"qua":"V1_LNX_NQ_3.2.12_28060_GW_B"},
  "3.2.12-28131": {"appid":537246140,"qua":"V1_LNX_NQ_3.2.12_28131_GW_B"},
  "6.9.55-28131": {"appid":537246115,"qua":"V1_MAC_NQ_6.9.55_28131_GW_B"},
  "9.9.15-28327": {"appid":537249321,"qua":"V1_WIN_NQ_9.9.15_28327_GW_B"},
  "3.2.12-28327": {"appid":537249393,"qua":"V1_LNX_NQ_3.2.12_28327_GW_B"},
  "9.9.15-28418": {"appid":537249321,"qua":"V1_WIN_NQ_9.9.15_28418_GW_B"},
  "3.2.12-28418": {"appid":537249393,"qua":"V1_LNX_NQ_3.2.12_28418_GW_B"},
  "6.9.56-28418": {"appid":537249367,"qua":"V1_MAC_NQ_6.9.56_28418_GW_B"},
  "9.9.15-28498": {"appid":537249321,"qua":"V1_WIN_NQ_9.9.15_28498_GW_B"},
  "3.2.13-28788": {"appid":537249787,"qua":"V1_LNX_NQ_3.2.13_28788_GW_B"},
  "9.9.16-28788": {"appid":537249739,"qua":"V1_WIN_NQ_9.9.16_28788_GW_B"},
  "9.9.16-28971": {"appid":537249775,"qua":"V1_WIN_NQ_9.9.16_28971_GW_B"},
  "3.2.13-28971": {"appid":537249848,"qua":"V1_LNX_NQ_3.2.13_28971_GW_B"},
  "6.9.58-28971": {"appid":537249826,"qua":"V1_MAC_NQ_6.9.58_28971_GW_B"},
  "9.9.16-29271": {"appid":537249813,"qua":"V1_WIN_NQ_9.9.16_29271_GW_B"},
  "3.2.13-29271": {"appid":537249913,"qua":"V1_LNX_NQ_3.2.13_29271_GW_B"},
  "6.9.59-29271": {"appid":537249863,"qua":"V1_MAC_NQ_6.9.59_29271_GW_B"},
  "9.9.16-29456": {"appid":537249875,"qua":"V1_WIN_NQ_9.9.16_29456_GW_B"},
  "3.2.13-29456": {"appid":537249996,"qua":"V1_LNX_NQ_3.2.13_29456_GW_B"},
  "6.9.59-29456": {"appid":537249961,"qua":"V1_MAC_NQ_6.9.59_29456_GW_B"},
  "9.9.16-29927": {"appid":537255812,"qua":"V1_WIN_NQ_9.9.16_29927_GW_B"},
  "3.2.13-29927": {"appid":537255847,"qua":"V1_LNX_NQ_3.2.13_29927_GW_B"},
  "6.9.61-29927": {"appid":537255836,"qua":"V1_MAC_NQ_6.9.61_29927_GW_B"},
  "9.9.17-30366": {"appid":537258389,"qua":"V1_WIN_NQ_9.9.17_30366_GW_B"},
  "3.2.15-30366": {"appid":537258413,"qua":"V1_LNX_NQ_3.2.15_30366_GW_B"},
  "6.9.62-30366": {"appid":537258401,"qua":"V1_MAC_NQ_6.9.62_30366_GW_B"},
  "9.9.17-30483": {"appid":537258439,"qua":"V1_WIN_NQ_9.9.17_30483_GW_B"},
  "6.9.62-30483": {"appid":537258463,"qua":"V1_MAC_NQ_6.9.62_30483_GW_B"},
  "3.2.15-30483": {"appid":537258474,"qua":"V1_LNX_NQ_3.2.15_30483_GW_B"},
  "9.9.17-30594": {"appid":537258439,"qua":"V1_WIN_NQ_9.9.17_30594_GW_B"},
  "6.9.62-30594": {"appid":537258463,"qua":"V1_MAC_NQ_6.9.62_30594_GW_B"},
  "3.2.15-30594": {"appid":537258474,"qua":"V1_LNX_NQ_3.2.15_30594_GW_B"},
  "9.9.17-30851": {"appid":537263796,"qua":"V1_WIN_NQ_9.9.17_30851_GW_B"},
  "3.2.15-30851": {"appid":537263831,"qua":"V1_LNX_NQ_3.2.15_30851_GW_B"},
  "6.9.63-30851": {"appid":537263820,"qua":"V1_MAC_NQ_6.9.63_30851_GW_B"},
  "9.9.17-30899": {"appid":537263796,"qua":"V1_WIN_NQ_9.9.17_30899_GW_B"},
  "3.2.15-30899": {"appid":537263831,"qua":"V1_LNX_NQ_3.2.15_30899_GW_B"},
  "6.9.63-30899": {"appid":537263820,"qua":"V1_MAC_NQ_6.9.63_30899_GW_B"},
  "9.9.17-31219": {"appid":537266450,"qua":"V1_WIN_NQ_9.9.17_31219_GW_B"},
  "9.9.17-31245": {"appid":537266450,"qua":"V1_WIN_NQ_9.9.17_31245_GW_B"},
  "3.2.15-31245": {"appid":537266485,"qua":"V1_LNX_NQ_3.2.15_31245_GW_B"},
  "6.9.63-31245": {"appid":537266474,"qua":"V1_MAC_NQ_6.9.63_31245_GW_B"},
  "3.2.15-31363": {"appid":537266535,"qua":"V1_LNX_NQ_3.2.15_31363_GW_B"},
  "6.9.65-31363": {"appid":537266524,"qua":"V1_MAC_NQ_6.9.65_31363_GW_B"},
  "9.9.17-31363": {"appid":537266500,"qua":"V1_WIN_NQ_9.9.17_31363_GW_B"},
  "3.2.16-32690": {"appid":537271229,"qua":"V1_LNX_NQ_3.2.16_32690_GW_B"},
  "9.9.18-32690": {"appid":537271194,"qua":"V1_WIN_NQ_9.9.18_32690_GW_B"},
  "6.9.66-32690": {"appid":537271218,"qua":"V1_MAC_NQ_6.9.66_32690_GW_B"},
  "3.2.16-32721": {"appid":537271229,"qua":"V1_LNX_NQ_3.2.16_32721_GW_B"},
  "9.9.18-32793": {"appid":537271244,"qua":"V1_WIN_NQ_9.9.18_32793_GW_B"},
  "3.2.16-32793": {"appid":537271279,"qua":"V1_LNX_NQ_3.2.16_32793_GW_B"},
  "3.2.16-32869": {"appid":537271329,"qua":"V1_LNX_NQ_3.2.16_32869_GW_B"},
  "9.9.18-32869": {"appid":537271294,"qua":"V1_WIN_NQ_9.9.18_32869_GW_B"},
  "3.2.16-33139": {"appid":537273909,"qua":"V1_LNX_NQ_3.2.16_33139_GW_B"},
  "9.9.18-33139": {"appid":537273874,"qua":"V1_WIN_NQ_9.9.18_33139_GW_B"},
  "9.9.18-33800": {"appid":537273974,"qua":"V1_WIN_NQ_9.9.18_33800_GW_B"},
  "3.2.16-33800": {"appid":537274009,"qua":"V1_LNX_NQ_3.2.16_33800_GW_B"},
  "9.9.19-34231": {"appid":537279209,"qua":"V1_WIN_NQ_9.9.19_34231_GW_B"},
  "3.2.17-34231": {"appid":537279245,"qua":"V1_LNX_NQ_3.2.17_34231_GW_B"},
  "9.9.19-34362": {"appid":537279260,"qua":"V1_WIN_NQ_9.9.19_34362_GW_B"},
  "3.2.17-34362": {"appid":537279296,"qua":"V1_LNX_NQ_3.2.17_34362_GW_B"},
  "9.9.19-34467": {"appid":537282256,"qua":"V1_WIN_NQ_9.9.19_34467_GW_B"},
  "3.2.17-34467": {"appid":537282292,"qua":"V1_LNX_NQ_3.2.17_34467_GW_B"},
  "9.9.19-34566": {"appid":537282307,"qua":"V1_WIN_NQ_9.9.19_34566_GW_B"},
  "3.2.17-34566": {"appid":537282343,"qua":"V1_LNX_NQ_3.2.17_34566_GW_B"},
  "3.2.17-34606": {"appid":537282343,"qua":"V1_LNX_NQ_3.2.17_34606_GW_B"},
  "9.9.19-34606": {"appid":537282307,"qua":"V1_WIN_NQ_9.9.19_34606_GW_B"},
  "9.9.19-34740": {"appid":537290691,"qua":"V1_WIN_NQ_9.9.19_34740_GW_B"},
  "3.2.17-34740": {"appid":537290727,"qua":"V1_LNX_NQ_3.2.17_34740_GW_B"},
  "9.9.19-34958": {"appid":537290742,"qua":"V1_WIN_NQ_9.9.19_34958_GW_B"},
  "3.2.17-35184": {"appid":537291084,"qua":"V1_LNX_NQ_3.2.17_35184_GW_B"},
  "9.9.19-35184": {"appid":537291048,"qua":"V1_WIN_NQ_9.9.19_35184_GW_B"},
  "3.2.17-35341": {"appid":537291383,"qua":"V1_LNX_NQ_3.2.17_35341_GW_B"},
  "9.9.19-35341": {"appid":537291347,"qua":"V1_WIN_NQ_9.9.19_35341_GW_B"},
  "9.9.19-35469": {"appid":537291398,"qua":"V1_WIN_NQ_9.9.19_35469_GW_B"},
  "3.2.18-35951": {"appid":537296013,"qua":"V1_LNX_NQ_3.2.18_35951_GW_B"},
  "9.9.20-35951": {"appid":537295977,"qua":"V1_WIN_NQ_9.9.20_35951_GW_B"},
  "3.2.18-36580": {"appid":537298509,"qua":"V1_LNX_NQ_3.2.18_36580_GW_B"},
  "9.9.20-36580": {"appid":537298473,"qua":"V1_WIN_NQ_9.9.20_36580_GW_B"},
  "9.9.20-37012": {"appid":537304071,"qua":"V1_WIN_NQ_9.9.20_37012_GW_B"},
  "3.2.18-37012": {"appid":537304107,"qua":"V1_LNX_NQ_3.2.18_37012_GW_B"},
  "3.2.18-37051": {"appid":537304158,"qua":"V1_LNX_NQ_3.2.18_37051_GW_B"},
  "9.9.20-37051": {"appid":537304122,"qua":"V1_WIN_NQ_9.9.20_37051_GW_B"},
  "9.9.20-37475": {"appid":537304173,"qua":"V1_WIN_NQ_9.9.20_37475_GW_B"},
  "3.2.18-37475": {"appid":537304210,"qua":"V1_LNX_NQ_3.2.18_37475_GW_B"},
  "9.9.20-37625": {"appid":537304224,"qua":"V1_WIN_NQ_9.9.20_37625_GW_B"},
  "3.2.18-37625": {"appid":537304261,"qua":"V1_LNX_NQ_3.2.18_37625_GW_B"},
  "9.9.21-38503": {"appid":537307604,"qua":"V1_WIN_NQ_9.9.21_38503_GW_B"},
  "3.2.19-38503": {"appid":537307640,"qua":"V1_LNX_NQ_3.2.19_38503_GW_B"},
  "3.2.19-38626": {"appid":537307691,"qua":"V1_LNX_NQ_3.2.19_38626_GW_B"},
  "9.9.21-38711": {"appid":537307655,"qua":"V1_WIN_NQ_9.9.21_38626_GW_B"},
  "9.9.21-38960": {"appid":537313855,"qua":"V1_WIN_NQ_9.9.21_38960_GW_B"},
  "3.2.19-38960": {"appid":537313891,"qua":"V1_LNX_NQ_3.2.19_38960_GW_B"},
  "3.2.19-39038": {"appid":537313942,"qua":"V1_LNX_NQ_3.2.19_39038_GW_B"},
  "9.9.21-39038": {"appid":537313906,"qua":"V1_WIN_NQ_9.9.21_39038_GW_B"},
  "9.9.22-40362": {"appid":537314212,"qua":"V1_WIN_NQ_9.9.22_40362_GW_B"},
  "3.2.20-40768": {"appid":537319840,"qua":"V1_LNX_NQ_3.2.20_40768_GW_B"},
  "9.9.22-40768": {"appid":537319804,"qua":"V1_WIN_NQ_9.9.22_40768_GW_B"},
  "6.9.82-40768": {"appid":537319829,"qua":"V1_MAC_NQ_6.9.82_40768_GW_B"},
  "3.2.20-40824": {"appid":537319840,"qua":"V1_LNX_NQ_3.2.20_40824_GW_B"},
  "9.9.22-40824": {"appid":537319804,"qua":"V1_WIN_NQ_9.9.22_40824_GW_B"},
  "6.9.82-40824": {"appid":537319829,"qua":"V1_MAC_NQ_6.9.82_40824_GW_B"},
  "6.9.82-40990": {"appid":537319880,"qua":"V1_MAC_NQ_6.9.82_40990_GW_B"},
  "9.9.22-40990": {"appid":537319855,"qua":"V1_WIN_NQ_9.9.22.40990_GW_B"},
  "3.2.20-40990": {"appid":537319891,"qua":"V1_LNX_NQ_3.2.20_40990_GW_B"},
  "9.9.23-41679": {"appid":537320110,"qua":"V1_WIN_NQ_9.9.23_41679_GW_B"},
  "6.9.83-41679": {"appid":537320135,"qua":"V1_MAC_NQ_6.9.83_41679_GW_B"},
  "9.9.23-41785": {"appid":537320110,"qua":"V1_WIN_NQ_9.9.23_41785_GW_B"},
  "6.9.83-41785": {"appid":537320135,"qua":"V1_MAC_NQ_6.9.83_41785_GW_B"},
  "9.9.23-41857": {"appid":537320161,"qua":"V1_WIN_NQ_9.9.23_41857_GW_B"},
  "3.2.21-41857": {"appid":537320197,"qua":"V1_LNX_NQ_3.2.21_41857_GW_B"},
  "6.9.83-41857": {"appid":537320186,"qua":"V1_MAC_NQ_6.9.83_41857_GW_B"},
  "3.2.21-42086": {"appid":537320248,"qua":"V1_LNX_NQ_3.2.21_42086_GW_B"},
  "9.9.23-42086": {"appid":537320212,"qua":"V1_WIN_NQ_9.9.23_42086_GW_B"},
  "6.9.85-42086": {"appid":537320237,"qua":"V1_MAC_NQ_6.9.85_42086_GW_B"},
  "9.9.23-42430": {"appid":537320212,"qua":"V1_WIN_NQ_9.9.23_42430_GW_B"},
  "9.9.25-42744": {"appid":537328470,"qua":"V1_WIN_NQ_9.9.23_42744_GW_B"},
  "6.9.86-42744": {"appid":537328495,"qua":"V1_MAC_NQ_6.9.85_42744_GW_B"},
  "9.9.25-42905": {"appid":537328521,"qua":"V1_WIN_NQ_9.9.25_42905_GW_B"},
  "6.9.86-42905": {"appid":537328546,"qua":"V1_MAC_NQ_6.9.86_42905_GW_B"},
  "3.2.22-42941": {"appid":537328659,"qua":"V1_LNX_NQ_3.2.22_42941_GW_B"},
  "9.9.25-42941": {"appid":537328623,"qua":"V1_WIN_NQ_9.9.25_42941_GW_B"},
  "6.9.86-42941": {"appid":537328648,"qua":"V1_MAC_NQ_6.9.86_42941_GW_B"},
  "9.9.26-44175": {"appid":537336450,"qua":"V1_WIN_NQ_9.9.26_44175_GW_B"},
};

class QQBasicInfoWrapper {
  QQMainPath;
  QQPackageInfoPath;
  QQVersionConfigPath;
  isQuickUpdate;
  QQVersionConfig;
  QQPackageInfo;
  QQVersionAppid;
  QQVersionQua;
  context;
  constructor(context) {
    this.context = context;
    this.QQMainPath = process.execPath;
    this.QQVersionConfigPath = getQQVersionConfigPath(this.QQMainPath);
    this.isQuickUpdate = !!this.QQVersionConfigPath;
    this.QQVersionConfig = this.isQuickUpdate ? JSON.parse(fs$2.readFileSync(this.QQVersionConfigPath).toString()) : getDefaultQQVersionConfigInfo();
    this.QQPackageInfoPath = getQQPackageInfoPath(this.QQMainPath, this.QQVersionConfig?.curVersion);
    this.QQPackageInfo = JSON.parse(fs$2.readFileSync(this.QQPackageInfoPath).toString());
    const { appid: IQQVersionAppid, qua: IQQVersionQua } = this.getAppidV2();
    this.QQVersionAppid = IQQVersionAppid;
    this.QQVersionQua = IQQVersionQua;
  }
  // 基础函数
  getQQBuildStr() {
    return this.QQVersionConfig?.curVersion.split("-")[1] ?? this.QQPackageInfo?.buildVersion;
  }
  getFullQQVersion() {
    const version = this.isQuickUpdate ? this.QQVersionConfig?.curVersion : this.QQPackageInfo?.version;
    if (!version) throw new Error("QQ版本获取失败");
    return version;
  }
  requireMinNTQQBuild(buildStr) {
    const currentBuild = +(this.getQQBuildStr() ?? "0");
    if (currentBuild === 0) throw new Error("QQBuildStr获取失败");
    return currentBuild >= parseInt(buildStr);
  }
  // 此方法不要直接使用
  getQUAFallback() {
    const platformMapping = {
      win32: `V1_WIN_${this.getFullQQVersion()}_${this.getQQBuildStr()}_GW_B`,
      darwin: `V1_MAC_${this.getFullQQVersion()}_${this.getQQBuildStr()}_GW_B`,
      linux: `V1_LNX_${this.getFullQQVersion()}_${this.getQQBuildStr()}_GW_B`
    };
    return platformMapping[systemPlatform] ?? platformMapping.win32;
  }
  getAppIdFallback() {
    const platformMapping = {
      win32: "537246092",
      darwin: "537246140",
      linux: "537246140"
    };
    return platformMapping[systemPlatform] ?? "537246092";
  }
  getAppidV2() {
    const appidTbale = AppidTable;
    const fullVersion = this.getFullQQVersion();
    if (fullVersion) {
      const data = appidTbale[fullVersion];
      if (data) {
        return data;
      }
    }
    try {
      const majorAppid = this.getAppidV2ByMajor(fullVersion);
      if (majorAppid) {
        this.context.logger.log("[QQ版本兼容性检测] 当前版本Appid未内置 通过Major获取 为了更好的性能请尝试更新NapCat");
        return { appid: majorAppid, qua: this.getQUAFallback() };
      }
    } catch {
      this.context.logger.log("[QQ版本兼容性检测] 通过Major 获取Appid异常 请检测NapCat/QQNT是否正常");
    }
    this.context.logger.log("[QQ版本兼容性检测] 获取Appid异常 请检测NapCat/QQNT是否正常");
    this.context.logger.log(`[QQ版本兼容性检测] ${fullVersion} 版本兼容性不佳，可能会导致一些功能无法正常使用`);
    return { appid: this.getAppIdFallback(), qua: this.getQUAFallback() };
  }
  getAppidV2ByMajor(QQVersion) {
    const majorPath = getMajorPath(QQVersion);
    const appid = parseAppidFromMajor(majorPath);
    return appid;
  }
}

class StatusHelper {
  psCpuUsage = process.cpuUsage();
  psCurrentTime = process.hrtime();
  cpuTimes = os$1.cpus().map((cpu) => cpu.times);
  replaceNaN(value) {
    return isNaN(value) ? 0 : value;
  }
  sysCpuInfo() {
    const currentTimes = os$1.cpus().map((cpu) => cpu.times);
    const { total, active } = currentTimes.map((times, index) => {
      const prevTimes = this.cpuTimes[index];
      const totalCurrent = times.user + times.nice + times.sys + times.idle + times.irq;
      const totalPrev = (prevTimes?.user ?? 0) + (prevTimes?.nice ?? 0) + (prevTimes?.sys ?? 0) + (prevTimes?.idle ?? 0) + (prevTimes?.irq ?? 0);
      const activeCurrent = totalCurrent - times.idle;
      const activePrev = totalPrev - (prevTimes?.idle ?? 0);
      return {
        total: totalCurrent - totalPrev,
        active: activeCurrent - activePrev
      };
    }).reduce((acc, cur) => ({
      total: acc.total + cur.total,
      active: acc.active + cur.active
    }), { total: 0, active: 0 });
    this.cpuTimes = currentTimes;
    return {
      usage: this.replaceNaN(active / total * 100).toFixed(2),
      model: os$1.cpus()[0]?.model ?? "none",
      speed: os$1.cpus()[0]?.speed ?? 0,
      core: os$1.cpus().length
    };
  }
  sysMemoryUsage() {
    const { total, free } = { total: os$1.totalmem(), free: os$1.freemem() };
    return ((total - free) / 1024 / 1024).toFixed(2);
  }
  qqUsage() {
    const mem = process.memoryUsage();
    const numCpus = os$1.cpus().length;
    const usageDiff = process.cpuUsage(this.psCpuUsage);
    const endTime = process.hrtime(this.psCurrentTime);
    this.psCpuUsage = process.cpuUsage();
    this.psCurrentTime = process.hrtime();
    const usageMS = (usageDiff.user + usageDiff.system) / 1e3;
    const totalMS = endTime[0] * 1e3 + endTime[1] / 1e6;
    const normPercent = usageMS / totalMS / numCpus * 100;
    return {
      cpu: this.replaceNaN(normPercent).toFixed(2),
      memory: ((mem.heapTotal + mem.external + mem.arrayBuffers) / 1024 / 1024).toFixed(2)
    };
  }
  systemStatus() {
    const qqUsage = this.qqUsage();
    const sysCpuInfo = this.sysCpuInfo();
    return {
      cpu: {
        core: sysCpuInfo.core,
        model: sysCpuInfo.model,
        speed: (sysCpuInfo.speed / 1e3).toFixed(2),
        usage: {
          system: sysCpuInfo.usage,
          qq: qqUsage.cpu
        }
      },
      memory: {
        total: (os$1.totalmem() / 1024 / 1024).toFixed(2),
        usage: {
          system: this.sysMemoryUsage(),
          qq: qqUsage.memory
        }
      },
      arch: `${os$1.platform()} ${os$1.arch()} ${os$1.release()}`
    };
  }
}
class StatusHelperSubscription extends EventEmitter {
  statusHelper;
  interval = null;
  constructor(time = 3e3) {
    super();
    this.statusHelper = new StatusHelper();
    this.on("newListener", (event) => {
      if (event === "statusUpdate" && this.listenerCount("statusUpdate") === 0) {
        this.startInterval(time);
      }
    });
    this.on("removeListener", (event) => {
      if (event === "statusUpdate" && this.listenerCount("statusUpdate") === 0) {
        this.stopInterval();
      }
    });
  }
  startInterval(time) {
    this.interval ??= setInterval(() => {
      const status = this.statusHelper.systemStatus();
      this.emit("statusUpdate", status);
    }, time);
  }
  stopInterval() {
    if (this.interval) {
      clearInterval(this.interval);
      this.interval = null;
    }
  }
}
const statusHelperSubscription = new StatusHelperSubscription();

async function handleUncaughtExceptions(logger) {
  process.on("uncaughtException", (err) => {
    logger.logError("[NapCat] [Error] Unhandled Exception:", err.message);
  });
  process.on("unhandledRejection", (reason) => {
    logger.logError("[NapCat] [Error] unhandledRejection:", reason);
  });
}
function getDataPaths(wrapper) {
  if (os__default.platform() === "darwin") {
    const userPath = os__default.homedir();
    const appDataPath = path__default.resolve(userPath, "./Library/Application Support/QQ");
    return [appDataPath, path__default.join(appDataPath, "global")];
  }
  let dataPath = wrapper.NodeQQNTWrapperUtil.getNTUserDataInfoConfig();
  if (!dataPath) {
    dataPath = path__default.resolve(os__default.homedir(), "./.config/QQ");
    fs__default.mkdirSync(dataPath, { recursive: true });
  }
  const dataPathGlobal = path__default.resolve(dataPath, "./nt_qq/global");
  return [dataPath, dataPathGlobal];
}
function getPlatformType() {
  const platformMapping = {
    win32: PlatformType.KWINDOWS,
    darwin: PlatformType.KMAC,
    linux: PlatformType.KLINUX
  };
  return platformMapping[os__default.platform()] ?? PlatformType.KWINDOWS;
}
async function initializeEngine(engine, basicInfoWrapper, dataPathGlobal, systemPlatform, systemVersion2) {
  engine.initWithDeskTopConfig(
    {
      base_path_prefix: "",
      platform_type: systemPlatform,
      app_type: 4,
      app_version: basicInfoWrapper.getFullQQVersion(),
      os_version: systemVersion2,
      use_xlog: false,
      qua: basicInfoWrapper.QQVersionQua ?? "",
      global_path_config: {
        desktopGlobalPath: dataPathGlobal
      },
      thumb_config: { maxSide: 324, minSide: 48, longLimit: 6, density: 2 }
    },
    new NodeIGlobalAdapter()
  );
}
async function initializeLoginService(loginService, basicInfoWrapper, dataPathGlobal, systemVersion2, hostname2) {
  loginService.initConfig({
    machineId: "",
    appid: basicInfoWrapper.QQVersionAppid ?? "",
    platVer: systemVersion2,
    commonPath: dataPathGlobal,
    clientVer: basicInfoWrapper.getFullQQVersion(),
    hostName: hostname2
  });
}
async function handleLogin(loginService, logger, pathWrapper, quickLoginUin, historyLoginList) {
  const context = { isLogined: false };
  let inner_resolve;
  const selfInfo = new Promise((resolve) => {
    inner_resolve = resolve;
  });
  const loginListener = new NodeIKernelLoginListener();
  loginListener.onUserLoggedIn = (userid) => {
    logger.logError(`当前账号(${userid})已登录,无法重复登录`);
  };
  loginListener.onQRCodeLoginSucceed = async (loginResult) => {
    context.isLogined = true;
    inner_resolve({
      uid: loginResult.uid,
      uin: loginResult.uin,
      nick: "",
      online: true
    });
  };
  loginListener.onLoginConnected = () => {
    waitForNetworkConnection(loginService, logger).then(() => {
      handleLoginInner(context, logger, loginService, quickLoginUin, historyLoginList).then().catch((e) => logger.logError(e));
      loginListener.onLoginConnected = () => {
      };
    });
  };
  loginListener.onQRCodeGetPicture = ({ pngBase64QrcodeData, qrcodeUrl }) => {
    WebUiDataRuntime.setQQLoginQrcodeURL(qrcodeUrl);
    const realBase64 = pngBase64QrcodeData.replace(/^data:image\/\w+;base64,/, "");
    const buffer = Buffer.from(realBase64, "base64");
    logger.logWarn("请扫描下面的二维码，然后在手Q上授权登录：");
    const qrcodePath = path__default.join(pathWrapper.cachePath, "qrcode.png");
    qrcode.generate(qrcodeUrl, { small: true }, (res) => {
      logger.logWarn([
        "\n",
        res,
        "二维码解码URL: " + qrcodeUrl,
        "如果控制台二维码无法扫码，可以复制解码url到二维码生成网站生成二维码再扫码，也可以打开下方的二维码路径图片进行扫码。"
      ].join("\n"));
      fs__default.writeFile(qrcodePath, buffer, {}, () => {
        logger.logWarn("二维码已保存到", qrcodePath);
      });
    });
  };
  loginListener.onQRCodeSessionFailed = (errType, errCode) => {
    if (!context.isLogined) {
      logger.logError("[Core] [Login] Login Error,ErrType: ", errType, " ErrCode:", errCode);
      loginService.getQRCodePicture();
    }
  };
  loginListener.onLoginFailed = (...args) => {
    logger.logError("[Core] [Login] Login Error , ErrInfo: ", JSON.stringify(args));
  };
  loginService.addKernelLoginListener(proxiedListenerOf(loginListener, logger));
  loginService.connect();
  return await selfInfo;
}
async function handleLoginInner(context, logger, loginService, quickLoginUin, historyLoginList) {
  WebUiDataRuntime.setQuickLoginCall(async (uin) => {
    return await new Promise((resolve) => {
      if (uin) {
        logger.log("正在快速登录 ", uin);
        loginService.quickLoginWithUin(uin).then((res) => {
          if (res.loginErrorInfo.errMsg) {
            resolve({ result: false, message: res.loginErrorInfo.errMsg });
          }
          resolve({ result: true, message: "" });
        }).catch((e) => {
          logger.logError(e);
          resolve({ result: false, message: "快速登录发生错误" });
        });
      } else {
        resolve({ result: false, message: "快速登录失败" });
      }
    });
  });
  if (quickLoginUin) {
    if (historyLoginList.some((u) => u.uin === quickLoginUin)) {
      logger.log("正在快速登录 ", quickLoginUin);
      loginService.quickLoginWithUin(quickLoginUin).then((result) => {
        if (result.loginErrorInfo.errMsg) {
          logger.logError("快速登录错误：", result.loginErrorInfo.errMsg);
          if (!context.isLogined) loginService.getQRCodePicture();
        }
      }).catch();
    } else {
      logger.logError("快速登录失败，未找到该 QQ 历史登录记录，将使用二维码登录方式");
      if (!context.isLogined) loginService.getQRCodePicture();
    }
  } else {
    logger.log("没有 -q 指令指定快速登录，将使用二维码登录方式");
    if (historyLoginList.length > 0) {
      logger.log(`可用于快速登录的 QQ：
${historyLoginList.map((u, index) => `${index + 1}. ${u.uin} ${u.nickName}`).join("\n")}`);
    }
    loginService.getQRCodePicture();
    try {
      await WebUiDataRuntime.runWebUiConfigQuickFunction();
    } catch (error) {
      logger.logError("WebUi 快速登录失败 执行失败", error);
    }
  }
  loginService.getLoginList().then((res) => {
    const list = res.LocalLoginInfoList.filter((item) => item.isQuickLogin);
    WebUiDataRuntime.setQQQuickLoginList(list.map((item) => item.uin.toString()));
    WebUiDataRuntime.setQQNewLoginList(list);
  });
}
async function initializeSession(session, sessionConfig, startupSession) {
  return new Promise((resolve, reject) => {
    const sessionListener = new NodeIKernelSessionListener();
    sessionListener.onOpentelemetryInit = (info) => {
      if (info.is_init) {
        resolve();
      } else {
        reject(new Error("opentelemetry init failed"));
      }
    };
    session.init(
      sessionConfig,
      new NodeIDependsAdapter(),
      new NodeIDispatcherAdapter(),
      sessionListener
    );
    if (startupSession) {
      startupSession.start();
    } else {
      try {
        session.startNT(0);
      } catch {
        try {
          session.startNT();
        } catch (e) {
          reject(new Error("init failed " + e.message));
        }
      }
    }
  });
}
async function handleProxy(session, logger) {
  if (process.env["NAPCAT_PROXY_PORT"]) {
    session.getMSFService().setNetworkProxy({
      userName: "",
      userPwd: "",
      address: process.env["NAPCAT_PROXY_ADDRESS"] || "127.0.0.1",
      port: +process.env["NAPCAT_PROXY_PORT"],
      proxyType: 2,
      domain: "",
      isSocket: true
    });
    logger.logWarn("已设置代理", process.env["NAPCAT_PROXY_ADDRESS"], process.env["NAPCAT_PROXY_PORT"]);
  } else if (process.env["NAPCAT_PROXY_CLOSE"]) {
    session.getMSFService().setNetworkProxy({
      userName: "",
      userPwd: "",
      address: "",
      port: 0,
      proxyType: 0,
      domain: "",
      isSocket: false
    });
  }
}
async function waitForNetworkConnection(loginService, logger) {
  let network_ok = false;
  while (!network_ok) {
    network_ok = loginService.getMsfStatus() !== 3;
    logger.log("等待网络连接...");
    await sleep(500);
  }
  logger.log("网络已连接");
  return network_ok;
}
async function NCoreInitShell() {
  console.log("NapCat Shell App Loading...");
  const pathWrapper = new NapCatPathWrapper();
  const logger = new LogWrapper(pathWrapper.logsPath);
  handleUncaughtExceptions(logger);
  await applyPendingUpdates(pathWrapper);
  await FFmpegService.init(pathWrapper.binaryPath, logger);
  if (process.env["NAPCAT_DISABLE_PIPE"] !== "1") {
    await connectToNamedPipe(logger).catch((e) => logger.logError("命名管道连接失败", e));
  }
  const basicInfoWrapper = new QQBasicInfoWrapper({ logger });
  const wrapper = loadQQWrapper(basicInfoWrapper.getFullQQVersion());
  const nativePacketHandler = new NativePacketHandler({ logger });
  await nativePacketHandler.init(basicInfoWrapper.getFullQQVersion());
  const o3Service = wrapper.NodeIO3MiscService.get();
  o3Service.addO3MiscListener(new NodeIO3MiscListener());
  logger.log("[NapCat] [Core] NapCat.Core Version: " + napCatVersion);
  WebUiDataRuntime.setWorkingEnv(NapCatCoreWorkingEnv$1.Shell);
  InitWebUi(logger, pathWrapper, logSubscription$1, statusHelperSubscription).then().catch((e) => logger.logError(e));
  const engine = wrapper.NodeIQQNTWrapperEngine.get();
  const loginService = wrapper.NodeIKernelLoginService.get();
  let session;
  let startupSession = null;
  try {
    startupSession = wrapper.NodeIQQNTStartupSessionWrapper.create();
    session = wrapper.NodeIQQNTWrapperSession.getNTWrapperSession("nt_1");
  } catch (e) {
    try {
      session = wrapper.NodeIQQNTWrapperSession.create();
    } catch (error) {
      logger.logError("创建 StartupSession 失败", e);
      logger.logError("创建 Session 失败", error);
      throw error;
    }
  }
  const [dataPath, dataPathGlobal] = getDataPaths(wrapper);
  const systemPlatform = getPlatformType();
  if (!basicInfoWrapper.QQVersionAppid || !basicInfoWrapper.QQVersionQua) throw new Error("QQVersionAppid or QQVersionQua  is not defined");
  await initializeEngine(engine, basicInfoWrapper, dataPathGlobal, systemPlatform, systemVersion);
  await initializeLoginService(loginService, basicInfoWrapper, dataPathGlobal, systemVersion, hostname);
  handleProxy(session, logger);
  let quickLoginUin;
  try {
    const args = process.argv;
    const qIndex = args.findIndex((arg) => arg === "-q" || arg === "--qq");
    if (qIndex !== -1 && qIndex + 1 < args.length) {
      quickLoginUin = args[qIndex + 1];
    }
  } catch (error) {
    logger.logWarn("解析命令行参数失败，无法使用快速登录功能", error);
  }
  const historyLoginList = (await loginService.getLoginList()).LocalLoginInfoList;
  const dataTimestape = (/* @__PURE__ */ new Date()).getTime().toString();
  o3Service.reportAmgomWeather("login", "a1", [dataTimestape, "0", "0"]);
  const selfInfo = await handleLogin(loginService, logger, pathWrapper, quickLoginUin, historyLoginList);
  const amgomDataPiece = "eb1fd6ac257461580dc7438eb099f23aae04ca679f4d88f53072dc56e3bb1129";
  o3Service.setAmgomDataPiece(basicInfoWrapper.QQVersionAppid, new Uint8Array(Buffer.from(amgomDataPiece, "hex")));
  let guid = loginService.getMachineGuid();
  guid = guid.slice(0, 8) + "-" + guid.slice(8, 12) + "-" + guid.slice(12, 16) + "-" + guid.slice(16, 20) + "-" + guid.slice(20);
  o3Service.reportAmgomWeather("login", "a6", [dataTimestape, "184", "329"]);
  const sessionConfig = await genSessionConfig(
    guid,
    basicInfoWrapper.QQVersionAppid,
    basicInfoWrapper.getFullQQVersion(),
    selfInfo.uin,
    selfInfo.uid,
    dataPath
  );
  await initializeSession(session, sessionConfig, startupSession);
  const accountDataPath = path__default.resolve(dataPath, "./NapCat/data");
  if (dataPath !== "/" && /^[a-zA-Z]:\\$/.test(dataPath) === false) {
    try {
      fs__default.mkdirSync(accountDataPath, { recursive: true });
    } catch (error) {
      logger.logError("创建accountDataPath失败", error);
    }
  }
  logger.logDebug("本账号数据/缓存目录：", accountDataPath);
  await new NapCatShell(
    wrapper,
    session,
    logger,
    loginService,
    selfInfo,
    basicInfoWrapper,
    pathWrapper,
    nativePacketHandler
  ).InitNapCat();
}
class NapCatShell {
  core;
  context;
  constructor(wrapper, session, logger, loginService, selfInfo, basicInfoWrapper, pathWrapper, packetHandler) {
    this.context = {
      packetHandler,
      workingEnv: NapCatCoreWorkingEnv$1.Shell,
      wrapper,
      session,
      logger,
      loginService,
      basicInfoWrapper,
      pathWrapper
    };
    this.core = new NapCatCore(this.context, selfInfo);
  }
  async InitNapCat() {
    await this.core.initCore();
    const oneBotAdapter = new NapCatOneBot11Adapter(this.core, this.context, this.context.pathWrapper);
    WebUiDataRuntime.setOneBotContext(oneBotAdapter);
    oneBotAdapter.InitOneBot().catch((e) => this.context.logger.logError("初始化OneBot失败", e));
  }
}

NCoreInitShell();
