'use strict';

const Item = require('./Item-00ce8c24.js');
const ok = require('./ok-97a5fd0b.js');
const index = require('./index-c910887e.js');
const Token = require('./Token-8c5ba5d9.js');
require('./index-9d95c045.js');
const index$1 = require('./index-cc85865d.js');
const index$2 = require('./index-0b2930ca.js');
const TextDecoder = require('./TextDecoder-753156f3.js');

var Creatable$5;
(function (Creatable) {
    function is(value) {
        return (typeof value == "object" &&
            (value.number == undefined || typeof value.number == "string") &&
            (value.amount == undefined || typeof value.amount == "number") &&
            (value.auto == undefined || value.auto == true) &&
            (value.descriptor == undefined || typeof value.descriptor == "string"));
    }
    Creatable.is = is;
    function flaw(value) {
        return {
            type: "Capture.Creatable",
            flaws: typeof value != "object"
                ? undefined
                : [
                    value.number == undefined ||
                        typeof value.number == "string" || { property: "number", type: "string | undefined" },
                    value.amount == undefined ||
                        typeof value.amount == "number" || { property: "amount", type: "number | undefined" },
                    value.auto == undefined || value.auto == true || { property: "auto", type: "true | undefined" },
                    value.descriptor == undefined ||
                        typeof value.descriptor == "string" || { property: "descriptor", type: "string | undefined" },
                ].filter(ok.Flaw.is),
        };
    }
    Creatable.flaw = flaw;
})(Creatable$5 || (Creatable$5 = {}));

var Capture$1;
(function (Capture) {
    function is(value) {
        return (typeof value == "object" &&
            (value.number == undefined || typeof value.number == "string") &&
            index.DateTime.is(value.created) &&
            (value.reference == undefined || typeof value.reference == "string") &&
            (value.approved == undefined || index.DateTime.is(value.approved)) &&
            typeof value.amount == "number" &&
            (value.auto == undefined || value.auto == true) &&
            (value.descriptor == undefined || typeof value.descriptor == "string") &&
            ["approved", "settled", "pending"].some(v => v == value.status));
    }
    Capture.is = is;
    function flaw(value) {
        return {
            type: "Capture",
            flaws: typeof value != "object"
                ? undefined
                : [
                    value.number == undefined ||
                        typeof value.number == "string" || { property: "number", type: "string | undefined" },
                    index.DateTime.is(value.created) || { property: "created", type: "isoly.DateTime" },
                    value.reference == undefined ||
                        typeof value.reference == "string" || { property: "reference", type: "string | undefined" },
                    value.approved == undefined ||
                        index.DateTime.is(value.approved) || { property: "approved", type: "isoly.DateTime | undefined" },
                    typeof value.amount == "number" || { property: "amount", type: "number" },
                    value.auto == undefined || value.auto == true || { property: "auto", type: "true | undefined" },
                    value.descriptor == undefined ||
                        typeof value.descriptor == "string" || { property: "descriptor", type: "string | undefined" },
                    ["approved", "pending"].some(v => v == value.status) || {
                        property: "status",
                        type: '"approved" | "pending"',
                    },
                ].filter(ok.Flaw.is),
        };
    }
    Capture.flaw = flaw;
    (function (Creatable) {
        Creatable.is = Creatable$5.is;
        Creatable.flaw = Creatable$5.flaw;
    })(Capture.Creatable || (Capture.Creatable = {}));
})(Capture$1 || (Capture$1 = {}));

var Creatable$4;
(function (Creatable) {
    function is(value) {
        return (typeof value == "object" &&
            (value.number == undefined || typeof value.number == "string") &&
            (value.amount == undefined || typeof value.amount == "number") &&
            (value.descriptor == undefined || typeof value.descriptor == "string"));
    }
    Creatable.is = is;
    function flaw(value) {
        return {
            type: "Refund.Creatable",
            flaws: typeof value != "object"
                ? undefined
                : [
                    value.number == undefined ||
                        typeof value.number == "string" || { property: "number", type: "string | undefined" },
                    value.amount == undefined ||
                        typeof value.amount == "number" || { property: "amount", type: "number | undefined" },
                    value.descriptor == undefined ||
                        typeof value.descriptor == "string" || { property: "descriptor", type: "string | undefined" },
                ].filter(ok.Flaw.is),
        };
    }
    Creatable.flaw = flaw;
})(Creatable$4 || (Creatable$4 = {}));

var Refund$1;
(function (Refund) {
    function is(value) {
        return (typeof value == "object" &&
            (value.number == undefined || typeof value.number == "string") &&
            index.DateTime.is(value.created) &&
            (value.reference == undefined || typeof value.reference == "string") &&
            (value.approved == undefined || index.DateTime.is(value.approved)) &&
            typeof value.amount == "number" &&
            (value.descriptor == undefined || typeof value.descriptor == "string") &&
            ["approved", "settled", "pending"].some(v => v == value.status));
    }
    Refund.is = is;
    function flaw(value) {
        return {
            type: "Refund",
            flaws: typeof value != "object"
                ? undefined
                : [
                    value.number == undefined ||
                        typeof value.number == "string" || { property: "number", type: "string | undefined" },
                    index.DateTime.is(value.created) || { property: "created", type: "isoly.DateTime" },
                    value.reference == undefined ||
                        typeof value.reference == "string" || { property: "reference", type: "string | undefined" },
                    value.approved == undefined ||
                        index.DateTime.is(value.approved) || { property: "approved", type: "isoly.DateTime | undefined" },
                    typeof value.amount == "number" || { property: "amount", type: "number" },
                    value.descriptor == undefined ||
                        typeof value.descriptor == "string" || { property: "descriptor", type: "string | undefined" },
                    ["approved", "pending"].some(v => v == value.status) || {
                        property: "status",
                        type: '"approved" | "pending"',
                    },
                ].filter(ok.Flaw.is),
        };
    }
    Refund.flaw = flaw;
    (function (Creatable) {
        Creatable.is = Creatable$4.is;
        Creatable.flaw = Creatable$4.flaw;
    })(Refund.Creatable || (Refund.Creatable = {}));
})(Refund$1 || (Refund$1 = {}));

var Creatable$3;
(function (Creatable) {
    function is(value) {
        return (typeof value == "object" &&
            (value.number == undefined || typeof value.number == "string") &&
            (value.amount == undefined || typeof value.amount == "number"));
    }
    Creatable.is = is;
    function flaw(value) {
        return {
            type: "Authorization.Change.Creatable",
            flaws: typeof value != "object"
                ? undefined
                : [
                    value.number == undefined ||
                        typeof value.number == "string" || { property: "number", type: "string | undefined" },
                    value.amount == undefined ||
                        typeof value.amount == "number" || { property: "amount", type: "number | undefined" },
                ].filter(ok.Flaw.is),
        };
    }
    Creatable.flaw = flaw;
})(Creatable$3 || (Creatable$3 = {}));

var Change;
(function (Change) {
    function is(value) {
        return (typeof value == "object" &&
            (value.number == undefined || typeof value.number == "string") &&
            index.DateTime.is(value.created) &&
            typeof value.amount == "number");
    }
    Change.is = is;
    function flaw(value) {
        return {
            type: "Authorization.Change",
            flaws: typeof value != "object"
                ? undefined
                : [
                    value.number == undefined ||
                        typeof value.number == "string" || { property: "number", type: "string | undefined" },
                    index.DateTime.is(value.created) || { property: "created", type: "isoly.DateTime" },
                    typeof value.amount == "number" || { property: "amount", type: "number" },
                ].filter(ok.Flaw.is),
        };
    }
    Change.flaw = flaw;
    (function (Creatable) {
        Creatable.is = Creatable$3.is;
        Creatable.flaw = Creatable$3.flaw;
    })(Change.Creatable || (Change.Creatable = {}));
})(Change || (Change = {}));

var Recurring;
(function (Recurring) {
    function is(value) {
        return value == "initial" || isInitial(value) || isSubsequent(value) || isScheduled(value);
    }
    Recurring.is = is;
    function isInitial(value) {
        return typeof value == "object" && value.type == "initial" && value.initiator == "cardholder";
    }
    function isSubsequent(value) {
        return (typeof value == "object" &&
            value.type == "subsequent" &&
            typeof value.reference == "string" &&
            ["cardholder", "merchant"].includes(value.initiator) &&
            value.scheduled != true);
    }
    function isScheduled(value) {
        return (typeof value == "object" &&
            value.initiator == "merchant" &&
            value.reference == "string" &&
            value.scheduled == true &&
            value.type == "subsequent");
    }
    Recurring.template = new index.dist.Type.Union([
        new index.dist.Type.String("initial"),
        new index.dist.Type.Object({
            type: new index.dist.Type.Union([
                new index.dist.Type.String("initial"),
                new index.dist.Type.String("subsequent"),
            ]),
            initiator: new index.dist.Type.Union([
                new index.dist.Type.String("cardholder"),
                new index.dist.Type.String("merchant"),
            ]),
            scheduled: new index.dist.Type.Boolean(),
            reference: new index.dist.Type.String(),
        }),
    ]);
})(Recurring || (Recurring = {}));

var Creatable$2;
(function (Creatable) {
    function is(value) {
        return (typeof value == "object" &&
            typeof value.number == "string" &&
            typeof value.amount == "number" &&
            index.Currency.is(value.currency) &&
            (index.Token.is(value.card) || index$1.Card.Creatable.is(value.card)) &&
            (value.descriptor == undefined || typeof value.descriptor == "string") &&
            (value.capture == undefined || ["auto"].some(v => v == value.capture)) &&
            (value.recurring == undefined || Recurring.is(value.recurring)) &&
            (value.category == undefined || value.category == "purchase" || value.category == "withdrawal"));
    }
    Creatable.is = is;
    function flaw(value) {
        return {
            type: "Authorization.Creatable",
            flaws: typeof value != "object"
                ? undefined
                : [
                    typeof value.number == "string" || { property: "number", type: "string" },
                    typeof value.amount == "number" || { property: "amount", type: "number" },
                    index.Currency.is(value.currency) || { property: "currency", type: "isoly.Currency" },
                    index.Token.is(value.card) ||
                        index$1.Card.Creatable.is(value.card) || {
                        property: "card",
                        type: "authly.Token | model.Card.Creatable",
                    },
                    value.descriptor == undefined ||
                        typeof value.descriptor == "string" || { property: "descriptor", type: "string | undefined" },
                    value.capture == undefined ||
                        ["auto"].some(v => v == value.capture) || { property: "capture", type: '"auto" | undefined' },
                    value.recurring == undefined ||
                        Recurring.is(value.recurring) || {
                        property: "recurring",
                        type: `Authorization.Recurring | undefined`,
                    },
                    value.category == undefined ||
                        value.category == "purchase" ||
                        value.category == "withdrawal" || {
                        property: "category",
                        type: `"purchase" | "withdrawal" | undefined`,
                    },
                ].filter(ok.Flaw.is),
        };
    }
    Creatable.flaw = flaw;
})(Creatable$2 || (Creatable$2 = {}));

var Error;
(function (Error) {
    function databaseFailure(error, message) {
        return ok.databaseFailure(message, error);
    }
    Error.databaseFailure = databaseFailure;
    function unauthorized() {
        return ok.unauthorized("unauthorized");
    }
    Error.unauthorized = unauthorized;
    function backendFailure(details) {
        return ok.backendFailure("Intergiro", details, undefined, "backend problem");
    }
    Error.backendFailure = backendFailure;
    function flawedContent(error, flaw) {
        return ok.flawedContent(flaw, error);
    }
    Error.flawedContent = flawedContent;
    function invalidContent(error, type, description, details) {
        return ok.invalidContent(type, description, details, error);
    }
    Error.invalidContent = invalidContent;
    function malformedContent(error, property, type, description, details) {
        return ok.malformedContent(property, type, description, details, error);
    }
    Error.malformedContent = malformedContent;
    function invalidPathArgument(path, name, type, description) {
        return ok.invalidPathArgument(path, name, type, description, "invalid input");
    }
    Error.invalidPathArgument = invalidPathArgument;
    function invalidQueryArgument(name, type, description) {
        return ok.invalidQueryArgument(name, type, description, "invalid input");
    }
    Error.invalidQueryArgument = invalidQueryArgument;
    function misconfigured(key, description) {
        return ok.misconfigured(key, description, "backend problem");
    }
    Error.misconfigured = misconfigured;
    function unknown(details) {
        return ok.unknown(details, "unknown error");
    }
    Error.unknown = unknown;
    function unavailable() {
        return ok.unavailable("backend problem");
    }
    Error.unavailable = unavailable;
    (function (Code) {
        function is(value) {
            return Code.types.includes(value);
        }
        Code.is = is;
        Code.types = [
            "3ds problem",
            "3ds authentication failure",
            "acquirer error",
            "amount limit",
            "authentication required",
            "authorization not found",
            "backend problem",
            "blocked merchant",
            "card declined",
            "card lost or stolen",
            "card restricted",
            "card expired",
            "invalid card number",
            "invalid csc",
            "invalid currency",
            "invalid descriptor",
            "invalid expire date",
            "invalid input",
            "invalid transaction",
            "insufficient funds",
            "merchant not found",
            "rule violation",
            "suspected fraud",
            "unauthorized",
            "unknown error",
            "unsupported card",
            "verification required",
        ];
    })(Error.Code || (Error.Code = {}));
})(Error || (Error = {}));

var Capture;
(function (Capture) {
    function isBase(value) {
        return (typeof value == "object" &&
            typeof value.merchant == "string" &&
            typeof value.number == "string" &&
            index.DateTime.is(value.date) &&
            value.type == "capture" &&
            typeof value.amount == "number" &&
            index.Currency.is(value.currency));
    }
    function isFail(value) {
        return (typeof value == "object" &&
            value.status == "fail" &&
            Error.Code.is(value.reason) &&
            ok.Error.is(value.error) &&
            isBase(value));
    }
    Capture.isFail = isFail;
    function isSuccess(value) {
        return typeof value == "object" && value.status == "success" && typeof value.reference == "string" && isBase(value);
    }
    Capture.isSuccess = isSuccess;
    function is(value) {
        return isFail(value) || isSuccess(value);
    }
    Capture.is = is;
    function create(merchant, authorization, amount, input) {
        var _a;
        return {
            merchant,
            type: "capture",
            date: index.DateTime.now(),
            number: authorization.number,
            currency: authorization.currency,
            amount,
            ...(ok.Error.is(input)
                ? { status: "fail", reason: Error.Code.is(input.error) ? input.error : "unknown error", error: input }
                : { status: "success", reference: (_a = input.reference) !== null && _a !== void 0 ? _a : "unknown reference" }),
        };
    }
    Capture.create = create;
})(Capture || (Capture = {}));

var Card;
(function (Card) {
    function is(value) {
        return (typeof value == "object" &&
            index$1.Card.Scheme.is(value.scheme) &&
            typeof value.iin == "string" &&
            value.iin.length == 6 &&
            typeof value.last4 == "string" &&
            value.last4.length == 4 &&
            index.Date.is(value.expires) &&
            (value.type == undefined || index$1.Card.Type.is(value.type)) &&
            (value.csc == undefined || ["matched", "mismatched", "present"].includes(value.csc)));
    }
    Card.is = is;
    function isPartial(value) {
        return (typeof value == "object" &&
            (value.scheme == undefined || index$1.Card.Scheme.is(value.scheme)) &&
            (value.iin == undefined || (typeof value.iin == "string" && value.iin.length == 6)) &&
            (value.last4 == undefined || (typeof value.last4 == "string" && value.last4.length == 4)) &&
            (value.expires == undefined || index.Date.is(value.expires)) &&
            (value.type == undefined || index$1.Card.Type.is(value.type)) &&
            (value.csc == undefined || ["matched", "mismatched", "present"].includes(value.csc)));
    }
    Card.isPartial = isPartial;
    function from(card) {
        return {
            ...(index$1.Card.is(card) ? card : index$1.Card.from(card)),
            expires: (2000 + card.expires[1]).toString() +
                "-" +
                card.expires[0].toString().padStart(2, "0") +
                "-" +
                lastDayOfMonth(2000 + card.expires[1], card.expires[0]),
        };
    }
    Card.from = from;
    function lastDayOfMonth(year, month) {
        let result;
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
            default:
                result = "31";
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                result = "30";
                break;
            case 2:
                result = year % 4 == 0 ? "29" : "28";
                break;
        }
        return result;
    }
    Card.template = new index.dist.Type.Object({
        scheme: new index.dist.Type.Union([
            new index.dist.Type.String("unknown"),
            new index.dist.Type.String("amex"),
            new index.dist.Type.String("dankort"),
            new index.dist.Type.String("diners"),
            new index.dist.Type.String("discover"),
            new index.dist.Type.String("electron"),
            new index.dist.Type.String("interpayment"),
            new index.dist.Type.String("jcb"),
            new index.dist.Type.String("maestro"),
            new index.dist.Type.String("mastercard"),
            new index.dist.Type.String("unionpay"),
            new index.dist.Type.String("visa"),
        ]),
        iin: new index.dist.Type.String(),
        last4: new index.dist.Type.String(),
        expires: new index.dist.Type.String(),
        type: new index.dist.Type.Union([new index.dist.Type.String("debit"), new index.dist.Type.String("credit")]),
        csc: new index.dist.Type.Union([
            new index.dist.Type.String("matched"),
            new index.dist.Type.String("mismatched"),
            new index.dist.Type.String("present"),
        ]),
    });
})(Card || (Card = {}));

var Statistics;
(function (Statistics) {
    function is(value) {
        return (typeof value == "object" &&
            Token.Identifier.is(value.merchant, 8) &&
            index.Currency.is(value.currency) &&
            typeof value.captured == "object" &&
            Object.entries(value.captured).every(e => index.Date.is(e[0]) && typeof e[1] == "number") &&
            typeof value.settled == "object" &&
            Object.entries(value.settled).every(e => index.Date.is(e[0]) && typeof e[1] == "number") &&
            typeof value.refunded == "object" &&
            Object.entries(value.refunded).every(e => index.Date.is(e[0]) && typeof e[1] == "number") &&
            typeof value.fees == "object" &&
            Object.entries(value.fees).every(e => index.Date.is(e[0]) && typeof e[1] == "number") &&
            typeof value.reserves == "object" &&
            typeof value.reserves.in == "object" &&
            Object.entries(value.reserves.in).every(e => index.Date.is(e[0]) && typeof e[1] == "number") &&
            typeof value.reserves.out == "object" &&
            Object.entries(value.reserves.out).every(e => index.Date.is(e[0]) && typeof e[1] == "number"));
    }
    Statistics.is = is;
    function initialize(id, currency) {
        return { merchant: id, currency, captured: {}, refunded: {}, settled: {}, fees: {}, reserves: { in: {}, out: {} } };
    }
    Statistics.initialize = initialize;
    function merge(input, merchant, currency, rate) {
        var _a, _b;
        const result = initialize(merchant, currency);
        const types = ["captured", "refunded", "settled", "fees"];
        for (const statistic of input) {
            const factor = (_a = rate[statistic.currency]) !== null && _a !== void 0 ? _a : 1;
            for (const key of types)
                for (const entry of Object.entries(statistic[key]))
                    result[key][entry[0]] = ((_b = result[key][entry[0]]) !== null && _b !== void 0 ? _b : 0) + entry[1] * factor;
            for (const entry of Object.entries(statistic.reserves.in))
                result.reserves.in[entry[0]] = result.reserves.in[entry[0]] + entry[1] * factor;
            for (const entry of Object.entries(statistic.reserves.out))
                result.reserves.out[entry[0]] = result.reserves.out[entry[0]] + entry[1] * factor;
        }
        return result;
    }
    Statistics.merge = merge;
    function applySettlement(statistic, date, settlement) {
        var _a, _b, _c, _d;
        statistic.fees[date] = typeof settlement.fee == "object" ? settlement.fee.total : settlement.fee;
        statistic.settled[date] = settlement.net;
        statistic.reserves.in[date] = (_b = (_a = settlement.reserve) === null || _a === void 0 ? void 0 : _a.amount) !== null && _b !== void 0 ? _b : 0;
        if ((_c = settlement.reserve) === null || _c === void 0 ? void 0 : _c.payout)
            statistic.reserves.out[settlement.reserve.payout] =
                ((_d = statistic.reserves.out[settlement.reserve.payout]) !== null && _d !== void 0 ? _d : 0) - settlement.reserve.amount;
        return statistic;
    }
    Statistics.applySettlement = applySettlement;
    function refundable(statistics) {
        return index.Currency.round(sum(statistics.captured, undefined, 1) - sum(statistics.refunded, undefined, 1) + sum(statistics.reserves.in), statistics.currency);
    }
    Statistics.refundable = refundable;
    function sum(record, currency, from, to) {
        if (typeof from == "number") {
            const date = new Date();
            date.setDate(date.getDate() - (from !== null && from !== void 0 ? from : 0));
            from = index.Date.create(date);
        }
        const result = Object.entries(record).reduce((r, e) => ((!from || e[0] >= from) && e[0] <= (to !== null && to !== void 0 ? to : index.Date.now()) ? (r += e[1]) : r), 0);
        return !currency ? result : index.Currency.round(result, currency);
    }
    Statistics.sum = sum;
    function summarize(statistics, from, to) {
        return {
            ...statistics,
            captured: sum(statistics.captured, statistics.currency, from, to),
            refunded: sum(statistics.refunded, statistics.currency, from, to),
            settled: sum(statistics.settled, statistics.currency, from, to),
            fees: sum(statistics.fees, statistics.currency, from, to),
            reserves: sum(statistics.reserves.in, statistics.currency, from, to) +
                sum(statistics.reserves.out, statistics.currency, from, to),
        };
    }
    Statistics.summarize = summarize;
})(Statistics || (Statistics = {}));

var Merchant;
(function (Merchant) {
    function is(value) {
        return (typeof value == "object" &&
            Token.Identifier.is(value.id) &&
            typeof value.descriptor == "string" &&
            index.Alpha2.is(value.country) &&
            typeof value.name == "string" &&
            index.Currency.is(value.currency) &&
            Array.isArray(value.scheme) &&
            value.scheme.every(index$1.Card.Scheme.is) &&
            typeof value.refundable == "number" &&
            typeof value.captured == "number" &&
            typeof value.settled == "number" &&
            typeof value.fees == "number");
    }
    Merchant.is = is;
    function from(merchant, statistics) {
        var _a;
        const limit = index.Date.create(new Date(Date.now() - 1000 * 60 * 60 * 24 * 30));
        return {
            id: merchant.id,
            descriptor: (_a = merchant.descriptor) !== null && _a !== void 0 ? _a : merchant.name,
            country: merchant.country,
            name: merchant.name,
            currency: merchant.currency,
            scheme: Object.keys(merchant.reconciliation.fees).filter(index$1.Card.Scheme.is),
            refundable: Statistics.refundable(statistics),
            captured: calculate(statistics.captured, limit),
            settled: calculate(statistics.settled, limit),
            fees: calculate(statistics.fees, limit),
        };
    }
    Merchant.from = from;
    Merchant.template = new index.dist.Type.Object({
        id: new index.dist.Type.String(),
        descriptor: new index.dist.Type.String(),
        country: new index.dist.Type.Union(index.Alpha2.types.map(c => new index.dist.Type.String(c))),
        name: new index.dist.Type.String(),
        currency: new index.dist.Type.Union(index.Currency.types.map(c => new index.dist.Type.String(c))),
        scheme: new index.dist.Type.Array([
            new index.dist.Type.Union([
                new index.dist.Type.String("unknown"),
                new index.dist.Type.String("amex"),
                new index.dist.Type.String("dankort"),
                new index.dist.Type.String("diners"),
                new index.dist.Type.String("discover"),
                new index.dist.Type.String("electron"),
                new index.dist.Type.String("interpayment"),
                new index.dist.Type.String("jcb"),
                new index.dist.Type.String("maestro"),
                new index.dist.Type.String("mastercard"),
                new index.dist.Type.String("unionpay"),
                new index.dist.Type.String("visa"),
            ]),
        ]),
        refundable: new index.dist.Type.Number(),
        captured: new index.dist.Type.Number(),
        settled: new index.dist.Type.Number(),
        fees: new index.dist.Type.Number(),
    });
})(Merchant || (Merchant = {}));
function calculate(values, limit) {
    return Object.entries(values).reduce((r, c) => r + (c[0] > limit ? c[1] : 0), 0);
}

exports.Authorization = void 0;
(function (Authorization) {
    function is(value) {
        return (typeof value == "object" &&
            (Merchant.is(value.merchant) || (typeof value.merchant == "object" && Token.Identifier.is(value.merchant.id))) &&
            typeof value.authorization == "object" &&
            typeof value.authorization.id == "string" &&
            typeof value.authorization.number == "string" &&
            typeof value.authorization.reference == "string" &&
            typeof value.authorization.amount == "number" &&
            index.Currency.is(value.authorization.currency) &&
            Card.is(value.authorization.card) &&
            (value.authorization.descriptor == undefined || typeof value.authorization.descriptor == "string") &&
            (value.authorization.recurring == undefined ||
                exports.Authorization$1.Recurring.is(value.authorization.recurring)) &&
            [undefined, "verified", "unavailable", "rejected"].includes(value.authorization.verification) &&
            Array.isArray(value.authorization.history) &&
            value.authorization.history.every(exports.Authorization$1.History.is) &&
            typeof value.authorization.captured == "object" &&
            Array.isArray(value.authorization.captured.history) &&
            value.authorization.captured.history.every(Capture$1.is) &&
            (value.authorization.change == undefined ||
                (Array.isArray(value.authorization.change) &&
                    value.authorization.change.every(exports.Authorization$1.Change.is))) &&
            typeof value.authorization.captured.amount == "number" &&
            (value.authorization.captured.latest == undefined || index.DateTime.is(value.authorization.captured.latest)) &&
            (value.authorization.captured.auto == undefined || value.authorization.captured.auto == true) &&
            typeof value.authorization.refunded == "object" &&
            Array.isArray(value.authorization.refunded.history) &&
            value.authorization.refunded.history.every(Refund$1.is) &&
            typeof value.authorization.refunded.amount == "number" &&
            (value.authorization.refunded.latest == undefined || index.DateTime.is(value.authorization.refunded.latest)) &&
            typeof value.authorization.settled == "object" &&
            Array.isArray(value.authorization.settled.history) &&
            value.authorization.settled.history.every(index$2.Transaction.is) &&
            typeof value.authorization.settled.gross == "number" &&
            typeof value.authorization.settled.fee == "number" &&
            typeof value.authorization.settled.net == "number" &&
            (value.authorization.settled.latest == undefined || index.Date.is(value.authorization.settled.latest)) &&
            (value.authorization.voided == undefined || index.DateTime.is(value.authorization.voided)) &&
            Array.isArray(value.authorization.status) &&
            value.authorization.status.every(exports.Authorization$1.Status.is) &&
            index.DateTime.is(value.authorization.created) &&
            (value.authorization.category == undefined ||
                value.authorization.category == "purchase" ||
                value.authorization.category == "withdrawal"));
    }
    Authorization.is = is;
    function to(state) {
        var _a;
        return exports.Authorization$1.calculateStatus(clear({
            id: state.authorization.id,
            merchant: state.merchant.id,
            number: state.authorization.number,
            reference: state.authorization.reference,
            created: state.authorization.created,
            amount: state.authorization.amount,
            currency: state.authorization.currency,
            card: {
                ...state.authorization.card,
                expires: [
                    +state.authorization.card.expires.substr(5, 2),
                    +state.authorization.card.expires.substr(2, 2),
                ],
            },
            descriptor: state.authorization.descriptor,
            recurring: state.authorization.recurring,
            history: state.authorization.history,
            change: state.authorization.change,
            capture: state.authorization.captured.history,
            refund: state.authorization.refunded.history,
            void: state.authorization.voided,
            status: {},
            category: (_a = state.authorization.category) !== null && _a !== void 0 ? _a : "purchase",
        }));
    }
    Authorization.to = to;
    function from(authorization, merchant, statistics) {
        var _a;
        const result = {
            merchant: statistics && index.Merchant.is(merchant) ? Merchant.from(merchant, statistics) : { id: merchant.id },
            authorization: {
                id: authorization.id,
                amount: authorization.amount,
                currency: authorization.currency,
                card: Card.from(authorization.card),
                created: authorization.created,
                descriptor: authorization.descriptor,
                number: authorization.number,
                reference: typeof authorization.reference == "object" ? authorization.reference.network : authorization.reference,
                history: authorization.history,
                change: authorization.change,
                captured: toCaptured(authorization.capture, authorization.currency),
                refunded: toRefunded(authorization.refund, authorization.currency),
                settled: toSettled(authorization),
                voided: authorization.void,
                recurring: authorization.recurring,
                status: Object.entries(authorization.status)
                    .map(c => (c[1] ? c[0] : undefined))
                    .filter(exports.Authorization$1.Status.is),
                category: (_a = authorization.category) !== null && _a !== void 0 ? _a : "purchase",
            },
        };
        if (result.authorization.status.length < 1)
            result.authorization.status.push(authorization.void ? "cancelled" : "authorized");
        return result;
    }
    Authorization.from = from;
    function toCaptured(capture, currency) {
        const result = capture.reduce((r, c) => {
            r.amount += c.amount;
            r.latest = !r.latest || r.latest < c.created ? c.created : r.latest;
            if (c.auto)
                r.auto = true;
            return r;
        }, { history: capture, amount: 0 });
        result.amount = index.Currency.round(result.amount, currency);
        return result;
    }
    Authorization.toCaptured = toCaptured;
    function toRefunded(refund, currency) {
        const result = refund.reduce((r, c) => {
            r.amount += c.amount;
            r.latest = !r.latest || r.latest < c.created ? c.created : r.latest;
            return r;
        }, { history: refund, amount: 0 });
        result.amount = index.Currency.round(result.amount, currency);
        return result;
    }
    Authorization.toRefunded = toRefunded;
    function toSettled(authorization) {
        const result = [...authorization.capture, ...authorization.refund]
            .map(a => a.settlement)
            .filter(index$2.Transaction.is)
            .reduce((r, c) => {
            r.history.push(c);
            r.gross += c.gross;
            r.fee += typeof c.fee == "number" ? c.fee : c.fee.total;
            r.net += c.net;
            r.latest = !r.latest || r.latest < c.created ? c.created : r.latest;
            return r;
        }, { history: [], gross: 0, fee: 0, net: 0 });
        result.gross = index.Currency.round(result.gross, authorization.currency);
        result.fee = index.Currency.round(result.fee, authorization.currency);
        result.net = index.Currency.round(result.net, authorization.currency);
        return result;
    }
    Authorization.toSettled = toSettled;
    function toCsv(authorizations) {
        return exports.Authorization$1.toCsv(authorizations.map(to));
    }
    Authorization.toCsv = toCsv;
    Authorization.template = new index.dist.Type.Object({
        merchant: Merchant.template,
        authorization: new index.dist.Type.Object({
            id: new index.dist.Type.String(),
            number: new index.dist.Type.String(),
            reference: new index.dist.Type.String(),
            amount: new index.dist.Type.Number(),
            currency: new index.dist.Type.Union(index.Currency.types.map(c => new index.dist.Type.String(c))),
            card: Card.template,
            descriptor: new index.dist.Type.String(),
            recurring: Recurring.template,
            verification: new index.dist.Type.Union([
                new index.dist.Type.String("verified"),
                new index.dist.Type.String("unavailable"),
                new index.dist.Type.String("rejected"),
            ]),
            capture: new index.dist.Type.String("auto"),
            captured: new index.dist.Type.Object({
                amount: new index.dist.Type.Number(),
                latest: new index.dist.Type.String(),
                auto: new index.dist.Type.String("true"),
            }),
            refunded: new index.dist.Type.Object({
                amount: new index.dist.Type.Number(),
                latest: new index.dist.Type.String(),
            }),
            settled: new index.dist.Type.Object({
                gross: new index.dist.Type.Number(),
                fee: new index.dist.Type.Number(),
                net: new index.dist.Type.Number(),
                latest: new index.dist.Type.String(),
            }),
            voided: new index.dist.Type.String(),
            status: new index.dist.Type.Array([
                new index.dist.Type.Union([
                    new index.dist.Type.String("authorized"),
                    new index.dist.Type.String("cancelled"),
                    new index.dist.Type.String("captured"),
                    new index.dist.Type.String("refunded"),
                    new index.dist.Type.String("settled"),
                    new index.dist.Type.String("failed"),
                ]),
            ]),
            reason: new index.dist.Type.Array([new index.dist.Type.String()]),
            created: new index.dist.Type.String(),
            category: new index.dist.Type.Union([
                new index.dist.Type.String("purchase"),
                new index.dist.Type.String("withdrawal"),
            ]),
        }),
        today: new index.dist.Type.String(),
    });
})(exports.Authorization || (exports.Authorization = {}));

exports.FailedAuthorization = void 0;
(function (FailedAuthorization) {
    function is(value) {
        return (typeof value == "object" &&
            (Merchant.is(value.merchant) || (typeof value.merchant == "object" && Token.Identifier.is(value.merchant.id))) &&
            typeof value.authorization == "object" &&
            (value.authorization.id == undefined || typeof value.authorization.id == "string") &&
            typeof value.authorization.number == "string" &&
            (value.authorization.amount == undefined || typeof value.authorization.amount == "number") &&
            (value.authorization.currency == undefined || index.Currency.is(value.authorization.currency)) &&
            (value.authorization.card == undefined || Card.is(value.authorization.card)) &&
            (value.authorization.capture == undefined || value.authorization.capture == "auto") &&
            (value.authorization.descriptor == undefined || typeof value.authorization.descriptor == "string") &&
            (value.authorization.recurring == undefined || exports.Authorization$1.Recurring.is(value.authorization.recurring)) &&
            [undefined, "verified", "unavailable", "rejected"].includes(value.authorization.verification) &&
            Array.isArray(value.authorization.status) &&
            value.authorization.status.every((s) => s == "failed") &&
            typeof value.authorization.reason == "string" &&
            index.DateTime.is(value.authorization.created) &&
            Array.isArray(value.authorization.history) &&
            value.authorization.history.every(exports.Authorization$1.History.is) &&
            (value.authorization.category == undefined ||
                value.authorization.category == "purchase" ||
                value.authorization.category == "withdrawal"));
    }
    FailedAuthorization.is = is;
    function from(history) {
        const result = {
            merchant: { id: history[0].merchant },
            authorization: { status: ["failed"], created: "", reason: "unknown error", number: history[0].number, history },
        };
        for (const entry of history.sort((a, b) => (a.date > b.date ? 1 : -1))) {
            result.authorization.amount = "amount" in entry ? entry.amount : result.authorization.amount;
            result.authorization.currency = "currency" in entry ? entry.currency : result.authorization.currency;
            result.authorization.descriptor = "descriptor" in entry ? entry.descriptor : result.authorization.descriptor;
            result.authorization.card = "card" in entry && entry.card ? entry.card : result.authorization.card;
            result.authorization.recurring = "recurring" in entry ? entry.recurring : result.authorization.recurring;
            result.authorization.reason = "reason" in entry ? entry.reason : result.authorization.reason;
            result.authorization.created = entry.date;
            result.authorization.verification =
                "verification" in entry ? entry.verification : result.authorization.verification;
        }
        return clear(result);
    }
    FailedAuthorization.from = from;
    function load(histories) {
        var _a;
        const record = {};
        for (const history of histories)
            record[history.number] = [...((_a = record[history.number]) !== null && _a !== void 0 ? _a : []), history];
        return Object.values(record).map(from);
    }
    FailedAuthorization.load = load;
})(exports.FailedAuthorization || (exports.FailedAuthorization = {}));

var PostAuthorization;
(function (PostAuthorization) {
    function is(value) {
        return (typeof value == "object" &&
            Merchant.is(value.merchant) &&
            typeof value.amount == "number" &&
            typeof value.authorization == "object" &&
            typeof value.authorization.amount == "number" &&
            index.Currency.is(value.authorization.currency) &&
            Card.is(value.authorization.card) &&
            index.DateTime.is(value.authorization.created) &&
            (value.authorization.number == undefined || typeof value.authorization.number == "string") &&
            (value.authorization.captured == undefined ||
                (typeof value.authorization.captured == "object" &&
                    typeof value.authorization.captured.amount == "number" &&
                    index.DateTime.is(value.authorization.captured.latest))) &&
            (value.authorization.refunded == undefined ||
                (typeof value.authorization.refunded == "object" &&
                    typeof value.authorization.refunded.amount == "number" &&
                    index.DateTime.is(value.authorization.refunded.latest))) &&
            (value.authorization.voided == undefined || index.DateTime.is(value.authorization.voided)) &&
            (value.authorization.recurring == undefined ||
                ["initial", "subsequent"].includes(value.authorization.recurring)) &&
            (value.descriptor == undefined || typeof value.descriptor == "string") &&
            index.Date.is(value.now));
    }
    PostAuthorization.is = is;
    function from(authorization, creatable, merchant, statistics, rate) {
        var _a, _b;
        const factor = rate && merchant.currency != authorization.currency ? (_a = rate[authorization.currency]) !== null && _a !== void 0 ? _a : 1 : 1;
        return clear({
            merchant: Merchant.from(merchant, statistics),
            amount: index.Currency.round(creatable.amount * factor, merchant.currency),
            authorization: {
                amount: index.Currency.round(authorization.amount * factor, merchant.currency),
                currency: authorization.currency,
                card: Card.from(authorization.card),
                created: authorization.created,
                number: authorization.number,
                captured: fromHistory(authorization.capture),
                refunded: fromHistory(authorization.refund),
                voided: authorization.void,
                recurring: authorization.recurring == "initial" ? "initial" : (_b = authorization.recurring) === null || _b === void 0 ? void 0 : _b.type,
            },
            descriptor: authorization.descriptor,
            now: index.Date.now(),
        });
    }
    PostAuthorization.from = from;
    function fromHistory(history) {
        return history.length == 0
            ? undefined
            : history.reduce((r, c) => {
                return {
                    amount: r.amount + c.amount,
                    latest: r.latest < c.created ? c.created : r.latest,
                    auto: Capture$1.is(c) && c.auto ? c.auto : r.auto,
                };
            }, { amount: 0, latest: "" });
    }
})(PostAuthorization || (PostAuthorization = {}));

var PreAuthorization;
(function (PreAuthorization) {
    function is(value) {
        return (typeof value == "object" &&
            Merchant.is(value.merchant) &&
            typeof value.authorization == "object" &&
            typeof value.authorization.amount == "number" &&
            index.Currency.is(value.authorization.currency) &&
            Card.is(value.authorization.card) &&
            (value.authorization.card.csc == undefined || value.authorization.card.csc == "present") &&
            (value.authorization.capture == undefined || value.authorization.capture == "auto") &&
            (value.authorization.descriptor == undefined || typeof value.authorization.descriptor == "string") &&
            (value.authorization.number == undefined || typeof value.authorization.number == "string") &&
            (value.authorization.verification == undefined ||
                ["verified", "unavailable", "rejected"].includes(value.authorization.verification)) &&
            (value.authorization.recurring == undefined || exports.Authorization$1.Recurring.is(value.authorization.recurring)) &&
            typeof value.now == "string");
    }
    PreAuthorization.is = is;
    function from(authorization, merchant, statistics, verification, rate) {
        var _a;
        const factor = rate && merchant.currency != authorization.currency ? (_a = rate[authorization.currency]) !== null && _a !== void 0 ? _a : 1 : 1;
        return clear({
            merchant: Merchant.from(merchant, statistics),
            authorization: {
                amount: index.Currency.round(authorization.amount * factor, merchant.currency),
                currency: authorization.currency,
                card: Card.from(authorization.card),
                capture: authorization.capture,
                descriptor: authorization.descriptor,
                number: authorization.number,
                verification,
                recurring: authorization.recurring,
            },
            now: index.Date.now(),
        });
    }
    PreAuthorization.from = from;
})(PreAuthorization || (PreAuthorization = {}));

var Create;
(function (Create) {
    function isBase(value) {
        return (typeof value == "object" &&
            typeof value.merchant == "string" &&
            typeof value.number == "string" &&
            value.type == "create" &&
            index.DateTime.is(value.date));
    }
    function isFail(value) {
        return (typeof value == "object" &&
            (value.amount == undefined || typeof value.amount == "number") &&
            (value.currency == undefined || index.Currency.is(value.currency)) &&
            (value.card == undefined || Card.is(value.card)) &&
            (value.descriptor == undefined || typeof value.descriptor == "string") &&
            (value.verification == undefined || ["verified", "rejected", "unavailable"].includes(value.verification)) &&
            value.status == "fail" &&
            (value.rule == undefined || (Array.isArray(value.rule) && value.rule.every((r) => typeof r == "string"))) &&
            Error.Code.is(value.reason) &&
            ok.Error.is(value.error) &&
            (value.recurring == undefined || Recurring.is(value.recurring)) &&
            isBase(value));
    }
    Create.isFail = isFail;
    function isSuccess(value) {
        return (typeof value == "object" &&
            (value.verification == undefined || ["verified", "rejected", "unavailable"].includes(value.verification)) &&
            value.status == "success" &&
            isBase(value));
    }
    Create.isSuccess = isSuccess;
    function isPending(value) {
        return (typeof value == "object" &&
            value.status == "pending" &&
            Array.isArray(value.rule) &&
            value.rule.every((r) => typeof r == "string") &&
            value.reason == "verification required" &&
            (value.recurring == undefined || Recurring.is(value.recurring)) &&
            (value.amount == undefined || typeof value.amount == "number") &&
            (value.currency == undefined || index.Currency.is(value.currency)) &&
            (value.card == undefined || Card.is(value.card)) &&
            (value.descriptor == undefined || typeof value.descriptor == "string") &&
            isBase(value));
    }
    Create.isPending = isPending;
    function is(value) {
        return isFail(value) || isSuccess(value) || isPending(value);
    }
    Create.is = is;
    function create(state, input) {
        var _a, _b, _c;
        return {
            merchant: state.merchant.id,
            number: state.authorization.number,
            date: index.DateTime.now(),
            type: "create",
            ...(!ok.Error.is(input)
                ? { status: "success", verification: state.authorization.verification }
                : input.error != "verification required"
                    ? {
                        status: "fail",
                        ...state.authorization,
                        reason: Error.Code.is(input.error) ? input.error : "unknown error",
                        error: input,
                        rule: ok.FlawedContent.is(input) && input.error == "rule violation"
                            ? (_a = input.content.flaws) === null || _a === void 0 ? void 0 : _a.map(e => { var _a; return (_a = e.condition) !== null && _a !== void 0 ? _a : ""; })
                            : undefined,
                    }
                    : {
                        status: "pending",
                        ...state.authorization,
                        reason: input.error,
                        rule: ok.FlawedContent.is(input) ? (_c = (_b = input.content.flaws) === null || _b === void 0 ? void 0 : _b.map(e => { var _a; return (_a = e.condition) !== null && _a !== void 0 ? _a : ""; })) !== null && _c !== void 0 ? _c : [] : [],
                    }),
        };
    }
    Create.create = create;
})(Create || (Create = {}));

var Refund;
(function (Refund) {
    function isBase(value) {
        return (typeof value == "object" &&
            typeof value.merchant == "string" &&
            typeof value.number == "string" &&
            index.DateTime.is(value.date) &&
            value.type == "refund" &&
            typeof value.amount == "number" &&
            index.Currency.is(value.currency));
    }
    Refund.isBase = isBase;
    function isFail(value) {
        return (typeof value == "object" &&
            value.status == "fail" &&
            Error.Code.is(value.reason) &&
            ok.Error.is(value.error) &&
            isBase(value));
    }
    Refund.isFail = isFail;
    function isSuccess(value) {
        return typeof value == "object" && value.status == "success" && typeof value.reference == "string" && isBase(value);
    }
    Refund.isSuccess = isSuccess;
    function is(value) {
        return isFail(value) || isSuccess(value);
    }
    Refund.is = is;
    function create(merchant, authorization, amount, input) {
        var _a;
        return {
            merchant,
            type: "refund",
            date: index.DateTime.now(),
            number: authorization.number,
            currency: authorization.currency,
            amount,
            ...(ok.Error.is(input)
                ? { status: "fail", reason: Error.Code.is(input.error) ? input.error : "unknown error", error: input }
                : { status: "success", reference: (_a = input.reference) !== null && _a !== void 0 ? _a : "unknown reference" }),
        };
    }
    Refund.create = create;
})(Refund || (Refund = {}));

var Settlement;
(function (Settlement) {
    function is(value) {
        return (typeof value == "object" &&
            typeof value.merchant == "string" &&
            typeof value.number == "string" &&
            index.DateTime.is(value.date) &&
            value.type == "settlement" &&
            value.status == "settlement" &&
            typeof value.operation == "string" &&
            typeof value.reference == "string" &&
            index.Date.is(value.payout));
    }
    Settlement.is = is;
})(Settlement || (Settlement = {}));

const types = ["method", "challenge", "authorization", "postauthorization", "preauthorization"];
var Verification$1;
(function (Verification) {
    function isBase(value) {
        return (typeof value == "object" &&
            typeof value.merchant == "string" &&
            typeof value.number == "string" &&
            index.DateTime.is(value.date) &&
            value.type == "verification" &&
            ["fail", "success", "pending"].includes(value.status) &&
            ["preauthorization", "authorization", "postauthorization"].includes(value.step) &&
            typeof value.response == "object" &&
            Object.keys(value.response).every(k => types.includes(k)) &&
            (typeof value.items == "number" ||
                Item.Item.is(value.items) ||
                (Array.isArray(value.items) && value.items.every(Item.Item.is))) &&
            index.Currency.is(value.currency) &&
            (value.target == undefined || typeof value.target == "string") &&
            (value.browser == undefined || Item.Browser.is(value.browser)) &&
            (value.customer == undefined || Item.Contact.is(value.customer)) &&
            (value.contact == undefined || Item.Contact.is(value.contact)) &&
            (value.recurring == undefined || Recurring.is(value.recurring)));
    }
    function isFail(value) {
        return (typeof value == "object" &&
            value.status == "fail" &&
            Error.Code.is(value.reason) &&
            ok.Error.is(value.error) &&
            isBase(value));
    }
    Verification.isFail = isFail;
    function isSuccess(value) {
        return (typeof value == "object" &&
            value.status == "success" &&
            ["postauthorization", "authorization"].includes(value.step) &&
            isBase(value));
    }
    Verification.isSuccess = isSuccess;
    function isPending(value) {
        return (typeof value == "object" &&
            value.status == "pending" &&
            ["preauthorization", "authorization"].includes(value.step) &&
            isBase(value));
    }
    Verification.isPending = isPending;
    function is(value) {
        return isFail(value) || isSuccess(value) || isPending(value);
    }
    Verification.is = is;
    function create(merchant, creatable, step, response, input) {
        return {
            merchant,
            number: creatable.number,
            date: index.DateTime.now(),
            type: "verification",
            items: creatable.items,
            currency: creatable.currency,
            target: creatable.target,
            browser: creatable.browser,
            contact: creatable.contact,
            recurring: creatable.recurring,
            response,
            ...(!ok.Error.is(input)
                ? { status: "success", step: step }
                : input.error == "verification required"
                    ? { status: "pending", step: step }
                    : { status: "fail", step, reason: Error.Code.is(input.error) ? input.error : "unknown error", error: input }),
        };
    }
    Verification.create = create;
})(Verification$1 || (Verification$1 = {}));

var Void;
(function (Void) {
    function isBase(value) {
        return (typeof value == "object" &&
            typeof value.merchant == "string" &&
            typeof value.number == "string" &&
            index.DateTime.is(value.date) &&
            value.type == "void" &&
            ["fail", "success"].includes(value.status));
    }
    function isFail(value) {
        return (typeof value == "object" &&
            value.status == "fail" &&
            Error.Code.is(value.reason) &&
            ok.Error.is(value.error) &&
            isBase(value));
    }
    Void.isFail = isFail;
    function isSuccess(value) {
        return typeof value == "object" && value.status == "success" && isBase(value);
    }
    Void.isSuccess = isSuccess;
    function is(value) {
        return isFail(value) || isSuccess(value);
    }
    Void.is = is;
    function create(merchant, number, input) {
        return {
            merchant,
            number,
            date: index.DateTime.now(),
            type: "void",
            ...(ok.Error.is(input)
                ? { status: "fail", reason: Error.Code.is(input.error) ? input.error : "unknown error", error: input }
                : { status: "success" }),
        };
    }
    Void.create = create;
})(Void || (Void = {}));

var History;
(function (History) {
    function is(value) {
        return (Capture.is(value) ||
            Create.is(value) ||
            Refund.is(value) ||
            Settlement.is(value) ||
            Verification$1.is(value) ||
            Void.is(value));
    }
    History.is = is;
    History.capture = Capture.create;
    (function (Capture$1) {
        Capture$1.is = Capture.is;
    })(History.Capture || (History.Capture = {}));
    History.authorize = Create.create;
    (function (Create$1) {
        Create$1.is = Create.is;
    })(History.Create || (History.Create = {}));
    History.refund = Refund.create;
    (function (Refund$1) {
        Refund$1.is = Refund.is;
    })(History.Refund || (History.Refund = {}));
    (function (Settlement$1) {
        Settlement$1.is = Settlement.is;
    })(History.Settlement || (History.Settlement = {}));
    History.verify = Verification$1.create;
    (function (Verification) {
        Verification.is = Verification$1.is;
    })(History.Verification || (History.Verification = {}));
    History.cancel = Void.create;
    (function (Void$1) {
        Void$1.is = Void.is;
    })(History.Void || (History.Void = {}));
})(History || (History = {}));

var Creatable$1;
(function (Creatable) {
    function is(value) {
        return (typeof value == "object" &&
            Token.Identifier.is(value.id) &&
            (value.change == undefined || Change.Creatable.is(value.change)) &&
            (value.capture == undefined || Capture$1.Creatable.is(value.capture)) &&
            (value.refund == undefined || Refund$1.Creatable.is(value.refund)) &&
            (value.void == undefined || value.void == true));
    }
    Creatable.is = is;
})(Creatable$1 || (Creatable$1 = {}));

var Operation;
(function (Operation) {
    function is(value) {
        return (typeof value == "object" &&
            Token.Identifier.is(value.id) &&
            (value.change == undefined || Change.is(value.change) || ok.Error.is(value.change)) &&
            (value.capture == undefined || Capture$1.is(value.capture) || ok.Error.is(value.capture)) &&
            (value.refund == undefined || Refund$1.is(value.refund) || ok.Error.is(value.refund)) &&
            (value.void == undefined || index.DateTime.is(value.void) || ok.Error.is(value.void)));
    }
    Operation.is = is;
    (function (Creatable) {
        Creatable.is = Creatable$1.is;
    })(Operation.Creatable || (Operation.Creatable = {}));
})(Operation || (Operation = {}));

var Status;
(function (Status) {
    Status.types = ["authorized", "cancelled", "captured", "refunded", "settled"];
    function is(value) {
        return Status.types.some(v => v == value);
    }
    Status.is = is;
})(Status || (Status = {}));

exports.Authorization$1 = void 0;
(function (Authorization) {
    function is(value) {
        return (typeof value == "object" &&
            Token.Identifier.is(value.id, 16) &&
            Token.Identifier.is(value.merchant) &&
            typeof value.number == "string" &&
            (typeof value.reference == "string" ||
                (typeof value.reference == "object" && value.reference.network && value.reference.processor)) &&
            index.DateTime.is(value.created) &&
            typeof value.amount == "number" &&
            index.Currency.is(value.currency) &&
            index$1.Card.is(value.card) &&
            (value.descriptor == undefined || typeof value.descriptor == "string") &&
            (value.recurring == undefined || Recurring.is(value.recurring)) &&
            Array.isArray(value.history) &&
            value.history.every(History.is) &&
            (value.change == undefined || (Array.isArray(value.change) && value.change.every(Change.is))) &&
            Array.isArray(value.capture) &&
            value.capture.every(Capture$1.is) &&
            Array.isArray(value.refund) &&
            value.refund.every(Refund$1.is) &&
            (value.void == undefined || index.DateTime.is(value.void)) &&
            (value.category == undefined || value.category == "purchase" || value.category == "withdrawal"));
    }
    Authorization.is = is;
    function flaw(value) {
        return {
            type: "Authorization",
            flaws: typeof value != "object"
                ? undefined
                : [
                    Token.Identifier.is(value.id) || { property: "id", type: "authly.Identifier" },
                    Token.Identifier.is(value.merchant) || { property: "merchant", type: "authly.Identifier" },
                    value.number == undefined || typeof value.number == "string" || { property: "", type: "" },
                    typeof value.reference == "string" ||
                        (typeof value.reference == "object" && value.reference.network && value.reference.processor) || {
                        property: "reference",
                        type: `string | { network: string; processor: string }`,
                    },
                    index.DateTime.is(value.created) || { property: "created", type: "isoly.DateTime" },
                    typeof value.amount == "number" || { property: "amount", type: "number" },
                    index.Currency.is(value.currency) || { property: "currency", type: "isoly.Currency" },
                    value.descriptor == undefined ||
                        typeof value.descriptor == "string" || { property: "descriptor", type: "string | undefined" },
                    value.recurring == undefined ||
                        ["initial", "subsequent"].includes(value.recurring) || {
                        property: "recurring",
                        type: `"initial" | "subsequent" | undefined`,
                    },
                    (Array.isArray(value.history) && value.history.every(History.is)) || {
                        property: "history",
                        type: "Authorization.History[]",
                    },
                    value.change == undefined ||
                        (Array.isArray(value.change) && value.change.every(Change.is)) || {
                        property: "change",
                        type: "Authorization.Change[]",
                    },
                    (Array.isArray(value.capture) && value.capture.every(Capture$1.is)) || {
                        property: "capture",
                        type: "Capture[]",
                    },
                    (Array.isArray(value.refund) && value.refund.every(Refund$1.is)) || {
                        property: "refund",
                        type: "Refund[]",
                    },
                    value.void == undefined ||
                        index.DateTime.is(value.void) || { property: "void", type: "isoly.DateTime | undefined" },
                    value.category == undefined ||
                        value.category == "purchase" ||
                        value.category == "withdrawal" || {
                        property: "category",
                        type: `"purchase" | "withdrawal" | undefined`,
                    },
                ].filter(ok.Flaw.is),
        };
    }
    Authorization.flaw = flaw;
    function authorized(authorization) {
        var _a, _b;
        return index.Currency.round(authorization.amount + ((_b = (_a = authorization.change) === null || _a === void 0 ? void 0 : _a.reduce((total, change) => total + change.amount, 0)) !== null && _b !== void 0 ? _b : 0), authorization.currency);
    }
    Authorization.authorized = authorized;
    function captured(authorization) {
        return index.Currency.round(authorization.capture.reduce((total, capture) => total + (capture.status != "pending" ? capture.amount : 0), 0), authorization.currency);
    }
    Authorization.captured = captured;
    function refunded(authorization) {
        return index.Currency.round(authorization.refund.reduce((total, refund) => total + (refund.status != "pending" ? refund.amount : 0), 0), authorization.currency);
    }
    Authorization.refunded = refunded;
    function calculateStatus(authorization) {
        const capture = captured(authorization);
        const refund = refunded(authorization);
        const captureSettled = authorization.capture
            .filter(p => p.settlement)
            .reduce((r, p) => { var _a, _b; return r + Math.abs((_b = (_a = p.settlement) === null || _a === void 0 ? void 0 : _a.gross) !== null && _b !== void 0 ? _b : 0); }, 0);
        const refundSettled = authorization.refund
            .filter(p => p.settlement)
            .reduce((r, p) => { var _a, _b; return r + Math.abs((_b = (_a = p.settlement) === null || _a === void 0 ? void 0 : _a.gross) !== null && _b !== void 0 ? _b : 0); }, 0);
        const captureStatusSum = Math.max(capture - refund, 0) - Math.max(captureSettled - refundSettled, 0);
        const authorize = index.Currency.round(authorized(authorization) - capture, authorization.currency);
        const status = {
            authorized: !authorization.void ? authorize : 0,
            captured: index.Currency.round(Math.max(captureStatusSum, 0), authorization.currency),
            refunded: index.Currency.round(refund - refundSettled, authorization.currency),
            settled: index.Currency.round(Math.max(captureSettled, refundSettled) + Math.min(captureStatusSum, 0), authorization.currency),
            cancelled: authorization.void ? authorize : 0,
        };
        for (const key of Status.types)
            if (status[key] <= 0)
                delete status[key];
        if (Object.entries(status).length < 1)
            status[authorization.void ? "cancelled" : "authorized"] = 0;
        return { ...authorization, status };
    }
    Authorization.calculateStatus = calculateStatus;
    function toCsv(authorizations) {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        let result = "";
        result += "id,";
        result += "merchant,";
        result += "number,";
        result += "reference,";
        result += "created,";
        result += "category,";
        result += "amount,";
        result += "currency,";
        result += "card type,";
        result += "card scheme,";
        result += "card,";
        result += "card expires,";
        result += "descriptor,";
        result += "recurring,";
        result += "change,";
        result += "capture,";
        result += "refund,";
        result += "void,";
        result += "status";
        result += "\r\n";
        for (const value of authorizations) {
            result += `"${value.id}",`;
            result += `"${value.merchant}",`;
            result += `"${(_a = value.number) !== null && _a !== void 0 ? _a : ""}",`;
            result += `"${typeof value.reference == "object" ? value.reference.network : value.reference}",`;
            result += `"${value.created}",`;
            result += `"${(_b = value.category) !== null && _b !== void 0 ? _b : "purchase"}",`;
            result += `"${value.amount}",`;
            result += `"${value.currency}",`;
            result += `"${(_c = value.card.type) !== null && _c !== void 0 ? _c : "unknown"}",`;
            result += `"${value.card.scheme}",`;
            result += `"${value.card.iin + "**********" + value.card.last4}",`;
            result += `"${value.card.expires[0].toString().padStart(2, "0")}/${(2000 + value.card.expires[1]).toString()}",`;
            result += `"${(_d = value.descriptor) !== null && _d !== void 0 ? _d : ""}",`;
            result += `"${(_e = value.recurring) !== null && _e !== void 0 ? _e : ""}",`;
            result += `"${index.Currency.round((_g = (_f = value.change) === null || _f === void 0 ? void 0 : _f.reduce((r, h) => r + h.amount, 0)) !== null && _g !== void 0 ? _g : 0, value.currency)}",`;
            result += `"${captured(value)}",`;
            result += `"${refunded(value)}",`;
            result += `"${(_h = value.void) !== null && _h !== void 0 ? _h : ""}",`;
            result += `"${Object.keys(value.status).join(" ")}"`;
            result += "\r\n";
        }
        return result;
    }
    Authorization.toCsv = toCsv;
    Authorization.Creatable = Creatable$2;
    Authorization.History = History;
    (function (Change$1) {
        Change$1.is = Change.is;
        Change$1.flaw = Change.flaw;
        Change$1.Creatable = Change.Creatable;
    })(Authorization.Change || (Authorization.Change = {}));
    (function (Operation$1) {
        Operation$1.is = Operation.is;
        Operation$1.Creatable = Operation.Creatable;
    })(Authorization.Operation || (Authorization.Operation = {}));
    Authorization.Status = Status;
    (function (Recurring$1) {
        Recurring$1.is = Recurring.is;
        Recurring$1.template = Recurring.template;
    })(Authorization.Recurring || (Authorization.Recurring = {}));
})(exports.Authorization$1 || (exports.Authorization$1 = {}));

var Creatable;
(function (Creatable) {
    function is(value) {
        return (typeof value == "object" &&
            typeof value.number == "string" &&
            (typeof value.items == "number" ||
                Item.Item.is(value.items) ||
                (Array.isArray(value.items) && value.items.every(Item.Item.is))) &&
            (value.response == undefined ||
                (typeof value.response == "object" &&
                    ["method", "challenge", "pares"].includes(value.response.type) &&
                    typeof value.response.data == "string") ||
                (value.response.type == "method" &&
                    value.response.timeout == true &&
                    typeof value.response.ThreeDSServerTransID == "string")) &&
            (value.version == undefined || ["2.1.0", "2.2.0"].includes(value.version)) &&
            (value.browser == undefined || Item.Browser.is(value.browser)) &&
            index.Currency.is(value.currency) &&
            (index.Token.is(value.card) || index$1.Card.Creatable.is(value.card)) &&
            (value.recurring == undefined || exports.Authorization$1.Recurring.is(value.recurring)) &&
            (value.contact == undefined || Item.Contact.is(value.contact)) &&
            (value.target == undefined || typeof value.target == "string") &&
            (value.category == undefined || value.category == "purchase" || value.category == "withdrawal"));
    }
    Creatable.is = is;
    function flaw(value) {
        return {
            type: "Verification.Creatable",
            flaws: typeof value != "object"
                ? undefined
                : [
                    typeof value.number == "string" || { property: "number", type: "string" },
                    typeof value.items == "number" ||
                        Item.Item.is(value.items) ||
                        (Array.isArray(value.items) && value.items.every(Item.Item.is)) || {
                        property: "items",
                        type: "number | Item | Item[]",
                    },
                    value.response == undefined ||
                        (typeof value.response == "object" &&
                            ["method", "challenge", "pares"].includes(value.response.type) &&
                            typeof value.response.data == "string") ||
                        (value.response.type == "method" &&
                            value.response.timeout == true &&
                            typeof value.response.ThreeDSServerTransID == "string") || {
                        property: "response",
                        type: '{ type: "pares" | "method" | "challenge"; data: string } | { type: "method"; ThreeDSServerTransID: string; timeout: true }',
                    },
                    value.version == undefined ||
                        ["2.1.0", "2.2.0"].includes(value.version) || { property: "version", type: '"2.1.0" | "2.2.0"' },
                    value.browser == undefined ||
                        Item.Browser.is(value.browser) || { property: "browser", type: "base.Browser | undefined" },
                    index.Currency.is(value.currency) || { property: "currency", type: "isoly.Currency" },
                    index.Token.is(value.card) ||
                        index$1.Card.Creatable.is(value.card) || { property: "card", type: "Card.Creatable | authly.Token" },
                    value.recurring == undefined ||
                        ["initial", "subsequent"].includes(value.recurring) || {
                        property: "recurring",
                        type: '"initial" | "subsequent" | undefined',
                    },
                    value.contact == undefined || Item.Contact.is(value.contact) || Item.Contact.flaw(value.contact),
                    value.target == undefined ||
                        typeof value.target == "string" || { property: "target", type: "string | undefined" },
                    value.category == undefined ||
                        value.category == "purchase" ||
                        value.category == "withdrawal" || {
                        property: "category",
                        type: `"purchase" | "withdrawal" | undefined`,
                    },
                ].filter(ok.Flaw.is),
        };
    }
    Creatable.flaw = flaw;
})(Creatable || (Creatable = {}));

var Method;
(function (Method) {
    function is(value) {
        return (typeof value == "string" &&
            (value == "GET" ||
                value == "POST" ||
                value == "DELETE" ||
                value == "HEAD" ||
                value == "PATCH" ||
                value == "PUT" ||
                value == "OPTIONS" ||
                value == "TRACE" ||
                value == "CONNECT"));
    }
    Method.is = is;
    function parse(value) {
        value = value === null || value === void 0 ? void 0 : value.toUpperCase();
        return is(value) ? value : undefined;
    }
    Method.parse = parse;
})(Method || (Method = {}));

const parsers = {};
function add$1(parser, ...contentType) {
    contentType.forEach(t => (parsers[t] = parser));
}
function parse$1(request) {
    var _a;
    const contentType = request.headers.get("Content-Type");
    const type = contentType && contentType.split(";");
    const parser = parsers[(_a = type === null || type === void 0 ? void 0 : type[0]) !== null && _a !== void 0 ? _a : "plain/text"];
    return parser ? parser(request) : request.text();
}

const serializers = {};
function add(serializer, ...contentType) {
    contentType.forEach(t => (serializers[t] = serializer));
}
function serialize(body, contentType) {
    var _a;
    const serializer = serializers[(_a = contentType === null || contentType === void 0 ? void 0 : contentType.split(";")[0]) !== null && _a !== void 0 ? _a : ""];
    return serializer ? serializer(body, contentType) : body;
}

const fields$1 = [
    ["aIM", "A-IM", 1],
    ["accept", "Accept", 2],
    ["acceptCharset", "Accept-Charset", 2],
    ["acceptDatetime", "Accept-Datetime", 1],
    ["acceptEncoding", "Accept-Encoding", 2],
    ["acceptLanguage", "Accept-Language", 2],
    ["accessControlRequestMethod", "Access-Control-Request-Method", 1],
    ["accessControlRequestHeaders", "Access-Control-Request-Headers", 1],
    ["authorization", "Authorization", 1],
    ["cacheControl", "Cache-Control", 1],
    ["connection", "Connection", 1],
    ["contentLength", "Content-Length", 1],
    ["contentMD5", "Content-MD5", 1],
    ["contentType", "Content-Type", 1],
    ["cookie", "Cookie", 1],
    ["date", "Date", 1],
    ["expect", "Expect", 1],
    ["forwarded", "Forwarded", 1],
    ["from", "From", 1],
    ["host", "Host", 1],
    ["http2Settings", "HTTP2-Settings", 1],
    ["ifMatch", "If-Match", 2],
    ["ifModifiedSince", "If-Modified-Since", 1],
    ["ifNoneMatch", "If-None-Match", 2],
    ["ifRange", "If-Range", 1],
    ["ifUnmodifiedSince", "If-Unmodified-Since", 1],
    ["maxForwards", "Max-Forwards", 1],
    ["origin", "Origin", 1],
    ["pragma", "Pragma", 1],
    ["proxyAuthorization", "Proxy-Authorization", 1],
    ["range", "Range", 1],
    ["referer", "Referer", 1],
    ["te", "TE", 2],
    ["trailer", "Trailer", 1],
    ["transferEncoding", "Transfer-Encoding", 1],
    ["userAgent", "User-Agent", 1],
    ["upgrade", "Upgrade", 2],
    ["via", "Via", 2],
    ["warning", "Warning", 1],
    ["upgradeInsecureRequests", "Upgrade-Insecure-Requests", 1],
    ["xRequestedWith", "X-Requested-With", 1],
    ["dnt", "DNT", 1],
    ["xForwardedFor", "X-Forwarded-For", 1],
    ["xForwardedHost", "X-Forwarded-Host", 1],
    ["xForwardedProto", "X-Forwarded-Proto", 1],
    ["frontEndHttps", "Front-End-Https", 1],
    ["xHttpMethodOverride", "X-Http-Method-Override", 1],
    ["xAttDeviceId", "X-ATT-DeviceId", 1],
    ["xWapProfile", "X-Wap-Profile", 1],
    ["proxyConnection", "Proxy-Connection", 1],
    ["xCsrfToken", "X-Csrf-Token", 1],
    ["xCorrelationID", "X-Correlation-ID", 1],
    ["saveData", "Save-Data", 1],
];
var Header$1;
(function (Header) {
    function is(value) {
        function isString(value) {
            return value == undefined || typeof value == "string";
        }
        function isStringArray(value) {
            return value == undefined || (Array.isArray(value) && value.every(v => typeof v == "string"));
        }
        return typeof value == "object" && fields$1.every(field => (field[2] == 1 ? isString : isStringArray)(value[field[0]]));
    }
    Header.is = is;
    function to(header) {
        return Object.fromEntries(fields$1
            .map(([property, field, count]) => [field, header[property]])
            .filter(([field, value]) => value)
            .map(([field, value]) => [field, Array.isArray(value) ? value.join(", ") : value]));
    }
    Header.to = to;
    function from(headers) {
        const entries = Array.isArray(headers)
            ? headers.map(([field, ...value]) => [field, value.join(", ")])
            : isHeaders(headers)
                ? [...headers]
                : Object.entries(headers);
        const data = Object.fromEntries(entries.map(([field, value]) => [field.toLowerCase(), value]));
        return Object.fromEntries(fields$1.map(field => [field[0], data[field[1].toLowerCase()], field[2]]).filter(field => field[1]).map(field => [
            field[0],
            field[2] == 1 || typeof field[1] != "string" ? field[1] : field[1].split(",").map(v => v.trim())
        ]));
    }
    Header.from = from;
    function isHeaders(value) {
        return typeof value.entries == "function";
    }
})(Header$1 || (Header$1 = {}));

/// <reference lib="webworker.iterable" />
var Request;
(function (Request) {
    function is(value) {
        return (typeof value == "object" &&
            Object.keys(value).every(key => ["method", "url", "parameter", "search", "remote", "header", "body"].some(k => k == key)) &&
            Method.is(value.method) &&
            value.url instanceof URL &&
            typeof value.parameter == "object" &&
            Object.entries(value.parameter).every(([parameter, value]) => typeof parameter == "string" && typeof value == "string") &&
            typeof value.search == "object" &&
            Object.entries(value.search).every(([key, value]) => typeof key == "string" && typeof value == "string") &&
            (value.remote == undefined || typeof value.remote == "string") &&
            (value.header == undefined || Header$1.is(value.header)));
    }
    Request.is = is;
    async function to(request) {
        const r = is(request) ? request : create(request);
        return new globalThis.Request(r.url.toString(), {
            method: r.method,
            headers: Header$1.to(r.header),
            body: ["GET", "HEAD"].some(v => v == r.method)
                ? undefined
                : await serialize(await r.body, r.header.contentType),
        });
    }
    Request.to = to;
    function from(request) {
        var _a;
        const url = new URL(request.url);
        return {
            method: (_a = Method.parse(request.method)) !== null && _a !== void 0 ? _a : "GET",
            url,
            header: Header$1.from(request.headers),
            parameter: {},
            search: Object.fromEntries(url.searchParams.entries()),
            body: parse$1(request),
        };
    }
    Request.from = from;
    function create(request) {
        var _a, _b, _c;
        let result;
        if (typeof request == "string")
            result = create({ url: request });
        else {
            const url = typeof request.url == "string" ? new URL(request.url) : request.url;
            result = {
                method: (_a = Method.parse(request.method)) !== null && _a !== void 0 ? _a : "GET",
                url,
                parameter: (_b = request.parameter) !== null && _b !== void 0 ? _b : {},
                search: { ...request.search, ...Object.fromEntries(url.searchParams.entries()) },
                remote: request.remote,
                header: (_c = request.header) !== null && _c !== void 0 ? _c : {},
                body: request.body,
            };
        }
        return result;
    }
    Request.create = create;
    (function (Header) {
        Header.is = Header$1.is;
        Header.from = Header$1.from;
        Header.to = Header$1.to;
    })(Request.Header || (Request.Header = {}));
    (function (Method$1) {
        Method$1.is = Method.is;
        Method$1.parse = Method.parse;
    })(Request.Method || (Request.Method = {}));
})(Request || (Request = {}));

const fields = [
    ["accessControlAllowOrigin", "Access-Control-Allow-Origin", 1],
    ["accessControlAllowCredentials", "Access-Control-Allow-Credentials", 1],
    ["accessControlExposeHeaders", "Access-Control-Expose-Headers", 2],
    ["accessControlMaxAge", "Access-Control-Max-Age", 1],
    ["accessControlAllowMethods", "Access-Control-Allow-Methods", 2],
    ["accessControlAllowHeaders", "Access-Control-Allow-Headers", 2],
    ["acceptPatch", "Accept-Patch", 1],
    ["acceptRanges", "Accept-Ranges", 1],
    ["age", "Age", 1],
    ["allow", "Allow", 2],
    ["altSvc", "Alt-Svc", 1],
    ["cacheControl", "Cache-Control", 1],
    ["connection", "Connection", 1],
    ["contentDisposition", "Content-Disposition", 1],
    ["contentEncoding", "Content-Encoding", 1],
    ["contentLanguage", "Content-Language", 2],
    ["contentLength", "Content-Length", 1],
    ["contentLocation", "Content-Location", 1],
    ["contentMD5", "Content-MD5", 1],
    ["contentRange", "Content-Range", 1],
    ["contentSecurityPolicy", "Content-Security-Policy", 1],
    ["contentType", "Content-Type", 1],
    ["date", "Date", 1],
    ["deltaBase", "Delta-Base", 1],
    ["eTag", "ETag", 1],
    ["expires", "Expires", 1],
    ["iM", "IM", 1],
    ["lastModified", "Last-Modified", 1],
    ["link", "Link", 1],
    ["location", "Location", 1],
    ["p3P", "P3P", 1],
    ["pragma", "Pragma", 1],
    ["proxyAuthenticate", "Proxy-Authenticate", 1],
    ["publicKeyPins", "Public-Key-Pins", 1],
    ["refresh", "Refresh", 1],
    ["retryAfter", "Retry-After", 1],
    ["server", "Server", 1],
    ["setCookie", "Set-Cookie", 1],
    ["status", "Status", 1],
    ["strictTransportSecurity", "Strict-Transport-Security", 1],
    ["timingAllowOrigin", "Timing-Allow-Origin", 2],
    ["trailer", "Trailer", 1],
    ["transferEncoding", "Transfer-Encoding", 1],
    ["tk", "Tk", 1],
    ["upgrade", "Upgrade", 2],
    ["vary", "Vary", 2],
    ["via", "Via", 1],
    ["warning", "Warning", 1],
    ["wwwAuthenticate", "WWW-Authenticate", 1],
    ["xContentDuration", "X-Content-Duration", 1],
    ["xContentSecurityPolicy", "X-Content-Security-Policy", 1],
    ["xContentTypeOptions", "X-Content-Type-Options", 1],
    ["xCorrelationId", "X-Correlation-ID", 1],
    ["xFrameOptions", "X-Frame-Options", 1],
    ["xPoweredBy", "X-Powered-By", 1],
    ["xRequestId", "X-Request-ID", 1],
    ["xUACompatible", "X-UA-Compatible", 1],
    ["xWebkitCsp", "X-WebKit-CSP", 1],
    ["xXssProtection", "X-XSS-Protection", 1],
];
var Header;
(function (Header) {
    function is(value) {
        function isString(value) {
            return value == undefined || typeof value == "string";
        }
        function isStringArray(value) {
            return value == undefined || (Array.isArray(value) && value.every(v => typeof v == "string"));
        }
        return typeof value == "object" && fields.every(field => (field[2] == 1 ? isString : isStringArray)(value[field[0]]));
    }
    Header.is = is;
    function to(header) {
        return Object.fromEntries(fields
            .map(([property, field, count]) => [field, header[property]])
            .filter(([field, value]) => value)
            .map(([field, value]) => [field, Array.isArray(value) ? value.join(", ") : value]));
    }
    Header.to = to;
    function from(headers) {
        const entries = Array.isArray(headers)
            ? headers.map(([field, ...value]) => [field, value.join(", ")])
            : isHeaders(headers)
                ? getEntries(headers)
                : Object.entries(headers);
        const data = Object.fromEntries(entries.map(([field, value]) => [field.toLowerCase(), value]));
        return Object.fromEntries(fields.map(field => [field[0], data[field[1].toLowerCase()], field[2]]).filter(field => field[1]).map(field => [
            field[0],
            field[2] == 1 || typeof field[1] != "string" ? field[1] : field[1].split(",").map(v => v.trim())
        ]));
    }
    Header.from = from;
    function isHeaders(value) {
        return typeof value.forEach == "function";
    }
    function getEntries(headers) {
        const result = [];
        headers.forEach((value, key) => result.push([key, value]));
        return result;
    }
})(Header || (Header = {}));

var Like;
(function (Like) {
    function is(value) {
        return (typeof value == "object" &&
            Object.keys(value).every(key => ["status", "header", "body"].some(property => property == key)) &&
            (value.status == undefined || typeof value.status == "number") &&
            (value.header == undefined || Header.is(value.header)) &&
            (value.status || value.header || value.body));
    }
    Like.is = is;
})(Like || (Like = {}));

var Response;
(function (Response) {
    function is(value) {
        return (typeof value == "object" &&
            Object.keys(value).every(key => ["status", "header", "body"].some(k => k == key)) &&
            (value.status == undefined || typeof value.status == "number") &&
            (value.header == undefined || Header.is(value.header)));
    }
    Response.is = is;
    async function to(request) {
        return new globalThis.Response(await serialize(await request.body, request.header.contentType), {
            status: request.status,
            headers: new globalThis.Headers(Header.to(request.header)),
        });
    }
    Response.to = to;
    function from(response) {
        return {
            status: response.status,
            header: Header.from(response.headers),
            body: parse$1(response),
        };
    }
    Response.from = from;
    function create(response, contentType) {
        const result = Like.is(response)
            ? { status: 200, header: {}, body: "", ...response }
            : {
                status: (typeof response == "object" && typeof response.status == "number" && response.status) || 200,
                header: (response.status == 301 || response.status == 302) && response.location
                    ? { location: response.location }
                    : {},
                body: response,
            };
        if (!result.header.contentType)
            switch (typeof result.body) {
                default:
                case "object":
                    result.header.contentType = contentType !== null && contentType !== void 0 ? contentType : "application/json; charset=utf-8";
                    break;
                case "string":
                    result.header.contentType =
                        result.body.slice(0, 9).toLowerCase() == "<!doctype"
                            ? "text/html; charset=utf-8"
                            : /^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/.test(result.body)
                                ? "application/jwt; charset=utf-8"
                                : "text/plain; charset=utf-8";
                    break;
            }
        return result;
    }
    Response.create = create;
    (function (Header$1) {
        Header$1.to = Header.to;
        Header$1.from = Header.from;
    })(Response.Header || (Response.Header = {}));
})(Response || (Response = {}));

const fetch = create(globalThis.fetch);
fetch.create = create;
function create(fetch) {
    return async (request) => {
        const r = Request.create(request);
        return Response.from(await fetch(r.url.toString(), await Request.to(r)));
    };
}

function stringify(data) {
    const result = [];
    const map = (key, value) => {
        switch (typeof value) {
            default:
            case "bigint":
            case "boolean":
            case "number":
            case "string":
                result.push(`${key}=${encodeURIComponent(value.toString())}`);
                break;
            case "undefined":
                break;
            case "object":
                for (const property in value)
                    if (Object.prototype.hasOwnProperty.call(value, property))
                        map(key ? key + `[${property}]` : property, value[property]);
                break;
        }
    };
    map("", data);
    return result.join("&");
}
function parse(data) {
    const insert = (target, key, value) => {
        var _a;
        target[key[0]] = key.length > 1 ? insert((_a = target[key[0]]) !== null && _a !== void 0 ? _a : {}, key.slice(1), value) : value;
        return target;
    };
    const entries = data.split("&").map(d => d.split("=", 2)).map(([k, v]) => [k.split("[").map(p => p.replace("]", "")), decodeURIComponent(v)]);
    return entries.reduce((result, [key, value]) => insert(result, key, value), {});
}

add$1(async (request) => await request.text(), "text/plain", "text/html");
add$1(async (request) => await request.json(), "application/json");
add$1(async (request) => Object.fromEntries((await request.formData()).entries()), "multipart/form-data");
add$1(async (request) => parse(await request.text()), "application/x-www-form-urlencoded");
add(async (body) => (typeof body == "string" ? body : body.toString()), "text/plain", "text/html");
add(async (body) => JSON.stringify(body), "application/json");
add(async (body) => stringify(body), "application/x-www-form-urlencoded");

var Pares;
(function (Pares) {
    function is(value) {
        return (typeof value == "object" &&
            typeof value.cavv == "string" &&
            typeof value.xid == "string" &&
            ["0", "1", "2", "5", "6", "7"].includes(value.eci) &&
            ["Y", "U", "A", "N"].includes(value.status));
    }
    Pares.is = is;
    function fromEci(eci) {
        let result;
        switch (eci) {
            case "2":
            case "5":
                result = "Y";
                break;
            case "6":
            case "1":
                result = "A";
                break;
            case "0":
            case "7":
                result = "N";
                break;
            default:
                result = undefined;
        }
        return result;
    }
    Pares.fromEci = fromEci;
    async function check(configuration, pares) {
        var _a;
        const response = !configuration
            ? Error.unauthorized()
            : typeof pares != "string"
                ? { body: { pares } }
                : pares.startsWith("eyJhbW91bnQ")
                    ? { body: unpackSimulated(pares) }
                    : await fetch({
                        url: configuration.url + "/check",
                        method: "POST",
                        header: {
                            contentType: "application/x-www-form-urlencoded",
                            authorization: `Basic ${Token.encode(configuration.key + ":", "standard", "=")}`,
                        },
                        body: { pares },
                    })
                        .catch(_ => undefined);
        const result = !response ? Error.unavailable() : await response.body;
        if (typeof result == "object")
            result.status = (_a = result.status) !== null && _a !== void 0 ? _a : fromEci(result.eci);
        return ok.Error.is(result) || is(result)
            ? result
            : Error.malformedContent("3ds problem", "verification", "Pares", "Cannot unpack pares.");
    }
    Pares.check = check;
    function unpackSimulated(pares) {
        let result;
        try {
            result = JSON.parse(new TextDecoder.TextDecoder().decode(Token.decode(pares, "url")));
            if ((result === null || result === void 0 ? void 0 : result.cavv) == "")
                result.cavv = "123456789012345678901234";
        }
        catch (_) {
            result = undefined;
        }
        return result;
    }
})(Pares || (Pares = {}));

var Verification;
(function (Verification) {
    function is(value) {
        return (typeof value == "object" &&
            value &&
            ((value.type == "pares" && Pares.is(value.data)) ||
                (["method", "challenge"].includes(value.type) &&
                    typeof value.data == "object" &&
                    typeof value.data.authentication == "string" &&
                    ["A", "N", "U", "Y", "C", "R"].includes(value.data.status) &&
                    typeof value.data.reference == "object" &&
                    typeof value.data.reference.server == "string" &&
                    typeof value.data.reference.directory == "string" &&
                    (value.data.reference.access == undefined || typeof value.data.reference.access == "string"))));
    }
    Verification.is = is;
    (function (Creatable$1) {
        Creatable$1.is = Creatable.is;
        Creatable$1.flaw = Creatable.flaw;
    })(Verification.Creatable || (Verification.Creatable = {}));
    (function (Pares$1) {
        Pares$1.is = Pares.is;
        Pares$1.check = Pares.check;
        Pares$1.fromEci = Pares.fromEci;
    })(Verification.Pares || (Verification.Pares = {}));
})(Verification || (Verification = {}));

var Description;
(function (Description) {
    function is(value) {
        return (typeof value == "object" &&
            value != null &&
            (value.arguments == undefined ||
                (typeof value.arguments == "object" &&
                    Object.entries(value.arguments).every(k => typeof k[0] == "string" && typeof k[1] == "string"))) &&
            (value.example == undefined ||
                (typeof value.example == "object" &&
                    Object.entries(value.example).every(k => typeof k[0] == "string" && typeof k[1] == "string"))) &&
            (value.summary == undefined || typeof value.summary == "string"));
    }
    Description.is = is;
})(Description || (Description = {}));

var Detail;
(function (Detail) {
    function is(value) {
        return (typeof value == "object" &&
            value != null &&
            (value.description == undefined || Description.is(value.description)) &&
            typeof value.definition == "string" &&
            Array.isArray(value.arguments) &&
            value.arguments.every((v) => typeof v == "string"));
    }
    Detail.is = is;
    (function (Descripton) {
        Descripton.is = Description.is;
    })(Detail.Descripton || (Detail.Descripton = {}));
})(Detail || (Detail = {}));

var Functions;
(function (Functions) {
    function is(value) {
        return (typeof value == "object" &&
            value != null &&
            Object.keys(value).every(v => /[A-Za-z][A-Za-z0-9_]*/.test(v)) &&
            Object.values(value).every(Detail.is));
    }
    Functions.is = is;
    (function (Detail$1) {
        Detail$1.is = Detail.is;
        (function (Description) {
            Description.is = Detail.Descripton.is;
        })(Detail$1.Description || (Detail$1.Description = {}));
    })(Functions.Detail || (Functions.Detail = {}));
})(Functions || (Functions = {}));

function clear(value) {
    for (const entry of Object.entries(value)) {
        if (entry[1] == undefined)
            delete value[entry[0]];
        else if (typeof entry[1] == "object")
            value[entry[0]] = clear(entry[1]);
    }
    return value;
}
