'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const core = require('./core-906e2cc9.js');
const _commonjsHelpers = require('./_commonjsHelpers-72d386ba.js');
const index = require('./index-da2f731d.js');

var crypto_browser = _commonjsHelpers.createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.crypto = window.crypto;

});

_commonjsHelpers.unwrapExports(crypto_browser);

var TextEncoder_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
class TextEncoder {
    constructor() {
        this.encoding = "utf-8";
    }
    encode(data) {
        return Uint8Array.from(unescape(encodeURIComponent(data)).split(""), c => c.charCodeAt(0));
    }
}
exports.TextEncoder = TextEncoder;

});

_commonjsHelpers.unwrapExports(TextEncoder_1);

var Base64 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });

const tables = {
    standard: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
    url: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
};
function encode(value, standard = "standard", padding = "") {
    if (typeof (value) == "string")
        value = new TextEncoder_1.TextEncoder().encode(value);
    const table = tables[standard];
    const result = [];
    for (let c = 0; c < value.length; c += 3) {
        const c0 = value[c];
        const c1 = c + 1 < value.length ? value[c + 1] : 0;
        const c2 = c + 2 < value.length ? value[c + 2] : 0;
        result.push(table[c0 >>> 2]);
        result.push(table[(c0 & 3) << 4 | (c1 >>> 4)]);
        result.push(table[((c1 & 15) << 2) | (c2 >>> 6)]);
        result.push(table[c2 & 63]);
    }
    const length = Math.ceil(value.length / 3 * 4);
    return result.join("").substr(0, length) + padding.repeat(result.length - length);
}
exports.encode = encode;
function decode(value, standard = "standard") {
    while (value.endsWith("=") && value.length > 0)
        value = value.substr(0, value.length - 1);
    const table = tables[standard];
    const data = value.split("").map(c => table.indexOf(c));
    const result = new Uint8Array(Math.floor(data.length / 4 * 3));
    for (let c = 0; c < result.length; c += 3) {
        const d0 = data.shift() || 0;
        const d1 = data.shift() || 0;
        const d2 = data.shift() || 0;
        const d3 = data.shift() || 0;
        result[c] = (d0 << 2) | (d1 >>> 4);
        result[c + 1] = ((d1 & 15) << 4) | (d2 >>> 2);
        result[c + 2] = ((d2 & 3) << 6) | d3;
    }
    return result;
}
exports.decode = decode;

});

_commonjsHelpers.unwrapExports(Base64);

var TextDecoder_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
class TextDecoder {
    constructor() {
        this.encoding = "utf-8";
    }
    decode(view, options) {
        return !view ? "" : decodeURIComponent(escape(Array.from(new Uint8Array(view.buffer, view.byteOffset, view.byteLength), c => String.fromCharCode(c)).join("")));
    }
}
exports.TextDecoder = TextDecoder;

});

_commonjsHelpers.unwrapExports(TextDecoder_1);

var PropertyCrypto_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
var __awaiter = (_commonjsHelpers.commonjsGlobal && _commonjsHelpers.commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });




class PropertyCrypto {
    constructor(secret, ...properties) {
        this.secret = secret;
        this.encoder = new TextEncoder_1.TextEncoder();
        this.decoder = new TextDecoder_1.TextDecoder();
        this.properties = properties.map(p => p.split("."));
    }
    encrypt(payload) {
        return this.process(payload, value => this.encoder.encode(JSON.stringify(value)), value => Base64.encode(value, "url"));
    }
    decrypt(payload) {
        return this.process(payload, value => typeof (value) == "string" ? Base64.decode(value, "url") : new Uint8Array(), value => JSON.parse(this.decoder.decode(value)));
    }
    process(payload, preprocess, postprocess) {
        return __awaiter(this, void 0, void 0, function* () {
            const secret = this.secret + payload.sub + payload.iat;
            for (const property of this.properties)
                payload = yield this.processProperty(payload, property, secret + property.join("."), preprocess, postprocess);
            return payload;
        });
    }
    processProperty(payload, property, secret, preprocess, postprocess) {
        return __awaiter(this, void 0, void 0, function* () {
            const result = Object.assign({}, payload);
            if (result[property[0]])
                if (property.length == 1) {
                    const data = preprocess(payload[property[0]]);
                    const key = new Uint8Array(yield crypto_browser.crypto.subtle.digest("SHA-512", this.encoder.encode(secret)));
                    const processed = new Uint8Array(data.length);
                    for (let index = 0; index < data.length; index++)
                        processed[index] = data[index] ^ key[index];
                    result[property[0]] = postprocess(processed);
                }
                else
                    result[property[0]] = yield this.processProperty(result[property[0]], property.slice(1), secret, preprocess, postprocess);
            return result;
        });
    }
    static create(secret, ...properties) {
        return secret && new PropertyCrypto(secret, ...properties) || undefined;
    }
}
exports.PropertyCrypto = PropertyCrypto;

});

_commonjsHelpers.unwrapExports(PropertyCrypto_1);

var Actor_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });

class Actor {
    constructor(id) {
        this.id = id;
        this.cryptos = [];
    }
    add(secret, ...properties) {
        const crypto = PropertyCrypto_1.PropertyCrypto.create(secret, ...properties);
        if (crypto)
            this.cryptos.push(crypto);
        return this;
    }
}
exports.Actor = Actor;

});

_commonjsHelpers.unwrapExports(Actor_1);

var Symmetric_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
var Symmetric;
(function (Symmetric) {
    function is(value) {
        return value == "HS256" ||
            value == "HS384" ||
            value == "HS512";
    }
    Symmetric.is = is;
})(Symmetric = exports.Symmetric || (exports.Symmetric = {}));

});

_commonjsHelpers.unwrapExports(Symmetric_1);

var Asymmetric_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
var Asymmetric;
(function (Asymmetric) {
    function is(value) {
        return value == "RS256" ||
            value == "RS384" ||
            value == "RS512" ||
            value == "ES256" ||
            value == "ES384" ||
            value == "ES512" ||
            value == "PS256" ||
            value == "PS384" ||
            value == "PS512";
    }
    Asymmetric.is = is;
})(Asymmetric = exports.Asymmetric || (exports.Asymmetric = {}));

});

_commonjsHelpers.unwrapExports(Asymmetric_1);

var Name_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });


var Name;
(function (Name) {
    function is(value) {
        return value == "none" || Symmetric_1.Symmetric.is(value) || Asymmetric_1.Asymmetric.is(value);
    }
    Name.is = is;
    let Symmetric;
    (function (Symmetric) {
        Symmetric.is = Symmetric_1.Symmetric.is;
    })(Symmetric = Name.Symmetric || (Name.Symmetric = {}));
    let Asymmetric;
    (function (Asymmetric) {
        Asymmetric.is = Asymmetric_1.Asymmetric.is;
    })(Asymmetric = Name.Asymmetric || (Name.Asymmetric = {}));
})(Name = exports.Name || (exports.Name = {}));

});

_commonjsHelpers.unwrapExports(Name_1);

var Algorithm_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
var __awaiter = (_commonjsHelpers.commonjsGlobal && _commonjsHelpers.commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });



class Algorithm {
    sign(data) {
        return __awaiter(this, void 0, void 0, function* () {
            return typeof (data) == "string" ? Base64.encode(yield this.signBinary(new TextEncoder_1.TextEncoder().encode(data)), "url") : this.signBinary(data);
        });
    }
    verify(data, signature) {
        if (typeof (signature) == "string")
            signature = Base64.decode(signature, "url");
        return typeof (data) == "string" ? this.verifyBinary(new TextEncoder_1.TextEncoder().encode(data), signature) : this.verifyBinary(data, signature);
    }
    static create(name, publicKey, privateKey) {
        const create = algorithms[name];
        return create && create([publicKey, privateKey]);
    }
    static none() {
        return Algorithm.create("none");
    }
    static HS256(key) {
        return Algorithm.create("HS256", key);
    }
    static HS384(key) {
        return Algorithm.create("HS384", key);
    }
    static HS512(key) {
        return Algorithm.create("HS512", key);
    }
    static RS256(publicKey, privateKey) {
        return Algorithm.create("RS256", publicKey, privateKey);
    }
    static RS384(publicKey, privateKey) {
        return Algorithm.create("RS384", publicKey, privateKey);
    }
    static RS512(publicKey, privateKey) {
        return Algorithm.create("RS512", publicKey, privateKey);
    }
    static ES256(publicKey, privateKey) {
        return Algorithm.create("ES256", publicKey, privateKey);
    }
    static ES384(publicKey, privateKey) {
        return Algorithm.create("ES384", publicKey, privateKey);
    }
    static ES512(publicKey, privateKey) {
        return Algorithm.create("ES512", publicKey, privateKey);
    }
    static PS256(publicKey, privateKey) {
        return Algorithm.create("PS256", publicKey, privateKey);
    }
    static PS384(publicKey, privateKey) {
        return Algorithm.create("PS384", publicKey, privateKey);
    }
    static PS512(publicKey, privateKey) {
        return Algorithm.create("PS512", publicKey, privateKey);
    }
}
exports.Algorithm = Algorithm;
const algorithms = {};
function register(name, create) {
    algorithms[name] = create;
}
exports.register = register;
(function (Algorithm) {
    let Name;
    (function (Name) {
        Name.is = Name_1.Name.is;
        let Symmetric;
        (function (Symmetric) {
            Symmetric.is = Name_1.Name.Symmetric.is;
        })(Symmetric = Name.Symmetric || (Name.Symmetric = {}));
        let Asymmetric;
        (function (Asymmetric) {
            Asymmetric.is = Name_1.Name.Asymmetric.is;
        })(Asymmetric = Name.Asymmetric || (Name.Asymmetric = {}));
    })(Name = Algorithm.Name || (Algorithm.Name = {}));
})(Algorithm = exports.Algorithm || (exports.Algorithm = {}));

});

_commonjsHelpers.unwrapExports(Algorithm_1);

var Symmetric_1$1 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
var __awaiter = (_commonjsHelpers.commonjsGlobal && _commonjsHelpers.commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });


class Symmetric extends Algorithm_1.Algorithm {
    verifyBinary(data, signature) {
        return __awaiter(this, void 0, void 0, function* () {
            return Base64.encode(yield this.signBinary(data), "url") == Base64.encode(signature, "url");
        });
    }
}
exports.Symmetric = Symmetric;

});

_commonjsHelpers.unwrapExports(Symmetric_1$1);

var None_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });


class None extends Symmetric_1$1.Symmetric {
    get name() { return "none"; }
    signBinary(_) { return Promise.resolve(new Uint8Array(0)); }
}
exports.None = None;
Algorithm_1.register("none", (_) => new None());

});

_commonjsHelpers.unwrapExports(None_1);

var HS_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
var __awaiter = (_commonjsHelpers.commonjsGlobal && _commonjsHelpers.commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });




class HS extends Symmetric_1$1.Symmetric {
    constructor(length, key) {
        super();
        this.length = length;
        if (typeof (key) == "string")
            key = Base64.decode(key, "url");
        this.key = crypto_browser.crypto.subtle.importKey("raw", key, { name: "HMAC", hash: { name: "SHA-" + this.length } }, false, ["sign", "verify"]);
    }
    get name() { return "HS" + this.length; }
    signBinary(data) {
        return __awaiter(this, void 0, void 0, function* () {
            return new Uint8Array(yield crypto_browser.crypto.subtle.sign("HMAC", yield this.key, data));
        });
    }
}
exports.HS = HS;
Algorithm_1.register("HS256", (keys) => keys[0] && new HS("256", keys[0]) || undefined);
Algorithm_1.register("HS384", (keys) => keys[0] && new HS("384", keys[0]) || undefined);
Algorithm_1.register("HS512", (keys) => keys[0] && new HS("512", keys[0]) || undefined);

});

_commonjsHelpers.unwrapExports(HS_1);

var RS_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
var __awaiter = (_commonjsHelpers.commonjsGlobal && _commonjsHelpers.commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });



class RS extends Algorithm_1.Algorithm {
    constructor(length, publicKey, privateKey) {
        super();
        this.length = length;
        if (publicKey) {
            if (typeof (publicKey) == "string")
                publicKey = Base64.decode(publicKey);
            this.publicKey = crypto_browser.crypto.subtle.importKey("spki", publicKey, { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-" + this.length } }, false, ["verify"]);
        }
        if (privateKey) {
            if (typeof (privateKey) == "string")
                privateKey = Base64.decode(privateKey);
            this.privateKey = crypto_browser.crypto.subtle.importKey("pkcs8", privateKey, { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-" + this.length } }, true, ["sign", "verify"]);
        }
    }
    get name() { return "RS" + this.length; }
    signBinary(data) {
        return __awaiter(this, void 0, void 0, function* () {
            return new Uint8Array(yield crypto_browser.crypto.subtle.sign("RSASSA-PKCS1-v1_5", yield this.privateKey, data));
        });
    }
    verifyBinary(data, signature) {
        return __awaiter(this, void 0, void 0, function* () {
            return crypto_browser.crypto.subtle.verify("RSASSA-PKCS1-v1_5", yield this.publicKey, signature, data);
        });
    }
}
exports.RS = RS;
Algorithm_1.register("RS256", (keys) => new RS("256", keys[0], keys[1]));
Algorithm_1.register("RS384", (keys) => new RS("384", keys[0], keys[1]));
Algorithm_1.register("RS512", (keys) => new RS("512", keys[0], keys[1]));

});

_commonjsHelpers.unwrapExports(RS_1);

var Algorithm = _commonjsHelpers.createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });

exports.Algorithm = Algorithm_1.Algorithm;




});

_commonjsHelpers.unwrapExports(Algorithm);

var Issuer_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
var __awaiter = (_commonjsHelpers.commonjsGlobal && _commonjsHelpers.commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });



class Issuer extends Actor_1.Actor {
    constructor(issuer, algorithm) {
        super(issuer);
        this.algorithm = algorithm;
    }
    get header() {
        return {
            alg: this.algorithm.name,
            typ: "JWT",
        };
    }
    get payload() {
        const result = { iss: this.id, iat: Issuer.issuedAt };
        if (this.audience)
            result.aud = this.audience;
        if (this.duration && result.iat)
            result.exp = result.iat + this.duration;
        return result;
    }
    sign(payload, issuedAt) {
        return __awaiter(this, void 0, void 0, function* () {
            payload = Object.assign(Object.assign({}, this.payload), payload);
            if (issuedAt)
                payload.iat = typeof (issuedAt) == "number" ? issuedAt : issuedAt.getTime();
            payload = yield this.cryptos.reduce((p, c) => __awaiter(this, void 0, void 0, function* () { return c.encrypt(yield p); }), Promise.resolve(payload));
            const data = `${Base64.encode(new TextEncoder_1.TextEncoder().encode(JSON.stringify(this.header)))}.${Base64.encode(new TextEncoder_1.TextEncoder().encode(JSON.stringify(payload)))}`;
            return `${data}.${yield this.algorithm.sign(data)}`;
        });
    }
    static get issuedAt() {
        return Issuer.defaultIssuedAt == undefined ? Date.now() :
            typeof (Issuer.defaultIssuedAt) == "number" ? Issuer.defaultIssuedAt :
                Issuer.defaultIssuedAt.getTime();
    }
    static create(issuer, algorithm) {
        return algorithm && new Issuer(issuer, algorithm) || undefined;
    }
}
exports.Issuer = Issuer;

});

_commonjsHelpers.unwrapExports(Issuer_1);

var Password_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
var __awaiter = (_commonjsHelpers.commonjsGlobal && _commonjsHelpers.commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });


var Password;
(function (Password) {
    function is(value) {
        return typeof (value) == "string" || (typeof (value) == "object" &&
            typeof (value.hash) == "string" &&
            typeof (value.salt) == "string");
    }
    Password.is = is;
    function hash(algorithm, password, salt) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!salt)
                salt = Base64.encode(crypto_browser.crypto.getRandomValues(new Uint8Array(64)));
            return {
                hash: yield algorithm.sign(salt + password),
                salt,
            };
        });
    }
    Password.hash = hash;
    function verify(algorithm, hash, password) {
        return __awaiter(this, void 0, void 0, function* () {
            return (yield Password.hash(algorithm, password, hash.salt)).hash == hash.hash;
        });
    }
    Password.verify = verify;
    let Hashed;
    (function (Hashed) {
        function is(value) {
            return typeof (value) == "object" &&
                typeof (value.hash) == "string" &&
                typeof (value.salt) == "string";
        }
        Hashed.is = is;
    })(Hashed = Password.Hashed || (Password.Hashed = {}));
})(Password = exports.Password || (exports.Password = {}));

});

_commonjsHelpers.unwrapExports(Password_1);

var Token_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
var Token;
(function (Token) {
    function is(value) {
        return typeof (value) == "string" && /^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/.test(value);
    }
    Token.is = is;
})(Token = exports.Token || (exports.Token = {}));

});

_commonjsHelpers.unwrapExports(Token_1);

var Verifier_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
var __awaiter = (_commonjsHelpers.commonjsGlobal && _commonjsHelpers.commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });



class Verifier extends Actor_1.Actor {
    constructor(audience, ...algorithms) {
        super(audience);
        if (algorithms.length > 0) {
            this.algorithms = {};
            for (const algorithm of algorithms)
                this.algorithms[algorithm.name] = algorithm;
        }
        else
            this.algorithms = undefined;
    }
    verify(token) {
        return __awaiter(this, void 0, void 0, function* () {
            let result;
            if (token) {
                const splitted = token.split(".", 3);
                if (splitted.length < 2)
                    result = undefined;
                else {
                    try {
                        const header = JSON.parse(new TextDecoder_1.TextDecoder().decode(Base64.decode(splitted[0])));
                        result = JSON.parse(new TextDecoder_1.TextDecoder().decode(Base64.decode(splitted[1])));
                        if (this.algorithms) {
                            const algorithm = this.algorithms[header.alg];
                            result = splitted.length == 3 && algorithm && (yield algorithm.verify(`${splitted[0]}.${splitted[1]}`, splitted[2])) ? result : undefined;
                        }
                    }
                    catch (_a) {
                        result = undefined;
                    }
                    const now = Date.now();
                    result = result &&
                        (result.exp == undefined || result.exp > now) &&
                        (result.iat == undefined || result.iat <= now) &&
                        this.verifyAudience(result.aud) ?
                        result : undefined;
                }
                if (result)
                    result = yield this.cryptos.reduce((p, c) => __awaiter(this, void 0, void 0, function* () { return c.decrypt(yield p); }), Promise.resolve(result));
            }
            return result;
        });
    }
    verifyAudience(audience) {
        return audience == undefined || typeof (audience) == "string" && audience == this.id || Array.isArray(audience) && audience.some(a => a == this.id);
    }
    authenticate(authorization) {
        return __awaiter(this, void 0, void 0, function* () {
            return authorization && authorization.startsWith("Bearer ") ? this.verify(authorization.substr(7)) : undefined;
        });
    }
    static create(audience, ...algorithms) {
        return (algorithms.length == 0 || algorithms.some(a => !!a)) && new Verifier(audience, ...algorithms.filter(a => !!a)) || undefined;
    }
}
exports.Verifier = Verifier;

});

_commonjsHelpers.unwrapExports(Verifier_1);

var Identifier_1 = _commonjsHelpers.createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });


var Identifier;
(function (Identifier) {
    function is(value) {
        return typeof (value) == "string" && Array.from(value).every(c => c >= "0" && c <= "9" || c >= "A" && c <= "Z" || c >= "a" && c <= "z" || c == "-" || c == "_");
    }
    Identifier.is = is;
    function fromBinary(identifier) {
        return Base64.encode(identifier, "url");
    }
    Identifier.fromBinary = fromBinary;
    function toBinary(identifier) {
        return Base64.decode(identifier, "url");
    }
    Identifier.toBinary = toBinary;
    function generate(length) {
        return fromBinary(crypto_browser.crypto.getRandomValues(new Uint8Array(length / 4 * 3)));
    }
    Identifier.generate = generate;
    function fromHexadecimal(identifier) {
        if (identifier.length % 2 == 1)
            identifier += "0";
        const result = new Uint8Array(identifier.length / 2);
        for (let index = 0; index < result.length; index++)
            result[index] = Number.parseInt(identifier[index * 2], 16) * 16 + Number.parseInt(identifier[index * 2 + 1], 16);
        return fromBinary(result);
    }
    Identifier.fromHexadecimal = fromHexadecimal;
    function toHexadecimal(identifier, length) {
        const data = Base64.decode(identifier, "url");
        let result = [];
        for (let index = 0; index < data.length; index++)
            result.push(Math.floor(data[index] / 16).toString(16), (data[index] % 16).toString(16));
        if (length)
            result = result.slice(0, length);
        return result.join("");
    }
    Identifier.toHexadecimal = toHexadecimal;
    Identifier.lengths = [4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80, 84, 88, 92, 96, 100, 104, 108, 112, 116, 120, 124, 128];
    let Lengths;
    (function (Lengths) {
        function is(value) {
            return typeof (value) == "number" &&
                value >= 4 &&
                value <= 128 &&
                (value & 252) == value;
        }
        Lengths.is = is;
    })(Lengths = Identifier.Lengths || (Identifier.Lengths = {}));
})(Identifier = exports.Identifier || (exports.Identifier = {}));

});

_commonjsHelpers.unwrapExports(Identifier_1);

var dist = _commonjsHelpers.createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });

exports.Actor = Actor_1.Actor;

exports.Algorithm = Algorithm.Algorithm;

exports.Base64 = Base64;

exports.Issuer = Issuer_1.Issuer;

exports.Password = Password_1.Password;

exports.PropertyCrypto = PropertyCrypto_1.PropertyCrypto;

exports.TextDecoder = TextDecoder_1.TextDecoder;

exports.TextEncoder = TextEncoder_1.TextEncoder;

exports.Token = Token_1.Token;

exports.Verifier = Verifier_1.Verifier;

exports.Identifier = Identifier_1.Identifier;

});

_commonjsHelpers.unwrapExports(dist);
var dist_10 = dist.Verifier;

const Form = class {
    constructor(hostRef) {
        core.registerInstance(this, hostRef);
        this.state = "created";
        this.changed = core.createEvent(this, "changed", 7);
    }
    componentWillLoad() {
        dist_10.create("public").verify(this.apiKey).then(payload => this.payload = payload);
        const styleLink = document.querySelector("link[rel=stylesheet][href^='https://theme.payfunc.com/']");
        if (styleLink) {
            const themeLink = styleLink.href.substring(26);
            this.theme = themeLink.substring(0, themeLink.indexOf("/"));
        }
    }
    async handleTrigger(event) {
        if (event.detail.value && event.detail.value.status == 400 && event.detail.value.type == "missing property" && event.detail.value.content && event.detail.value.content.property == "pares") {
            this.verify = { pareq: event.detail.value.content.pareq, url: event.detail.value.content.url, issuer: this.payload ? this.payload.iss ? this.payload.iss : "" : "" };
        }
        else if (event.detail.name == "pares") {
            this.verify = undefined;
            if (this.authorization)
                this.frame.send("card", { name: "submit", value: { authorization: this.authorization, key: this.apiKey, parent: window.location.origin } });
        }
        else {
            this.verify = undefined;
            this.changed.emit(this.value = event.detail.value);
            this.state = event.detail.name == "cardPaymentSuccess" ? "succeeded" : "failed";
            if (this.received) {
                this.received(this.state, event.detail.value);
                this.received = undefined;
            }
        }
    }
    submit(authorization) {
        this.authorization = authorization;
        return new Promise(callback => {
            if (this.frame) {
                this.received = (_, response) => callback(response);
                this.frame.send("card", { name: "submit", value: { authorization, key: this.apiKey, parent: window.location.origin } });
                this.state = "processing";
            }
        });
    }
    render() {
        return [
            this.payload ? core.h("smoothly-frame", { url: this.payload.iss + "/ui/web-app/" + (this.theme ? "?theme=" + this.theme : ""), name: "card", ref: (element) => this.frame = element }) : [],
            this.verify ?
                core.h("smoothly-dialog", { closable: true }, core.h("smoothly-frame", { url: `${this.verify.issuer}/redirect/post?target=${encodeURIComponent(this.verify.url)}&PaReq=${encodeURIComponent(this.verify.pareq)}&MD=MD&TermUrl=${encodeURIComponent(`${this.verify.issuer}/emv3d/done?parent=${window.location.origin}`)}`, name: "parent", style: { height: "90vh" } })) :
                [],
        ];
    }
    static get style() { return ":host{display:block;height:calc(5em - 3px);overflow:hidden;width:100%}:host[hidden]{display:none}"; }
};

const SmoothlyDialog = class {
    constructor(hostRef) {
        core.registerInstance(this, hostRef);
        this.open = true;
        this.closable = false;
    }
    TriggerListener(event) {
        if (index.dist_9.is(event.detail) && event.detail.name == "close")
            this.open = false;
    }
    hostData() {
        return {
            style: {
                display: this.open ? "block" : "none",
            },
        };
    }
    __stencil_render() {
        return [
            core.h("header", null, this.closable ? core.h("smoothly-trigger", { fill: "clear", name: "close" }, core.h("smoothly-icon", { name: "close-circle", fill: "solid", color: this.color })) : [], this.header ? core.h("h1", null, this.header) : core.h("slot", { name: "header" })),
            core.h("main", null, core.h("slot", null))
        ];
    }
    render() { return core.h(core.Host, this.hostData(), this.__stencil_render()); }
    static get style() { return ".sc-smoothly-dialog-h{display:block;position:fixed;left:0;top:0;width:100%;height:100%;z-index:1;background:rgba(var(--smoothly-default-color),var(--smoothly-semitransparent))!important}[hidden].sc-smoothly-dialog-h{display:none}.sc-smoothly-dialog-h > header.sc-smoothly-dialog{border-top-left-radius:8px;border-top-right-radius:8px;margin-top:2em;color:rgb(var(--smoothly-primary-contrast));background:rgb(var(--smoothly-primary-color))}.sc-smoothly-dialog-h > *.sc-smoothly-dialog{position:relative;color:rgb(var(--smoothly-default-contrast));background-color:rgb(var(--smoothly-default-color));border-color:rgb(var(--smoothly-color));border-width:1px;border-style:solid;max-width:40em;width:calc(100vw - 4em - 2px);max-height:calc(100vh - 6em - 2px);height:auto;margin-left:auto;margin-right:auto;border-collapse:collapse}.sc-smoothly-dialog-h > main.sc-smoothly-dialog{border-bottom-left-radius:8px;border-bottom-right-radius:8px;margin-bottom:2em}.sc-smoothly-dialog-h > *.sc-smoothly-dialog > smoothly-trigger.sc-smoothly-dialog{position:absolute;right:-2em;top:-2em}.sc-smoothly-dialog-h > *.sc-smoothly-dialog > *.sc-smoothly-dialog{margin:10px}"; }
};

const SmoothlyFrame = class {
    constructor(hostRef) {
        core.registerInstance(this, hostRef);
        this.trigger = core.createEvent(this, "trigger", 7);
        this.message = core.createEvent(this, "message", 7);
    }
    get contentWindow() {
        const iframe = this.element && this.element.firstElementChild ? this.element.firstElementChild : undefined;
        return iframe && iframe.contentWindow || undefined;
    }
    get urlOrigin() {
        const match = this.url.match(/^(([a-z]+\+)*[a-z]+:\/\/)?[^\/^\n]+/);
        return match ? match[0] : "*";
    }
    componentDidLoad() {
        if (this.contentWindow)
            index.dist_6.listen(this.urlOrigin, (destination, content) => {
                if (destination == this.name)
                    if (index.dist_9.is(content))
                        this.trigger.emit(content);
                    else
                        this.message.emit({ destination, content });
            }, window);
    }
    async send(message, content) {
        if (typeof (message) == "string")
            index.dist_6.send(this.urlOrigin + "#" + message, content, this.contentWindow);
        else if (index.dist_6.is(message) && this.contentWindow)
            index.dist_6.send({ destination: this.urlOrigin + "#" + message.destination, content: message.destination }, this.contentWindow);
    }
    render() {
        return core.h("iframe", { src: this.url + "#" + window.location.origin, height: "100%", width: "100%" });
    }
    get element() { return core.getElement(this); }
    static get style() { return ".sc-smoothly-frame-h{display:block;width:100%;height:100%}[hidden].sc-smoothly-frame-h{display:none}.sc-smoothly-frame-h > iframe.sc-smoothly-frame{border:none;padding:none;margin:none}"; }
};

const SmoothlyIcon = class {
    constructor(hostRef) {
        core.registerInstance(this, hostRef);
        this.fill = "solid";
        this.size = "medium";
    }
    async loadDocument() {
        if (this.name) {
            const url = `https://unpkg.com/ionicons@5.0.0/dist/svg/${this.name}.svg`;
            const response = await fetch(url);
            this.document = response.ok ? (await response.text()).replace(/(<title>)[\w\d\s\-]*(<\/title>)/, `<title>${this.toolTip || ""}</title>`) : undefined;
        }
    }
    async componentWillLoad() {
        await this.loadDocument();
    }
    hostData() {
        return {
            innerHTML: this.document ? this.document.replace(` width="512" height="512"`, "") : undefined,
        };
    }
    __stencil_render() {
        return [];
    }
    static get watchers() { return {
        "name": ["loadDocument"]
    }; }
    render() { return core.h(core.Host, this.hostData(), this.__stencil_render()); }
    static get style() { return ".sc-smoothly-icon-h{display:block;background:none!important}[hidden].sc-smoothly-icon-h{display:none}[size=small].sc-smoothly-icon-h{width:1.4em;height:1.4em}[size=medium].sc-smoothly-icon-h{width:1.8em;height:1.8em}[size=large].sc-smoothly-icon-h{width:2.8em;height:2.8em}[size=xlarge].sc-smoothly-icon-h{width:4em;height:4em}"; }
};

const SmoothlyTrigger = class {
    constructor(hostRef) {
        core.registerInstance(this, hostRef);
        this.disabled = false;
        this.trigger = core.createEvent(this, "trigger", 7);
    }
    onClick(e) {
        this.trigger.emit({ name: this.name, value: this.value });
        e.stopPropagation();
        e.preventDefault();
    }
    render() {
        return core.h("button", { disabled: this.disabled, name: this.name }, core.h("slot", null));
    }
    static get style() { return ".sc-smoothly-trigger-h{display:block;border-style:solid;border-width:1px;border-radius:3px}[hidden].sc-smoothly-trigger-h{display:none}[disabled].sc-smoothly-trigger-h{opacity:.5}button.sc-smoothly-trigger{border-color:transparent;padding:.2em .3em;font-size:110%;font-weight:400}.sc-smoothly-trigger-h:not([processing]):not([disabled]):active, .sc-smoothly-trigger-h:not([processing]):not([disabled]):focus, .sc-smoothly-trigger-h:not([processing]):not([disabled]):hover{border-color:var(--smoothly-trigger-border)}[expand=block].sc-smoothly-trigger-h > button.sc-smoothly-trigger, [expand=fill].sc-smoothly-trigger-h > button.sc-smoothly-trigger{width:100%}[expand=fill].sc-smoothly-trigger-h{border-left:none;border-right:none}"; }
};

exports.cardfunc_element = Form;
exports.smoothly_dialog = SmoothlyDialog;
exports.smoothly_frame = SmoothlyFrame;
exports.smoothly_icon = SmoothlyIcon;
exports.smoothly_trigger = SmoothlyTrigger;
