UNPKG

@auth0/auth0-spa-js

Version:

Auth0 SDK for Single Page Applications using Authorization Code Grant Flow with PKCE

11,743 lines 504 kB
"use strict";

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

function __rest(s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
        if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
    }
    return t;
}

function __classPrivateFieldGet(receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}

function __classPrivateFieldSet(receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), 
    value;
}

typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};

function _OverloadYield(e, d) {
    this.v = e, this.k = d;
}

function _arrayLikeToArray(r, a) {
    (null == a || a > r.length) && (a = r.length);
    for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
    return n;
}

function _arrayWithHoles(r) {
    if (Array.isArray(r)) return r;
}

function _assertClassBrand(e, t, n) {
    if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
    throw new TypeError("Private element is not present on this object");
}

function _awaitAsyncGenerator(e) {
    return new _OverloadYield(e, 0);
}

function _checkPrivateRedeclaration(e, t) {
    if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
}

function _classPrivateFieldGet2(s, a) {
    return s.get(_assertClassBrand(s, a));
}

function _classPrivateFieldInitSpec(e, t, a) {
    _checkPrivateRedeclaration(e, t), t.set(e, a);
}

function _classPrivateFieldSet2(s, a, r) {
    return s.set(_assertClassBrand(s, a), r), r;
}

function _classPrivateMethodInitSpec(e, a) {
    _checkPrivateRedeclaration(e, a), a.add(e);
}

function _defineProperty(e, r, t) {
    return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
        value: t,
        enumerable: !0,
        configurable: !0,
        writable: !0
    }) : e[r] = t, e;
}

function _iterableToArrayLimit(r, l) {
    var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
    if (null != t) {
        var e, n, i, u, a = [], f = !0, o = !1;
        try {
            if (i = (t = t.call(r)).next, 0 === l) {
                if (Object(t) !== t) return;
                f = !1;
            } else for (;!(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) ;
        } catch (r) {
            o = !0, n = r;
        } finally {
            try {
                if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
            } finally {
                if (o) throw n;
            }
        }
        return a;
    }
}

function _nonIterableRest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}

function ownKeys(e, r) {
    var t = Object.keys(e);
    if (Object.getOwnPropertySymbols) {
        var o = Object.getOwnPropertySymbols(e);
        r && (o = o.filter(function(r) {
            return Object.getOwnPropertyDescriptor(e, r).enumerable;
        })), t.push.apply(t, o);
    }
    return t;
}

function _objectSpread2(e) {
    for (var r = 1; r < arguments.length; r++) {
        var t = null != arguments[r] ? arguments[r] : {};
        r % 2 ? ownKeys(Object(t), !0).forEach(function(r) {
            _defineProperty(e, r, t[r]);
        }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {
            Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
        });
    }
    return e;
}

function _objectWithoutProperties(e, t) {
    if (null == e) return {};
    var o, r, i = _objectWithoutPropertiesLoose(e, t);
    if (Object.getOwnPropertySymbols) {
        var n = Object.getOwnPropertySymbols(e);
        for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
    }
    return i;
}

function _objectWithoutPropertiesLoose(r, e) {
    if (null == r) return {};
    var t = {};
    for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
        if (-1 !== e.indexOf(n)) continue;
        t[n] = r[n];
    }
    return t;
}

function _slicedToArray(r, e) {
    return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
}

function _toPrimitive(t, r) {
    if ("object" != typeof t || !t) return t;
    var e = t[Symbol.toPrimitive];
    if (void 0 !== e) {
        var i = e.call(t, r || "default");
        if ("object" != typeof i) return i;
        throw new TypeError("@@toPrimitive must return a primitive value.");
    }
    return ("string" === r ? String : Number)(t);
}

function _toPropertyKey(t) {
    var i = _toPrimitive(t, "string");
    return "symbol" == typeof i ? i : i + "";
}

function _unsupportedIterableToArray(r, a) {
    if (r) {
        if ("string" == typeof r) return _arrayLikeToArray(r, a);
        var t = {}.toString.call(r).slice(8, -1);
        return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
    }
}

function _wrapAsyncGenerator(e) {
    return function() {
        return new AsyncGenerator(e.apply(this, arguments));
    };
}

function AsyncGenerator(e) {
    var t, n;
    function resume(t, n) {
        try {
            var r = e[t](n), o = r.value, u = o instanceof _OverloadYield;
            Promise.resolve(u ? o.v : o).then(function(n) {
                if (u) {
                    var i = "return" === t && o.k ? t : "next";
                    if (!o.k || n.done) return resume(i, n);
                    n = e[i](n).value;
                }
                settle(!!r.done, n);
            }, function(e) {
                resume("throw", e);
            });
        } catch (e) {
            settle(2, e);
        }
    }
    function settle(e, r) {
        2 === e ? t.reject(r) : t.resolve({
            value: r,
            done: e
        }), (t = t.next) ? resume(t.key, t.arg) : n = null;
    }
    this._invoke = function(e, r) {
        return new Promise(function(o, u) {
            var i = {
                key: e,
                arg: r,
                resolve: o,
                reject: u,
                next: null
            };
            n ? n = n.next = i : (t = n = i, resume(e, r));
        });
    }, "function" != typeof e.return && (this.return = void 0);
}

AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function() {
    return this;
}, AsyncGenerator.prototype.next = function(e) {
    return this._invoke("next", e);
}, AsyncGenerator.prototype.throw = function(e) {
    return this._invoke("throw", e);
}, AsyncGenerator.prototype.return = function(e) {
    return this._invoke("return", e);
};

var version = "2.26.0";

const DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS = 60;

const DEFAULT_POPUP_CONFIG_OPTIONS = {
    timeoutInSeconds: DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS
};

const DEFAULT_SILENT_TOKEN_RETRY_COUNT = 3;

const CLEANUP_IFRAME_TIMEOUT_IN_SECONDS = 2;

const DEFAULT_FETCH_TIMEOUT_MS = 1e4;

const CACHE_LOCATION_MEMORY = "memory";

const MISSING_REFRESH_TOKEN_ERROR_MESSAGE = "Missing Refresh Token";

const INVALID_REFRESH_TOKEN_ERROR_MESSAGE = "invalid refresh token";

const USER_BLOCKED_ERROR_MESSAGE = "user is blocked";

const MFA_STEP_UP_ERROR_DESCRIPTION = "Multifactor authentication required";

const DEFAULT_SCOPE = "openid profile email";

const ONLINE_ACCESS_SCOPE = "online_access";

const DEFAULT_SESSION_CHECK_EXPIRY_DAYS = 1;

const DEFAULT_AUTH0_CLIENT = {
    name: "auth0-spa-js",
    version: version
};

const DEFAULT_NOW_PROVIDER = () => Date.now();

const SESSION_EXPIRY_LEEWAY_SECONDS = 30;

const DEFAULT_AUDIENCE = "default";

class GenericError extends Error {
    constructor(error, error_description) {
        super(error_description);
        this.error = error;
        this.error_description = error_description;
        Object.setPrototypeOf(this, GenericError.prototype);
    }
    static fromPayload(_ref) {
        let error = _ref.error, error_description = _ref.error_description;
        return new GenericError(error, error_description);
    }
}

class InvalidConfigurationError extends GenericError {
    constructor(message, suggestion) {
        super("invalid_configuration", "".concat(message, " ").concat(suggestion));
        this.suggestion = suggestion;
        Object.setPrototypeOf(this, InvalidConfigurationError.prototype);
    }
}

class AuthenticationError extends GenericError {
    constructor(error, error_description, state) {
        let appState = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
        super(error, error_description);
        this.state = state;
        this.appState = appState;
        Object.setPrototypeOf(this, AuthenticationError.prototype);
    }
}

class ConnectError extends GenericError {
    constructor(error, error_description, connection, state) {
        let appState = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
        super(error, error_description);
        this.connection = connection;
        this.state = state;
        this.appState = appState;
        Object.setPrototypeOf(this, ConnectError.prototype);
    }
}

class TimeoutError extends GenericError {
    constructor() {
        super("timeout", "Timeout");
        Object.setPrototypeOf(this, TimeoutError.prototype);
    }
}

class PopupTimeoutError extends TimeoutError {
    constructor(popup) {
        super();
        this.popup = popup;
        Object.setPrototypeOf(this, PopupTimeoutError.prototype);
    }
}

class PopupCancelledError extends GenericError {
    constructor(popup) {
        super("cancelled", "Popup closed");
        this.popup = popup;
        Object.setPrototypeOf(this, PopupCancelledError.prototype);
    }
}

class PopupOpenError extends GenericError {
    constructor() {
        super("popup_open", "Unable to open a popup for loginWithPopup - window.open returned `null`");
        Object.setPrototypeOf(this, PopupOpenError.prototype);
    }
}

class MfaRequiredError extends GenericError {
    constructor(error, error_description, mfa_token, mfa_requirements) {
        super(error, error_description);
        this.mfa_token = mfa_token;
        this.mfa_requirements = mfa_requirements;
        Object.setPrototypeOf(this, MfaRequiredError.prototype);
    }
}

class MissingRefreshTokenError extends GenericError {
    constructor(audience, scope) {
        super("missing_refresh_token", "Missing Refresh Token (audience: '".concat(valueOrEmptyString(audience, [ "default" ]), "', scope: '").concat(valueOrEmptyString(scope), "')"));
        this.audience = audience;
        this.scope = scope;
        Object.setPrototypeOf(this, MissingRefreshTokenError.prototype);
    }
}

class MissingScopesError extends GenericError {
    constructor(audience, scope) {
        super("missing_scopes", "Missing requested scopes after refresh (audience: '".concat(valueOrEmptyString(audience, [ "default" ]), "', missing scope: '").concat(valueOrEmptyString(scope), "')"));
        this.audience = audience;
        this.scope = scope;
        Object.setPrototypeOf(this, MissingScopesError.prototype);
    }
}

class UseDpopNonceError extends GenericError {
    constructor(newDpopNonce) {
        super("use_dpop_nonce", "Server rejected DPoP proof: wrong nonce");
        this.newDpopNonce = newDpopNonce;
        Object.setPrototypeOf(this, UseDpopNonceError.prototype);
    }
}

function valueOrEmptyString(value) {
    let exclude = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
    return value && !exclude.includes(value) ? value : "";
}

const parseAuthenticationResult = queryString => {
    if (queryString.indexOf("#") > -1) {
        queryString = queryString.substring(0, queryString.indexOf("#"));
    }
    const searchParams = new URLSearchParams(queryString);
    return {
        state: searchParams.get("state"),
        code: searchParams.get("code") || undefined,
        connect_code: searchParams.get("connect_code") || undefined,
        error: searchParams.get("error") || undefined,
        error_description: searchParams.get("error_description") || undefined
    };
};

const runIframe = function runIframe(authorizeUrl, eventOrigin) {
    let timeoutInSeconds = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS;
    return new Promise((res, rej) => {
        const iframe = window.document.createElement("iframe");
        iframe.setAttribute("width", "0");
        iframe.setAttribute("height", "0");
        iframe.style.display = "none";
        const removeIframe = () => {
            if (window.document.body.contains(iframe)) {
                window.document.body.removeChild(iframe);
                window.removeEventListener("message", _iframeEventHandler, false);
            }
        };
        let _iframeEventHandler;
        const timeoutSetTimeoutId = setTimeout(() => {
            rej(new TimeoutError);
            removeIframe();
        }, timeoutInSeconds * 1e3);
        _iframeEventHandler = function iframeEventHandler(e) {
            if (e.origin != eventOrigin) return;
            if (!e.data || e.data.type !== "authorization_response") return;
            const eventSource = e.source;
            if (eventSource) {
                eventSource.close();
            }
            e.data.response.error ? rej(GenericError.fromPayload(e.data.response)) : res(e.data.response);
            clearTimeout(timeoutSetTimeoutId);
            window.removeEventListener("message", _iframeEventHandler, false);
            setTimeout(removeIframe, CLEANUP_IFRAME_TIMEOUT_IN_SECONDS * 1e3);
        };
        window.addEventListener("message", _iframeEventHandler, false);
        window.document.body.appendChild(iframe);
        iframe.setAttribute("src", authorizeUrl);
    });
};

const openPopup = url => {
    const width = 400;
    const height = 600;
    const left = window.screenX + (window.innerWidth - width) / 2;
    const top = window.screenY + (window.innerHeight - height) / 2;
    return window.open(url, "auth0:authorize:popup", "left=".concat(left, ",top=").concat(top, ",width=").concat(width, ",height=").concat(height, ",resizable,scrollbars=yes,status=1"));
};

const runPopup = (config, eventOrigin) => new Promise((resolve, reject) => {
    let _popupEventListener;
    const popupTimer = setInterval(() => {
        if (config.popup && config.popup.closed) {
            clearInterval(popupTimer);
            clearTimeout(timeoutId);
            window.removeEventListener("message", _popupEventListener, false);
            reject(new PopupCancelledError(config.popup));
        }
    }, 1e3);
    const timeoutId = setTimeout(() => {
        clearInterval(popupTimer);
        reject(new PopupTimeoutError(config.popup));
        window.removeEventListener("message", _popupEventListener, false);
    }, (config.timeoutInSeconds || DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS) * 1e3);
    _popupEventListener = function popupEventListener(e) {
        if (e.origin !== eventOrigin) return;
        if (!e.data || e.data.type !== "authorization_response") {
            return;
        }
        clearTimeout(timeoutId);
        clearInterval(popupTimer);
        window.removeEventListener("message", _popupEventListener, false);
        if (config.closePopup !== false) {
            config.popup.close();
        }
        if (e.data.response.error) {
            return reject(GenericError.fromPayload(e.data.response));
        }
        resolve(e.data.response);
    };
    window.addEventListener("message", _popupEventListener);
});

const getCrypto = () => window.crypto;

const createRandomString = () => {
    const charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";
    const validMax = 256 - 256 % charset.length;
    let random = "";
    while (random.length < 43) {
        const bytes = getCrypto().getRandomValues(new Uint8Array(43 - random.length));
        for (const byte of bytes) {
            if (random.length < 43 && byte < validMax) {
                random += charset[byte % charset.length];
            }
        }
    }
    return random;
};

const encode$3 = value => btoa(value);

const stripUndefined = params => Object.keys(params).filter(k => typeof params[k] !== "undefined").reduce((acc, key) => Object.assign(Object.assign({}, acc), {
    [key]: params[key]
}), {});

const ALLOWED_AUTH0CLIENT_PROPERTIES = [ {
    key: "name",
    type: [ "string" ]
}, {
    key: "version",
    type: [ "string", "number" ]
}, {
    key: "env",
    type: [ "object" ]
} ];

const stripAuth0Client = function stripAuth0Client(auth0Client) {
    let excludeEnv = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    return Object.keys(auth0Client).reduce((acc, key) => {
        if (excludeEnv && key === "env") {
            return acc;
        }
        const allowedProperty = ALLOWED_AUTH0CLIENT_PROPERTIES.find(p => p.key === key);
        if (allowedProperty && allowedProperty.type.includes(typeof auth0Client[key])) {
            acc[key] = auth0Client[key];
        }
        return acc;
    }, {});
};

const createQueryParams = _a => {
    var client_id = _a.clientId, params = __rest(_a, [ "clientId" ]);
    return new URLSearchParams(stripUndefined(Object.assign({
        client_id: client_id
    }, params))).toString();
};

const sha256 = async s => {
    const digestOp = getCrypto().subtle.digest({
        name: "SHA-256"
    }, (new TextEncoder).encode(s));
    return await digestOp;
};

const urlEncodeB64 = input => {
    const b64Chars = {
        "+": "-",
        "/": "_",
        "=": ""
    };
    return input.replace(/[+/=]/g, m => b64Chars[m]);
};

const decodeB64 = input => decodeURIComponent(atob(input).split("").map(c => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2)).join(""));

const urlDecodeB64 = input => decodeB64(input.replace(/_/g, "/").replace(/-/g, "+"));

const bufferToBase64UrlEncoded = input => {
    const ie11SafeInput = new Uint8Array(input);
    return urlEncodeB64(window.btoa(String.fromCharCode(...Array.from(ie11SafeInput))));
};

const validateCrypto = () => {
    if (!getCrypto()) {
        throw new Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");
    }
    if (typeof getCrypto().subtle === "undefined") {
        throw new Error("\n      auth0-spa-js must run on a secure origin. See https://github.com/auth0/auth0-spa-js/blob/main/FAQ.md#why-do-i-get-auth0-spa-js-must-run-on-a-secure-origin for more information.\n    ");
    }
};

const getDomain = domainUrl => {
    if (!/^https?:\/\//.test(domainUrl)) {
        return "https://".concat(domainUrl);
    }
    return domainUrl;
};

const getTokenIssuer = (issuer, domainUrl) => {
    if (issuer) {
        return issuer.startsWith("https://") ? issuer : "https://".concat(issuer, "/");
    }
    return "".concat(domainUrl, "/");
};

const parseNumber = value => {
    if (typeof value !== "string") {
        return value;
    }
    return parseInt(value, 10) || undefined;
};

const fromEntries = iterable => [ ...iterable ].reduce((obj, _ref) => {
    let _ref2 = _slicedToArray(_ref, 2), key = _ref2[0], val = _ref2[1];
    obj[key] = val;
    return obj;
}, {});

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

var browserTabsLock = {};

var processLock = {};

Object.defineProperty(processLock, "__esModule", {
    value: true
});

var ProcessLocking = function() {
    function ProcessLocking() {
        var _this = this;
        this.locked = new Map;
        this.addToLocked = function(key, toAdd) {
            var callbacks = _this.locked.get(key);
            if (callbacks === undefined) {
                if (toAdd === undefined) {
                    _this.locked.set(key, []);
                } else {
                    _this.locked.set(key, [ toAdd ]);
                }
            } else {
                if (toAdd !== undefined) {
                    callbacks.unshift(toAdd);
                    _this.locked.set(key, callbacks);
                }
            }
        };
        this.isLocked = function(key) {
            return _this.locked.has(key);
        };
        this.lock = function(key) {
            return new Promise(function(resolve, reject) {
                if (_this.isLocked(key)) {
                    _this.addToLocked(key, resolve);
                } else {
                    _this.addToLocked(key);
                    resolve();
                }
            });
        };
        this.unlock = function(key) {
            var callbacks = _this.locked.get(key);
            if (callbacks === undefined || callbacks.length === 0) {
                _this.locked.delete(key);
                return;
            }
            var toCall = callbacks.pop();
            _this.locked.set(key, callbacks);
            if (toCall !== undefined) {
                setTimeout(toCall, 0);
            }
        };
    }
    ProcessLocking.getInstance = function() {
        if (ProcessLocking.instance === undefined) {
            ProcessLocking.instance = new ProcessLocking;
        }
        return ProcessLocking.instance;
    };
    return ProcessLocking;
}();

function getLock() {
    return ProcessLocking.getInstance();
}

processLock.default = getLock;

var __awaiter = commonjsGlobal && commonjsGlobal.__awaiter || function(thisArg, _arguments, P, generator) {
    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) : new P(function(resolve) {
                resolve(result.value);
            }).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};

var __generator = commonjsGlobal && commonjsGlobal.__generator || function(thisArg, body) {
    var _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    }, f, y, t, g;
    return g = {
        next: verb(0),
        throw: verb(1),
        return: verb(2)
    }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
        return this;
    }), g;
    function verb(n) {
        return function(v) {
            return step([ n, v ]);
        };
    }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 
            0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [ op[0] & 2, t.value ];
            switch (op[0]) {
              case 0:
              case 1:
                t = op;
                break;

              case 4:
                _.label++;
                return {
                    value: op[1],
                    done: false
                };

              case 5:
                _.label++;
                y = op[1];
                op = [ 0 ];
                continue;

              case 7:
                op = _.ops.pop();
                _.trys.pop();
                continue;

              default:
                if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                    _ = 0;
                    continue;
                }
                if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                    _.label = op[1];
                    break;
                }
                if (op[0] === 6 && _.label < t[1]) {
                    _.label = t[1];
                    t = op;
                    break;
                }
                if (t && _.label < t[2]) {
                    _.label = t[2];
                    _.ops.push(op);
                    break;
                }
                if (t[2]) _.ops.pop();
                _.trys.pop();
                continue;
            }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [ 6, e ];
            y = 0;
        } finally {
            f = t = 0;
        }
        if (op[0] & 5) throw op[1];
        return {
            value: op[0] ? op[1] : void 0,
            done: true
        };
    }
};

var _this = commonjsGlobal;

Object.defineProperty(browserTabsLock, "__esModule", {
    value: true
});

var processLock_1 = processLock;

var LOCK_STORAGE_KEY = "browser-tabs-lock-key";

var DEFAULT_STORAGE_HANDLER = {
    key: function(index) {
        return __awaiter(_this, void 0, void 0, function() {
            return __generator(this, function(_a) {
                throw new Error("Unsupported");
            });
        });
    },
    getItem: function(key) {
        return __awaiter(_this, void 0, void 0, function() {
            return __generator(this, function(_a) {
                throw new Error("Unsupported");
            });
        });
    },
    clear: function() {
        return __awaiter(_this, void 0, void 0, function() {
            return __generator(this, function(_a) {
                return [ 2, window.localStorage.clear() ];
            });
        });
    },
    removeItem: function(key) {
        return __awaiter(_this, void 0, void 0, function() {
            return __generator(this, function(_a) {
                throw new Error("Unsupported");
            });
        });
    },
    setItem: function(key, value) {
        return __awaiter(_this, void 0, void 0, function() {
            return __generator(this, function(_a) {
                throw new Error("Unsupported");
            });
        });
    },
    keySync: function(index) {
        return window.localStorage.key(index);
    },
    getItemSync: function(key) {
        return window.localStorage.getItem(key);
    },
    clearSync: function() {
        return window.localStorage.clear();
    },
    removeItemSync: function(key) {
        return window.localStorage.removeItem(key);
    },
    setItemSync: function(key, value) {
        return window.localStorage.setItem(key, value);
    }
};

function delay(milliseconds) {
    return new Promise(function(resolve) {
        return setTimeout(resolve, milliseconds);
    });
}

function generateRandomString(length) {
    var CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var randomstring = "";
    for (var i = 0; i < length; i++) {
        var INDEX = Math.floor(Math.random() * CHARS.length);
        randomstring += CHARS[INDEX];
    }
    return randomstring;
}

function getLockId() {
    return Date.now().toString() + generateRandomString(15);
}

var SuperTokensLock = function() {
    function SuperTokensLock(storageHandler) {
        this.acquiredIatSet = new Set;
        this.storageHandler = undefined;
        this.id = getLockId();
        this.acquireLock = this.acquireLock.bind(this);
        this.releaseLock = this.releaseLock.bind(this);
        this.releaseLock__private__ = this.releaseLock__private__.bind(this);
        this.waitForSomethingToChange = this.waitForSomethingToChange.bind(this);
        this.refreshLockWhileAcquired = this.refreshLockWhileAcquired.bind(this);
        this.storageHandler = storageHandler;
        if (SuperTokensLock.waiters === undefined) {
            SuperTokensLock.waiters = [];
        }
    }
    SuperTokensLock.prototype.acquireLock = function(lockKey, timeout) {
        if (timeout === void 0) {
            timeout = 5e3;
        }
        return __awaiter(this, void 0, void 0, function() {
            var iat, MAX_TIME, STORAGE_KEY, STORAGE, lockObj, TIMEOUT_KEY, lockObjPostDelay, parsedLockObjPostDelay;
            return __generator(this, function(_a) {
                switch (_a.label) {
                  case 0:
                    iat = Date.now() + generateRandomString(4);
                    MAX_TIME = Date.now() + timeout;
                    STORAGE_KEY = LOCK_STORAGE_KEY + "-" + lockKey;
                    STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
                    _a.label = 1;

                  case 1:
                    if (!(Date.now() < MAX_TIME)) return [ 3, 8 ];
                    return [ 4, delay(30) ];

                  case 2:
                    _a.sent();
                    lockObj = STORAGE.getItemSync(STORAGE_KEY);
                    if (!(lockObj === null)) return [ 3, 5 ];
                    TIMEOUT_KEY = this.id + "-" + lockKey + "-" + iat;
                    return [ 4, delay(Math.floor(Math.random() * 25)) ];

                  case 3:
                    _a.sent();
                    STORAGE.setItemSync(STORAGE_KEY, JSON.stringify({
                        id: this.id,
                        iat: iat,
                        timeoutKey: TIMEOUT_KEY,
                        timeAcquired: Date.now(),
                        timeRefreshed: Date.now()
                    }));
                    return [ 4, delay(30) ];

                  case 4:
                    _a.sent();
                    lockObjPostDelay = STORAGE.getItemSync(STORAGE_KEY);
                    if (lockObjPostDelay !== null) {
                        parsedLockObjPostDelay = JSON.parse(lockObjPostDelay);
                        if (parsedLockObjPostDelay.id === this.id && parsedLockObjPostDelay.iat === iat) {
                            this.acquiredIatSet.add(iat);
                            this.refreshLockWhileAcquired(STORAGE_KEY, iat);
                            return [ 2, true ];
                        }
                    }
                    return [ 3, 7 ];

                  case 5:
                    SuperTokensLock.lockCorrector(this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler);
                    return [ 4, this.waitForSomethingToChange(MAX_TIME) ];

                  case 6:
                    _a.sent();
                    _a.label = 7;

                  case 7:
                    iat = Date.now() + generateRandomString(4);
                    return [ 3, 1 ];

                  case 8:
                    return [ 2, false ];
                }
            });
        });
    };
    SuperTokensLock.prototype.refreshLockWhileAcquired = function(storageKey, iat) {
        return __awaiter(this, void 0, void 0, function() {
            var _this = this;
            return __generator(this, function(_a) {
                setTimeout(function() {
                    return __awaiter(_this, void 0, void 0, function() {
                        var STORAGE, lockObj, parsedLockObj;
                        return __generator(this, function(_a) {
                            switch (_a.label) {
                              case 0:
                                return [ 4, processLock_1.default().lock(iat) ];

                              case 1:
                                _a.sent();
                                if (!this.acquiredIatSet.has(iat)) {
                                    processLock_1.default().unlock(iat);
                                    return [ 2 ];
                                }
                                STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
                                lockObj = STORAGE.getItemSync(storageKey);
                                if (lockObj !== null) {
                                    parsedLockObj = JSON.parse(lockObj);
                                    parsedLockObj.timeRefreshed = Date.now();
                                    STORAGE.setItemSync(storageKey, JSON.stringify(parsedLockObj));
                                    processLock_1.default().unlock(iat);
                                } else {
                                    processLock_1.default().unlock(iat);
                                    return [ 2 ];
                                }
                                this.refreshLockWhileAcquired(storageKey, iat);
                                return [ 2 ];
                            }
                        });
                    });
                }, 1e3);
                return [ 2 ];
            });
        });
    };
    SuperTokensLock.prototype.waitForSomethingToChange = function(MAX_TIME) {
        return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
                switch (_a.label) {
                  case 0:
                    return [ 4, new Promise(function(resolve) {
                        var resolvedCalled = false;
                        var startedAt = Date.now();
                        var MIN_TIME_TO_WAIT = 50;
                        var removedListeners = false;
                        function stopWaiting() {
                            if (!removedListeners) {
                                window.removeEventListener("storage", stopWaiting);
                                SuperTokensLock.removeFromWaiting(stopWaiting);
                                clearTimeout(timeOutId);
                                removedListeners = true;
                            }
                            if (!resolvedCalled) {
                                resolvedCalled = true;
                                var timeToWait = MIN_TIME_TO_WAIT - (Date.now() - startedAt);
                                if (timeToWait > 0) {
                                    setTimeout(resolve, timeToWait);
                                } else {
                                    resolve(null);
                                }
                            }
                        }
                        window.addEventListener("storage", stopWaiting);
                        SuperTokensLock.addToWaiting(stopWaiting);
                        var timeOutId = setTimeout(stopWaiting, Math.max(0, MAX_TIME - Date.now()));
                    }) ];

                  case 1:
                    _a.sent();
                    return [ 2 ];
                }
            });
        });
    };
    SuperTokensLock.addToWaiting = function(func) {
        this.removeFromWaiting(func);
        if (SuperTokensLock.waiters === undefined) {
            return;
        }
        SuperTokensLock.waiters.push(func);
    };
    SuperTokensLock.removeFromWaiting = function(func) {
        if (SuperTokensLock.waiters === undefined) {
            return;
        }
        SuperTokensLock.waiters = SuperTokensLock.waiters.filter(function(i) {
            return i !== func;
        });
    };
    SuperTokensLock.notifyWaiters = function() {
        if (SuperTokensLock.waiters === undefined) {
            return;
        }
        var waiters = SuperTokensLock.waiters.slice();
        waiters.forEach(function(i) {
            return i();
        });
    };
    SuperTokensLock.prototype.releaseLock = function(lockKey) {
        return __awaiter(this, void 0, void 0, function() {
            return __generator(this, function(_a) {
                switch (_a.label) {
                  case 0:
                    return [ 4, this.releaseLock__private__(lockKey) ];

                  case 1:
                    return [ 2, _a.sent() ];
                }
            });
        });
    };
    SuperTokensLock.prototype.releaseLock__private__ = function(lockKey) {
        return __awaiter(this, void 0, void 0, function() {
            var STORAGE, STORAGE_KEY, lockObj, parsedlockObj;
            return __generator(this, function(_a) {
                switch (_a.label) {
                  case 0:
                    STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
                    STORAGE_KEY = LOCK_STORAGE_KEY + "-" + lockKey;
                    lockObj = STORAGE.getItemSync(STORAGE_KEY);
                    if (lockObj === null) {
                        return [ 2 ];
                    }
                    parsedlockObj = JSON.parse(lockObj);
                    if (!(parsedlockObj.id === this.id)) return [ 3, 2 ];
                    return [ 4, processLock_1.default().lock(parsedlockObj.iat) ];

                  case 1:
                    _a.sent();
                    this.acquiredIatSet.delete(parsedlockObj.iat);
                    STORAGE.removeItemSync(STORAGE_KEY);
                    processLock_1.default().unlock(parsedlockObj.iat);
                    SuperTokensLock.notifyWaiters();
                    _a.label = 2;

                  case 2:
                    return [ 2 ];
                }
            });
        });
    };
    SuperTokensLock.lockCorrector = function(storageHandler) {
        var MIN_ALLOWED_TIME = Date.now() - 5e3;
        var STORAGE = storageHandler;
        var KEYS = [];
        var currIndex = 0;
        while (true) {
            var key = STORAGE.keySync(currIndex);
            if (key === null) {
                break;
            }
            KEYS.push(key);
            currIndex++;
        }
        var notifyWaiters = false;
        for (var i = 0; i < KEYS.length; i++) {
            var LOCK_KEY = KEYS[i];
            if (LOCK_KEY.includes(LOCK_STORAGE_KEY)) {
                var lockObj = STORAGE.getItemSync(LOCK_KEY);
                if (lockObj !== null) {
                    var parsedlockObj = JSON.parse(lockObj);
                    if (parsedlockObj.timeRefreshed === undefined && parsedlockObj.timeAcquired < MIN_ALLOWED_TIME || parsedlockObj.timeRefreshed !== undefined && parsedlockObj.timeRefreshed < MIN_ALLOWED_TIME) {
                        STORAGE.removeItemSync(LOCK_KEY);
                        notifyWaiters = true;
                    }
                }
            }
        }
        if (notifyWaiters) {
            SuperTokensLock.notifyWaiters();
        }
    };
    SuperTokensLock.waiters = undefined;
    return SuperTokensLock;
}();

var _default = browserTabsLock.default = SuperTokensLock;

class WebLocksApiManager {
    async runWithLock(key, timeout, callback) {
        const controller = new AbortController;
        const timeoutId = setTimeout(() => controller.abort(), timeout);
        try {
            return await navigator.locks.request(key, {
                mode: "exclusive",
                signal: controller.signal
            }, async lock => {
                clearTimeout(timeoutId);
                if (!lock) throw new Error("Lock not available");
                return await callback();
            });
        } catch (error) {
            clearTimeout(timeoutId);
            if ((error === null || error === void 0 ? void 0 : error.name) === "AbortError") throw new TimeoutError;
            throw error;
        }
    }
}

class LegacyLockManager {
    constructor() {
        this.activeLocks = new Set;
        this.lock = new _default;
        this.pagehideHandler = () => {
            this.activeLocks.forEach(key => this.lock.releaseLock(key));
            this.activeLocks.clear();
        };
    }
    async runWithLock(key, timeout, callback) {
        const retryAttempts = 10;
        let acquired = false;
        for (let i = 0; i < retryAttempts && !acquired; i++) {
            acquired = await this.lock.acquireLock(key, timeout);
        }
        if (!acquired) {
            throw new TimeoutError;
        }
        this.activeLocks.add(key);
        if (this.activeLocks.size === 1 && typeof window !== "undefined") {
            window.addEventListener("pagehide", this.pagehideHandler);
        }
        try {
            return await callback();
        } finally {
            this.activeLocks.delete(key);
            await this.lock.releaseLock(key);
            if (this.activeLocks.size === 0 && typeof window !== "undefined") {
                window.removeEventListener("pagehide", this.pagehideHandler);
            }
        }
    }
}

function isWebLocksSupported() {
    var _a;
    return typeof navigator !== "undefined" && typeof ((_a = navigator.locks) === null || _a === void 0 ? void 0 : _a.request) === "function";
}

function createLockManager() {
    return isWebLocksSupported() ? new WebLocksApiManager : new LegacyLockManager;
}

let lockManager = null;

function getLockManager() {
    if (!lockManager) {
        lockManager = createLockManager();
    }
    return lockManager;
}

const encoder$2 = new TextEncoder;

const decoder$2 = new TextDecoder;

function buf$1(input) {
    if (typeof input === "string") {
        return encoder$2.encode(input);
    }
    return decoder$2.decode(input);
}

function checkRsaKeyAlgorithm$1(algorithm) {
    if (typeof algorithm.modulusLength !== "number" || algorithm.modulusLength < 2048) {
        throw new OperationProcessingError$1(`${algorithm.name} modulusLength must be at least 2048 bits`);
    }
}

function subtleAlgorithm(key) {
    switch (key.algorithm.name) {
      case "ECDSA":
        return {
            name: key.algorithm.name,
            hash: "SHA-256"
        };

      case "RSA-PSS":
        checkRsaKeyAlgorithm$1(key.algorithm);
        return {
            name: key.algorithm.name,
            saltLength: 256 >> 3
        };

      case "RSASSA-PKCS1-v1_5":
        checkRsaKeyAlgorithm$1(key.algorithm);
        return {
            name: key.algorithm.name
        };

      case "Ed25519":
        return {
            name: key.algorithm.name
        };
    }
    throw new UnsupportedOperationError$1;
}

async function jwt(header, claimsSet, key) {
    if (key.usages.includes("sign") === false) {
        throw new TypeError('private CryptoKey instances used for signing assertions must include "sign" in their "usages"');
    }
    const input = `${b64u$1(buf$1(JSON.stringify(header)))}.${b64u$1(buf$1(JSON.stringify(claimsSet)))}`;
    const signature = b64u$1(await crypto.subtle.sign(subtleAlgorithm(key), key, buf$1(input)));
    return `${input}.${signature}`;
}

let encodeBase64Url$1;

if (Uint8Array.prototype.toBase64) {
    encodeBase64Url$1 = input => {
        if (input instanceof ArrayBuffer) {
            input = new Uint8Array(input);
        }
        return input.toBase64({
            alphabet: "base64url",
            omitPadding: true
        });
    };
} else {
    const CHUNK_SIZE = 32768;
    encodeBase64Url$1 = input => {
        if (input instanceof ArrayBuffer) {
            input = new Uint8Array(input);
        }
        const arr = [];
        for (let i = 0; i < input.byteLength; i += CHUNK_SIZE) {
            arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
        }
        return btoa(arr.join("")).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
    };
}

function b64u$1(input) {
    return encodeBase64Url$1(input);
}

class UnsupportedOperationError$1 extends Error {
    constructor(message) {
        var _a;
        super(message !== null && message !== void 0 ? message : "operation not supported");
        this.name = this.constructor.name;
        (_a = Error.captureStackTrace) === null || _a === void 0 ? void 0 : _a.call(Error, this, this.constructor);
    }
}

class OperationProcessingError$1 extends Error {
    constructor(message) {
        var _a;
        super(message);
        this.name = this.constructor.name;
        (_a = Error.captureStackTrace) === null || _a === void 0 ? void 0 : _a.call(Error, this, this.constructor);
    }
}

function psAlg$1(key) {
    switch (key.algorithm.hash.name) {
      case "SHA-256":
        return "PS256";

      default:
        throw new UnsupportedOperationError$1("unsupported RsaHashedKeyAlgorithm hash name");
    }
}

function rsAlg$1(key) {
    switch (key.algorithm.hash.name) {
      case "SHA-256":
        return "RS256";

      default:
        throw new UnsupportedOperationError$1("unsupported RsaHashedKeyAlgorithm hash name");
    }
}

function esAlg$1(key) {
    switch (key.algorithm.namedCurve) {
      case "P-256":
        return "ES256";

      default:
        throw new UnsupportedOperationError$1("unsupported EcKeyAlgorithm namedCurve");
    }
}

function determineJWSAlgorithm(key) {
    switch (key.algorithm.name) {
      case "RSA-PSS":
        return psAlg$1(key);

      case "RSASSA-PKCS1-v1_5":
        return rsAlg$1(key);

      case "ECDSA":
        return esAlg$1(key);

      case "Ed25519":
        return "Ed25519";

      default:
        throw new UnsupportedOperationError$1("unsupported CryptoKey algorithm name");
    }
}

function isCryptoKey$1(key) {
    return key instanceof CryptoKey;
}

function isPrivateKey(key) {
    return isCryptoKey$1(key) && key.type === "private";
}

function isPublicKey(key) {
    return isCryptoKey$1(key) && key.type === "public";
}

function epochTime$1() {
    return Math.floor(Date.now() / 1e3);
}

async function generateProof$1(keypair, htu, htm, nonce, accessToken, additional) {
    const privateKey = keypair === null || keypair === void 0 ? void 0 : keypair.privateKey;
    const publicKey = keypair === null || keypair === void 0 ? void 0 : keypair.publicKey;
    if (!isPrivateKey(privateKey)) {
        throw new TypeError('"keypair.privateKey" must be a private CryptoKey');
    }
    if (!isPublicKey(publicKey)) {
        throw new TypeError('"keypair.publicKey" must be a public CryptoKey');
    }
    if (publicKey.extractable !== true) {
        throw new TypeError('"keypair.publicKey.extractable" must be true');
    }
    if (typeof htu !== "string") {
        throw new TypeError('"htu" must be a string');
    }
    if (typeof htm !== "string") {
        throw new TypeError('"htm" must be a string');
    }
    if (nonce !== undefined && typeof nonce !== "string") {
        throw new TypeError('"nonce" must be a string or undefined');
    }
    if (accessToken !== undefined && typeof accessToken !== "string") {
        throw new TypeError('"accessToken" must be a string or undefined');
    }
    if (additional !== undefined && (typeof additional !== "object" || additional === null || Array.isArray(additional))) {
        throw new TypeError('"additional" must be an object');
    }
    const claimsSet = Object.assign(Object.create(null), additional, {
        iat: epochTime$1(),
        jti: crypto.randomUUID(),
        htm: htm,
        nonce: nonce,
        htu: htu,
        ath: accessToken ? b64u$1(await crypto.subtle.digest("SHA-256", buf$1(accessToken))) : undefined
    });
    return jwt({
        alg: determineJWSAlgorithm(privateKey),
        typ: "dpop+jwt",
        jwk: await publicJwk(publicKey)
    }, claimsSet, privateKey);
}

async function publicJwk(key) {
    const {kty: kty, e: e, n: n, x: x, y: y, crv: crv} = await crypto.subtle.exportKey("jwk", key);
    return {
        kty: kty,
        crv: crv,
        e: e,
        n: n,
        x: x,
        y: y
    };
}

async function generateKeyPair$1(alg, options) {
    var _a;
    let algorithm;
    if (typeof alg !== "string" || alg.length === 0) {
        throw new TypeError('"alg" must be a non-empty string');
    }
    switch (alg) {
      case "PS256":
        algorithm = {
            name: "RSA-PSS",
            hash: "SHA-256",
            modulusLength: 2048,
            publicExponent: new Uint8Array([ 1, 0, 1 ])
        };
        break;

      case "RS256":
        algorithm = {
            name: "RSASSA-PKCS1-v1_5",
            hash: "SHA-256",
            modulusLength: 2048,
            publicExponent: new Uint8Array([ 1, 0, 1 ])
        };
        break;

      case "ES256":
        algorithm = {
            name: "ECDSA",
            namedCurve: "P-256"
        };
        break;

      case "Ed25519":
        algorithm = {
            name: "Ed25519"
        };
        break;

      default:
        throw new UnsupportedOperationError$1;
    }
    return crypto.subtle.generateKey(algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, [ "sign", "verify" ]);
}

async function calculateThumbprint$1(publicKey) {
    if (!isPublicKey(publicKey)) {
        throw new TypeError('"publicKey" must be a public CryptoKey');
    }
    if (publicKey.extractable !== true) {
        throw new TypeError('"publicKey.extractable" must be true');
    }
    const jwk = await publicJwk(publicKey);
    let components;
    switch (jwk.kty) {
      case "EC":
        components = {
            crv: jwk.crv,
            kty: jwk.kty,
            x: jwk.x,
            y: jwk.y
        };
        break;

      case "OKP":
        components = {
            crv: jwk.crv,
            kty: jwk.kty,
            x: jwk.x
        };
        break;

      case "RSA":
        components = {
            e: jwk.e,
            kty: jwk.kty,
            n: jwk.n
        };
        break;

      default:
        throw new UnsupportedOperationError$1("unsupported JWK kty");
    }
    return b64u$1(await crypto.subtle.digest({
        name: "SHA-256"
    }, buf$1(JSON.stringify(components))));
}

const DPOP_NONCE_HEADER = "dpop-nonce";

const KEY_PAIR_ALGORITHM = "ES256";

const SUPPORTED_GRANT_TYPES = [ "authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:token-exchange", "urn:okta:params:oauth:grant-type:webauthn", "http://auth0.com/oauth/grant-type/mfa-oob", "http://auth0.com/oauth/grant-type/mfa-otp", "http://auth0.com/oauth/grant-type/mfa-recovery-code" ];

function generateKeyPair() {
    return generateKeyPair$1(KEY_PAIR_ALGORITHM, {
        extractable: false
    });
}

function calculateThumbprint(keyPair) {
    return calculateThumbprint$1(keyPair.publicKey);
}

function normalizeUrl(url) {
    const parsedUrl = new URL(url);
    parsedUrl.search = "";
    parsedUrl.hash = "";
    return parsedUrl.href;
}

function generateProof(_ref) {
    let keyPair = _ref.keyPair, url = _ref.url, method = _ref.method, nonce = _ref.nonce, accessToken = _ref.accessToken;
    const normalizedUrl = normalizeUrl(url);
    return generateProof$1(keyPair, normalizedUrl, method, nonce, accessToken);
}

function isGrantTypeSupported(grantType) {
    return SUPPORTED_GRANT_TYPES.includes(grantType);
}

const sendMessage = (message, to) => new Promise(function(resolve, reject) {
    const messageChannel = new MessageChannel;
    messageChannel.port1.onmessage = function(event) {
        if (event.data.error) {
            reject(new Error(event.data.error));
        } else {
            resolve(event.data);
        }
        messageChannel.port1.close();
    };
    to.postMessage(message, [ messageChannel.port2 ]);
});

const createAbortController = () => new AbortController;

const fetchWithTimeout = (fetchUrl, fetchOptions, timeout) => {
    const controller = createAbortController();
    fetchOptions.signal = controller.signal;
    let timeoutId;
    return Promise.race([ fetch(fetchUrl, fetchOptions), new Promise((_, reject) => {
        timeoutId = setTimeout(() => {
            controller.abort();
            reject(new Error("Timeout when executing 'fetch'"));
        }, timeout);
    }) ]).finally(() => {
        clearTimeout(timeoutId);
    });
};

const fetchWithoutWorker = async (fetchUrl, fetchOptions, timeout) => {
    const response = await fetchWithTimeout(fetchUrl, fetchOptions, timeout);
    return {
        ok: response.ok,
        json: await response.json(),
        headers: fromEntries(response.headers)
    };
};

const fetchWithWorker = async (fetchUrl, audience, scope, fetchOptions, timeout, worker, useFormData, useMrrt, skipTokenStorage, preserveRefreshToken) => sendMessage({
    type: "refresh",
    auth: {
        audience: audience,
        scope: scope
    },
    timeout: timeout,
    fetchUrl: fetchUrl,
    fetchOptions: fetchOptions,
    useFormData: useFormData,
    useMrrt: useMrrt,
    skipTokenStorage: skipTokenStorage,
    preserveRefreshToken: preserveRefreshToken
}, worker);

const switchFetch = async function switchFetch(fetchUrl, audience, scope, fetchOptions, worker, useFormData) {
    let timeout = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : DEFAULT_FETCH_TIMEOUT_MS;
    let useMrrt = arguments.length > 7 ? arguments[7] : undefined;
    let skipTokenStorage = arguments.length > 8 ? arguments[8] : undefined;
    let preserveRefreshToken = arguments.length > 9 ? arguments[9] : undefined;
    if (worker) {
        return fetchWithWorker(fetchUrl, audience, scope, fetchOptions, timeout, worker, useFormData, useMrrt, skipTokenStorage, preserveRefreshToken);
    } else {
        return fetchWithoutWorker(fetchUrl, fetchOptions, timeout);
    }
};

async function getJSON(url, timeout, audience, scope, options, worker, useFormData, useMrrt, dpop, isDpopRetry, skipTokenStorage, preserveRefreshToken) {
    if (dpop) {
        const dpopProof = await dpop.generateProof({
            url: url,
            method: options.method || "GET",
            nonce: await dpop.getNonce()
        });
        options.headers = Object.assign(Object.assign({}, options.headers), {
            dpop: dpopProof
        });
    }
    let fetchError = null;
    let response;
    for (let i = 0; i < DEFAULT_SILENT_TOKEN_RETRY_COUNT; i++) {
        try {
            response = await switchFetch(url, audience, scope, options, worker, useFormData, timeout, useMrrt, skipTokenStorage, preserveRefreshToken);
            fetchError = null;
            break;
        } catch (e) {
            fetchError = e;
        }
    }
    if (fetchError) {
        throw fetchError;
    }
    const _a = response.json, error = _a.error, error_description = _a.error_description, data = __rest(_a, [ "error", "error_description" ]), _response = response, headers = _response.headers, ok = _response.ok;
    let newDpopNonce;
    if (dpop) {
        newDpopNonce = headers[DPOP_NONCE_HEADER];
        if (newDpopNonce) {
            await dpop.setNonce(newDpopNonce);
        }
    }
    if (!ok) {
        const errorMessage = error_description || "HTTP error. Unable to fetch ".concat(url);
        if (error === "mfa_required") {
            throw new MfaRequiredError(error, errorMessage, data.mfa_token, data.mfa_requirements);
        }
        if (error === "missing_refresh_token") {
            throw new MissingRefreshTokenError(audience, scope);
        }
        if (error === "use_dpop_nonce") {
            if (!dpop || !newDpopNonce || isDpopRetry) {
                throw new UseDpopNonceError(newDpopNonce);
            }
            return getJSON(url, timeout, audience, scope, options, worker, useFormData, useMrrt, dpop, true, skipTokenStorage, preserveRefreshToken);
        }
        throw new GenericError(error || "request_error", errorMessage);
    }
    return data;
}

async function oauthToken(_a, worker, skipTokenStorage) {
    var baseUrl = _a.baseUrl, timeout = _a.timeout, audience = _a.audience, scope = _a.scope, auth0Client = _a.auth0Client, useFormData = _a.useFormData, useMrrt = _a.useMrrt, dpop = _a.dpop, preserveRefreshToken = _a.preserveRefreshToken, options = __rest(_a, [ "baseUrl", "timeout", "audience", "scope", "auth0Client", "useFormData", "useMrrt", "dpop", "preserveRefreshToken" ]);
    const isTokenExchange = options.grant_type === "urn:ietf:params:oauth:grant-type:token-exchange";
    const isWebAuthn = options.grant_type === "urn:okta:params:oauth:grant-type:webauthn";
    const refreshWithMrrt = options.grant_type === "refresh_token" && useMrrt;
    const includeAudienceAndScope = isTokenExchange || isWebAuthn || refreshWithMrrt;
    const allParams = Object.assign(Object.assign(Object.assign({}, options), includeAudienceAndScope && audience && {
        audience: audience
    }), includeAudienceAndScope && scope && {
        scope: scope
    });
    const useJson = isWebAuthn || !useFormData;
    const body = useJson ? JSON.stringify(allParams) : createQueryParams(allParams);
    const isDpopSupported = isGrantTypeSupported(options.grant_type);
    return await getJSON("".concat(baseUrl, "/oauth/token"), timeout, audience || DEFAULT_AUDIENCE, scope, {
        method: "POST",
        body: body,
        headers: {
            "Content-Type": useJson ? "application/json" : "application/x-www-form-urlencoded",
            "Auth0-Client": btoa(JSON.stringify(stripAuth0Client(auth0Client || DEFAULT_AUTH0_CLIENT)))
        }
    }, worker, useFormData, useMrrt, isDpopSupported ? dpop : undefined, undefined, skipTokenStorage, preserveRefreshToken);
}

async function revokeToken(_ref, worker) {
    let baseUrl = _ref.baseUrl, timeout = _ref.timeout, auth0Client = _ref.auth0Client, useFormData = _ref.useFormData, refreshTokens = _ref.refreshTokens, audience = _ref.audience, client_id = _ref.client_id, onRefreshTokenRevoked = _ref.onRefreshTokenRevoked;
    const resolvedTimeout = timeout || DEFAULT_FETCH_TIMEOUT_MS;
    const token_type_hint = "refresh_token";
    const fetchUrl = "".concat(baseUrl, "/oauth/revoke");
    const headers = {
        "Content-Type": useFormData ? "application/x-www-form-urlencoded" : "application/json",
        "Auth0-Client": btoa(JSON.stringify(stripAuth0Client(auth0Client || DEFAULT_AUTH0_CLIENT)))
    };
    if (worker) {
        const baseParams = {
            client_id: client_id,
            token_type_hint: token_type_hint
        };
        const body = useFormData ? createQueryParams(baseParams) : JSON.stringify(baseParams);
        try {
            return await sendMessage({
                type: "revoke",
                timeout: resolvedTimeout,
                fetchUrl: fetchUrl,
                fetchOptions: {
                    method: "POST",
                    body: body,
                    headers: headers
                },
                useFormData: useFormData,
                auth: {
                    audience: audience !== null && audience !== void 0 ? audience : DEFAULT_AUDIENCE
                }
            }, worker);
        } catch (e) {
            throw new GenericError("revoke_error", e.message);
        }
    }
    for (const refreshToken of refreshTokens) {
        const params = {
            client_id: client_id,
            token_type_hint: token_type_hint,
            token: refreshToken
        };
        const body = useFormData ? createQueryParams(params) : JSON.stringify(params);
        const response = await fetchWithTimeout(fetchUrl, {
            method: "POST",
            body: body,
            headers: headers
        }, resolvedTimeout);
        if (!response.ok) {
            let error;
            let errorDescription;
            try {
                var _JSON$parse = JSON.parse(await response.text());
                error = _JSON$parse.error;
                errorDescription = _JSON$parse.error_description;
            } catch (_a) {}
            throw new GenericError(error || "revoke_error", errorDescription || "HTTP error ".concat(response.status));
        }
        await (onRefreshTokenRevoked === null || onRefreshTokenRevoked === void 0 ? void 0 : onRefreshTokenRevoked(refreshToken));
    }
}

const dedupe = arr => Array.from(new Set(arr));

const getUniqueScopes = function getUniqueScopes() {
    for (var _len = arguments.length, scopes = new Array(_len), _key = 0; _key < _len; _key++) {
        scopes[_key] = arguments[_key];
    }
    return dedupe(scopes.filter(Boolean).join(" ").trim().split(/\s+/)).join(" ");
};

const injectDefaultScopes = function injectDefaultScopes(authScopes, openIdScope) {
    for (var _len2 = arguments.length, extraScopes = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
        extraScopes[_key2 - 2] = arguments[_key2];
    }
    if (typeof authScopes !== "object") {
        return {
            [DEFAULT_AUDIENCE]: getUniqueScopes(openIdScope, authScopes, ...extraScopes)
        };
    }
    let requestedScopes = {
        [DEFAULT_AUDIENCE]: getUniqueScopes(openIdScope, ...extraScopes)
    };
    Object.keys(authScopes).forEach(key => {
        const audienceScopes = authScopes[key];
        requestedScopes[key] = getUniqueScopes(openIdScope, audienceScopes, ...extraScopes);
    });
    return requestedScopes;
};

const scopesToRequest = (authScopes, methodScopes, audience) => {
    let scope;
    if (audience) {
        scope = authScopes[audience];
    }
    if (!scope) {
        scope = authScopes[DEFAULT_AUDIENCE];
    }
    return getUniqueScopes(scope, methodScopes);
};

const CACHE_KEY_PREFIX = "@@auth0spajs@@";

const CACHE_KEY_ID_TOKEN_SUFFIX = "@@user@@";

class CacheKey {
    constructor(data) {
        let prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CACHE_KEY_PREFIX;
        let suffix = arguments.length > 2 ? arguments[2] : undefined;
        this.prefix = prefix;
        this.suffix = suffix;
        this.clientId = data.clientId;
        this.scope = data.scope;
        this.audience = data.audience;
    }
    toKey() {
        return [ this.prefix, this.clientId, this.audience, this.scope, this.suffix ].filter(Boolean).join("::");
    }
    static fromKey(key) {
        const _key$split = key.split("::"), _key$split2 = _slicedToArray(_key$split, 4), prefix = _key$split2[0], clientId = _key$split2[1], audience = _key$split2[2], scope = _key$split2[3];
        return new CacheKey({
            clientId: clientId,
            scope: scope,
            audience: audience
        }, prefix);
    }
    static fromCacheEntry(entry) {
        const scope = entry.scope, audience = entry.audience, clientId = entry.client_id;
        return new CacheKey({
            scope: scope,
            audience: audience,
            clientId: clientId
        });
    }
}

class LocalStorageCache {
    set(key, entry) {
        localStorage.setItem(key, JSON.stringify(entry));
    }
    get(key) {
        const json = window.localStorage.getItem(key);
        if (!json) return;
        try {
            const payload = JSON.parse(json);
            return payload;
        } catch (e) {
            return;
        }
    }
    remove(key) {
        localStorage.removeItem(key);
    }
    allKeys() {
        return Object.keys(window.localStorage).filter(key => key.startsWith(CACHE_KEY_PREFIX));
    }
}

class InMemoryCache {
    constructor() {
        this.enclosedCache = function() {
            let cache = {};
            return {
                set(key, entry) {
                    cache[key] = entry;
                },
                get(key) {
                    const cacheEntry = cache[key];
                    if (!cacheEntry) {
                        return;
                    }
                    return cacheEntry;
                },
                remove(key) {
                    delete cache[key];
                },
                allKeys() {
                    return Object.keys(cache);
                }
            };
        }();
    }
}

const DEFAULT_EXPIRY_ADJUSTMENT_SECONDS = 0;

class CacheManager {
    constructor(cache, keyManifest, nowProvider) {
        this.cache = cache;
        this.keyManifest = keyManifest;
        this.nowProvider = nowProvider || DEFAULT_NOW_PROVIDER;
    }
    async setIdToken(clientId, idToken, decodedToken) {
        var _a;
        const cacheKey = this.getIdTokenCacheKey(clientId);
        await this.cache.set(cacheKey, {
            id_token: idToken,
            decodedToken: decodedToken
        });
        await ((_a = this.keyManifest) === null || _a === void 0 ? void 0 : _a.add(cacheKey));
    }
    async getIdToken(cacheKey) {
        const entry = await this.cache.get(this.getIdTokenCacheKey(cacheKey.clientId));
        if (!entry && cacheKey.scope && cacheKey.audience) {
            const entryByScope = await this.get(cacheKey);
            if (!entryByScope) {
                return;
            }
            if (!entryByScope.id_token || !entryByScope.decodedToken) {
                return;
            }
            return {
                id_token: entryByScope.id_token,
                decodedToken: entryByScope.decodedToken
            };
        }
        if (!entry) {
            return;
        }
        return {
            id_token: entry.id_token,
            decodedToken: entry.decodedToken
        };
    }
    async get(cacheKey) {
        let expiryAdjustmentSeconds = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_EXPIRY_ADJUSTMENT_SECONDS;
        let useMrrt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        let cacheMode = arguments.length > 3 ? arguments[3] : undefined;
        var _a;
        let wrappedEntry = await this.cache.get(cacheKey.toKey());
        let resolvedCacheKey = cacheKey;
        if (!wrappedEntry) {
            const keys = await this.getCacheKeys();
            if (!keys) return;
            const matchedKey = this.matchExistingCacheKey(cacheKey, keys);
            if (matchedKey) {
                wrappedEntry = await this.cache.get(matchedKey);
                resolvedCacheKey = CacheKey.fromKey(matchedKey);
            }
            if (!wrappedEntry && useMrrt && cacheMode !== "cache-only") {
                return this.getEntryWithRefreshToken(cacheKey, keys);
            }
        }
        if (!wrappedEntry) {
            return;
        }
        const now = await this.nowProvider();
        const nowSeconds = Math.floor(now / 1e3);
        if (wrappedEntry.expiresAt - expiryAdjustmentSeconds < nowSeconds) {
            if (wrappedEntry.body.refresh_token) {
                return this.modifiedCachedEntry(wrappedEntry, resolvedCacheKey);
            }
            await this.cache.remove(resolvedCacheKey.toKey());
            await ((_a = this.keyManifest) === null || _a === void 0 ? void 0 : _a.remove(resolvedCacheKey.toKey()));
            return;
        }
        return wrappedEntry.body;
    }
    async modifiedCachedEntry(wrappedEntry, cacheKey) {
        const strippedBody = {
            refresh_token: wrappedEntry.body.refresh_token,
            audience: wrappedEntry.body.audience,
            scope: wrappedEntry.body.scope
        };
        const strippedEntry = {
            body: strippedBody,
            expiresAt: wrappedEntry.expiresAt
        };
        await this.cache.set(cacheKey.toKey(), strippedEntry);
        return {
            refresh_token: strippedBody.refresh_token,
            audience: strippedBody.audience,
            scope: strippedBody.scope
        };
    }
    async set(entry) {
        var _a;
        const cacheKey = new CacheKey({
            clientId: entry.client_id,
            scope: entry.scope,
            audience: entry.audience
        });
        const wrappedEntry = await this.wrapCacheEntry(entry);
        await this.cache.set(cacheKey.toKey(), wrappedEntry);
        await ((_a = this.keyManifest) === null || _a === void 0 ? void 0 : _a.add(cacheKey.toKey()));
    }
    async remove(client_id, audience, scope) {
        const cacheKey = new CacheKey({
            clientId: client_id,
            scope: scope,
            audience: audience
        });
        await this.cache.remove(cacheKey.toKey());
    }
    async stripRefreshToken(refreshToken) {
        var _a;
        const keys = await this.getCacheKeys();
        if (!keys) return;
        for (const key of keys) {
            const entry = await this.cache.get(key);
            if (((_a = entry === null || entry === void 0 ? void 0 : entry.body) === null || _a === void 0 ? void 0 : _a.refresh_token) === refreshToken) {
                delete entry.body.refresh_token;
                await this.cache.set(key, entry);
            }
        }
    }
    async clear(clientId) {
        var _a;
        const keys = await this.getCacheKeys();
        if (!keys) return;
        await keys.filter(key => clientId ? key.includes(clientId) : true).reduce(async (memo, key) => {
            await memo;
            await this.cache.remove(key);
        }, Promise.resolve());
        await ((_a = this.keyManifest) === null || _a === void 0 ? void 0 : _a.clear());
    }
    async wrapCacheEntry(entry) {
        const now = await this.nowProvider();
        const expiresInTime = Math.floor(now / 1e3) + entry.expires_in;
        return {
            body: entry,
            expiresAt: expiresInTime
        };
    }
    async getCacheKeys() {
        var _a;
        if (this.keyManifest) {
            return (_a = await this.keyManifest.get()) === null || _a === void 0 ? void 0 : _a.keys;
        } else if (this.cache.allKeys) {
            return this.cache.allKeys();
        }
    }
    getIdTokenCacheKey(clientId) {
        return new CacheKey({
            clientId: clientId
        }, CACHE_KEY_PREFIX, CACHE_KEY_ID_TOKEN_SUFFIX).toKey();
    }
    matchExistingCacheKey(keyToMatch, allKeys) {
        return allKeys.filter(key => {
            var _a;
            const cacheKey = CacheKey.fromKey(key);
            const scopeSet = new Set(cacheKey.scope && cacheKey.scope.split(" "));
            const scopesToMatch = ((_a = keyToMatch.scope) === null || _a === void 0 ? void 0 : _a.split(" ")) || [];
            const hasAllScopes = cacheKey.scope && scopesToMatch.reduce((acc, current) => acc && scopeSet.has(current), true);
            return cacheKey.prefix === CACHE_KEY_PREFIX && cacheKey.clientId === keyToMatch.clientId && cacheKey.audience === keyToMatch.audience && hasAllScopes;
        })[0];
    }
    async getEntryWithRefreshToken(keyToMatch, allKeys) {
        var _a;
        for (const key of allKeys) {
            const cacheKey = CacheKey.fromKey(key);
            if (cacheKey.prefix === CACHE_KEY_PREFIX && cacheKey.clientId === keyToMatch.clientId) {
                const cachedEntry = await this.cache.get(key);
                if ((_a = cachedEntry === null || cachedEntry === void 0 ? void 0 : cachedEntry.body) === null || _a === void 0 ? void 0 : _a.refresh_token) {
                    return {
                        refresh_token: cachedEntry.body.refresh_token,
                        audience: cachedEntry.body.audience,
                        scope: cachedEntry.body.scope
                    };
                }
            }
        }
        return undefined;
    }
    async getRefreshTokensByAudience(audience, clientId) {
        var _a;
        const keys = await this.getCacheKeys();
        if (!keys) return [];
        const tokens = new Set;
        for (const key of keys) {
            const cacheKey = CacheKey.fromKey(key);
            if (cacheKey.prefix === CACHE_KEY_PREFIX && cacheKey.clientId === clientId && cacheKey.audience === audience) {
                const entry = await this.cache.get(key);
                if ((_a = entry === null || entry === void 0 ? void 0 : entry.body) === null || _a === void 0 ? void 0 : _a.refresh_token) {
                    tokens.add(entry.body.refresh_token);
                }
            }
        }
        return Array.from(tokens);
    }
    async updateEntry(oldRefreshToken, newRefreshToken, clientId) {
        let useMrrt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
        const allKeys = await this.getCacheKeys();
        if (!allKeys) return;
        for (const key of allKeys) {
            if (CacheKey.fromKey(key).clientId !== clientId) continue;
            const entry = await this.cache.get(key);
            if (!(entry === null || entry === void 0 ? void 0 : entry.body)) continue;
            const rt = entry.body.refresh_token;
            if (rt && (useMrrt || rt === oldRefreshToken)) {
                entry.body.refresh_token = newRefreshToken;
                await this.cache.set(key, entry);
            }
        }
    }
}

const TRANSACTION_STORAGE_KEY_PREFIX = "a0.spajs.txs";

class TransactionManager {
    constructor(storage, clientId, cookieDomain) {
        this.storage = storage;
        this.clientId = clientId;
        this.cookieDomain = cookieDomain;
        this.storageKey = "".concat(TRANSACTION_STORAGE_KEY_PREFIX, ".").concat(this.clientId);
    }
    create(transaction) {
        this.storage.save(this.storageKey, transaction, {
            daysUntilExpire: 1,
            cookieDomain: this.cookieDomain
        });
    }
    get() {
        return this.storage.get(this.storageKey);
    }
    remove() {
        this.storage.remove(this.storageKey, {
            cookieDomain: this.cookieDomain
        });
    }
}

const isNumber = n => typeof n === "number";

const idTokendecoded = [ "iss", "aud", "exp", "nbf", "iat", "jti", "azp", "nonce", "auth_time", "at_hash", "c_hash", "acr", "amr", "sub_jwk", "cnf", "sip_from_tag", "sip_date", "sip_callid", "sip_cseq_num", "sip_via_branch", "orig", "dest", "mky", "events", "toe", "txn", "rph", "sid", "vot", "vtm" ];

const decode$1 = token => {
    const parts = token.split(".");
    const _parts = _slicedToArray(parts, 3), header = _parts[0], payload = _parts[1], signature = _parts[2];
    if (parts.length !== 3 || !header || !payload || !signature) {
        throw new Error("ID token could not be decoded");
    }
    const payloadJSON = JSON.parse(urlDecodeB64(payload));
    const claims = {
        __raw: token
    };
    const user = {};
    Object.keys(payloadJSON).forEach(k => {
        claims[k] = payloadJSON[k];
        if (!idTokendecoded.includes(k)) {
            user[k] = payloadJSON[k];
        }
    });
    return {
        encoded: {
            header: header,
            payload: payload,
            signature: signature
        },
        header: JSON.parse(urlDecodeB64(header)),
        claims: claims,
        user: user
    };
};

const verify$1 = options => {
    if (!options.id_token) {
        throw new Error("ID token is required but missing");
    }
    const decoded = decode$1(options.id_token);
    if (!decoded.claims.iss) {
        throw new Error("Issuer (iss) claim must be a string present in the ID token");
    }
    if (decoded.claims.iss !== options.iss) {
        throw new Error('Issuer (iss) claim mismatch in the ID token; expected "'.concat(options.iss, '", found "').concat(decoded.claims.iss, '"'));
    }
    if (!decoded.user.sub) {
        throw new Error("Subject (sub) claim must be a string present in the ID token");
    }
    if (decoded.header.alg !== "RS256") {
        throw new Error('Signature algorithm of "'.concat(decoded.header.alg, '" is not supported. Expected the ID token to be signed with "RS256".'));
    }
    if (!decoded.claims.aud || !(typeof decoded.claims.aud === "string" || Array.isArray(decoded.claims.aud))) {
        throw new Error("Audience (aud) claim must be a string or array of strings present in the ID token");
    }
    if (Array.isArray(decoded.claims.aud)) {
        if (!decoded.claims.aud.includes(options.aud)) {
            throw new Error('Audience (aud) claim mismatch in the ID token; expected "'.concat(options.aud, '" but was not one of "').concat(decoded.claims.aud.join(", "), '"'));
        }
        if (decoded.claims.aud.length > 1) {
            if (!decoded.claims.azp) {
                throw new Error("Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values");
            }
            if (decoded.claims.azp !== options.aud) {
                throw new Error('Authorized Party (azp) claim mismatch in the ID token; expected "'.concat(options.aud, '", found "').concat(decoded.claims.azp, '"'));
            }
        }
    } else if (decoded.claims.aud !== options.aud) {
        throw new Error('Audience (aud) claim mismatch in the ID token; expected "'.concat(options.aud, '" but found "').concat(decoded.claims.aud, '"'));
    }
    if (options.nonce) {
        if (!decoded.claims.nonce) {
            throw new Error("Nonce (nonce) claim must be a string present in the ID token");
        }
        if (decoded.claims.nonce !== options.nonce) {
            throw new Error('Nonce (nonce) claim mismatch in the ID token; expected "'.concat(options.nonce, '", found "').concat(decoded.claims.nonce, '"'));
        }
    }
    if (options.max_age && !isNumber(decoded.claims.auth_time)) {
        throw new Error("Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified");
    }
    if (decoded.claims.exp == null || !isNumber(decoded.claims.exp)) {
        throw new Error("Expiration Time (exp) claim must be a number present in the ID token");
    }
    if (!isNumber(decoded.claims.iat)) {
        throw new Error("Issued At (iat) claim must be a number present in the ID token");
    }
    const leeway = options.leeway || 60;
    const now = new Date(options.now || Date.now());
    const expDate = new Date(0);
    expDate.setUTCSeconds(decoded.claims.exp + leeway);
    if (now > expDate) {
        throw new Error("Expiration Time (exp) claim error in the ID token; current time (".concat(now, ") is after expiration time (").concat(expDate, ")"));
    }
    if (decoded.claims.nbf != null && isNumber(decoded.claims.nbf)) {
        const nbfDate = new Date(0);
        nbfDate.setUTCSeconds(decoded.claims.nbf - leeway);
        if (now < nbfDate) {
            throw new Error("Not Before time (nbf) claim in the ID token indicates that this token can't be used just yet. Current time (".concat(now, ") is before ").concat(nbfDate));
        }
    }
    if (decoded.claims.auth_time != null && isNumber(decoded.claims.auth_time)) {
        const authTimeDate = new Date(0);
        authTimeDate.setUTCSeconds(parseInt(decoded.claims.auth_time) + options.max_age + leeway);
        if (now > authTimeDate) {
            throw new Error("Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Current time (".concat(now, ") is after last auth at ").concat(authTimeDate));
        }
    }
    if (options.organization) {
        const org = options.organization.trim();
        if (org.startsWith("org_")) {
            const orgId = org;
            if (!decoded.claims.org_id) {
                throw new Error("Organization ID (org_id) claim must be a string present in the ID token");
            } else if (orgId !== decoded.claims.org_id) {
                throw new Error('Organization ID (org_id) claim mismatch in the ID token; expected "'.concat(orgId, '", found "').concat(decoded.claims.org_id, '"'));
            }
        } else {
            const orgName = org.toLowerCase();
            if (!decoded.claims.org_name) {
                throw new Error("Organization Name (org_name) claim must be a string present in the ID token");
            } else if (orgName !== decoded.claims.org_name) {
                throw new Error('Organization Name (org_name) claim mismatch in the ID token; expected "'.concat(orgName, '", found "').concat(decoded.claims.org_name, '"'));
            }
        }
    }
    return decoded;
};

var __assign = commonjsGlobal && commonjsGlobal.__assign || function() {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};

function stringifyAttribute(name, value) {
    if (!value) {
        return "";
    }
    var stringified = "; " + name;
    if (value === true) {
        return stringified;
    }
    return stringified + "=" + value;
}

function stringifyAttributes(attributes) {
    if (typeof attributes.expires === "number") {
        var expires = new Date;
        expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e5);
        attributes.expires = expires;
    }
    return stringifyAttribute("Expires", attributes.expires ? attributes.expires.toUTCString() : "") + stringifyAttribute("Domain", attributes.domain) + stringifyAttribute("Path", attributes.path) + stringifyAttribute("Secure", attributes.secure) + stringifyAttribute("SameSite", attributes.sameSite);
}

function encode$2(name, value, attributes) {
    return encodeURIComponent(name).replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent).replace(/\(/g, "%28").replace(/\)/g, "%29") + "=" + encodeURIComponent(value).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent) + stringifyAttributes(attributes);
}

function parse(cookieString) {
    var result = {};
    var cookies = cookieString ? cookieString.split("; ") : [];
    var rdecode = /(%[\dA-F]{2})+/gi;
    for (var i = 0; i < cookies.length; i++) {
        var parts = cookies[i].split("=");
        var cookie = parts.slice(1).join("=");
        if (cookie.charAt(0) === '"') {
            cookie = cookie.slice(1, -1);
        }
        try {
            var name_1 = parts[0].replace(rdecode, decodeURIComponent);
            result[name_1] = cookie.replace(rdecode, decodeURIComponent);
        } catch (e) {}
    }
    return result;
}

function getAll() {
    return parse(document.cookie);
}

function get(name) {
    return getAll()[name];
}

var get_1 = get;

function set(name, value, attributes) {
    document.cookie = encode$2(name, value, __assign({
        path: "/"
    }, attributes));
}

var set_1 = set;

function remove(name, attributes) {
    set(name, "", __assign(__assign({}, attributes), {
        expires: -1
    }));
}

var remove_1 = remove;

const CookieStorage = {
    get(key) {
        const value = get_1(key);
        if (typeof value === "undefined") {
            return;
        }
        return JSON.parse(value);
    },
    save(key, value, options) {
        let cookieAttributes = {};
        if ("https:" === window.location.protocol) {
            cookieAttributes = {
                secure: true,
                sameSite: "none"
            };
        }
        if (options === null || options === void 0 ? void 0 : options.daysUntilExpire) {
            cookieAttributes.expires = options.daysUntilExpire;
        }
        if (options === null || options === void 0 ? void 0 : options.cookieDomain) {
            cookieAttributes.domain = options.cookieDomain;
        }
        set_1(key, JSON.stringify(value), cookieAttributes);
    },
    remove(key, options) {
        let cookieAttributes = {};
        if (options === null || options === void 0 ? void 0 : options.cookieDomain) {
            cookieAttributes.domain = options.cookieDomain;
        }
        remove_1(key, cookieAttributes);
    }
};

const LEGACY_PREFIX = "_legacy_";

const CookieStorageWithLegacySameSite = {
    get(key) {
        const value = CookieStorage.get(key);
        if (value) {
            return value;
        }
        return CookieStorage.get("".concat(LEGACY_PREFIX).concat(key));
    },
    save(key, value, options) {
        let cookieAttributes = {};
        if ("https:" === window.location.protocol) {
            cookieAttributes = {
                secure: true
            };
        }
        if (options === null || options === void 0 ? void 0 : options.daysUntilExpire) {
            cookieAttributes.expires = options.daysUntilExpire;
        }
        if (options === null || options === void 0 ? void 0 : options.cookieDomain) {
            cookieAttributes.domain = options.cookieDomain;
        }
        set_1("".concat(LEGACY_PREFIX).concat(key), JSON.stringify(value), cookieAttributes);
        CookieStorage.save(key, value, options);
    },
    remove(key, options) {
        let cookieAttributes = {};
        if (options === null || options === void 0 ? void 0 : options.cookieDomain) {
            cookieAttributes.domain = options.cookieDomain;
        }
        remove_1(key, cookieAttributes);
        CookieStorage.remove(key, options);
        CookieStorage.remove("".concat(LEGACY_PREFIX).concat(key), options);
    }
};

const SessionStorage = {
    get(key) {
        if (typeof sessionStorage === "undefined") {
            return;
        }
        const value = sessionStorage.getItem(key);
        if (value == null) {
            return;
        }
        return JSON.parse(value);
    },
    save(key, value) {
        sessionStorage.setItem(key, JSON.stringify(value));
    },
    remove(key) {
        sessionStorage.removeItem(key);
    }
};

const RefreshTokenMode = {
    Offline: "offline",
    Online: "online"
};

exports.ResponseType = void 0;

(function(ResponseType) {
    ResponseType["Code"] = "code";
    ResponseType["ConnectCode"] = "connect_code";
})(exports.ResponseType || (exports.ResponseType = {}));

class User {}

function decodeBase64$1(base64, enableUnicode) {
    var binaryString = atob(base64);
    if (enableUnicode) {
        var binaryView = new Uint8Array(binaryString.length);
        for (var i = 0, n = binaryString.length; i < n; ++i) {
            binaryView[i] = binaryString.charCodeAt(i);
        }
        return String.fromCharCode.apply(null, new Uint16Array(binaryView.buffer));
    }
    return binaryString;
}

function createURL(base64, sourcemapArg, enableUnicodeArg) {
    var sourcemap = sourcemapArg === undefined ? null : sourcemapArg;
    var enableUnicode = enableUnicodeArg === undefined ? false : enableUnicodeArg;
    var source = decodeBase64$1(base64, enableUnicode);
    var start = source.indexOf("\n", 10) + 1;
    var body = source.substring(start) + (sourcemap ? "//# sourceMappingURL=" + sourcemap : "");
    var blob = new Blob([ body ], {
        type: "application/javascript"
    });
    return URL.createObjectURL(blob);
}

function createBase64WorkerFactory(base64, sourcemapArg, enableUnicodeArg) {
    var url;
    return function WorkerFactory(options) {
        url = url || createURL(base64, sourcemapArg, enableUnicodeArg);
        return new Worker(url, options);
    };
}

var WorkerFactory = createBase64WorkerFactory("Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24oKSB7CiAgICAidXNlIHN0cmljdCI7CiAgICBmdW5jdGlvbiBfYXJyYXlMaWtlVG9BcnJheShyLCBhKSB7CiAgICAgICAgKG51bGwgPT0gYSB8fCBhID4gci5sZW5ndGgpICYmIChhID0gci5sZW5ndGgpOwogICAgICAgIGZvciAodmFyIGUgPSAwLCBuID0gQXJyYXkoYSk7IGUgPCBhOyBlKyspIG5bZV0gPSByW2VdOwogICAgICAgIHJldHVybiBuOwogICAgfQogICAgZnVuY3Rpb24gX2FycmF5V2l0aEhvbGVzKHIpIHsKICAgICAgICBpZiAoQXJyYXkuaXNBcnJheShyKSkgcmV0dXJuIHI7CiAgICB9CiAgICBmdW5jdGlvbiBfaXRlcmFibGVUb0FycmF5TGltaXQociwgbCkgewogICAgICAgIHZhciB0ID0gbnVsbCA9PSByID8gbnVsbCA6ICJ1bmRlZmluZWQiICE9IHR5cGVvZiBTeW1ib2wgJiYgcltTeW1ib2wuaXRlcmF0b3JdIHx8IHJbIkBAaXRlcmF0b3IiXTsKICAgICAgICBpZiAobnVsbCAhPSB0KSB7CiAgICAgICAgICAgIHZhciBlLCBuLCBpLCB1LCBhID0gW10sIGYgPSAhMCwgbyA9ICExOwogICAgICAgICAgICB0cnkgewogICAgICAgICAgICAgICAgaWYgKGkgPSAodCA9IHQuY2FsbChyKSkubmV4dCwgMCA9PT0gbCkgewogICAgICAgICAgICAgICAgICAgIGlmIChPYmplY3QodCkgIT09IHQpIHJldHVybjsKICAgICAgICAgICAgICAgICAgICBmID0gITE7CiAgICAgICAgICAgICAgICB9IGVsc2UgZm9yICg7IShmID0gKGUgPSBpLmNhbGwodCkpLmRvbmUpICYmIChhLnB1c2goZS52YWx1ZSksIGEubGVuZ3RoICE9PSBsKTsgZiA9ICEwKSA7CiAgICAgICAgICAgIH0gY2F0Y2ggKHIpIHsKICAgICAgICAgICAgICAgIG8gPSAhMCwgbiA9IHI7CiAgICAgICAgICAgIH0gZmluYWxseSB7CiAgICAgICAgICAgICAgICB0cnkgewogICAgICAgICAgICAgICAgICAgIGlmICghZiAmJiBudWxsICE9IHQucmV0dXJuICYmICh1ID0gdC5yZXR1cm4oKSwgT2JqZWN0KHUpICE9PSB1KSkgcmV0dXJuOwogICAgICAgICAgICAgICAgfSBmaW5hbGx5IHsKICAgICAgICAgICAgICAgICAgICBpZiAobykgdGhyb3cgbjsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgICAgICByZXR1cm4gYTsKICAgICAgICB9CiAgICB9CiAgICBmdW5jdGlvbiBfbm9uSXRlcmFibGVSZXN0KCkgewogICAgICAgIHRocm93IG5ldyBUeXBlRXJyb3IoIkludmFsaWQgYXR0ZW1wdCB0byBkZXN0cnVjdHVyZSBub24taXRlcmFibGUgaW5zdGFuY2UuXG5JbiBvcmRlciB0byBiZSBpdGVyYWJsZSwgbm9uLWFycmF5IG9iamVjdHMgbXVzdCBoYXZlIGEgW1N5bWJvbC5pdGVyYXRvcl0oKSBtZXRob2QuIik7CiAgICB9CiAgICBmdW5jdGlvbiBfc2xpY2VkVG9BcnJheShyLCBlKSB7CiAgICAgICAgcmV0dXJuIF9hcnJheVdpdGhIb2xlcyhyKSB8fCBfaXRlcmFibGVUb0FycmF5TGltaXQociwgZSkgfHwgX3Vuc3VwcG9ydGVkSXRlcmFibGVUb0FycmF5KHIsIGUpIHx8IF9ub25JdGVyYWJsZVJlc3QoKTsKICAgIH0KICAgIGZ1bmN0aW9uIF91bnN1cHBvcnRlZEl0ZXJhYmxlVG9BcnJheShyLCBhKSB7CiAgICAgICAgaWYgKHIpIHsKICAgICAgICAgICAgaWYgKCJzdHJpbmciID09IHR5cGVvZiByKSByZXR1cm4gX2FycmF5TGlrZVRvQXJyYXkociwgYSk7CiAgICAgICAgICAgIHZhciB0ID0ge30udG9TdHJpbmcuY2FsbChyKS5zbGljZSg4LCAtMSk7CiAgICAgICAgICAgIHJldHVybiAiT2JqZWN0IiA9PT0gdCAmJiByLmNvbnN0cnVjdG9yICYmICh0ID0gci5jb25zdHJ1Y3Rvci5uYW1lKSwgIk1hcCIgPT09IHQgfHwgIlNldCIgPT09IHQgPyBBcnJheS5mcm9tKHIpIDogIkFyZ3VtZW50cyIgPT09IHQgfHwgL14oPzpVaXxJKW50KD86OHwxNnwzMikoPzpDbGFtcGVkKT9BcnJheSQvLnRlc3QodCkgPyBfYXJyYXlMaWtlVG9BcnJheShyLCBhKSA6IHZvaWQgMDsKICAgICAgICB9CiAgICB9CiAgICBjbGFzcyBHZW5lcmljRXJyb3IgZXh0ZW5kcyBFcnJvciB7CiAgICAgICAgY29uc3RydWN0b3IoZXJyb3IsIGVycm9yX2Rlc2NyaXB0aW9uKSB7CiAgICAgICAgICAgIHN1cGVyKGVycm9yX2Rlc2NyaXB0aW9uKTsKICAgICAgICAgICAgdGhpcy5lcnJvciA9IGVycm9yOwogICAgICAgICAgICB0aGlzLmVycm9yX2Rlc2NyaXB0aW9uID0gZXJyb3JfZGVzY3JpcHRpb247CiAgICAgICAgICAgIE9iamVjdC5zZXRQcm90b3R5cGVPZih0aGlzLCBHZW5lcmljRXJyb3IucHJvdG90eXBlKTsKICAgICAgICB9CiAgICAgICAgc3RhdGljIGZyb21QYXlsb2FkKF9yZWYpIHsKICAgICAgICAgICAgbGV0IGVycm9yID0gX3JlZi5lcnJvciwgZXJyb3JfZGVzY3JpcHRpb24gPSBfcmVmLmVycm9yX2Rlc2NyaXB0aW9uOwogICAgICAgICAgICByZXR1cm4gbmV3IEdlbmVyaWNFcnJvcihlcnJvciwgZXJyb3JfZGVzY3JpcHRpb24pOwogICAgICAgIH0KICAgIH0KICAgIGNsYXNzIE1pc3NpbmdSZWZyZXNoVG9rZW5FcnJvciBleHRlbmRzIEdlbmVyaWNFcnJvciB7CiAgICAgICAgY29uc3RydWN0b3IoYXVkaWVuY2UsIHNjb3BlKSB7CiAgICAgICAgICAgIHN1cGVyKCJtaXNzaW5nX3JlZnJlc2hfdG9rZW4iLCAiTWlzc2luZyBSZWZyZXNoIFRva2VuIChhdWRpZW5jZTogJyIuY29uY2F0KHZhbHVlT3JFbXB0eVN0cmluZyhhdWRpZW5jZSwgWyAiZGVmYXVsdCIgXSksICInLCBzY29wZTogJyIpLmNvbmNhdCh2YWx1ZU9yRW1wdHlTdHJpbmcoc2NvcGUpLCAiJykiKSk7CiAgICAgICAgICAgIHRoaXMuYXVkaWVuY2UgPSBhdWRpZW5jZTsKICAgICAgICAgICAgdGhpcy5zY29wZSA9IHNjb3BlOwogICAgICAgICAgICBPYmplY3Quc2V0UHJvdG90eXBlT2YodGhpcywgTWlzc2luZ1JlZnJlc2hUb2tlbkVycm9yLnByb3RvdHlwZSk7CiAgICAgICAgfQogICAgfQogICAgZnVuY3Rpb24gdmFsdWVPckVtcHR5U3RyaW5nKHZhbHVlKSB7CiAgICAgICAgbGV0IGV4Y2x1ZGUgPSBhcmd1bWVudHMubGVuZ3RoID4gMSAmJiBhcmd1bWVudHNbMV0gIT09IHVuZGVmaW5lZCA/IGFyZ3VtZW50c1sxXSA6IFtdOwogICAgICAgIHJldHVybiB2YWx1ZSAmJiAhZXhjbHVkZS5pbmNsdWRlcyh2YWx1ZSkgPyB2YWx1ZSA6ICIiOwogICAgfQogICAgZnVuY3Rpb24gX19yZXN0KHMsIGUpIHsKICAgICAgICB2YXIgdCA9IHt9OwogICAgICAgIGZvciAodmFyIHAgaW4gcykgaWYgKE9iamVjdC5wcm90b3R5cGUuaGFzT3duUHJvcGVydHkuY2FsbChzLCBwKSAmJiBlLmluZGV4T2YocCkgPCAwKSB0W3BdID0gc1twXTsKICAgICAgICBpZiAocyAhPSBudWxsICYmIHR5cGVvZiBPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzID09PSAiZnVuY3Rpb24iKSBmb3IgKHZhciBpID0gMCwgcCA9IE9iamVjdC5nZXRPd25Qcm9wZXJ0eVN5bWJvbHMocyk7IGkgPCBwLmxlbmd0aDsgaSsrKSB7CiAgICAgICAgICAgIGlmIChlLmluZGV4T2YocFtpXSkgPCAwICYmIE9iamVjdC5wcm90b3R5cGUucHJvcGVydHlJc0VudW1lcmFibGUuY2FsbChzLCBwW2ldKSkgdFtwW2ldXSA9IHNbcFtpXV07CiAgICAgICAgfQogICAgICAgIHJldHVybiB0OwogICAgfQogICAgdHlwZW9mIFN1cHByZXNzZWRFcnJvciA9PT0gImZ1bmN0aW9uIiA/IFN1cHByZXNzZWRFcnJvciA6IGZ1bmN0aW9uKGVycm9yLCBzdXBwcmVzc2VkLCBtZXNzYWdlKSB7CiAgICAgICAgdmFyIGUgPSBuZXcgRXJyb3IobWVzc2FnZSk7CiAgICAgICAgcmV0dXJuIGUubmFtZSA9ICJTdXBwcmVzc2VkRXJyb3IiLCBlLmVycm9yID0gZXJyb3IsIGUuc3VwcHJlc3NlZCA9IHN1cHByZXNzZWQsIGU7CiAgICB9OwogICAgY29uc3Qgc3RyaXBVbmRlZmluZWQgPSBwYXJhbXMgPT4gT2JqZWN0LmtleXMocGFyYW1zKS5maWx0ZXIoayA9PiB0eXBlb2YgcGFyYW1zW2tdICE9PSAidW5kZWZpbmVkIikucmVkdWNlKChhY2MsIGtleSkgPT4gT2JqZWN0LmFzc2lnbihPYmplY3QuYXNzaWduKHt9LCBhY2MpLCB7CiAgICAgICAgW2tleV06IHBhcmFtc1trZXldCiAgICB9KSwge30pOwogICAgY29uc3QgY3JlYXRlUXVlcnlQYXJhbXMgPSBfYSA9PiB7CiAgICAgICAgdmFyIGNsaWVudF9pZCA9IF9hLmNsaWVudElkLCBwYXJhbXMgPSBfX3Jlc3QoX2EsIFsgImNsaWVudElkIiBdKTsKICAgICAgICByZXR1cm4gbmV3IFVSTFNlYXJjaFBhcmFtcyhzdHJpcFVuZGVmaW5lZChPYmplY3QuYXNzaWduKHsKICAgICAgICAgICAgY2xpZW50X2lkOiBjbGllbnRfaWQKICAgICAgICB9LCBwYXJhbXMpKSkudG9TdHJpbmcoKTsKICAgIH07CiAgICBjb25zdCBmcm9tRW50cmllcyA9IGl0ZXJhYmxlID0+IFsgLi4uaXRlcmFibGUgXS5yZWR1Y2UoKG9iaiwgX3JlZikgPT4gewogICAgICAgIGxldCBfcmVmMiA9IF9zbGljZWRUb0FycmF5KF9yZWYsIDIpLCBrZXkgPSBfcmVmMlswXSwgdmFsID0gX3JlZjJbMV07CiAgICAgICAgb2JqW2tleV0gPSB2YWw7CiAgICAgICAgcmV0dXJuIG9iajsKICAgIH0sIHt9KTsKICAgIGxldCByZWZyZXNoVG9rZW5zID0ge307CiAgICBsZXQgYWxsb3dlZEJhc2VVcmwgPSBudWxsOwogICAgY29uc3QgY2FjaGVLZXkgPSAoYXVkaWVuY2UsIHNjb3BlKSA9PiAiIi5jb25jYXQoYXVkaWVuY2UsICJ8IikuY29uY2F0KHNjb3BlKTsKICAgIGNvbnN0IGNhY2hlS2V5Q29udGFpbnNBdWRpZW5jZSA9IChhdWRpZW5jZSwgY2FjaGVLZXkpID0+IGNhY2hlS2V5LnN0YXJ0c1dpdGgoIiIuY29uY2F0KGF1ZGllbmNlLCAifCIpKTsKICAgIGNvbnN0IGdldFJlZnJlc2hUb2tlbiA9IChhdWRpZW5jZSwgc2NvcGUpID0+IHJlZnJlc2hUb2tlbnNbY2FjaGVLZXkoYXVkaWVuY2UsIHNjb3BlKV07CiAgICBjb25zdCBzZXRSZWZyZXNoVG9rZW4gPSAocmVmcmVzaFRva2VuLCBhdWRpZW5jZSwgc2NvcGUpID0+IHJlZnJlc2hUb2tlbnNbY2FjaGVLZXkoYXVkaWVuY2UsIHNjb3BlKV0gPSByZWZyZXNoVG9rZW47CiAgICBjb25zdCBkZWxldGVSZWZyZXNoVG9rZW4gPSAoYXVkaWVuY2UsIHNjb3BlKSA9PiBkZWxldGUgcmVmcmVzaFRva2Vuc1tjYWNoZUtleShhdWRpZW5jZSwgc2NvcGUpXTsKICAgIGNvbnN0IGdldFJlZnJlc2hUb2tlbnNCeUF1ZGllbmNlID0gYXVkaWVuY2UgPT4gewogICAgICAgIGNvbnN0IHNlZW4gPSBuZXcgU2V0OwogICAgICAgIE9iamVjdC5lbnRyaWVzKHJlZnJlc2hUb2tlbnMpLmZvckVhY2goX3JlZiA9PiB7CiAgICAgICAgICAgIGxldCBfcmVmMiA9IF9zbGljZWRUb0FycmF5KF9yZWYsIDIpLCBrZXkgPSBfcmVmMlswXSwgdG9rZW4gPSBfcmVmMlsxXTsKICAgICAgICAgICAgaWYgKGNhY2hlS2V5Q29udGFpbnNBdWRpZW5jZShhdWRpZW5jZSwga2V5KSkgewogICAgICAgICAgICAgICAgc2Vlbi5hZGQodG9rZW4pOwogICAgICAgICAgICB9CiAgICAgICAgfSk7CiAgICAgICAgcmV0dXJuIEFycmF5LmZyb20oc2Vlbik7CiAgICB9OwogICAgY29uc3QgZGVsZXRlUmVmcmVzaFRva2Vuc0J5VmFsdWUgPSByZWZyZXNoVG9rZW4gPT4gewogICAgICAgIE9iamVjdC5lbnRyaWVzKHJlZnJlc2hUb2tlbnMpLmZvckVhY2goX3JlZjMgPT4gewogICAgICAgICAgICBsZXQgX3JlZjQgPSBfc2xpY2VkVG9BcnJheShfcmVmMywgMiksIGtleSA9IF9yZWY0WzBdLCB0b2tlbiA9IF9yZWY0WzFdOwogICAgICAgICAgICBpZiAodG9rZW4gPT09IHJlZnJlc2hUb2tlbikgewogICAgICAgICAgICAgICAgZGVsZXRlIHJlZnJlc2hUb2tlbnNba2V5XTsKICAgICAgICAgICAgfQogICAgICAgIH0pOwogICAgfTsKICAgIGNvbnN0IHdhaXQgPSB0aW1lID0+IG5ldyBQcm9taXNlKHJlc29sdmUgPT4gc2V0VGltZW91dChyZXNvbHZlLCB0aW1lKSk7CiAgICBjb25zdCBmb3JtRGF0YVRvT2JqZWN0ID0gZm9ybURhdGEgPT4gewogICAgICAgIGNvbnN0IHF1ZXJ5UGFyYW1zID0gbmV3IFVSTFNlYXJjaFBhcmFtcyhmb3JtRGF0YSk7CiAgICAgICAgY29uc3QgcGFyc2VkUXVlcnkgPSB7fTsKICAgICAgICBxdWVyeVBhcmFtcy5mb3JFYWNoKCh2YWwsIGtleSkgPT4gewogICAgICAgICAgICBwYXJzZWRRdWVyeVtrZXldID0gdmFsOwogICAgICAgIH0pOwogICAgICAgIHJldHVybiBwYXJzZWRRdWVyeTsKICAgIH07CiAgICBjb25zdCB1cGRhdGVSZWZyZXNoVG9rZW5zID0gKG9sZFJlZnJlc2hUb2tlbiwgbmV3UmVmcmVzaFRva2VuKSA9PiB7CiAgICAgICAgT2JqZWN0LmVudHJpZXMocmVmcmVzaFRva2VucykuZm9yRWFjaChfcmVmNSA9PiB7CiAgICAgICAgICAgIGxldCBfcmVmNiA9IF9zbGljZWRUb0FycmF5KF9yZWY1LCAyKSwga2V5ID0gX3JlZjZbMF0sIHRva2VuID0gX3JlZjZbMV07CiAgICAgICAgICAgIGlmICh0b2tlbiA9PT0gb2xkUmVmcmVzaFRva2VuKSB7CiAgICAgICAgICAgICAgICByZWZyZXNoVG9rZW5zW2tleV0gPSBuZXdSZWZyZXNoVG9rZW47CiAgICAgICAgICAgIH0KICAgICAgICB9KTsKICAgIH07CiAgICBjb25zdCBjaGVja0Rvd25zY29waW5nID0gKHNjb3BlLCBhdWRpZW5jZSkgPT4gewogICAgICAgIGNvbnN0IGZpbmRDb2luY2lkZW5jZSA9IE9iamVjdC5rZXlzKHJlZnJlc2hUb2tlbnMpLmZpbmQoa2V5ID0+IHsKICAgICAgICAgICAgaWYgKGtleSAhPT0gImxhdGVzdF9yZWZyZXNoX3Rva2VuIikgewogICAgICAgICAgICAgICAgY29uc3QgaXNTYW1lQXVkaWVuY2UgPSBjYWNoZUtleUNvbnRhaW5zQXVkaWVuY2UoYXVkaWVuY2UsIGtleSk7CiAgICAgICAgICAgICAgICBjb25zdCBzY29wZXNLZXkgPSBrZXkuc3BsaXQoInwiKVsxXS5zcGxpdCgiICIpOwogICAgICAgICAgICAgICAgY29uc3QgcmVxdWVzdGVkU2NvcGVzID0gc2NvcGUuc3BsaXQoIiAiKTsKICAgICAgICAgICAgICAgIGNvbnN0IHNjb3Blc0FyZUluY2x1ZGVkID0gcmVxdWVzdGVkU2NvcGVzLmV2ZXJ5KGtleSA9PiBzY29wZXNLZXkuaW5jbHVkZXMoa2V5KSk7CiAgICAgICAgICAgICAgICByZXR1cm4gaXNTYW1lQXVkaWVuY2UgJiYgc2NvcGVzQXJlSW5jbHVkZWQ7CiAgICAgICAgICAgIH0KICAgICAgICB9KTsKICAgICAgICByZXR1cm4gZmluZENvaW5jaWRlbmNlID8gdHJ1ZSA6IGZhbHNlOwogICAgfTsKICAgIGNvbnN0IG1lc3NhZ2VIYW5kbGVyID0gYXN5bmMgX3JlZjcgPT4gewogICAgICAgIGxldCBfcmVmNyRkYXRhID0gX3JlZjcuZGF0YSwgdGltZW91dCA9IF9yZWY3JGRhdGEudGltZW91dCwgYXV0aCA9IF9yZWY3JGRhdGEuYXV0aCwgZmV0Y2hVcmwgPSBfcmVmNyRkYXRhLmZldGNoVXJsLCBmZXRjaE9wdGlvbnMgPSBfcmVmNyRkYXRhLmZldGNoT3B0aW9ucywgdXNlRm9ybURhdGEgPSBfcmVmNyRkYXRhLnVzZUZvcm1EYXRhLCB1c2VNcnJ0ID0gX3JlZjckZGF0YS51c2VNcnJ0LCBza2lwVG9rZW5TdG9yYWdlID0gX3JlZjckZGF0YS5za2lwVG9rZW5TdG9yYWdlLCBwcmVzZXJ2ZVJlZnJlc2hUb2tlbiA9IF9yZWY3JGRhdGEucHJlc2VydmVSZWZyZXNoVG9rZW4sIF9yZWY3JHBvcnRzID0gX3NsaWNlZFRvQXJyYXkoX3JlZjcucG9ydHMsIDEpLCBwb3J0ID0gX3JlZjckcG9ydHNbMF07CiAgICAgICAgbGV0IGhlYWRlcnMgPSB7fTsKICAgICAgICBsZXQganNvbjsKICAgICAgICBsZXQgcmVmcmVzaFRva2VuOwogICAgICAgIGNvbnN0IF9yZWY4ID0gYXV0aCB8fCB7fSwgYXVkaWVuY2UgPSBfcmVmOC5hdWRpZW5jZSwgc2NvcGUgPSBfcmVmOC5zY29wZTsKICAgICAgICB0cnkgewogICAgICAgICAgICBjb25zdCBib2R5ID0gdXNlRm9ybURhdGEgPyBmb3JtRGF0YVRvT2JqZWN0KGZldGNoT3B0aW9ucy5ib2R5KSA6IEpTT04ucGFyc2UoZmV0Y2hPcHRpb25zLmJvZHkpOwogICAgICAgICAgICBpZiAoIWJvZHkucmVmcmVzaF90b2tlbiAmJiBib2R5LmdyYW50X3R5cGUgPT09ICJyZWZyZXNoX3Rva2VuIikgewogICAgICAgICAgICAgICAgcmVmcmVzaFRva2VuID0gZ2V0UmVmcmVzaFRva2VuKGF1ZGllbmNlLCBzY29wZSk7CiAgICAgICAgICAgICAgICBpZiAoIXJlZnJlc2hUb2tlbiAmJiB1c2VNcnJ0KSB7CiAgICAgICAgICAgICAgICAgICAgY29uc3QgbGF0ZXN0UmVmcmVzaFRva2VuID0gcmVmcmVzaFRva2Vuc1sibGF0ZXN0X3JlZnJlc2hfdG9rZW4iXTsKICAgICAgICAgICAgICAgICAgICBjb25zdCBpc0Rvd25zY29waW5nID0gY2hlY2tEb3duc2NvcGluZyhzY29wZSwgYXVkaWVuY2UpOwogICAgICAgICAgICAgICAgICAgIGlmIChsYXRlc3RSZWZyZXNoVG9rZW4gJiYgIWlzRG93bnNjb3BpbmcpIHsKICAgICAgICAgICAgICAgICAgICAgICAgcmVmcmVzaFRva2VuID0gbGF0ZXN0UmVmcmVzaFRva2VuOwogICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGlmICghcmVmcmVzaFRva2VuKSB7CiAgICAgICAgICAgICAgICAgICAgdGhyb3cgbmV3IE1pc3NpbmdSZWZyZXNoVG9rZW5FcnJvcihhdWRpZW5jZSwgc2NvcGUpOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgZmV0Y2hPcHRpb25zLmJvZHkgPSB1c2VGb3JtRGF0YSA/IGNyZWF0ZVF1ZXJ5UGFyYW1zKE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSwgYm9keSksIHsKICAgICAgICAgICAgICAgICAgICByZWZyZXNoX3Rva2VuOiByZWZyZXNoVG9rZW4KICAgICAgICAgICAgICAgIH0pKSA6IEpTT04uc3RyaW5naWZ5KE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSwgYm9keSksIHsKICAgICAgICAgICAgICAgICAgICByZWZyZXNoX3Rva2VuOiByZWZyZXNoVG9rZW4KICAgICAgICAgICAgICAgIH0pKTsKICAgICAgICAgICAgfSBlbHNlIGlmIChib2R5Lm1mYV90b2tlbikgewogICAgICAgICAgICAgICAgcmVmcmVzaFRva2VuID0gZ2V0UmVmcmVzaFRva2VuKGF1ZGllbmNlLCBzY29wZSk7CiAgICAgICAgICAgICAgICBpZiAoIXJlZnJlc2hUb2tlbiAmJiB1c2VNcnJ0KSB7CiAgICAgICAgICAgICAgICAgICAgcmVmcmVzaFRva2VuID0gcmVmcmVzaFRva2Vuc1sibGF0ZXN0X3JlZnJlc2hfdG9rZW4iXTsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgICAgICBsZXQgYWJvcnRDb250cm9sbGVyOwogICAgICAgICAgICBpZiAodHlwZW9mIEFib3J0Q29udHJvbGxlciA9PT0gImZ1bmN0aW9uIikgewogICAgICAgICAgICAgICAgYWJvcnRDb250cm9sbGVyID0gbmV3IEFib3J0Q29udHJvbGxlcjsKICAgICAgICAgICAgICAgIGZldGNoT3B0aW9ucy5zaWduYWwgPSBhYm9ydENvbnRyb2xsZXIuc2lnbmFsOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGxldCByZXNwb25zZTsKICAgICAgICAgICAgdHJ5IHsKICAgICAgICAgICAgICAgIHJlc3BvbnNlID0gYXdhaXQgUHJvbWlzZS5yYWNlKFsgd2FpdCh0aW1lb3V0KSwgZmV0Y2goZmV0Y2hVcmwsIE9iamVjdC5hc3NpZ24oe30sIGZldGNoT3B0aW9ucykpIF0pOwogICAgICAgICAgICB9IGNhdGNoIChlcnJvcikgewogICAgICAgICAgICAgICAgcG9ydC5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgICAgICAgICAgZXJyb3I6IGVycm9yLm1lc3NhZ2UKICAgICAgICAgICAgICAgIH0pOwogICAgICAgICAgICAgICAgcmV0dXJuOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGlmICghcmVzcG9uc2UpIHsKICAgICAgICAgICAgICAgIGlmIChhYm9ydENvbnRyb2xsZXIpIGFib3J0Q29udHJvbGxlci5hYm9ydCgpOwogICAgICAgICAgICAgICAgcG9ydC5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgICAgICAgICAgZXJyb3I6ICJUaW1lb3V0IHdoZW4gZXhlY3V0aW5nICdmZXRjaCciCiAgICAgICAgICAgICAgICB9KTsKICAgICAgICAgICAgICAgIHJldHVybjsKICAgICAgICAgICAgfQogICAgICAgICAgICBoZWFkZXJzID0gZnJvbUVudHJpZXMocmVzcG9uc2UuaGVhZGVycyk7CiAgICAgICAgICAgIGpzb24gPSBhd2FpdCByZXNwb25zZS5qc29uKCk7CiAgICAgICAgICAgIGlmIChza2lwVG9rZW5TdG9yYWdlKSB7CiAgICAgICAgICAgICAgICBkZWxldGUganNvbi5yZWZyZXNoX3Rva2VuOwogICAgICAgICAgICAgICAgcG9ydC5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgICAgICAgICAgb2s6IHJlc3BvbnNlLm9rLAogICAgICAgICAgICAgICAgICAgIGpzb246IGpzb24sCiAgICAgICAgICAgICAgICAgICAgaGVhZGVyczogaGVhZGVycwogICAgICAgICAgICAgICAgfSk7CiAgICAgICAgICAgICAgICByZXR1cm47CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKGpzb24ucmVmcmVzaF90b2tlbikgewogICAgICAgICAgICAgICAgaWYgKHVzZU1ycnQpIHsKICAgICAgICAgICAgICAgICAgICByZWZyZXNoVG9rZW5zWyJsYXRlc3RfcmVmcmVzaF90b2tlbiJdID0ganNvbi5yZWZyZXNoX3Rva2VuOwogICAgICAgICAgICAgICAgICAgIHVwZGF0ZVJlZnJlc2hUb2tlbnMocmVmcmVzaFRva2VuLCBqc29uLnJlZnJlc2hfdG9rZW4pOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgc2V0UmVmcmVzaFRva2VuKGpzb24ucmVmcmVzaF90b2tlbiwgYXVkaWVuY2UsIHNjb3BlKTsKICAgICAgICAgICAgICAgIGRlbGV0ZSBqc29uLnJlZnJlc2hfdG9rZW47CiAgICAgICAgICAgIH0gZWxzZSBpZiAoIXByZXNlcnZlUmVmcmVzaFRva2VuKSB7CiAgICAgICAgICAgICAgICBkZWxldGVSZWZyZXNoVG9rZW4oYXVkaWVuY2UsIHNjb3BlKTsKICAgICAgICAgICAgfQogICAgICAgICAgICBwb3J0LnBvc3RNZXNzYWdlKHsKICAgICAgICAgICAgICAgIG9rOiByZXNwb25zZS5vaywKICAgICAgICAgICAgICAgIGpzb246IGpzb24sCiAgICAgICAgICAgICAgICBoZWFkZXJzOiBoZWFkZXJzCiAgICAgICAgICAgIH0pOwogICAgICAgIH0gY2F0Y2ggKGVycm9yKSB7CiAgICAgICAgICAgIHBvcnQucG9zdE1lc3NhZ2UoewogICAgICAgICAgICAgICAgb2s6IGZhbHNlLAogICAgICAgICAgICAgICAganNvbjogewogICAgICAgICAgICAgICAgICAgIGVycm9yOiBlcnJvci5lcnJvciwKICAgICAgICAgICAgICAgICAgICBlcnJvcl9kZXNjcmlwdGlvbjogZXJyb3IubWVzc2FnZQogICAgICAgICAgICAgICAgfSwKICAgICAgICAgICAgICAgIGhlYWRlcnM6IGhlYWRlcnMKICAgICAgICAgICAgfSk7CiAgICAgICAgfQogICAgfTsKICAgIGNvbnN0IHJldm9rZU1lc3NhZ2VIYW5kbGVyID0gYXN5bmMgX3JlZjkgPT4gewogICAgICAgIGxldCBfcmVmOSRkYXRhID0gX3JlZjkuZGF0YSwgdGltZW91dCA9IF9yZWY5JGRhdGEudGltZW91dCwgYXV0aCA9IF9yZWY5JGRhdGEuYXV0aCwgZmV0Y2hVcmwgPSBfcmVmOSRkYXRhLmZldGNoVXJsLCBmZXRjaE9wdGlvbnMgPSBfcmVmOSRkYXRhLmZldGNoT3B0aW9ucywgdXNlRm9ybURhdGEgPSBfcmVmOSRkYXRhLnVzZUZvcm1EYXRhLCBfcmVmOSRwb3J0cyA9IF9zbGljZWRUb0FycmF5KF9yZWY5LnBvcnRzLCAxKSwgcG9ydCA9IF9yZWY5JHBvcnRzWzBdOwogICAgICAgIGNvbnN0IF9yZWYwID0gYXV0aCB8fCB7fSwgYXVkaWVuY2UgPSBfcmVmMC5hdWRpZW5jZTsKICAgICAgICB0cnkgewogICAgICAgICAgICBjb25zdCB0b2tlbnNUb1Jldm9rZSA9IGdldFJlZnJlc2hUb2tlbnNCeUF1ZGllbmNlKGF1ZGllbmNlKTsKICAgICAgICAgICAgaWYgKHRva2Vuc1RvUmV2b2tlLmxlbmd0aCA9PT0gMCkgewogICAgICAgICAgICAgICAgcG9ydC5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgICAgICAgICAgb2s6IHRydWUKICAgICAgICAgICAgICAgIH0pOwogICAgICAgICAgICAgICAgcmV0dXJuOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGNvbnN0IGJhc2VCb2R5ID0gdXNlRm9ybURhdGEgPyBmb3JtRGF0YVRvT2JqZWN0KGZldGNoT3B0aW9ucy5ib2R5KSA6IEpTT04ucGFyc2UoZmV0Y2hPcHRpb25zLmJvZHkpOwogICAgICAgICAgICBmb3IgKGNvbnN0IHJlZnJlc2hUb2tlbiBvZiB0b2tlbnNUb1Jldm9rZSkgewogICAgICAgICAgICAgICAgY29uc3QgYm9keSA9IHVzZUZvcm1EYXRhID8gY3JlYXRlUXVlcnlQYXJhbXMoT2JqZWN0LmFzc2lnbihPYmplY3QuYXNzaWduKHt9LCBiYXNlQm9keSksIHsKICAgICAgICAgICAgICAgICAgICB0b2tlbjogcmVmcmVzaFRva2VuCiAgICAgICAgICAgICAgICB9KSkgOiBKU09OLnN0cmluZ2lmeShPYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30sIGJhc2VCb2R5KSwgewogICAgICAgICAgICAgICAgICAgIHRva2VuOiByZWZyZXNoVG9rZW4KICAgICAgICAgICAgICAgIH0pKTsKICAgICAgICAgICAgICAgIGxldCBhYm9ydENvbnRyb2xsZXI7CiAgICAgICAgICAgICAgICBsZXQgc2lnbmFsOwogICAgICAgICAgICAgICAgaWYgKHR5cGVvZiBBYm9ydENvbnRyb2xsZXIgPT09ICJmdW5jdGlvbiIpIHsKICAgICAgICAgICAgICAgICAgICBhYm9ydENvbnRyb2xsZXIgPSBuZXcgQWJvcnRDb250cm9sbGVyOwogICAgICAgICAgICAgICAgICAgIHNpZ25hbCA9IGFib3J0Q29udHJvbGxlci5zaWduYWw7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICBsZXQgdGltZW91dElkOwogICAgICAgICAgICAgICAgbGV0IHJlc3BvbnNlOwogICAgICAgICAgICAgICAgdHJ5IHsKICAgICAgICAgICAgICAgICAgICByZXNwb25zZSA9IGF3YWl0IFByb21pc2UucmFjZShbIG5ldyBQcm9taXNlKHJlc29sdmUgPT4gewogICAgICAgICAgICAgICAgICAgICAgICB0aW1lb3V0SWQgPSBzZXRUaW1lb3V0KHJlc29sdmUsIHRpbWVvdXQpOwogICAgICAgICAgICAgICAgICAgIH0pLCBmZXRjaChmZXRjaFVybCwgT2JqZWN0LmFzc2lnbihPYmplY3QuYXNzaWduKHt9LCBmZXRjaE9wdGlvbnMpLCB7CiAgICAgICAgICAgICAgICAgICAgICAgIGJvZHk6IGJvZHksCiAgICAgICAgICAgICAgICAgICAgICAgIHNpZ25hbDogc2lnbmFsCiAgICAgICAgICAgICAgICAgICAgfSkpIF0pLmZpbmFsbHkoKCkgPT4gY2xlYXJUaW1lb3V0KHRpbWVvdXRJZCkpOwogICAgICAgICAgICAgICAgfSBjYXRjaCAoZXJyb3IpIHsKICAgICAgICAgICAgICAgICAgICBwb3J0LnBvc3RNZXNzYWdlKHsKICAgICAgICAgICAgICAgICAgICAgICAgZXJyb3I6IGVycm9yLm1lc3NhZ2UKICAgICAgICAgICAgICAgICAgICB9KTsKICAgICAgICAgICAgICAgICAgICByZXR1cm47CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICBpZiAoIXJlc3BvbnNlKSB7CiAgICAgICAgICAgICAgICAgICAgaWYgKGFib3J0Q29udHJvbGxlcikgYWJvcnRDb250cm9sbGVyLmFib3J0KCk7CiAgICAgICAgICAgICAgICAgICAgcG9ydC5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgICAgICAgICAgICAgIGVycm9yOiAiVGltZW91dCB3aGVuIGV4ZWN1dGluZyAnZmV0Y2gnIgogICAgICAgICAgICAgICAgICAgIH0pOwogICAgICAgICAgICAgICAgICAgIHJldHVybjsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGlmICghcmVzcG9uc2Uub2spIHsKICAgICAgICAgICAgICAgICAgICBsZXQgZXJyb3JEZXNjcmlwdGlvbjsKICAgICAgICAgICAgICAgICAgICB0cnkgewogICAgICAgICAgICAgICAgICAgICAgICBjb25zdCBfSlNPTiRwYXJzZSA9IEpTT04ucGFyc2UoYXdhaXQgcmVzcG9uc2UudGV4dCgpKSwgZXJyb3JfZGVzY3JpcHRpb24gPSBfSlNPTiRwYXJzZS5lcnJvcl9kZXNjcmlwdGlvbjsKICAgICAgICAgICAgICAgICAgICAgICAgZXJyb3JEZXNjcmlwdGlvbiA9IGVycm9yX2Rlc2NyaXB0aW9uOwogICAgICAgICAgICAgICAgICAgIH0gY2F0Y2ggKF9hKSB7fQogICAgICAgICAgICAgICAgICAgIHBvcnQucG9zdE1lc3NhZ2UoewogICAgICAgICAgICAgICAgICAgICAgICBlcnJvcjogZXJyb3JEZXNjcmlwdGlvbiB8fCAiSFRUUCBlcnJvciAiLmNvbmNhdChyZXNwb25zZS5zdGF0dXMpCiAgICAgICAgICAgICAgICAgICAgfSk7CiAgICAgICAgICAgICAgICAgICAgcmV0dXJuOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgZGVsZXRlUmVmcmVzaFRva2Vuc0J5VmFsdWUocmVmcmVzaFRva2VuKTsKICAgICAgICAgICAgfQogICAgICAgICAgICBwb3J0LnBvc3RNZXNzYWdlKHsKICAgICAgICAgICAgICAgIG9rOiB0cnVlCiAgICAgICAgICAgIH0pOwogICAgICAgIH0gY2F0Y2ggKGVycm9yKSB7CiAgICAgICAgICAgIHBvcnQucG9zdE1lc3NhZ2UoewogICAgICAgICAgICAgICAgZXJyb3I6IGVycm9yLm1lc3NhZ2UgfHwgIlVua25vd24gZXJyb3IgZHVyaW5nIHRva2VuIHJldm9jYXRpb24iCiAgICAgICAgICAgIH0pOwogICAgICAgIH0KICAgIH07CiAgICBjb25zdCBpc0F1dGhvcml6ZWRXb3JrZXJSZXF1ZXN0ID0gKHdvcmtlclJlcXVlc3QsIGV4cGVjdGVkUGF0aCkgPT4gewogICAgICAgIGlmICghYWxsb3dlZEJhc2VVcmwpIHsKICAgICAgICAgICAgcmV0dXJuIGZhbHNlOwogICAgICAgIH0KICAgICAgICB0cnkgewogICAgICAgICAgICBjb25zdCBhbGxvd2VkQmFzZU9yaWdpbiA9IG5ldyBVUkwoYWxsb3dlZEJhc2VVcmwpLm9yaWdpbjsKICAgICAgICAgICAgY29uc3QgcmVxdWVzdGVkVXJsID0gbmV3IFVSTCh3b3JrZXJSZXF1ZXN0LmZldGNoVXJsKTsKICAgICAgICAgICAgcmV0dXJuIHJlcXVlc3RlZFVybC5vcmlnaW4gPT09IGFsbG93ZWRCYXNlT3JpZ2luICYmIHJlcXVlc3RlZFVybC5wYXRobmFtZSA9PT0gZXhwZWN0ZWRQYXRoOwogICAgICAgIH0gY2F0Y2ggKF9hKSB7CiAgICAgICAgICAgIHJldHVybiBmYWxzZTsKICAgICAgICB9CiAgICB9OwogICAgY29uc3QgbWVzc2FnZVJvdXRlciA9IGV2ZW50ID0+IHsKICAgICAgICBjb25zdCBkYXRhID0gZXZlbnQuZGF0YSwgcG9ydHMgPSBldmVudC5wb3J0czsKICAgICAgICBjb25zdCBfcG9ydHMgPSBfc2xpY2VkVG9BcnJheShwb3J0cywgMSksIHBvcnQgPSBfcG9ydHNbMF07CiAgICAgICAgaWYgKCJ0eXBlIiBpbiBkYXRhICYmIGRhdGEudHlwZSA9PT0gImluaXQiKSB7CiAgICAgICAgICAgIGlmIChhbGxvd2VkQmFzZVVybCA9PT0gbnVsbCkgewogICAgICAgICAgICAgICAgdHJ5IHsKICAgICAgICAgICAgICAgICAgICBuZXcgVVJMKGRhdGEuYWxsb3dlZEJhc2VVcmwpOwogICAgICAgICAgICAgICAgICAgIGFsbG93ZWRCYXNlVXJsID0gZGF0YS5hbGxvd2VkQmFzZVVybDsKICAgICAgICAgICAgICAgIH0gY2F0Y2ggKF9hKSB7CiAgICAgICAgICAgICAgICAgICAgcmV0dXJuOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIHJldHVybjsKICAgICAgICB9CiAgICAgICAgaWYgKCJ0eXBlIiBpbiBkYXRhICYmIGRhdGEudHlwZSA9PT0gImNsZWFyIikgewogICAgICAgICAgICByZWZyZXNoVG9rZW5zID0ge307CiAgICAgICAgICAgIHBvcnQgPT09IG51bGwgfHwgcG9ydCA9PT0gdm9pZCAwID8gdm9pZCAwIDogcG9ydC5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgICAgICBvazogdHJ1ZQogICAgICAgICAgICB9KTsKICAgICAgICAgICAgcmV0dXJuOwogICAgICAgIH0KICAgICAgICBpZiAoInR5cGUiIGluIGRhdGEgJiYgZGF0YS50eXBlID09PSAicmV2b2tlIikgewogICAgICAgICAgICBpZiAoIWlzQXV0aG9yaXplZFdvcmtlclJlcXVlc3QoZGF0YSwgIi9vYXV0aC9yZXZva2UiKSkgewogICAgICAgICAgICAgICAgcG9ydCA9PT0gbnVsbCB8fCBwb3J0ID09PSB2b2lkIDAgPyB2b2lkIDAgOiBwb3J0LnBvc3RNZXNzYWdlKHsKICAgICAgICAgICAgICAgICAgICBvazogZmFsc2UsCiAgICAgICAgICAgICAgICAgICAganNvbjogewogICAgICAgICAgICAgICAgICAgICAgICBlcnJvcjogImludmFsaWRfZmV0Y2hfdXJsIiwKICAgICAgICAgICAgICAgICAgICAgICAgZXJyb3JfZGVzY3JpcHRpb246ICJVbmF1dGhvcml6ZWQgZmV0Y2ggVVJMIgogICAgICAgICAgICAgICAgICAgIH0sCiAgICAgICAgICAgICAgICAgICAgaGVhZGVyczoge30KICAgICAgICAgICAgICAgIH0pOwogICAgICAgICAgICAgICAgcmV0dXJuOwogICAgICAgICAgICB9CiAgICAgICAgICAgIHJldm9rZU1lc3NhZ2VIYW5kbGVyKGV2ZW50KTsKICAgICAgICAgICAgcmV0dXJuOwogICAgICAgIH0KICAgICAgICBpZiAoISgiZmV0Y2hVcmwiIGluIGRhdGEpIHx8ICFpc0F1dGhvcml6ZWRXb3JrZXJSZXF1ZXN0KGRhdGEsICIvb2F1dGgvdG9rZW4iKSkgewogICAgICAgICAgICBwb3J0ID09PSBudWxsIHx8IHBvcnQgPT09IHZvaWQgMCA/IHZvaWQgMCA6IHBvcnQucG9zdE1lc3NhZ2UoewogICAgICAgICAgICAgICAgb2s6IGZhbHNlLAogICAgICAgICAgICAgICAganNvbjogewogICAgICAgICAgICAgICAgICAgIGVycm9yOiAiaW52YWxpZF9mZXRjaF91cmwiLAogICAgICAgICAgICAgICAgICAgIGVycm9yX2Rlc2NyaXB0aW9uOiAiVW5hdXRob3JpemVkIGZldGNoIFVSTCIKICAgICAgICAgICAgICAgIH0sCiAgICAgICAgICAgICAgICBoZWFkZXJzOiB7fQogICAgICAgICAgICB9KTsKICAgICAgICAgICAgcmV0dXJuOwogICAgICAgIH0KICAgICAgICBtZXNzYWdlSGFuZGxlcihldmVudCk7CiAgICB9OwogICAgewogICAgICAgIGFkZEV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLCBtZXNzYWdlUm91dGVyKTsKICAgIH0KfSkoKTsKCg==", null, false);

class CacheKeyManifest {
    constructor(cache, clientId) {
        this.cache = cache;
        this.clientId = clientId;
        this.manifestKey = this.createManifestKeyFrom(this.clientId);
    }
    async add(key) {
        var _a;
        const keys = new Set(((_a = await this.cache.get(this.manifestKey)) === null || _a === void 0 ? void 0 : _a.keys) || []);
        keys.add(key);
        await this.cache.set(this.manifestKey, {
            keys: [ ...keys ]
        });
    }
    async remove(key) {
        const entry = await this.cache.get(this.manifestKey);
        if (entry) {
            const keys = new Set(entry.keys);
            keys.delete(key);
            if (keys.size > 0) {
                return await this.cache.set(this.manifestKey, {
                    keys: [ ...keys ]
                });
            }
            return await this.cache.remove(this.manifestKey);
        }
    }
    get() {
        return this.cache.get(this.manifestKey);
    }
    clear() {
        return this.cache.remove(this.manifestKey);
    }
    createManifestKeyFrom(clientId) {
        return "".concat(CACHE_KEY_PREFIX, "::").concat(clientId);
    }
}

const GET_TOKEN_SILENTLY_LOCK_KEY = "auth0.lock.getTokenSilently";

const GET_TOKEN_FROM_IFRAME_LOCK_KEY = "auth0.lock.getTokenFromIFrame";

const buildGetTokenSilentlyLockKey = (clientId, audience) => "".concat(GET_TOKEN_SILENTLY_LOCK_KEY, ".").concat(clientId, ".").concat(audience);

const buildIframeLockKey = clientId => "".concat(GET_TOKEN_FROM_IFRAME_LOCK_KEY, ".").concat(clientId);

const buildOrganizationHintCookieName = clientId => "auth0.".concat(clientId, ".organization_hint");

const OLD_IS_AUTHENTICATED_COOKIE_NAME = "auth0.is.authenticated";

const buildIsAuthenticatedCookieName = clientId => "auth0.".concat(clientId, ".is.authenticated");

const cacheLocationBuilders = {
    memory: () => (new InMemoryCache).enclosedCache,
    localstorage: () => new LocalStorageCache
};

const cacheFactory = location => cacheLocationBuilders[location];

const getAuthorizeParams = (clientOptions, scope, authorizationParams, state, nonce, code_challenge, redirect_uri, response_mode, thumbprint) => Object.assign(Object.assign(Object.assign({
    client_id: clientOptions.clientId
}, clientOptions.authorizationParams), authorizationParams), {
    scope: scopesToRequest(scope, authorizationParams.scope, authorizationParams.audience),
    response_type: "code",
    response_mode: response_mode || "query",
    state: state,
    nonce: nonce,
    redirect_uri: redirect_uri || clientOptions.authorizationParams.redirect_uri,
    code_challenge: code_challenge,
    code_challenge_method: "S256",
    dpop_jkt: thumbprint
});

const patchOpenUrlWithOnRedirect = options => {
    const openUrl = options.openUrl, onRedirect = options.onRedirect, originalOptions = __rest(options, [ "openUrl", "onRedirect" ]);
    const result = Object.assign(Object.assign({}, originalOptions), {
        openUrl: openUrl === false || openUrl ? openUrl : onRedirect
    });
    return result;
};

const withoutOnlineAccessScope = scopes => scopes.filter(scope => scope !== ONLINE_ACCESS_SCOPE);

const allScopesAreIncluded = (scopeToInclude, scopes) => {
    const scopeGroup = (scopes === null || scopes === void 0 ? void 0 : scopes.split(" ")) || [];
    const scopesToInclude = (scopeToInclude === null || scopeToInclude === void 0 ? void 0 : scopeToInclude.split(" ")) || [];
    return scopesToInclude.every(key => scopeGroup.includes(key));
};

const getMissingScopes = (requestedScope, respondedScope, onlineAccess) => {
    const splitRequested = (requestedScope === null || requestedScope === void 0 ? void 0 : requestedScope.split(" ")) || [];
    const requestedScopes = onlineAccess ? withoutOnlineAccessScope(splitRequested) : splitRequested;
    const respondedScopes = (respondedScope === null || respondedScope === void 0 ? void 0 : respondedScope.split(" ")) || [];
    const missingScopes = requestedScopes.filter(scope => respondedScopes.indexOf(scope) == -1);
    return missingScopes.join(",");
};

const getScopeToRequest = (useMrrt, authorizationParams, cachedAudience, cachedScope) => {
    var _a;
    if (useMrrt && cachedAudience && cachedScope) {
        if (authorizationParams.audience !== cachedAudience) {
            return authorizationParams.scope;
        }
        const cachedScopes = cachedScope.split(" ");
        const newScopes = ((_a = authorizationParams.scope) === null || _a === void 0 ? void 0 : _a.split(" ")) || [];
        const newScopesAreIncluded = newScopes.every(scope => cachedScopes.includes(scope));
        return cachedScopes.length >= newScopes.length && newScopesAreIncluded ? cachedScope : authorizationParams.scope;
    }
    return authorizationParams.scope;
};

const isRefreshWithMrrt = (cachedAudience, cachedScope, requestAudience, requestScope) => {
    if (cachedAudience !== requestAudience) {
        return true;
    }
    return !allScopesAreIncluded(requestScope, cachedScope);
};

const VERSION = 1;

const NAME = "auth0-spa-js";

const TABLES = {
    NONCE: "nonce",
    KEYPAIR: "keypair"
};

const AUTH0_NONCE_ID = "auth0";

class DpopStorage {
    constructor(clientId) {
        this.clientId = clientId;
    }
    getVersion() {
        return VERSION;
    }
    createDbHandle() {
        const req = window.indexedDB.open(NAME, this.getVersion());
        return new Promise((resolve, reject) => {
            req.onupgradeneeded = () => Object.values(TABLES).forEach(t => req.result.createObjectStore(t));
            req.onerror = () => reject(req.error);
            req.onsuccess = () => resolve(req.result);
        });
    }
    async getDbHandle() {
        if (!this.dbHandle) {
            this.dbHandle = await this.createDbHandle();
        }
        return this.dbHandle;
    }
    async executeDbRequest(table, mode, requestFactory) {
        const db = await this.getDbHandle();
        const txn = db.transaction(table, mode);
        const store = txn.objectStore(table);
        const request = requestFactory(store);
        return new Promise((resolve, reject) => {
            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(request.error);
        });
    }
    buildKey(id) {
        const finalId = id ? "_".concat(id) : AUTH0_NONCE_ID;
        return "".concat(this.clientId, "::").concat(finalId);
    }
    setNonce(nonce, id) {
        return this.save(TABLES.NONCE, this.buildKey(id), nonce);
    }
    setKeyPair(keyPair) {
        return this.save(TABLES.KEYPAIR, this.buildKey(), keyPair);
    }
    async save(table, key, obj) {
        return void await this.executeDbRequest(table, "readwrite", table => table.put(obj, key));
    }
    findNonce(id) {
        return this.find(TABLES.NONCE, this.buildKey(id));
    }
    findKeyPair() {
        return this.find(TABLES.KEYPAIR, this.buildKey());
    }
    find(table, key) {
        return this.executeDbRequest(table, "readonly", table => table.get(key));
    }
    async deleteBy(table, predicate) {
        const allKeys = await this.executeDbRequest(table, "readonly", table => table.getAllKeys());
        await Promise.all((allKeys === null || allKeys === void 0 ? void 0 : allKeys.filter(predicate).map(k => this.executeDbRequest(table, "readwrite", table => table.delete(k)))) || []);
    }
    deleteByClientId(table, clientId) {
        return this.deleteBy(table, k => typeof k === "string" && k.startsWith("".concat(clientId, "::")));
    }
    clearNonces() {
        return this.deleteByClientId(TABLES.NONCE, this.clientId);
    }
    clearKeyPairs() {
        return this.deleteByClientId(TABLES.KEYPAIR, this.clientId);
    }
}

class Dpop {
    constructor(clientId) {
        this.storage = new DpopStorage(clientId);
    }
    getNonce(id) {
        return this.storage.findNonce(id);
    }
    setNonce(nonce, id) {
        return this.storage.setNonce(nonce, id);
    }
    async getOrGenerateKeyPair() {
        let keyPair = await this.storage.findKeyPair();
        if (!keyPair) {
            keyPair = await generateKeyPair();
            await this.storage.setKeyPair(keyPair);
        }
        return keyPair;
    }
    async generateProof(params) {
        const keyPair = await this.getOrGenerateKeyPair();
        return generateProof(Object.assign({
            keyPair: keyPair
        }, params));
    }
    async calculateThumbprint() {
        const keyPair = await this.getOrGenerateKeyPair();
        return calculateThumbprint(keyPair);
    }
    async clear() {
        await Promise.all([ this.storage.clearNonces(), this.storage.clearKeyPairs() ]);
    }
}

var TokenType;

(function(TokenType) {
    TokenType["Bearer"] = "Bearer";
    TokenType["DPoP"] = "DPoP";
})(TokenType || (TokenType = {}));

class Fetcher {
    constructor(config, hooks) {
        this.hooks = hooks;
        this.config = Object.assign(Object.assign({}, config), {
            fetch: config.fetch || (typeof window === "undefined" ? fetch : window.fetch.bind(window))
        });
    }
    isAbsoluteUrl(url) {
        return /^(https?:)?\/\//i.test(url);
    }
    buildUrl(baseUrl, url) {
        if (url) {
            if (this.isAbsoluteUrl(url)) {
                return url;
            }
            if (baseUrl) {
                return "".concat(baseUrl.replace(/\/?\/$/, ""), "/").concat(url.replace(/^\/+/, ""));
            }
        }
        throw new TypeError("`url` must be absolute or `baseUrl` non-empty.");
    }
    getAccessToken(authParams) {
        return this.config.getAccessToken ? this.config.getAccessToken(authParams) : this.hooks.getAccessToken(authParams);
    }
    extractUrl(info) {
        if (typeof info === "string") {
            return info;
        }
        if (info instanceof URL) {
            return info.href;
        }
        return info.url;
    }
    buildBaseRequest(info, init) {
        if (!this.config.baseUrl) {
            return new Request(info, init);
        }
        const finalUrl = this.buildUrl(this.config.baseUrl, this.extractUrl(info));
        const finalInfo = info instanceof Request ? new Request(finalUrl, info) : finalUrl;
        return new Request(finalInfo, init);
    }
    setAuthorizationHeader(request, accessToken) {
        let tokenType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : TokenType.Bearer;
        request.headers.set("authorization", "".concat(tokenType, " ").concat(accessToken));
    }
    async setDpopProofHeader(request, accessToken) {
        if (!this.config.dpopNonceId) {
            return;
        }
        const dpopNonce = await this.hooks.getDpopNonce();
        const dpopProof = await this.hooks.generateDpopProof({
            accessToken: accessToken,
            method: request.method,
            nonce: dpopNonce,
            url: request.url
        });
        request.headers.set("dpop", dpopProof);
    }
    async prepareRequest(request, authParams) {
        const accessTokenResponse = await this.getAccessToken(authParams);
        if (accessTokenResponse === undefined) {
            throw new GenericError("missing_access_token", "No access token available");
        }
        let tokenType;
        let accessToken;
        if (typeof accessTokenResponse === "string") {
            tokenType = this.config.dpopNonceId ? TokenType.DPoP : TokenType.Bearer;
            accessToken = accessTokenResponse;
        } else {
            tokenType = accessTokenResponse.token_type;
            accessToken = accessTokenResponse.access_token;
        }
        this.setAuthorizationHeader(request, accessToken, tokenType);
        if (tokenType === TokenType.DPoP) {
            await this.setDpopProofHeader(request, accessToken);
        }
    }
    getHeader(headers, name) {
        if (Array.isArray(headers)) {
            return new Headers(headers).get(name) || "";
        }
        if (typeof headers.get === "function") {
            return headers.get(name) || "";
        }
        return headers[name] || "";
    }
    hasUseDpopNonceError(response) {
        if (response.status !== 401) {
            return false;
        }
        const wwwAuthHeader = this.getHeader(response.headers, "www-authenticate");
        return wwwAuthHeader.includes("invalid_dpop_nonce") || wwwAuthHeader.includes("use_dpop_nonce");
    }
    async handleResponse(response, callbacks) {
        const newDpopNonce = this.getHeader(response.headers, DPOP_NONCE_HEADER);
        if (newDpopNonce) {
            await this.hooks.setDpopNonce(newDpopNonce);
        }
        if (!this.hasUseDpopNonceError(response)) {
            return response;
        }
        if (!newDpopNonce || !callbacks.onUseDpopNonceError) {
            throw new UseDpopNonceError(newDpopNonce);
        }
        return callbacks.onUseDpopNonceError();
    }
    async internalFetchWithAuth(info, init, callbacks, authParams) {
        const request = this.buildBaseRequest(info, init);
        await this.prepareRequest(request, authParams);
        const response = await this.config.fetch(request);
        return this.handleResponse(response, callbacks);
    }
    fetchWithAuth(info, init, authParams) {
        const callbacks = {
            onUseDpopNonceError: () => this.internalFetchWithAuth(info, init, Object.assign(Object.assign({}, callbacks), {
                onUseDpopNonceError: undefined
            }), authParams)
        };
        return this.internalFetchWithAuth(info, init, callbacks, authParams);
    }
}

class MyAccountApiClient {
    constructor(myAccountFetcher, apiBase) {
        this.myAccountFetcher = myAccountFetcher;
        this.apiBase = apiBase;
    }
    async connectAccount(params) {
        const res = await this.myAccountFetcher.fetchWithAuth("".concat(this.apiBase, "v1/connected-accounts/connect"), {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(params)
        }, {
            scope: [ "create:me:connected_accounts" ]
        });
        return this._handleResponse(res);
    }
    async completeAccount(params) {
        const res = await this.myAccountFetcher.fetchWithAuth("".concat(this.apiBase, "v1/connected-accounts/complete"), {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(params)
        }, {
            scope: [ "create:me:connected_accounts" ]
        });
        return this._handleResponse(res);
    }
    async getFactors() {
        const res = await this.myAccountFetcher.fetchWithAuth("".concat(this.apiBase, "v1/factors"), {
            method: "GET"
        }, {
            scope: [ "read:me:factors" ]
        });
        const body = await this._handleResponse(res);
        return body.factors;
    }
    async getAuthenticationMethods(type) {
        const query = type ? "?".concat(new URLSearchParams({
            type: type
        })) : "";
        const res = await this.myAccountFetcher.fetchWithAuth("".concat(this.apiBase, "v1/authentication-methods").concat(query), {
            method: "GET"
        }, {
            scope: [ "read:me:authentication_methods" ]
        });
        const body = await this._handleResponse(res);
        return body.authentication_methods;
    }
    async getAuthenticationMethod(id) {
        const res = await this.myAccountFetcher.fetchWithAuth("".concat(this.apiBase, "v1/authentication-methods/").concat(encodeURIComponent(id)), {
            method: "GET"
        }, {
            scope: [ "read:me:authentication_methods" ]
        });
        return this._handleResponse(res);
    }
    async deleteAuthenticationMethod(id) {
        const res = await this.myAccountFetcher.fetchWithAuth("".concat(this.apiBase, "v1/authentication-methods/").concat(encodeURIComponent(id)), {
            method: "DELETE"
        }, {
            scope: [ "delete:me:authentication_methods" ]
        });
        if (!res.ok) {
            await this._handleResponse(res);
        }
    }
    async updateAuthenticationMethod(id, data) {
        const res = await this.myAccountFetcher.fetchWithAuth("".concat(this.apiBase, "v1/authentication-methods/").concat(encodeURIComponent(id)), {
            method: "PATCH",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(data)
        }, {
            scope: [ "update:me:authentication_methods" ]
        });
        return this._handleResponse(res);
    }
    async enrollmentChallenge(options) {
        var _a;
        const res = await this.myAccountFetcher.fetchWithAuth("".concat(this.apiBase, "v1/authentication-methods"), {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(options)
        }, {
            scope: [ "create:me:authentication_methods" ]
        });
        const raw = await this._handleResponse(res);
        const location = (_a = res.headers.get("location")) !== null && _a !== void 0 ? _a : "";
        const id = decodeURIComponent(location.split("/").pop() || "");
        return Object.assign(Object.assign({}, raw), {
            id: id,
            location: location
        });
    }
    async enrollmentVerify(options) {
        const _a = options, location = _a.location;
        _a.type;
        const body = __rest(_a, [ "location", "type" ]);
        const res = await this.myAccountFetcher.fetchWithAuth("".concat(location, "/verify"), {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(body)
        }, {
            scope: [ "create:me:authentication_methods" ]
        });
        return this._handleResponse(res);
    }
    async _handleResponse(res) {
        let body;
        try {
            body = await res.text();
            body = JSON.parse(body);
        } catch (err) {
            throw new MyAccountApiError({
                type: "invalid_json",
                status: res.status,
                title: "Invalid JSON response",
                detail: body || String(err)
            });
        }
        if (res.ok) {
            return body;
        } else {
            throw new MyAccountApiError(body);
        }
    }
}

class MyAccountApiError extends Error {
    constructor(_ref) {
        let type = _ref.type, status = _ref.status, title = _ref.title, detail = _ref.detail, validation_errors = _ref.validation_errors;
        super(detail);
        this.name = "MyAccountApiError";
        this.type = type;
        this.status = status;
        this.title = title;
        this.detail = detail;
        this.validation_errors = validation_errors;
        Object.setPrototypeOf(this, MyAccountApiError.prototype);
    }
}

const FACTOR_MAPPING = {
    otp: {
        authenticatorTypes: [ "otp" ]
    },
    sms: {
        authenticatorTypes: [ "oob" ],
        oobChannels: [ "sms" ]
    },
    email: {
        authenticatorTypes: [ "oob" ],
        oobChannels: [ "email" ]
    },
    push: {
        authenticatorTypes: [ "oob" ],
        oobChannels: [ "auth0" ]
    },
    voice: {
        authenticatorTypes: [ "oob" ],
        oobChannels: [ "voice" ]
    }
};

const MfaGrantTypes = {
    OTP: "http://auth0.com/oauth/grant-type/mfa-otp",
    OOB: "http://auth0.com/oauth/grant-type/mfa-oob",
    RECOVERY_CODE: "http://auth0.com/oauth/grant-type/mfa-recovery-code"
};

function getAuthJsEnrollParams(params) {
    const mapping = FACTOR_MAPPING[params.factorType];
    return Object.assign(Object.assign(Object.assign({
        mfaToken: params.mfaToken,
        authenticatorTypes: mapping.authenticatorTypes
    }, mapping.oobChannels && {
        oobChannels: mapping.oobChannels
    }), "phoneNumber" in params && {
        phoneNumber: params.phoneNumber
    }), "email" in params && {
        email: params.email
    });
}

function getGrantType(params) {
    if ("otp" in params && params.otp) {
        return MfaGrantTypes.OTP;
    }
    if ("oobCode" in params && params.oobCode) {
        return MfaGrantTypes.OOB;
    }
    if ("recoveryCode" in params && params.recoveryCode) {
        return MfaGrantTypes.RECOVERY_CODE;
    }
    return undefined;
}

var _navigator$userAgent$2, _navigator$userAgent$$2;

let USER_AGENT$2;

if (typeof navigator === "undefined" || !((_navigator$userAgent$2 = navigator.userAgent) !== null && _navigator$userAgent$2 !== void 0 && (_navigator$userAgent$$2 = _navigator$userAgent$2.startsWith) !== null && _navigator$userAgent$$2 !== void 0 && _navigator$userAgent$$2.call(_navigator$userAgent$2, "Mozilla/5.0 "))) {
    const NAME = "oauth4webapi";
    const VERSION = "v3.8.6";
    USER_AGENT$2 = "".concat(NAME, "/").concat(VERSION);
}

function looseInstanceOf(input, expected) {
    if (input == null) {
        return false;
    }
    try {
        return input instanceof expected || Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag];
    } catch (_unused) {
        return false;
    }
}

const ERR_INVALID_ARG_VALUE$1 = "ERR_INVALID_ARG_VALUE";

const ERR_INVALID_ARG_TYPE$1 = "ERR_INVALID_ARG_TYPE";

function CodedTypeError$1(message, code, cause) {
    const err = new TypeError(message, {
        cause: cause
    });
    Object.assign(err, {
        code: code
    });
    return err;
}

const allowInsecureRequests$1 = Symbol();

const clockSkew = Symbol();

const clockTolerance = Symbol();

const customFetch$2 = Symbol();

const modifyAssertion = Symbol();

const jweDecrypt = Symbol();

const encoder$1 = new TextEncoder;

const decoder$1 = new TextDecoder;

function buf(input) {
    if (typeof input === "string") {
        return encoder$1.encode(input);
    }
    return decoder$1.decode(input);
}

let encodeBase64Url;

if (Uint8Array.prototype.toBase64) {
    encodeBase64Url = input => {
        if (input instanceof ArrayBuffer) {
            input = new Uint8Array(input);
        }
        return input.toBase64({
            alphabet: "base64url",
            omitPadding: true
        });
    };
} else {
    const CHUNK_SIZE = 32768;
    encodeBase64Url = input => {
        if (input instanceof ArrayBuffer) {
            input = new Uint8Array(input);
        }
        const arr = [];
        for (let i = 0; i < input.byteLength; i += CHUNK_SIZE) {
            arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
        }
        return btoa(arr.join("")).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
    };
}

let decodeBase64Url;

if (Uint8Array.fromBase64) {
    decodeBase64Url = input => {
        try {
            return Uint8Array.fromBase64(input, {
                alphabet: "base64url"
            });
        } catch (cause) {
            throw CodedTypeError$1("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE$1, cause);
        }
    };
} else {
    decodeBase64Url = input => {
        try {
            const binary = atob(input.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""));
            const bytes = new Uint8Array(binary.length);
            for (let i = 0; i < binary.length; i++) {
                bytes[i] = binary.charCodeAt(i);
            }
            return bytes;
        } catch (cause) {
            throw CodedTypeError$1("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE$1, cause);
        }
    };
}

function b64u(input) {
    if (typeof input === "string") {
        return decodeBase64Url(input);
    }
    return encodeBase64Url(input);
}

class UnsupportedOperationError extends Error {
    constructor(message, options) {
        var _Error$captureStackTr;
        super(message, options);
        _defineProperty(this, "code", void 0);
        this.name = this.constructor.name;
        this.code = UNSUPPORTED_OPERATION;
        (_Error$captureStackTr = Error.captureStackTrace) === null || _Error$captureStackTr === void 0 || _Error$captureStackTr.call(Error, this, this.constructor);
    }
}

class OperationProcessingError extends Error {
    constructor(message, options) {
        var _Error$captureStackTr2;
        super(message, options);
        _defineProperty(this, "code", void 0);
        this.name = this.constructor.name;
        if (options !== null && options !== void 0 && options.code) {
            this.code = options === null || options === void 0 ? void 0 : options.code;
        }
        (_Error$captureStackTr2 = Error.captureStackTrace) === null || _Error$captureStackTr2 === void 0 || _Error$captureStackTr2.call(Error, this, this.constructor);
    }
}

function OPE(message, code, cause) {
    return new OperationProcessingError(message, {
        code: code,
        cause: cause
    });
}

function assertCryptoKey(key, it) {
    if (!(key instanceof CryptoKey)) {
        throw CodedTypeError$1("".concat(it, " must be a CryptoKey"), ERR_INVALID_ARG_TYPE$1);
    }
}

function assertPrivateKey(key, it) {
    assertCryptoKey(key, it);
    if (key.type !== "private") {
        throw CodedTypeError$1("".concat(it, " must be a private CryptoKey"), ERR_INVALID_ARG_VALUE$1);
    }
}

function isJsonObject(input) {
    if (input === null || typeof input !== "object" || Array.isArray(input)) {
        return false;
    }
    return true;
}

function prepareHeaders(input) {
    if (looseInstanceOf(input, Headers)) {
        input = Object.fromEntries(input.entries());
    }
    const headers = new Headers(input !== null && input !== void 0 ? input : {});
    if (USER_AGENT$2 && !headers.has("user-agent")) {
        headers.set("user-agent", USER_AGENT$2);
    }
    if (headers.has("authorization")) {
        throw CodedTypeError$1('"options.headers" must not include the "authorization" header name', ERR_INVALID_ARG_VALUE$1);
    }
    return headers;
}

function signal$1(url, value) {
    if (value !== undefined) {
        if (typeof value === "function") {
            value = value(url.href);
        }
        if (!(value instanceof AbortSignal)) {
            throw CodedTypeError$1('"options.signal" must return or be an instance of AbortSignal', ERR_INVALID_ARG_TYPE$1);
        }
        return value;
    }
    return undefined;
}

function replaceDoubleSlash(pathname) {
    if (pathname.includes("//")) {
        return pathname.replace("//", "/");
    }
    return pathname;
}

function prependWellKnown(url, wellKnown) {
    let allowTerminatingSlash = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
    if (url.pathname === "/") {
        url.pathname = wellKnown;
    } else {
        url.pathname = replaceDoubleSlash("".concat(wellKnown, "/").concat(allowTerminatingSlash ? url.pathname : url.pathname.replace(/(\/)$/, "")));
    }
    return url;
}

function appendWellKnown(url, wellKnown) {
    url.pathname = replaceDoubleSlash("".concat(url.pathname, "/").concat(wellKnown));
    return url;
}

async function performDiscovery$1(input, urlName, transform, options) {
    if (!(input instanceof URL)) {
        throw CodedTypeError$1('"'.concat(urlName, '" must be an instance of URL'), ERR_INVALID_ARG_TYPE$1);
    }
    checkProtocol(input, (options === null || options === void 0 ? void 0 : options[allowInsecureRequests$1]) !== true);
    const url = transform(new URL(input.href));
    const headers = prepareHeaders(options === null || options === void 0 ? void 0 : options.headers);
    headers.set("accept", "application/json");
    return ((options === null || options === void 0 ? void 0 : options[customFetch$2]) || fetch)(url.href, {
        body: undefined,
        headers: Object.fromEntries(headers.entries()),
        method: "GET",
        redirect: "manual",
        signal: signal$1(url, options === null || options === void 0 ? void 0 : options.signal)
    });
}

async function discoveryRequest(issuerIdentifier, options) {
    return performDiscovery$1(issuerIdentifier, "issuerIdentifier", url => {
        switch (options === null || options === void 0 ? void 0 : options.algorithm) {
          case undefined:
          case "oidc":
            appendWellKnown(url, ".well-known/openid-configuration");
            break;

          case "oauth2":
            prependWellKnown(url, ".well-known/oauth-authorization-server");
            break;

          default:
            throw CodedTypeError$1('"options.algorithm" must be "oidc" (default), or "oauth2"', ERR_INVALID_ARG_VALUE$1);
        }
        return url;
    }, options);
}

function assertNumber(input, allow0, it, code, cause) {
    try {
        if (typeof input !== "number" || !Number.isFinite(input)) {
            throw CodedTypeError$1("".concat(it, " must be a number"), ERR_INVALID_ARG_TYPE$1, cause);
        }
        if (input > 0) return;
        if (allow0) {
            if (input !== 0) {
                throw CodedTypeError$1("".concat(it, " must be a non-negative number"), ERR_INVALID_ARG_VALUE$1, cause);
            }
            return;
        }
        throw CodedTypeError$1("".concat(it, " must be a positive number"), ERR_INVALID_ARG_VALUE$1, cause);
    } catch (err) {
        if (code) {
            throw OPE(err.message, code, cause);
        }
        throw err;
    }
}

function assertString$1(input, it, code, cause) {
    try {
        if (typeof input !== "string") {
            throw CodedTypeError$1("".concat(it, " must be a string"), ERR_INVALID_ARG_TYPE$1, cause);
        }
        if (input.length === 0) {
            throw CodedTypeError$1("".concat(it, " must not be empty"), ERR_INVALID_ARG_VALUE$1, cause);
        }
    } catch (err) {
        if (code) {
            throw OPE(err.message, code, cause);
        }
        throw err;
    }
}

async function processDiscoveryResponse(expectedIssuerIdentifier, response) {
    const expected = expectedIssuerIdentifier;
    if (!(expected instanceof URL) && expected !== _nodiscoverycheck) {
        throw CodedTypeError$1('"expectedIssuerIdentifier" must be an instance of URL', ERR_INVALID_ARG_TYPE$1);
    }
    if (!looseInstanceOf(response, Response)) {
        throw CodedTypeError$1('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE$1);
    }
    if (response.status !== 200) {
        throw OPE('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);
    }
    assertReadableResponse(response);
    const json = await getResponseJsonBody(response);
    assertString$1(json.issuer, '"response" body "issuer" property', INVALID_RESPONSE, {
        body: json
    });
    if (expected !== _nodiscoverycheck && new URL(json.issuer).href !== expected.href) {
        throw OPE('"response" body "issuer" property does not match the expected value', JSON_ATTRIBUTE_COMPARISON, {
            expected: expected.href,
            body: json,
            attribute: "issuer"
        });
    }
    return json;
}

function assertApplicationJson(response) {
    assertContentType(response, "application/json");
}

function notJson(response) {
    let msg = '"response" content-type must be ';
    for (var _len = arguments.length, types = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        types[_key - 1] = arguments[_key];
    }
    if (types.length > 2) {
        const last = types.pop();
        msg += "".concat(types.join(", "), ", or ").concat(last);
    } else if (types.length === 2) {
        msg += "".concat(types[0], " or ").concat(types[1]);
    } else {
        msg += types[0];
    }
    return OPE(msg, RESPONSE_IS_NOT_JSON, response);
}

function assertContentType(response, contentType) {
    if (getContentType(response) !== contentType) {
        throw notJson(response, contentType);
    }
}

function randomBytes() {
    return b64u(crypto.getRandomValues(new Uint8Array(32)));
}

function generateRandomCodeVerifier() {
    return randomBytes();
}

async function calculatePKCECodeChallenge$1(codeVerifier) {
    assertString$1(codeVerifier, "codeVerifier");
    return b64u(await crypto.subtle.digest("SHA-256", buf(codeVerifier)));
}

function getKeyAndKid(input) {
    if (input instanceof CryptoKey) {
        return {
            key: input
        };
    }
    if (!((input === null || input === void 0 ? void 0 : input.key) instanceof CryptoKey)) {
        return {};
    }
    if (input.kid !== undefined) {
        assertString$1(input.kid, '"kid"');
    }
    return {
        key: input.key,
        kid: input.kid
    };
}

function psAlg(key) {
    switch (key.algorithm.hash.name) {
      case "SHA-256":
        return "PS256";

      case "SHA-384":
        return "PS384";

      case "SHA-512":
        return "PS512";

      default:
        throw new UnsupportedOperationError("unsupported RsaHashedKeyAlgorithm hash name", {
            cause: key
        });
    }
}

function rsAlg(key) {
    switch (key.algorithm.hash.name) {
      case "SHA-256":
        return "RS256";

      case "SHA-384":
        return "RS384";

      case "SHA-512":
        return "RS512";

      default:
        throw new UnsupportedOperationError("unsupported RsaHashedKeyAlgorithm hash name", {
            cause: key
        });
    }
}

function esAlg(key) {
    switch (key.algorithm.namedCurve) {
      case "P-256":
        return "ES256";

      case "P-384":
        return "ES384";

      case "P-521":
        return "ES512";

      default:
        throw new UnsupportedOperationError("unsupported EcKeyAlgorithm namedCurve", {
            cause: key
        });
    }
}

function keyToJws(key) {
    switch (key.algorithm.name) {
      case "RSA-PSS":
        return psAlg(key);

      case "RSASSA-PKCS1-v1_5":
        return rsAlg(key);

      case "ECDSA":
        return esAlg(key);

      case "Ed25519":
      case "ML-DSA-44":
      case "ML-DSA-65":
      case "ML-DSA-87":
        return key.algorithm.name;

      case "EdDSA":
        return "Ed25519";

      default:
        throw new UnsupportedOperationError("unsupported CryptoKey algorithm name", {
            cause: key
        });
    }
}

function getClockSkew(client) {
    const skew = client === null || client === void 0 ? void 0 : client[clockSkew];
    return typeof skew === "number" && Number.isFinite(skew) ? skew : 0;
}

function getClockTolerance(client) {
    const tolerance = client === null || client === void 0 ? void 0 : client[clockTolerance];
    return typeof tolerance === "number" && Number.isFinite(tolerance) && Math.sign(tolerance) !== -1 ? tolerance : 30;
}

function epochTime() {
    return Math.floor(Date.now() / 1e3);
}

function assertAs(as) {
    if (typeof as !== "object" || as === null) {
        throw CodedTypeError$1('"as" must be an object', ERR_INVALID_ARG_TYPE$1);
    }
    assertString$1(as.issuer, '"as.issuer"');
}

function assertClient(client) {
    if (typeof client !== "object" || client === null) {
        throw CodedTypeError$1('"client" must be an object', ERR_INVALID_ARG_TYPE$1);
    }
    assertString$1(client.client_id, '"client.client_id"');
}

function ClientSecretPost$1(clientSecret) {
    assertString$1(clientSecret, '"clientSecret"');
    return (_as, client, body, _headers) => {
        body.set("client_id", client.client_id);
        body.set("client_secret", clientSecret);
    };
}

function clientAssertionPayload(as, client) {
    const now = epochTime() + getClockSkew(client);
    return {
        jti: randomBytes(),
        aud: as.issuer,
        exp: now + 60,
        iat: now,
        nbf: now,
        iss: client.client_id,
        sub: client.client_id
    };
}

function PrivateKeyJwt$1(clientPrivateKey, options) {
    const _getKeyAndKid = getKeyAndKid(clientPrivateKey), key = _getKeyAndKid.key, kid = _getKeyAndKid.kid;
    assertPrivateKey(key, '"clientPrivateKey.key"');
    return async (as, client, body, _headers) => {
        var _options$modifyAssert;
        const header = {
            alg: keyToJws(key),
            kid: kid
        };
        const payload = clientAssertionPayload(as, client);
        options === null || options === void 0 || (_options$modifyAssert = options[modifyAssertion]) === null || _options$modifyAssert === void 0 || _options$modifyAssert.call(options, header, payload);
        body.set("client_id", client.client_id);
        body.set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
        body.set("client_assertion", await signJwt(header, payload, key));
    };
}

function None$1() {
    return (_as, client, body, _headers) => {
        body.set("client_id", client.client_id);
    };
}

function TlsClientAuth$1() {
    return None$1();
}

async function signJwt(header, payload, key) {
    if (!key.usages.includes("sign")) {
        throw CodedTypeError$1('CryptoKey instances used for signing assertions must include "sign" in their "usages"', ERR_INVALID_ARG_VALUE$1);
    }
    const input = "".concat(b64u(buf(JSON.stringify(header))), ".").concat(b64u(buf(JSON.stringify(payload))));
    const signature = b64u(await crypto.subtle.sign(keyToSubtle(key), key, buf(input)));
    return "".concat(input, ".").concat(signature);
}

const URLParse = URL.parse ? (url, base) => URL.parse(url, base) : (url, base) => {
    try {
        return new URL(url, base);
    } catch (_unused2) {
        return null;
    }
};

function checkProtocol(url, enforceHttps) {
    if (enforceHttps && url.protocol !== "https:") {
        throw OPE("only requests to HTTPS are allowed", HTTP_REQUEST_FORBIDDEN, url);
    }
    if (url.protocol !== "https:" && url.protocol !== "http:") {
        throw OPE("only HTTP and HTTPS requests are allowed", REQUEST_PROTOCOL_FORBIDDEN, url);
    }
}

function validateEndpoint(value, endpoint, useMtlsAlias, enforceHttps) {
    let url;
    if (typeof value !== "string" || !(url = URLParse(value))) {
        throw OPE("authorization server metadata does not contain a valid ".concat(useMtlsAlias ? '"as.mtls_endpoint_aliases.'.concat(endpoint, '"') : '"as.'.concat(endpoint, '"')), value === undefined ? MISSING_SERVER_METADATA : INVALID_SERVER_METADATA, {
            attribute: useMtlsAlias ? "mtls_endpoint_aliases.".concat(endpoint) : endpoint
        });
    }
    checkProtocol(url, enforceHttps);
    return url;
}

function resolveEndpoint(as, endpoint, useMtlsAlias, enforceHttps) {
    if (useMtlsAlias && as.mtls_endpoint_aliases && endpoint in as.mtls_endpoint_aliases) {
        return validateEndpoint(as.mtls_endpoint_aliases[endpoint], endpoint, useMtlsAlias, enforceHttps);
    }
    return validateEndpoint(as[endpoint], endpoint, useMtlsAlias, enforceHttps);
}

async function pushedAuthorizationRequest(as, client, clientAuthentication, parameters, options) {
    var _options$DPoP;
    assertAs(as);
    assertClient(client);
    const url = resolveEndpoint(as, "pushed_authorization_request_endpoint", client.use_mtls_endpoint_aliases, (options === null || options === void 0 ? void 0 : options[allowInsecureRequests$1]) !== true);
    const body = new URLSearchParams(parameters);
    body.set("client_id", client.client_id);
    const headers = prepareHeaders(options === null || options === void 0 ? void 0 : options.headers);
    headers.set("accept", "application/json");
    if ((options === null || options === void 0 ? void 0 : options.DPoP) !== undefined) {
        assertDPoP(options.DPoP);
        await options.DPoP.addProof(url, headers, "POST");
    }
    const response = await authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);
    options === null || options === void 0 || (_options$DPoP = options.DPoP) === null || _options$DPoP === void 0 || _options$DPoP.cacheNonce(response, url);
    return response;
}

function isDPoPNonceError(err) {
    if (err instanceof WWWAuthenticateChallengeError) {
        const _err$cause = err.cause, challenge = _err$cause[0], length = _err$cause.length;
        return length === 1 && challenge.scheme === "dpop" && challenge.parameters.error === "use_dpop_nonce";
    }
    if (err instanceof ResponseBodyError) {
        return err.error === "use_dpop_nonce";
    }
    return false;
}

class ResponseBodyError extends Error {
    constructor(message, options) {
        var _Error$captureStackTr3;
        super(message, options);
        _defineProperty(this, "cause", void 0);
        _defineProperty(this, "code", void 0);
        _defineProperty(this, "error", void 0);
        _defineProperty(this, "status", void 0);
        _defineProperty(this, "error_description", void 0);
        _defineProperty(this, "response", void 0);
        this.name = this.constructor.name;
        this.code = RESPONSE_BODY_ERROR;
        this.cause = options.cause;
        this.error = options.cause.error;
        this.status = options.response.status;
        this.error_description = options.cause.error_description;
        Object.defineProperty(this, "response", {
            enumerable: false,
            value: options.response
        });
        (_Error$captureStackTr3 = Error.captureStackTrace) === null || _Error$captureStackTr3 === void 0 || _Error$captureStackTr3.call(Error, this, this.constructor);
    }
}

class AuthorizationResponseError extends Error {
    constructor(message, options) {
        var _options$cause$get, _Error$captureStackTr4;
        super(message, options);
        _defineProperty(this, "cause", void 0);
        _defineProperty(this, "code", void 0);
        _defineProperty(this, "error", void 0);
        _defineProperty(this, "error_description", void 0);
        this.name = this.constructor.name;
        this.code = AUTHORIZATION_RESPONSE_ERROR;
        this.cause = options.cause;
        this.error = options.cause.get("error");
        this.error_description = (_options$cause$get = options.cause.get("error_description")) !== null && _options$cause$get !== void 0 ? _options$cause$get : undefined;
        (_Error$captureStackTr4 = Error.captureStackTrace) === null || _Error$captureStackTr4 === void 0 || _Error$captureStackTr4.call(Error, this, this.constructor);
    }
}

class WWWAuthenticateChallengeError extends Error {
    constructor(message, options) {
        var _Error$captureStackTr5;
        super(message, options);
        _defineProperty(this, "cause", void 0);
        _defineProperty(this, "code", void 0);
        _defineProperty(this, "response", void 0);
        _defineProperty(this, "status", void 0);
        this.name = this.constructor.name;
        this.code = WWW_AUTHENTICATE_CHALLENGE;
        this.cause = options.cause;
        this.status = options.response.status;
        this.response = options.response;
        Object.defineProperty(this, "response", {
            enumerable: false
        });
        (_Error$captureStackTr5 = Error.captureStackTrace) === null || _Error$captureStackTr5 === void 0 || _Error$captureStackTr5.call(Error, this, this.constructor);
    }
}

const tokenMatch = "[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+";

const token68Match = "[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}";

const quotedMatch = '"((?:[^"\\\\]|\\\\[\\s\\S])*)"';

const quotedParamMatcher = "(" + tokenMatch + ")\\s*=\\s*" + quotedMatch;

const paramMatcher = "(" + tokenMatch + ")\\s*=\\s*(" + tokenMatch + ")";

const schemeRE = new RegExp("^[,\\s]*(" + tokenMatch + ")");

const quotedParamRE = new RegExp("^[,\\s]*" + quotedParamMatcher + "[,\\s]*(.*)");

const unquotedParamRE = new RegExp("^[,\\s]*" + paramMatcher + "[,\\s]*(.*)");

const token68ParamRE = new RegExp("^(" + token68Match + ")(?:$|[,\\s])(.*)");

function parseWwwAuthenticateChallenges(response) {
    if (!looseInstanceOf(response, Response)) {
        throw CodedTypeError$1('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE$1);
    }
    const header = response.headers.get("www-authenticate");
    if (header === null) {
        return undefined;
    }
    const challenges = [];
    let rest = header;
    while (rest) {
        var _match;
        let match = rest.match(schemeRE);
        const scheme = (_match = match) === null || _match === void 0 ? void 0 : _match["1"].toLowerCase();
        if (!scheme) {
            return undefined;
        }
        const afterScheme = rest.substring(match[0].length);
        if (afterScheme && !afterScheme.match(/^[\s,]/)) {
            return undefined;
        }
        const spaceMatch = afterScheme.match(/^\s+(.*)$/);
        const hasParameters = !!spaceMatch;
        rest = spaceMatch ? spaceMatch[1] : undefined;
        const parameters = {};
        let token68;
        if (hasParameters) {
            while (rest) {
                let key;
                let value;
                if (match = rest.match(quotedParamRE)) {
                    var _match2 = match;
                    var _match3 = _slicedToArray(_match2, 4);
                    key = _match3[1];
                    value = _match3[2];
                    rest = _match3[3];
                    if (value.includes("\\")) {
                        try {
                            value = JSON.parse('"'.concat(value, '"'));
                        } catch (_unused4) {}
                    }
                    parameters[key.toLowerCase()] = value;
                    continue;
                }
                if (match = rest.match(unquotedParamRE)) {
                    var _match4 = match;
                    var _match5 = _slicedToArray(_match4, 4);
                    key = _match5[1];
                    value = _match5[2];
                    rest = _match5[3];
                    parameters[key.toLowerCase()] = value;
                    continue;
                }
                if (match = rest.match(token68ParamRE)) {
                    if (Object.keys(parameters).length) {
                        break;
                    }
                    var _match6 = match;
                    var _match7 = _slicedToArray(_match6, 3);
                    token68 = _match7[1];
                    rest = _match7[2];
                    break;
                }
                return undefined;
            }
        } else {
            rest = afterScheme || undefined;
        }
        const challenge = {
            scheme: scheme,
            parameters: parameters
        };
        if (token68) {
            challenge.token68 = token68;
        }
        challenges.push(challenge);
    }
    if (!challenges.length) {
        return undefined;
    }
    return challenges;
}

async function processPushedAuthorizationResponse(as, client, response) {
    assertAs(as);
    assertClient(client);
    if (!looseInstanceOf(response, Response)) {
        throw CodedTypeError$1('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE$1);
    }
    await checkOAuthBodyError(response, 201, "Pushed Authorization Request Endpoint");
    assertReadableResponse(response);
    const json = await getResponseJsonBody(response);
    assertString$1(json.request_uri, '"response" body "request_uri" property', INVALID_RESPONSE, {
        body: json
    });
    let expiresIn = typeof json.expires_in !== "number" ? parseFloat(json.expires_in) : json.expires_in;
    assertNumber(expiresIn, true, '"response" body "expires_in" property', INVALID_RESPONSE, {
        body: json
    });
    json.expires_in = expiresIn;
    return json;
}

async function parseOAuthResponseErrorBody(response) {
    if (response.status > 399 && response.status < 500) {
        assertReadableResponse(response);
        assertApplicationJson(response);
        try {
            const json = await response.clone().json();
            if (isJsonObject(json) && typeof json.error === "string" && json.error.length) {
                return json;
            }
        } catch (_unused5) {}
    }
    return undefined;
}

async function checkOAuthBodyError(response, expected, label) {
    if (response.status !== expected) {
        checkAuthenticationChallenges(response);
        let err;
        if (err = await parseOAuthResponseErrorBody(response)) {
            var _response$body;
            await ((_response$body = response.body) === null || _response$body === void 0 ? void 0 : _response$body.cancel());
            throw new ResponseBodyError("server responded with an error in the response body", {
                cause: err,
                response: response
            });
        }
        throw OPE('"response" is not a conform '.concat(label, " response (unexpected HTTP status code)"), RESPONSE_IS_NOT_CONFORM, response);
    }
}

function assertDPoP(option) {
    if (!branded.has(option)) {
        throw CodedTypeError$1('"options.DPoP" is not a valid DPoPHandle', ERR_INVALID_ARG_VALUE$1);
    }
}

async function resourceRequest(accessToken, method, url, headers, body, options) {
    var _options$DPoP2;
    assertString$1(accessToken, '"accessToken"');
    if (!(url instanceof URL)) {
        throw CodedTypeError$1('"url" must be an instance of URL', ERR_INVALID_ARG_TYPE$1);
    }
    checkProtocol(url, (options === null || options === void 0 ? void 0 : options[allowInsecureRequests$1]) !== true);
    headers = prepareHeaders(headers);
    if (options !== null && options !== void 0 && options.DPoP) {
        assertDPoP(options.DPoP);
        await options.DPoP.addProof(url, headers, method.toUpperCase(), accessToken);
    }
    headers.set("authorization", "".concat(headers.has("dpop") ? "DPoP" : "Bearer", " ").concat(accessToken));
    const response = await ((options === null || options === void 0 ? void 0 : options[customFetch$2]) || fetch)(url.href, {
        duplex: looseInstanceOf(body, ReadableStream) ? "half" : undefined,
        body: body,
        headers: Object.fromEntries(headers.entries()),
        method: method,
        redirect: "manual",
        signal: signal$1(url, options === null || options === void 0 ? void 0 : options.signal)
    });
    options === null || options === void 0 || (_options$DPoP2 = options.DPoP) === null || _options$DPoP2 === void 0 || _options$DPoP2.cacheNonce(response, url);
    return response;
}

async function userInfoRequest(as, client, accessToken, options) {
    assertAs(as);
    assertClient(client);
    const url = resolveEndpoint(as, "userinfo_endpoint", client.use_mtls_endpoint_aliases, (options === null || options === void 0 ? void 0 : options[allowInsecureRequests$1]) !== true);
    const headers = prepareHeaders(options === null || options === void 0 ? void 0 : options.headers);
    if (client.userinfo_signed_response_alg) {
        headers.set("accept", "application/jwt");
    } else {
        headers.set("accept", "application/json");
        headers.append("accept", "application/jwt");
    }
    return resourceRequest(accessToken, "GET", url, headers, null, _objectSpread2(_objectSpread2({}, options), {}, {
        [clockSkew]: getClockSkew(client)
    }));
}

const skipSubjectCheck$1 = Symbol();

function getContentType(input) {
    var _input$headers$get;
    return (_input$headers$get = input.headers.get("content-type")) === null || _input$headers$get === void 0 ? void 0 : _input$headers$get.split(";")[0];
}

async function processUserInfoResponse(as, client, expectedSubject, response, options) {
    assertAs(as);
    assertClient(client);
    if (!looseInstanceOf(response, Response)) {
        throw CodedTypeError$1('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE$1);
    }
    checkAuthenticationChallenges(response);
    if (response.status !== 200) {
        throw OPE('"response" is not a conform UserInfo Endpoint response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);
    }
    assertReadableResponse(response);
    let json;
    if (getContentType(response) === "application/jwt") {
        const _await$validateJwt$th = await validateJwt(await response.text(), checkSigningAlgorithm.bind(undefined, client.userinfo_signed_response_alg, as.userinfo_signing_alg_values_supported, undefined), getClockSkew(client), getClockTolerance(client), options === null || options === void 0 ? void 0 : options[jweDecrypt]).then(validateOptionalAudience.bind(undefined, client.client_id)).then(validateOptionalIssuer.bind(undefined, as)), claims = _await$validateJwt$th.claims, jwt = _await$validateJwt$th.jwt;
        jwtRefs.set(response, jwt);
        json = claims;
    } else {
        if (client.userinfo_signed_response_alg) {
            throw OPE("JWT UserInfo Response expected", JWT_USERINFO_EXPECTED, response);
        }
        json = await getResponseJsonBody(response);
    }
    assertString$1(json.sub, '"response" body "sub" property', INVALID_RESPONSE, {
        body: json
    });
    switch (expectedSubject) {
      case skipSubjectCheck$1:
        break;

      default:
        assertString$1(expectedSubject, '"expectedSubject"');
        if (json.sub !== expectedSubject) {
            throw OPE('unexpected "response" body "sub" property value', JSON_ATTRIBUTE_COMPARISON, {
                expected: expectedSubject,
                body: json,
                attribute: "sub"
            });
        }
    }
    return json;
}

async function authenticatedRequest(as, client, clientAuthentication, url, body, headers, options) {
    await clientAuthentication(as, client, body, headers);
    headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
    return ((options === null || options === void 0 ? void 0 : options[customFetch$2]) || fetch)(url.href, {
        body: body,
        headers: Object.fromEntries(headers.entries()),
        method: "POST",
        redirect: "manual",
        signal: signal$1(url, options === null || options === void 0 ? void 0 : options.signal)
    });
}

async function tokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {
    var _options$DPoP3;
    const url = resolveEndpoint(as, "token_endpoint", client.use_mtls_endpoint_aliases, (options === null || options === void 0 ? void 0 : options[allowInsecureRequests$1]) !== true);
    parameters.set("grant_type", grantType);
    const headers = prepareHeaders(options === null || options === void 0 ? void 0 : options.headers);
    headers.set("accept", "application/json");
    if ((options === null || options === void 0 ? void 0 : options.DPoP) !== undefined) {
        assertDPoP(options.DPoP);
        await options.DPoP.addProof(url, headers, "POST");
    }
    const response = await authenticatedRequest(as, client, clientAuthentication, url, parameters, headers, options);
    options === null || options === void 0 || (_options$DPoP3 = options.DPoP) === null || _options$DPoP3 === void 0 || _options$DPoP3.cacheNonce(response, url);
    return response;
}

async function refreshTokenGrantRequest(as, client, clientAuthentication, refreshToken, options) {
    assertAs(as);
    assertClient(client);
    assertString$1(refreshToken, '"refreshToken"');
    const parameters = new URLSearchParams(options === null || options === void 0 ? void 0 : options.additionalParameters);
    parameters.set("refresh_token", refreshToken);
    return tokenEndpointRequest(as, client, clientAuthentication, "refresh_token", parameters, options);
}

const idTokenClaims = new WeakMap;

const jwtRefs = new WeakMap;

function getValidatedIdTokenClaims(ref) {
    if (!ref.id_token) {
        return undefined;
    }
    const claims = idTokenClaims.get(ref);
    if (!claims) {
        throw CodedTypeError$1('"ref" was already garbage collected or did not resolve from the proper sources', ERR_INVALID_ARG_VALUE$1);
    }
    return claims;
}

async function processGenericAccessTokenResponse(as, client, response, additionalRequiredIdTokenClaims, decryptFn, recognizedTokenTypes) {
    assertAs(as);
    assertClient(client);
    if (!looseInstanceOf(response, Response)) {
        throw CodedTypeError$1('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE$1);
    }
    await checkOAuthBodyError(response, 200, "Token Endpoint");
    assertReadableResponse(response);
    const json = await getResponseJsonBody(response);
    assertString$1(json.access_token, '"response" body "access_token" property', INVALID_RESPONSE, {
        body: json
    });
    assertString$1(json.token_type, '"response" body "token_type" property', INVALID_RESPONSE, {
        body: json
    });
    json.token_type = json.token_type.toLowerCase();
    if (json.expires_in !== undefined) {
        let expiresIn = typeof json.expires_in !== "number" ? parseFloat(json.expires_in) : json.expires_in;
        assertNumber(expiresIn, true, '"response" body "expires_in" property', INVALID_RESPONSE, {
            body: json
        });
        json.expires_in = expiresIn;
    }
    if (json.refresh_token !== undefined) {
        assertString$1(json.refresh_token, '"response" body "refresh_token" property', INVALID_RESPONSE, {
            body: json
        });
    }
    if (json.scope !== undefined && typeof json.scope !== "string") {
        throw OPE('"response" body "scope" property must be a string', INVALID_RESPONSE, {
            body: json
        });
    }
    if (json.id_token !== undefined) {
        assertString$1(json.id_token, '"response" body "id_token" property', INVALID_RESPONSE, {
            body: json
        });
        const requiredClaims = [ "aud", "exp", "iat", "iss", "sub" ];
        if (client.require_auth_time === true) {
            requiredClaims.push("auth_time");
        }
        if (client.default_max_age !== undefined) {
            assertNumber(client.default_max_age, true, '"client.default_max_age"');
            requiredClaims.push("auth_time");
        }
        if (additionalRequiredIdTokenClaims !== null && additionalRequiredIdTokenClaims !== void 0 && additionalRequiredIdTokenClaims.length) {
            requiredClaims.push(...additionalRequiredIdTokenClaims);
        }
        const _await$validateJwt$th2 = await validateJwt(json.id_token, checkSigningAlgorithm.bind(undefined, client.id_token_signed_response_alg, as.id_token_signing_alg_values_supported, "RS256"), getClockSkew(client), getClockTolerance(client), decryptFn).then(validatePresence.bind(undefined, requiredClaims)).then(validateIssuer.bind(undefined, as)).then(validateAudience.bind(undefined, client.client_id)), claims = _await$validateJwt$th2.claims, jwt = _await$validateJwt$th2.jwt;
        if (Array.isArray(claims.aud) && claims.aud.length !== 1) {
            if (claims.azp === undefined) {
                throw OPE('ID Token "aud" (audience) claim includes additional untrusted audiences', JWT_CLAIM_COMPARISON, {
                    claims: claims,
                    claim: "aud"
                });
            }
            if (claims.azp !== client.client_id) {
                throw OPE('unexpected ID Token "azp" (authorized party) claim value', JWT_CLAIM_COMPARISON, {
                    expected: client.client_id,
                    claims: claims,
                    claim: "azp"
                });
            }
        }
        if (claims.auth_time !== undefined) {
            assertNumber(claims.auth_time, true, 'ID Token "auth_time" (authentication time)', INVALID_RESPONSE, {
                claims: claims
            });
        }
        jwtRefs.set(response, jwt);
        idTokenClaims.set(json, claims);
    }
    if ((recognizedTokenTypes === null || recognizedTokenTypes === void 0 ? void 0 : recognizedTokenTypes[json.token_type]) !== undefined) {
        recognizedTokenTypes[json.token_type](response, json);
    } else if (json.token_type !== "dpop" && json.token_type !== "bearer") {
        throw new UnsupportedOperationError("unsupported `token_type` value", {
            cause: {
                body: json
            }
        });
    }
    return json;
}

function checkAuthenticationChallenges(response) {
    let challenges;
    if (challenges = parseWwwAuthenticateChallenges(response)) {
        throw new WWWAuthenticateChallengeError("server responded with a challenge in the WWW-Authenticate HTTP Header", {
            cause: challenges,
            response: response
        });
    }
}

async function processRefreshTokenResponse(as, client, response, options) {
    return processGenericAccessTokenResponse(as, client, response, undefined, options === null || options === void 0 ? void 0 : options[jweDecrypt], options === null || options === void 0 ? void 0 : options.recognizedTokenTypes);
}

function validateOptionalAudience(expected, result) {
    if (result.claims.aud !== undefined) {
        return validateAudience(expected, result);
    }
    return result;
}

function validateAudience(expected, result) {
    if (Array.isArray(result.claims.aud)) {
        if (!result.claims.aud.includes(expected)) {
            throw OPE('unexpected JWT "aud" (audience) claim value', JWT_CLAIM_COMPARISON, {
                expected: expected,
                claims: result.claims,
                claim: "aud"
            });
        }
    } else if (result.claims.aud !== expected) {
        throw OPE('unexpected JWT "aud" (audience) claim value', JWT_CLAIM_COMPARISON, {
            expected: expected,
            claims: result.claims,
            claim: "aud"
        });
    }
    return result;
}

function validateOptionalIssuer(as, result) {
    if (result.claims.iss !== undefined) {
        return validateIssuer(as, result);
    }
    return result;
}

function validateIssuer(as, result) {
    var _as$_expectedIssuer, _as$_expectedIssuer2;
    const expected = (_as$_expectedIssuer = (_as$_expectedIssuer2 = as[_expectedIssuer]) === null || _as$_expectedIssuer2 === void 0 ? void 0 : _as$_expectedIssuer2.call(as, result)) !== null && _as$_expectedIssuer !== void 0 ? _as$_expectedIssuer : as.issuer;
    if (result.claims.iss !== expected) {
        throw OPE('unexpected JWT "iss" (issuer) claim value', JWT_CLAIM_COMPARISON, {
            expected: expected,
            claims: result.claims,
            claim: "iss"
        });
    }
    return result;
}

const branded = new WeakSet;

function brand(searchParams) {
    branded.add(searchParams);
    return searchParams;
}

const nopkce = Symbol();

async function authorizationCodeGrantRequest(as, client, clientAuthentication, callbackParameters, redirectUri, codeVerifier, options) {
    assertAs(as);
    assertClient(client);
    if (!branded.has(callbackParameters)) {
        throw CodedTypeError$1('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()', ERR_INVALID_ARG_VALUE$1);
    }
    assertString$1(redirectUri, '"redirectUri"');
    const code = getURLSearchParameter(callbackParameters, "code");
    if (!code) {
        throw OPE('no authorization code in "callbackParameters"', INVALID_RESPONSE);
    }
    const parameters = new URLSearchParams(options === null || options === void 0 ? void 0 : options.additionalParameters);
    parameters.set("redirect_uri", redirectUri);
    parameters.set("code", code);
    if (codeVerifier !== nopkce) {
        assertString$1(codeVerifier, '"codeVerifier"');
        parameters.set("code_verifier", codeVerifier);
    }
    return tokenEndpointRequest(as, client, clientAuthentication, "authorization_code", parameters, options);
}

const jwtClaimNames = {
    aud: "audience",
    c_hash: "code hash",
    client_id: "client id",
    exp: "expiration time",
    iat: "issued at",
    iss: "issuer",
    jti: "jwt id",
    nonce: "nonce",
    s_hash: "state hash",
    sub: "subject",
    ath: "access token hash",
    htm: "http method",
    htu: "http uri",
    cnf: "confirmation",
    auth_time: "authentication time"
};

function validatePresence(required, result) {
    for (const claim of required) {
        if (result.claims[claim] === undefined) {
            throw OPE('JWT "'.concat(claim, '" (').concat(jwtClaimNames[claim], ") claim missing"), INVALID_RESPONSE, {
                claims: result.claims
            });
        }
    }
    return result;
}

const expectNoNonce = Symbol();

const skipAuthTimeCheck = Symbol();

async function processAuthorizationCodeResponse(as, client, response, options) {
    if (typeof (options === null || options === void 0 ? void 0 : options.expectedNonce) === "string" || typeof (options === null || options === void 0 ? void 0 : options.maxAge) === "number" || options !== null && options !== void 0 && options.requireIdToken) {
        return processAuthorizationCodeOpenIDResponse(as, client, response, options.expectedNonce, options.maxAge, options[jweDecrypt], options.recognizedTokenTypes);
    }
    return processAuthorizationCodeOAuth2Response(as, client, response, options === null || options === void 0 ? void 0 : options[jweDecrypt], options === null || options === void 0 ? void 0 : options.recognizedTokenTypes);
}

async function processAuthorizationCodeOpenIDResponse(as, client, response, expectedNonce, maxAge, decryptFn, recognizedTokenTypes) {
    const additionalRequiredClaims = [];
    switch (expectedNonce) {
      case undefined:
        expectedNonce = expectNoNonce;
        break;

      case expectNoNonce:
        break;

      default:
        assertString$1(expectedNonce, '"expectedNonce" argument');
        additionalRequiredClaims.push("nonce");
    }
    maxAge !== null && maxAge !== void 0 ? maxAge : maxAge = client.default_max_age;
    switch (maxAge) {
      case undefined:
        maxAge = skipAuthTimeCheck;
        break;

      case skipAuthTimeCheck:
        break;

      default:
        assertNumber(maxAge, true, '"maxAge" argument');
        additionalRequiredClaims.push("auth_time");
    }
    const result = await processGenericAccessTokenResponse(as, client, response, additionalRequiredClaims, decryptFn, recognizedTokenTypes);
    assertString$1(result.id_token, '"response" body "id_token" property', INVALID_RESPONSE, {
        body: result
    });
    const claims = getValidatedIdTokenClaims(result);
    if (maxAge !== skipAuthTimeCheck) {
        const now = epochTime() + getClockSkew(client);
        const tolerance = getClockTolerance(client);
        if (claims.auth_time + maxAge < now - tolerance) {
            throw OPE("too much time has elapsed since the last End-User authentication", JWT_TIMESTAMP_CHECK, {
                claims: claims,
                now: now,
                tolerance: tolerance,
                claim: "auth_time"
            });
        }
    }
    if (expectedNonce === expectNoNonce) {
        if (claims.nonce !== undefined) {
            throw OPE('unexpected ID Token "nonce" claim value', JWT_CLAIM_COMPARISON, {
                expected: undefined,
                claims: claims,
                claim: "nonce"
            });
        }
    } else if (claims.nonce !== expectedNonce) {
        throw OPE('unexpected ID Token "nonce" claim value', JWT_CLAIM_COMPARISON, {
            expected: expectedNonce,
            claims: claims,
            claim: "nonce"
        });
    }
    return result;
}

async function processAuthorizationCodeOAuth2Response(as, client, response, decryptFn, recognizedTokenTypes) {
    const result = await processGenericAccessTokenResponse(as, client, response, undefined, decryptFn, recognizedTokenTypes);
    const claims = getValidatedIdTokenClaims(result);
    if (claims) {
        if (client.default_max_age !== undefined) {
            assertNumber(client.default_max_age, true, '"client.default_max_age"');
            const now = epochTime() + getClockSkew(client);
            const tolerance = getClockTolerance(client);
            if (claims.auth_time + client.default_max_age < now - tolerance) {
                throw OPE("too much time has elapsed since the last End-User authentication", JWT_TIMESTAMP_CHECK, {
                    claims: claims,
                    now: now,
                    tolerance: tolerance,
                    claim: "auth_time"
                });
            }
        }
        if (claims.nonce !== undefined) {
            throw OPE('unexpected ID Token "nonce" claim value', JWT_CLAIM_COMPARISON, {
                expected: undefined,
                claims: claims,
                claim: "nonce"
            });
        }
    }
    return result;
}

const WWW_AUTHENTICATE_CHALLENGE = "OAUTH_WWW_AUTHENTICATE_CHALLENGE";

const RESPONSE_BODY_ERROR = "OAUTH_RESPONSE_BODY_ERROR";

const UNSUPPORTED_OPERATION = "OAUTH_UNSUPPORTED_OPERATION";

const AUTHORIZATION_RESPONSE_ERROR = "OAUTH_AUTHORIZATION_RESPONSE_ERROR";

const JWT_USERINFO_EXPECTED = "OAUTH_JWT_USERINFO_EXPECTED";

const PARSE_ERROR = "OAUTH_PARSE_ERROR";

const INVALID_RESPONSE = "OAUTH_INVALID_RESPONSE";

const RESPONSE_IS_NOT_JSON = "OAUTH_RESPONSE_IS_NOT_JSON";

const RESPONSE_IS_NOT_CONFORM = "OAUTH_RESPONSE_IS_NOT_CONFORM";

const HTTP_REQUEST_FORBIDDEN = "OAUTH_HTTP_REQUEST_FORBIDDEN";

const REQUEST_PROTOCOL_FORBIDDEN = "OAUTH_REQUEST_PROTOCOL_FORBIDDEN";

const JWT_TIMESTAMP_CHECK = "OAUTH_JWT_TIMESTAMP_CHECK_FAILED";

const JWT_CLAIM_COMPARISON = "OAUTH_JWT_CLAIM_COMPARISON_FAILED";

const JSON_ATTRIBUTE_COMPARISON = "OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";

const MISSING_SERVER_METADATA = "OAUTH_MISSING_SERVER_METADATA";

const INVALID_SERVER_METADATA = "OAUTH_INVALID_SERVER_METADATA";

async function clientCredentialsGrantRequest(as, client, clientAuthentication, parameters, options) {
    assertAs(as);
    assertClient(client);
    return tokenEndpointRequest(as, client, clientAuthentication, "client_credentials", new URLSearchParams(parameters), options);
}

async function genericTokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {
    assertAs(as);
    assertClient(client);
    assertString$1(grantType, '"grantType"');
    return tokenEndpointRequest(as, client, clientAuthentication, grantType, new URLSearchParams(parameters), options);
}

async function processGenericTokenEndpointResponse(as, client, response, options) {
    return processGenericAccessTokenResponse(as, client, response, undefined, options === null || options === void 0 ? void 0 : options[jweDecrypt], options === null || options === void 0 ? void 0 : options.recognizedTokenTypes);
}

async function processClientCredentialsResponse(as, client, response, options) {
    return processGenericAccessTokenResponse(as, client, response, undefined, options === null || options === void 0 ? void 0 : options[jweDecrypt], options === null || options === void 0 ? void 0 : options.recognizedTokenTypes);
}

async function revocationRequest(as, client, clientAuthentication, token, options) {
    assertAs(as);
    assertClient(client);
    assertString$1(token, '"token"');
    const url = resolveEndpoint(as, "revocation_endpoint", client.use_mtls_endpoint_aliases, (options === null || options === void 0 ? void 0 : options[allowInsecureRequests$1]) !== true);
    const body = new URLSearchParams(options === null || options === void 0 ? void 0 : options.additionalParameters);
    body.set("token", token);
    const headers = prepareHeaders(options === null || options === void 0 ? void 0 : options.headers);
    headers.delete("accept");
    return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);
}

async function processRevocationResponse(response) {
    if (!looseInstanceOf(response, Response)) {
        throw CodedTypeError$1('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE$1);
    }
    await checkOAuthBodyError(response, 200, "Revocation Endpoint");
    return undefined;
}

function assertReadableResponse(response) {
    if (response.bodyUsed) {
        throw CodedTypeError$1('"response" body has been used already', ERR_INVALID_ARG_VALUE$1);
    }
}

function checkRsaKeyAlgorithm(key) {
    const algorithm = key.algorithm;
    if (typeof algorithm.modulusLength !== "number" || algorithm.modulusLength < 2048) {
        throw new UnsupportedOperationError("unsupported ".concat(algorithm.name, " modulusLength"), {
            cause: key
        });
    }
}

function ecdsaHashName(key) {
    const algorithm = key.algorithm;
    switch (algorithm.namedCurve) {
      case "P-256":
        return "SHA-256";

      case "P-384":
        return "SHA-384";

      case "P-521":
        return "SHA-512";

      default:
        throw new UnsupportedOperationError("unsupported ECDSA namedCurve", {
            cause: key
        });
    }
}

function keyToSubtle(key) {
    switch (key.algorithm.name) {
      case "ECDSA":
        return {
            name: key.algorithm.name,
            hash: ecdsaHashName(key)
        };

      case "RSA-PSS":
        {
            checkRsaKeyAlgorithm(key);
            switch (key.algorithm.hash.name) {
              case "SHA-256":
              case "SHA-384":
              case "SHA-512":
                return {
                    name: key.algorithm.name,
                    saltLength: parseInt(key.algorithm.hash.name.slice(-3), 10) >> 3
                };

              default:
                throw new UnsupportedOperationError("unsupported RSA-PSS hash name", {
                    cause: key
                });
            }
        }

      case "RSASSA-PKCS1-v1_5":
        checkRsaKeyAlgorithm(key);
        return key.algorithm.name;

      case "ML-DSA-44":
      case "ML-DSA-65":
      case "ML-DSA-87":
      case "Ed25519":
        return key.algorithm.name;
    }
    throw new UnsupportedOperationError("unsupported CryptoKey algorithm name", {
        cause: key
    });
}

async function validateJwt(jws, checkAlg, clockSkew, clockTolerance, decryptJwt) {
    let _jws$split = jws.split("."), protectedHeader = _jws$split[0], payload = _jws$split[1], length = _jws$split.length;
    if (length === 5) {
        if (decryptJwt !== undefined) {
            jws = await decryptJwt(jws);
            var _jws$split2 = jws.split(".");
            protectedHeader = _jws$split2[0];
            payload = _jws$split2[1];
            length = _jws$split2.length;
        } else {
            throw new UnsupportedOperationError("JWE decryption is not configured", {
                cause: jws
            });
        }
    }
    if (length !== 3) {
        throw OPE("Invalid JWT", INVALID_RESPONSE, jws);
    }
    let header;
    try {
        header = JSON.parse(buf(b64u(protectedHeader)));
    } catch (cause) {
        throw OPE("failed to parse JWT Header body as base64url encoded JSON", PARSE_ERROR, cause);
    }
    if (!isJsonObject(header)) {
        throw OPE("JWT Header must be a top level object", INVALID_RESPONSE, jws);
    }
    checkAlg(header);
    if (header.crit !== undefined) {
        throw new UnsupportedOperationError('no JWT "crit" header parameter extensions are supported', {
            cause: {
                header: header
            }
        });
    }
    let claims;
    try {
        claims = JSON.parse(buf(b64u(payload)));
    } catch (cause) {
        throw OPE("failed to parse JWT Payload body as base64url encoded JSON", PARSE_ERROR, cause);
    }
    if (!isJsonObject(claims)) {
        throw OPE("JWT Payload must be a top level object", INVALID_RESPONSE, jws);
    }
    const now = epochTime() + clockSkew;
    if (claims.exp !== undefined) {
        if (typeof claims.exp !== "number") {
            throw OPE('unexpected JWT "exp" (expiration time) claim type', INVALID_RESPONSE, {
                claims: claims
            });
        }
        if (claims.exp <= now - clockTolerance) {
            throw OPE('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp', JWT_TIMESTAMP_CHECK, {
                claims: claims,
                now: now,
                tolerance: clockTolerance,
                claim: "exp"
            });
        }
    }
    if (claims.iat !== undefined) {
        if (typeof claims.iat !== "number") {
            throw OPE('unexpected JWT "iat" (issued at) claim type', INVALID_RESPONSE, {
                claims: claims
            });
        }
    }
    if (claims.iss !== undefined) {
        if (typeof claims.iss !== "string") {
            throw OPE('unexpected JWT "iss" (issuer) claim type', INVALID_RESPONSE, {
                claims: claims
            });
        }
    }
    if (claims.nbf !== undefined) {
        if (typeof claims.nbf !== "number") {
            throw OPE('unexpected JWT "nbf" (not before) claim type', INVALID_RESPONSE, {
                claims: claims
            });
        }
        if (claims.nbf > now + clockTolerance) {
            throw OPE('unexpected JWT "nbf" (not before) claim value', JWT_TIMESTAMP_CHECK, {
                claims: claims,
                now: now,
                tolerance: clockTolerance,
                claim: "nbf"
            });
        }
    }
    if (claims.aud !== undefined) {
        if (typeof claims.aud !== "string" && !Array.isArray(claims.aud)) {
            throw OPE('unexpected JWT "aud" (audience) claim type', INVALID_RESPONSE, {
                claims: claims
            });
        }
    }
    return {
        header: header,
        claims: claims,
        jwt: jws
    };
}

async function consumeStream(request) {
    if (request.bodyUsed) {
        throw CodedTypeError$1("form_post Request instances must contain a readable body", ERR_INVALID_ARG_VALUE$1, {
            cause: request
        });
    }
    return request.text();
}

async function formPostResponse(request) {
    if (request.method !== "POST") {
        throw CodedTypeError$1("form_post responses are expected to use the POST method", ERR_INVALID_ARG_VALUE$1, {
            cause: request
        });
    }
    if (getContentType(request) !== "application/x-www-form-urlencoded") {
        throw CodedTypeError$1("form_post responses are expected to use the application/x-www-form-urlencoded content-type", ERR_INVALID_ARG_VALUE$1, {
            cause: request
        });
    }
    return consumeStream(request);
}

function checkSigningAlgorithm(client, issuer, fallback, header) {
    if (client !== undefined) {
        if (typeof client === "string" ? header.alg !== client : !client.includes(header.alg)) {
            throw OPE('unexpected JWT "alg" header parameter', INVALID_RESPONSE, {
                header: header,
                expected: client,
                reason: "client configuration"
            });
        }
        return;
    }
    if (Array.isArray(issuer)) {
        if (!issuer.includes(header.alg)) {
            throw OPE('unexpected JWT "alg" header parameter', INVALID_RESPONSE, {
                header: header,
                expected: issuer,
                reason: "authorization server metadata"
            });
        }
        return;
    }
    if (fallback !== undefined) {
        if (typeof fallback === "string" ? header.alg !== fallback : typeof fallback === "function" ? !fallback(header.alg) : !fallback.includes(header.alg)) {
            throw OPE('unexpected JWT "alg" header parameter', INVALID_RESPONSE, {
                header: header,
                expected: fallback,
                reason: "default value"
            });
        }
        return;
    }
    throw OPE('missing client or server configuration to verify used JWT "alg" header parameter', undefined, {
        client: client,
        issuer: issuer,
        fallback: fallback
    });
}

function getURLSearchParameter(parameters, name) {
    const _parameters$getAll = parameters.getAll(name), value = _parameters$getAll[0], length = _parameters$getAll.length;
    if (length > 1) {
        throw OPE('"'.concat(name, '" parameter must be provided only once'), INVALID_RESPONSE);
    }
    return value;
}

const skipStateCheck = Symbol();

const expectNoState = Symbol();

function validateAuthResponse(as, client, parameters, expectedState) {
    assertAs(as);
    assertClient(client);
    if (parameters instanceof URL) {
        parameters = parameters.searchParams;
    }
    if (!(parameters instanceof URLSearchParams)) {
        throw CodedTypeError$1('"parameters" must be an instance of URLSearchParams, or URL', ERR_INVALID_ARG_TYPE$1);
    }
    if (getURLSearchParameter(parameters, "response")) {
        throw OPE('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()', INVALID_RESPONSE, {
            parameters: parameters
        });
    }
    const iss = getURLSearchParameter(parameters, "iss");
    const state = getURLSearchParameter(parameters, "state");
    if (!iss && as.authorization_response_iss_parameter_supported) {
        throw OPE('response parameter "iss" (issuer) missing', INVALID_RESPONSE, {
            parameters: parameters
        });
    }
    if (iss && iss !== as.issuer) {
        throw OPE('unexpected "iss" (issuer) response parameter value', INVALID_RESPONSE, {
            expected: as.issuer,
            parameters: parameters
        });
    }
    switch (expectedState) {
      case undefined:
      case expectNoState:
        if (state !== undefined) {
            throw OPE('unexpected "state" response parameter encountered', INVALID_RESPONSE, {
                expected: undefined,
                parameters: parameters
            });
        }
        break;

      case skipStateCheck:
        break;

      default:
        assertString$1(expectedState, '"expectedState" argument');
        if (state !== expectedState) {
            throw OPE(state === undefined ? 'response parameter "state" missing' : 'unexpected "state" response parameter value', INVALID_RESPONSE, {
                expected: expectedState,
                parameters: parameters
            });
        }
    }
    const error = getURLSearchParameter(parameters, "error");
    if (error) {
        throw new AuthorizationResponseError("authorization response from the server is an error", {
            cause: parameters
        });
    }
    const id_token = getURLSearchParameter(parameters, "id_token");
    const token = getURLSearchParameter(parameters, "token");
    if (id_token !== undefined || token !== undefined) {
        throw new UnsupportedOperationError("implicit and hybrid flows are not supported");
    }
    return brand(new URLSearchParams(parameters));
}

async function backchannelAuthenticationRequest(as, client, clientAuthentication, parameters, options) {
    assertAs(as);
    assertClient(client);
    const url = resolveEndpoint(as, "backchannel_authentication_endpoint", client.use_mtls_endpoint_aliases, (options === null || options === void 0 ? void 0 : options[allowInsecureRequests$1]) !== true);
    const body = new URLSearchParams(parameters);
    body.set("client_id", client.client_id);
    const headers = prepareHeaders(options === null || options === void 0 ? void 0 : options.headers);
    headers.set("accept", "application/json");
    return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);
}

async function processBackchannelAuthenticationResponse(as, client, response) {
    assertAs(as);
    assertClient(client);
    if (!looseInstanceOf(response, Response)) {
        throw CodedTypeError$1('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE$1);
    }
    await checkOAuthBodyError(response, 200, "Backchannel Authentication Endpoint");
    assertReadableResponse(response);
    const json = await getResponseJsonBody(response);
    assertString$1(json.auth_req_id, '"response" body "auth_req_id" property', INVALID_RESPONSE, {
        body: json
    });
    let expiresIn = typeof json.expires_in !== "number" ? parseFloat(json.expires_in) : json.expires_in;
    assertNumber(expiresIn, true, '"response" body "expires_in" property', INVALID_RESPONSE, {
        body: json
    });
    json.expires_in = expiresIn;
    if (json.interval !== undefined) {
        assertNumber(json.interval, false, '"response" body "interval" property', INVALID_RESPONSE, {
            body: json
        });
    }
    return json;
}

async function backchannelAuthenticationGrantRequest(as, client, clientAuthentication, authReqId, options) {
    assertAs(as);
    assertClient(client);
    assertString$1(authReqId, '"authReqId"');
    const parameters = new URLSearchParams(options === null || options === void 0 ? void 0 : options.additionalParameters);
    parameters.set("auth_req_id", authReqId);
    return tokenEndpointRequest(as, client, clientAuthentication, "urn:openid:params:grant-type:ciba", parameters, options);
}

async function processBackchannelAuthenticationGrantResponse(as, client, response, options) {
    return processGenericAccessTokenResponse(as, client, response, undefined, options === null || options === void 0 ? void 0 : options[jweDecrypt], options === null || options === void 0 ? void 0 : options.recognizedTokenTypes);
}

async function getResponseJsonBody(response) {
    let check = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : assertApplicationJson;
    let json;
    try {
        json = await response.json();
    } catch (cause) {
        check(response);
        throw OPE('failed to parse "response" body as JSON', PARSE_ERROR, cause);
    }
    if (!isJsonObject(json)) {
        throw OPE('"response" body must be a top level object', INVALID_RESPONSE, {
            body: json
        });
    }
    return json;
}

const _nodiscoverycheck = Symbol();

const _expectedIssuer = Symbol();

const encoder = new TextEncoder;

const decoder = new TextDecoder;

const strictDecoder = new TextDecoder("utf-8", {
    fatal: true
});

function concat() {
    for (var _len = arguments.length, buffers = new Array(_len), _key = 0; _key < _len; _key++) {
        buffers[_key] = arguments[_key];
    }
    const size = buffers.reduce((acc, _ref) => {
        let length = _ref.length;
        return acc + length;
    }, 0);
    const buf = new Uint8Array(size);
    let i = 0;
    for (const buffer of buffers) {
        buf.set(buffer, i);
        i += buffer.length;
    }
    return buf;
}

function encode$1(string) {
    const bytes = new Uint8Array(string.length);
    for (let i = 0; i < string.length; i++) {
        const code = string.charCodeAt(i);
        if (code > 127) {
            throw new TypeError("non-ASCII string encountered in encode()");
        }
        bytes[i] = code;
    }
    return bytes;
}

const unusable = function unusable(name) {
    let prop = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "algorithm.name";
    return new TypeError("CryptoKey does not support this operation, its ".concat(prop, " must be ").concat(name));
};

function checkUsage(key, usage) {
    if (usage && !key.usages.includes(usage)) {
        throw new TypeError("CryptoKey does not support this operation, its usages must include ".concat(usage, "."));
    }
}

function checkModulusLength(alg, key) {
    const modulusLength = key.algorithm.modulusLength;
    if (typeof modulusLength !== "number" || modulusLength < 2048) {
        throw new TypeError("".concat(alg, " requires key modulusLength to be 2048 bits or larger"));
    }
}

function checkCryptoKey(key, expected, usage) {
    var _algorithm$hash;
    const algorithm = key.algorithm;
    if (algorithm.name !== expected.name) {
        throw unusable(expected.name);
    }
    if (expected.hash && ((_algorithm$hash = algorithm.hash) === null || _algorithm$hash === void 0 ? void 0 : _algorithm$hash.name) !== expected.hash) {
        throw unusable(expected.hash, "algorithm.hash");
    }
    if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve) {
        throw unusable(expected.namedCurve, "algorithm.namedCurve");
    }
    if (expected.length !== undefined && algorithm.length !== expected.length) {
        throw unusable(expected.length, "algorithm.length");
    }
    checkUsage(key, usage);
}

function message(msg, actual) {
    for (var _len = arguments.length, types = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
        types[_key - 2] = arguments[_key];
    }
    if (types.length > 2) {
        const last = types.pop();
        msg += "one of type ".concat(types.join(", "), ", or ").concat(last, ".");
    } else if (types.length === 2) {
        msg += "one of type ".concat(types[0], " or ").concat(types[1], ".");
    } else {
        msg += "of type ".concat(types[0], ".");
    }
    if (actual == null) {
        msg += " Received ".concat(actual);
    } else if (typeof actual === "function" && actual.name) {
        msg += " Received function ".concat(actual.name);
    } else if (typeof actual === "object" && actual != null) {
        var _actual$constructor;
        if ((_actual$constructor = actual.constructor) !== null && _actual$constructor !== void 0 && _actual$constructor.name) {
            msg += " Received an instance of ".concat(actual.constructor.name);
        }
    }
    return msg;
}

const withAlg = function withAlg(alg, actual) {
    for (var _len3 = arguments.length, types = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
        types[_key3 - 2] = arguments[_key3];
    }
    return message("Key for the ".concat(alg, " algorithm must be "), actual, ...types);
};

class JOSEError extends Error {
    constructor(message, options) {
        var _Error$captureStackTr;
        super(message, options);
        _defineProperty(this, "code", "ERR_JOSE_GENERIC");
        this.name = this.constructor.name;
        (_Error$captureStackTr = Error.captureStackTrace) === null || _Error$captureStackTr === void 0 || _Error$captureStackTr.call(Error, this, this.constructor);
    }
}

_defineProperty(JOSEError, "code", "ERR_JOSE_GENERIC");

class JWTClaimValidationFailed extends JOSEError {
    constructor(message, payload) {
        let claim = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "unspecified";
        let reason = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "unspecified";
        super(message, {
            cause: {
                claim: claim,
                reason: reason,
                payload: payload
            }
        });
        _defineProperty(this, "code", "ERR_JWT_CLAIM_VALIDATION_FAILED");
        _defineProperty(this, "claim", void 0);
        _defineProperty(this, "reason", void 0);
        _defineProperty(this, "payload", void 0);
        this.claim = claim;
        this.reason = reason;
        this.payload = payload;
    }
}

_defineProperty(JWTClaimValidationFailed, "code", "ERR_JWT_CLAIM_VALIDATION_FAILED");

class JWTExpired extends JOSEError {
    constructor(message, payload) {
        let claim = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "unspecified";
        let reason = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "unspecified";
        super(message, {
            cause: {
                claim: claim,
                reason: reason,
                payload: payload
            }
        });
        _defineProperty(this, "code", "ERR_JWT_EXPIRED");
        _defineProperty(this, "claim", void 0);
        _defineProperty(this, "reason", void 0);
        _defineProperty(this, "payload", void 0);
        this.claim = claim;
        this.reason = reason;
        this.payload = payload;
    }
}

_defineProperty(JWTExpired, "code", "ERR_JWT_EXPIRED");

class JOSEAlgNotAllowed extends JOSEError {
    constructor() {
        super(...arguments);
        _defineProperty(this, "code", "ERR_JOSE_ALG_NOT_ALLOWED");
    }
}

_defineProperty(JOSEAlgNotAllowed, "code", "ERR_JOSE_ALG_NOT_ALLOWED");

class JOSENotSupported extends JOSEError {
    constructor() {
        super(...arguments);
        _defineProperty(this, "code", "ERR_JOSE_NOT_SUPPORTED");
    }
}

_defineProperty(JOSENotSupported, "code", "ERR_JOSE_NOT_SUPPORTED");

class JWEDecryptionFailed extends JOSEError {
    constructor() {
        let message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "decryption operation failed";
        let options = arguments.length > 1 ? arguments[1] : undefined;
        super(message, options);
        _defineProperty(this, "code", "ERR_JWE_DECRYPTION_FAILED");
    }
}

_defineProperty(JWEDecryptionFailed, "code", "ERR_JWE_DECRYPTION_FAILED");

class JWEInvalid extends JOSEError {
    constructor() {
        super(...arguments);
        _defineProperty(this, "code", "ERR_JWE_INVALID");
    }
}

_defineProperty(JWEInvalid, "code", "ERR_JWE_INVALID");

class JWSInvalid extends JOSEError {
    constructor() {
        super(...arguments);
        _defineProperty(this, "code", "ERR_JWS_INVALID");
    }
}

_defineProperty(JWSInvalid, "code", "ERR_JWS_INVALID");

class JWTInvalid extends JOSEError {
    constructor() {
        super(...arguments);
        _defineProperty(this, "code", "ERR_JWT_INVALID");
    }
}

_defineProperty(JWTInvalid, "code", "ERR_JWT_INVALID");

class JWKInvalid extends JOSEError {
    constructor() {
        super(...arguments);
        _defineProperty(this, "code", "ERR_JWK_INVALID");
    }
}

_defineProperty(JWKInvalid, "code", "ERR_JWK_INVALID");

class JWKSInvalid extends JOSEError {
    constructor() {
        super(...arguments);
        _defineProperty(this, "code", "ERR_JWKS_INVALID");
    }
}

_defineProperty(JWKSInvalid, "code", "ERR_JWKS_INVALID");

class JWKSNoMatchingKey extends JOSEError {
    constructor() {
        let message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "no applicable key found in the JSON Web Key Set";
        let options = arguments.length > 1 ? arguments[1] : undefined;
        super(message, options);
        _defineProperty(this, "code", "ERR_JWKS_NO_MATCHING_KEY");
    }
}

_defineProperty(JWKSNoMatchingKey, "code", "ERR_JWKS_NO_MATCHING_KEY");

class JWKSMultipleMatchingKeys extends JOSEError {
    constructor() {
        let message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "multiple matching keys found in the JSON Web Key Set";
        let options = arguments.length > 1 ? arguments[1] : undefined;
        super(message, options);
        _defineProperty(this, Symbol.asyncIterator, _wrapAsyncGenerator(function*() {}));
        _defineProperty(this, "code", "ERR_JWKS_MULTIPLE_MATCHING_KEYS");
    }
}

_defineProperty(JWKSMultipleMatchingKeys, "code", "ERR_JWKS_MULTIPLE_MATCHING_KEYS");

class JWKSTimeout extends JOSEError {
    constructor() {
        let message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "request timed out";
        let options = arguments.length > 1 ? arguments[1] : undefined;
        super(message, options);
        _defineProperty(this, "code", "ERR_JWKS_TIMEOUT");
    }
}

_defineProperty(JWKSTimeout, "code", "ERR_JWKS_TIMEOUT");

class JWSSignatureVerificationFailed extends JOSEError {
    constructor() {
        let message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "signature verification failed";
        let options = arguments.length > 1 ? arguments[1] : undefined;
        super(message, options);
        _defineProperty(this, "code", "ERR_JWS_SIGNATURE_VERIFICATION_FAILED");
    }
}

_defineProperty(JWSSignatureVerificationFailed, "code", "ERR_JWS_SIGNATURE_VERIFICATION_FAILED");

const isCryptoKey = key => {
    if ((key === null || key === void 0 ? void 0 : key[Symbol.toStringTag]) === "CryptoKey") return true;
    try {
        return key instanceof CryptoKey;
    } catch (_unused) {
        return false;
    }
};

const isKeyObject = key => (key === null || key === void 0 ? void 0 : key[Symbol.toStringTag]) === "KeyObject";

const isKeyLike = key => isCryptoKey(key) || isKeyObject(key);

function encodeBase64(input) {
    if (Uint8Array.prototype.toBase64) {
        return input.toBase64();
    }
    const CHUNK_SIZE = 32768;
    const arr = [];
    for (let i = 0; i < input.length; i += CHUNK_SIZE) {
        arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
    }
    return btoa(arr.join(""));
}

function decodeBase64(encoded) {
    if (Uint8Array.fromBase64) {
        return Uint8Array.fromBase64(encoded);
    }
    const binary = atob(encoded);
    const bytes = new Uint8Array(binary.length);
    for (let i = 0; i < binary.length; i++) {
        bytes[i] = binary.charCodeAt(i);
    }
    return bytes;
}

const invalid = "The input to be decoded is not correctly encoded.";

function decode(input) {
    if (Uint8Array.fromBase64) {
        try {
            return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
                alphabet: "base64url"
            });
        } catch (cause) {
            throw new TypeError(invalid, {
                cause: cause
            });
        }
    }
    let encoded = input;
    if (encoded instanceof Uint8Array) {
        encoded = decoder.decode(encoded);
    }
    if (encoded.includes("+") || encoded.includes("/")) {
        throw new TypeError(invalid);
    }
    encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
    try {
        return decodeBase64(encoded);
    } catch (_unused) {
        throw new TypeError(invalid);
    }
}

function encode(input) {
    let unencoded = input;
    if (typeof unencoded === "string") {
        unencoded = encoder.encode(unencoded);
    }
    if (Uint8Array.prototype.toBase64) {
        return unencoded.toBase64({
            alphabet: "base64url",
            omitPadding: true
        });
    }
    return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
}

function isObject(input) {
    if (typeof input !== "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") {
        return false;
    }
    const prototype = Object.getPrototypeOf(input);
    return prototype === null || Object.getPrototypeOf(prototype) === null;
}

function isJwkSet(input) {
    return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject);
}

function assertNotSet(value, name) {
    if (value !== undefined) {
        throw new TypeError("".concat(name, " can only be called once"));
    }
}

function decodeBase64url(value, label, ErrorClass) {
    try {
        return decode(value);
    } catch (_unused) {
        throw new ErrorClass("Failed to base64url decode the ".concat(label));
    }
}

function encodeBase64url(value, label, ErrorClass) {
    try {
        return encode$1(value);
    } catch (_unused2) {
        throw new ErrorClass("The ".concat(label, " is not a valid base64url string"));
    }
}

function parseJoseHeader(b64, ErrorClass, message) {
    let parsed;
    try {
        parsed = JSON.parse(strictDecoder.decode(decode(b64)));
    } catch (_unused3) {
        throw new ErrorClass(message);
    }
    if (!isObject(parsed)) {
        throw new ErrorClass(message);
    }
    return parsed;
}

async function jwkToKey(entry, jwk) {
    var _entry$resolve, _entry$resolve2, _jwk$ext, _jwk$key_ops;
    if (jwk.kty === "RSA" && "oth" in jwk && jwk.oth !== undefined) {
        throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
    }
    if (!entry.kty.includes(jwk.kty)) {
        throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
    }
    const algorithm = (_entry$resolve = (_entry$resolve2 = entry.resolve) === null || _entry$resolve2 === void 0 ? void 0 : _entry$resolve2.call(entry, {
        kty: jwk.kty,
        crv: jwk.crv
    })) !== null && _entry$resolve !== void 0 ? _entry$resolve : entry.subtle;
    const isPrivate = !!(jwk.d || jwk.priv);
    const keyData = _objectSpread2({}, jwk);
    if (keyData.kty !== "AKP") {
        delete keyData.alg;
    }
    delete keyData.use;
    return crypto.subtle.importKey("jwk", keyData, algorithm, (_jwk$ext = jwk.ext) !== null && _jwk$ext !== void 0 ? _jwk$ext : !isPrivate, (_jwk$key_ops = jwk.key_ops) !== null && _jwk$key_ops !== void 0 ? _jwk$key_ops : entry.usages[isPrivate ? 1 : 0]);
}

function snapshotJwk(jwk) {
    return _objectSpread2({
        __proto__: null
    }, jwk);
}

function normalizeJwk(jwk) {
    const normalized = snapshotJwk(jwk);
    if (normalized.ext !== undefined && typeof normalized.ext !== "boolean") {
        throw new TypeError('"ext" (Extractable) Parameter must be a boolean');
    }
    if (normalized.key_ops !== undefined) {
        const value = normalized.key_ops;
        const keyOps = Array.isArray(value) ? [ ...value ] : undefined;
        if (!keyOps || keyOps.some(operation => typeof operation !== "string") || new Set(keyOps).size !== keyOps.length) {
            throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');
        }
        normalized.key_ops = keyOps;
    }
    return normalized;
}

const tag = key => key[Symbol.toStringTag];

const jwkMatchesOp = (entry, key, usage) => {
    const alg = entry.alg;
    if (key.use !== undefined) {
        const expected = usage === "sign" || usage === "verify" ? "sig" : "enc";
        if (key.use !== expected) {
            throw new TypeError('Invalid key for this operation, its "use" must be "'.concat(expected, '" when present'));
        }
    }
    if (key.alg !== undefined && key.alg !== alg) {
        throw new TypeError('Invalid key for this operation, its "alg" must be "'.concat(alg, '" when present'));
    }
    if (Array.isArray(key.key_ops)) {
        var _entry$ops;
        const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? (_entry$ops = entry.ops) === null || _entry$ops === void 0 ? void 0 : _entry$ops[usage === "encrypt" ? 0 : 1] : usage;
        if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp)) {
            throw new TypeError('Invalid key for this operation, its "key_ops" must include "'.concat(expectedKeyOp, '" when present'));
        }
    }
};

function checkKeyType(entry, key, usage) {
    const alg = entry.alg, secret = entry.secret;
    const privateKey = usage === "decrypt" || usage === "sign";
    if (secret && key instanceof Uint8Array) return [ BYTES, key ];
    if (isObject(key)) {
        const normalized = normalizeJwk(key);
        if (typeof normalized.kty !== "string") {
            throw new TypeError(secret ? withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array") : withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
        }
        const valid = secret ? normalized.kty === "oct" && typeof normalized.k === "string" : normalized.kty !== "oct" && (privateKey ? normalized.kty === "AKP" && typeof normalized.priv === "string" || typeof normalized.d === "string" : normalized.d === undefined && normalized.priv === undefined);
        if (!valid) {
            throw new TypeError(secret ? 'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present' : "JSON Web Key for this operation must be a ".concat(privateKey ? "private" : "public", " JWK"));
        }
        jwkMatchesOp(entry, normalized, usage);
        return [ JWK, key, normalized ];
    }
    if (!isKeyLike(key)) {
        throw new TypeError(secret ? withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array") : withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
    }
    if (secret) {
        if (key.type !== "secret") {
            throw new TypeError("".concat(tag(key), ' instances for symmetric algorithms must be of type "secret"'));
        }
    } else {
        if (key.type === "secret") {
            throw new TypeError("".concat(tag(key), ' instances for asymmetric algorithms must not be of type "secret"'));
        }
        const expectedType = privateKey ? "private" : "public";
        if ((key.type === "public" || key.type === "private") && key.type !== expectedType) {
            const operation = usage === "sign" ? "signing" : usage === "verify" ? "verifying" : "".concat(usage.slice(0, -1), "tion");
            throw new TypeError("".concat(tag(key), " instances for asymmetric algorithm ").concat(operation, ' must be of type "').concat(expectedType, '"'));
        }
    }
    return isCryptoKey(key) ? [ CRYPTO, key ] : [ KEYOBJECT, key ];
}

const BYTES = 0;

const CRYPTO = 1;

const KEYOBJECT = 2;

const JWK = 3;

let cache$1;

const nist = {
    __proto__: null,
    prime256v1: "P-256",
    secp384r1: "P-384",
    secp521r1: "P-521"
};

function cached(key, alg, value) {
    cache$1 || (cache$1 = new WeakMap);
    const entry = cache$1.get(key);
    if (value) {
        if (entry) {
            entry[alg] = value;
        } else {
            cache$1.set(key, {
                [alg]: value
            });
        }
    }
    return value !== null && value !== void 0 ? value : entry === null || entry === void 0 ? void 0 : entry[alg];
}

const handleJWK = async (key, jwk, entry) => {
    var _cached;
    return (_cached = cached(key, entry.alg)) !== null && _cached !== void 0 ? _cached : cached(key, entry.alg, await jwkToKey(entry, _objectSpread2(_objectSpread2({}, jwk), {}, {
        alg: entry.alg
    })));
};

const handleKeyObject = (keyObject, entry) => {
    var _keyObject$asymmetric, _entry$resolve, _entry$resolve2;
    const hit = cached(keyObject, entry.alg);
    if (hit) return hit;
    const isPublic = keyObject.type === "public";
    const usages = entry.usages[isPublic ? 0 : 1];
    const asymmetricKeyType = keyObject.asymmetricKeyType;
    const crv = nist[(_keyObject$asymmetric = keyObject.asymmetricKeyDetails) === null || _keyObject$asymmetric === void 0 ? void 0 : _keyObject$asymmetric.namedCurve];
    const params = (_entry$resolve = (_entry$resolve2 = entry.resolve) === null || _entry$resolve2 === void 0 ? void 0 : _entry$resolve2.call(entry, {
        crv: crv,
        asymmetricKeyType: asymmetricKeyType
    })) !== null && _entry$resolve !== void 0 ? _entry$resolve : entry.subtle;
    return cached(keyObject, entry.alg, keyObject.toCryptoKey(params, isPublic, usages));
};

async function prepareKey(entry, key, usage) {
    const tagged = checkKeyType(entry, key, usage);
    switch (tagged[0]) {
      case BYTES:
      case CRYPTO:
        return tagged[1];

      case JWK:
        {
            const key = tagged[1];
            const normalized = tagged[2];
            if (normalized.kty === "oct") {
                return decode(normalized.k);
            }
            if (!Object.isFrozen(key)) {
                const key_ops = key.key_ops;
                if (Array.isArray(key_ops)) Object.freeze(key_ops);
                Object.freeze(key);
            }
            return handleJWK(key, normalized, entry);
        }

      case KEYOBJECT:
        {
            const keyObject = tagged[1];
            if (keyObject.type === "secret") {
                return keyObject.export();
            }
            if ("toCryptoKey" in keyObject && typeof keyObject.toCryptoKey === "function") {
                return handleKeyObject(keyObject, entry);
            }
            return handleJWK(keyObject, keyObject.export({
                format: "jwk"
            }), entry);
        }
    }
}

function table(entries) {
    const out = {
        __proto__: null
    };
    for (const alg in entries) {
        out[alg] = _objectSpread2(_objectSpread2({}, entries[alg]), {}, {
            alg: alg
        });
    }
    return out;
}

const wrap = [ [ "encrypt", "wrapKey" ], [ "decrypt", "unwrapKey" ] ];

const derive = [ [], [ "deriveBits" ] ];

const none = [ [], [] ];

function rsaes(bits) {
    return {
        kty: [ "RSA" ],
        subtle: {
            name: "RSA-OAEP",
            hash: "SHA-".concat(bits)
        },
        usages: wrap,
        ops: [ "wrapKey", "unwrapKey" ]
    };
}

function ecdh() {
    return {
        kty: [ "EC", "OKP" ],
        subtle: {
            name: "ECDH"
        },
        resolve: _ref => {
            let kty = _ref.kty, crv = _ref.crv, asymmetricKeyType = _ref.asymmetricKeyType;
            if (crv === "X25519" || asymmetricKeyType === "x25519") {
                return {
                    name: "X25519"
                };
            }
            if (kty === "OKP") {
                throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
            }
            return {
                name: "ECDH",
                namedCurve: crv
            };
        },
        usages: derive,
        ops: [ undefined, "deriveBits" ]
    };
}

function aeskw(bits) {
    let gcm = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    return {
        kty: [ "oct" ],
        secret: true,
        subtle: {
            name: gcm ? "AES-GCM" : "AES-KW",
            length: bits
        },
        usages: none,
        ops: gcm ? [ "encrypt", "decrypt" ] : [ "wrapKey", "unwrapKey" ]
    };
}

function pbes2() {
    return {
        kty: [ "oct" ],
        secret: true,
        subtle: {
            name: "PBKDF2"
        },
        usages: none,
        ops: [ "deriveBits", "deriveBits" ]
    };
}

const JWE = table({
    dir: {
        kty: [ "oct" ],
        secret: true,
        subtle: {
            name: "AES-GCM"
        },
        usages: none,
        ops: [ "encrypt", "decrypt" ]
    },
    "RSA-OAEP": rsaes(1),
    "RSA-OAEP-256": rsaes(256),
    "RSA-OAEP-384": rsaes(384),
    "RSA-OAEP-512": rsaes(512),
    "ECDH-ES": ecdh(),
    "ECDH-ES+A128KW": ecdh(),
    "ECDH-ES+A192KW": ecdh(),
    "ECDH-ES+A256KW": ecdh(),
    A128KW: aeskw(128),
    A192KW: aeskw(192),
    A256KW: aeskw(256),
    A128GCMKW: aeskw(128, true),
    A192GCMKW: aeskw(192, true),
    A256GCMKW: aeskw(256, true),
    "PBES2-HS256+A128KW": pbes2(),
    "PBES2-HS384+A192KW": pbes2(),
    "PBES2-HS512+A256KW": pbes2()
});

const contentOps = [ "encrypt", "decrypt" ];

function contentEncryption(bits) {
    let cbc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    return {
        kty: [ "oct" ],
        secret: true,
        subtle: {
            name: cbc ? "AES-CBC" : "AES-GCM",
            length: bits
        },
        usages: none,
        ops: contentOps,
        cekBits: bits,
        ivBits: cbc ? 128 : 96,
        cbc: cbc
    };
}

table({
    A128GCM: contentEncryption(128),
    A192GCM: contentEncryption(192),
    A256GCM: contentEncryption(256),
    "A128CBC-HS256": contentEncryption(256, true),
    "A192CBC-HS384": contentEncryption(384, true),
    "A256CBC-HS512": contentEncryption(512, true)
});

const JWS_RECOGNIZED = {
    __proto__: null,
    b64: true
};

function validateAlgorithms(option, algorithms) {
    if (algorithms !== undefined && (!Array.isArray(algorithms) || algorithms.some(s => typeof s !== "string"))) {
        throw new TypeError('"'.concat(option, '" option must be an array of strings'));
    }
    if (!algorithms) {
        return undefined;
    }
    return new Set(algorithms);
}

function validateCritDuplicates(Err, protectedHeader) {
    const _ref = protectedHeader !== null && protectedHeader !== void 0 ? protectedHeader : {}, crit = _ref.crit;
    if (Array.isArray(crit) && new Set(crit).size !== crit.length) {
        throw new Err('"crit" (Critical) Header Parameter MUST NOT contain duplicate values');
    }
}

function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
    if (joseHeader.crit !== undefined && (protectedHeader === null || protectedHeader === void 0 ? void 0 : protectedHeader.crit) === undefined) {
        throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
    }
    if (!protectedHeader || protectedHeader.crit === undefined) {
        return [];
    }
    if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some(input => typeof input !== "string" || input.length === 0)) {
        throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
    }
    const recognized = recognizedOption === undefined ? recognizedDefault : _objectSpread2(_objectSpread2({
        __proto__: null
    }, recognizedOption), recognizedDefault);
    for (const parameter of protectedHeader.crit) {
        if (!(parameter in recognized)) {
            throw new JOSENotSupported('Extension Header Parameter "'.concat(parameter, '" is not recognized'));
        }
        if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === undefined) {
            throw new Err('Extension Header Parameter "'.concat(parameter, '" is missing'));
        }
        if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === undefined)) {
            throw new Err('Extension Header Parameter "'.concat(parameter, '" MUST be integrity protected'));
        }
    }
    return protectedHeader.crit;
}

function validateB64(protectedHeader, extensions) {
    if (extensions.includes("b64")) {
        const b64 = protectedHeader.b64;
        if (typeof b64 !== "boolean") {
            throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
        }
        return b64;
    }
    return true;
}

function serializeJoseHeader(Err, header) {
    let serialized;
    let parsed;
    try {
        serialized = JSON.stringify(header);
        parsed = JSON.parse(serialized);
    } catch (cause) {
        throw new Err("JOSE Header is not valid JSON", {
            cause: cause
        });
    }
    if (!isObject(parsed)) {
        throw new Err("JOSE Header is not a JSON object");
    }
    return [ parsed, serialized ];
}

var _navigator$userAgent$1, _navigator$userAgent$$1;

let headers;

let USER_AGENT$1;

if (typeof navigator === "undefined" || !((_navigator$userAgent$1 = navigator.userAgent) !== null && _navigator$userAgent$1 !== void 0 && (_navigator$userAgent$$1 = _navigator$userAgent$1.startsWith) !== null && _navigator$userAgent$$1 !== void 0 && _navigator$userAgent$$1.call(_navigator$userAgent$1, "Mozilla/5.0 "))) {
    const NAME = "openid-client";
    const VERSION = "v6.8.4";
    USER_AGENT$1 = "".concat(NAME, "/").concat(VERSION);
    headers = {
        "user-agent": USER_AGENT$1
    };
}

const int = config => props.get(config);

let props;

let tbi;

function ClientSecretPost(clientSecret) {
    if (clientSecret !== undefined) {
        return ClientSecretPost$1(clientSecret);
    }
    tbi || (tbi = new WeakMap);
    return (as, client, body, headers) => {
        let auth;
        if (!(auth = tbi.get(client))) {
            assertString(client.client_secret, '"metadata.client_secret"');
            auth = ClientSecretPost$1(client.client_secret);
            tbi.set(client, auth);
        }
        return auth(as, client, body, headers);
    };
}

function assertString(input, it) {
    if (typeof input !== "string") {
        throw CodedTypeError("".concat(it, " must be a string"), ERR_INVALID_ARG_TYPE);
    }
    if (input.length === 0) {
        throw CodedTypeError("".concat(it, " must not be empty"), ERR_INVALID_ARG_VALUE);
    }
}

function None() {
    return None$1();
}

function PrivateKeyJwt(clientPrivateKey, options) {
    return PrivateKeyJwt$1(clientPrivateKey, options);
}

function TlsClientAuth() {
    return TlsClientAuth$1();
}

const skipSubjectCheck = skipSubjectCheck$1;

const customFetch$1 = customFetch$2;

const ERR_INVALID_ARG_VALUE = "ERR_INVALID_ARG_VALUE";

const ERR_INVALID_ARG_TYPE = "ERR_INVALID_ARG_TYPE";

function CodedTypeError(message, code, cause) {
    const err = new TypeError(message, {
        cause: cause
    });
    Object.assign(err, {
        code: code
    });
    return err;
}

function calculatePKCECodeChallenge(codeVerifier) {
    return calculatePKCECodeChallenge$1(codeVerifier);
}

function randomPKCECodeVerifier() {
    return generateRandomCodeVerifier();
}

class ClientError extends Error {
    constructor(message, options) {
        var _Error$captureStackTr;
        super(message, options);
        _defineProperty(this, "code", void 0);
        this.name = this.constructor.name;
        this.code = options === null || options === void 0 ? void 0 : options.code;
        (_Error$captureStackTr = Error.captureStackTrace) === null || _Error$captureStackTr === void 0 || _Error$captureStackTr.call(Error, this, this.constructor);
    }
}

new TextDecoder;

function e(msg, cause, code) {
    return new ClientError(msg, {
        cause: cause,
        code: code
    });
}

function errorHandler(err) {
    if (err instanceof TypeError || err instanceof ClientError || err instanceof ResponseBodyError || err instanceof AuthorizationResponseError || err instanceof WWWAuthenticateChallengeError) {
        throw err;
    }
    if (err instanceof OperationProcessingError) {
        switch (err.code) {
          case HTTP_REQUEST_FORBIDDEN:
            throw e("only requests to HTTPS are allowed", err, err.code);

          case REQUEST_PROTOCOL_FORBIDDEN:
            throw e("only requests to HTTP or HTTPS are allowed", err, err.code);

          case RESPONSE_IS_NOT_CONFORM:
            throw e("unexpected HTTP response status code", err.cause, err.code);

          case RESPONSE_IS_NOT_JSON:
            throw e("unexpected response content-type", err.cause, err.code);

          case PARSE_ERROR:
            throw e("parsing error occured", err, err.code);

          case INVALID_RESPONSE:
            throw e("invalid response encountered", err, err.code);

          case JWT_CLAIM_COMPARISON:
            throw e("unexpected JWT claim value encountered", err, err.code);

          case JSON_ATTRIBUTE_COMPARISON:
            throw e("unexpected JSON attribute value encountered", err, err.code);

          case JWT_TIMESTAMP_CHECK:
            throw e("JWT timestamp claim value failed validation", err, err.code);

          default:
            throw e(err.message, err, err.code);
        }
    }
    if (err instanceof UnsupportedOperationError) {
        throw e("unsupported operation", err, err.code);
    }
    if (err instanceof DOMException) {
        switch (err.name) {
          case "OperationError":
            throw e("runtime operation error", err, UNSUPPORTED_OPERATION);

          case "NotSupportedError":
            throw e("runtime unsupported operation", err, UNSUPPORTED_OPERATION);

          case "TimeoutError":
            throw e("operation timed out", err, "OAUTH_TIMEOUT");

          case "AbortError":
            throw e("operation aborted", err, "OAUTH_ABORT");
        }
    }
    throw new ClientError("something went wrong", {
        cause: err
    });
}

function handleEntraId(server, as, options) {
    if (server.origin === "https://login.microsoftonline.com" && (!(options !== null && options !== void 0 && options.algorithm) || options.algorithm === "oidc")) {
        as[kEntraId] = true;
        return true;
    }
    return false;
}

function handleB2Clogin(server, options) {
    if (server.hostname.endsWith(".b2clogin.com") && (!(options !== null && options !== void 0 && options.algorithm) || options.algorithm === "oidc")) {
        return true;
    }
    return false;
}

async function discovery(server, clientId, metadata, clientAuthentication, options) {
    const as = await performDiscovery(server, options);
    const instance = new Configuration(as, clientId, metadata, clientAuthentication);
    let internals = int(instance);
    if (options !== null && options !== void 0 && options[customFetch$1]) {
        internals.fetch = options[customFetch$1];
    }
    if (options !== null && options !== void 0 && options.timeout) {
        internals.timeout = options.timeout;
    }
    if (options !== null && options !== void 0 && options.execute) {
        for (const extension of options.execute) {
            extension(instance);
        }
    }
    return instance;
}

async function performDiscovery(server, options) {
    var _options$timeout2, _options$execute2;
    if (!(server instanceof URL)) {
        throw CodedTypeError('"server" must be an instance of URL', ERR_INVALID_ARG_TYPE);
    }
    const resolve = !server.href.includes("/.well-known/");
    const timeout = (_options$timeout2 = options === null || options === void 0 ? void 0 : options.timeout) !== null && _options$timeout2 !== void 0 ? _options$timeout2 : 30;
    const signal = AbortSignal.timeout(timeout * 1e3);
    const as = await (resolve ? discoveryRequest(server, {
        algorithm: options === null || options === void 0 ? void 0 : options.algorithm,
        [customFetch$2]: options === null || options === void 0 ? void 0 : options[customFetch$1],
        [allowInsecureRequests$1]: options === null || options === void 0 || (_options$execute2 = options.execute) === null || _options$execute2 === void 0 ? void 0 : _options$execute2.includes(allowInsecureRequests),
        signal: signal,
        headers: new Headers(headers)
    }) : ((options === null || options === void 0 ? void 0 : options[customFetch$1]) || fetch)((_options$execute3 => {
        checkProtocol(server, options !== null && options !== void 0 && (_options$execute3 = options.execute) !== null && _options$execute3 !== void 0 && _options$execute3.includes(allowInsecureRequests) ? false : true);
        return server.href;
    })(), {
        headers: Object.fromEntries(new Headers(_objectSpread2({
            accept: "application/json"
        }, headers)).entries()),
        body: undefined,
        method: "GET",
        redirect: "manual",
        signal: signal
    })).then(response => processDiscoveryResponse(_nodiscoverycheck, response)).catch(errorHandler);
    if (resolve && new URL(as.issuer).href !== server.href) {
        handleEntraId(server, as, options) || handleB2Clogin(server, options) || (() => {
            throw new ClientError("discovered metadata issuer does not match the expected issuer", {
                code: JSON_ATTRIBUTE_COMPARISON,
                cause: {
                    expected: server.href,
                    body: as,
                    attribute: "issuer"
                }
            });
        })();
    }
    return as;
}

function getServerHelpers(metadata) {
    return {
        supportsPKCE: {
            __proto__: null,
            value() {
                var _metadata$code_challe;
                let method = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "S256";
                return ((_metadata$code_challe = metadata.code_challenge_methods_supported) === null || _metadata$code_challe === void 0 ? void 0 : _metadata$code_challe.includes(method)) === true;
            }
        }
    };
}

function addServerHelpers(metadata) {
    Object.defineProperties(metadata, getServerHelpers(metadata));
}

const kEntraId = Symbol();

class Configuration {
    constructor(server, clientId, metadata, clientAuthentication) {
        var _metadata, _metadata$oauth$clock3, _metadata2, _metadata$oauth$clock4, _metadata3;
        if (typeof clientId !== "string" || !clientId.length) {
            throw CodedTypeError('"clientId" must be a non-empty string', ERR_INVALID_ARG_TYPE);
        }
        if (typeof metadata === "string") {
            metadata = {
                client_secret: metadata
            };
        }
        if (((_metadata = metadata) === null || _metadata === void 0 ? void 0 : _metadata.client_id) !== undefined && clientId !== metadata.client_id) {
            throw CodedTypeError('"clientId" and "metadata.client_id" must be the same', ERR_INVALID_ARG_VALUE);
        }
        const client = _objectSpread2(_objectSpread2({}, structuredClone(metadata)), {}, {
            client_id: clientId
        });
        client[clockSkew] = (_metadata$oauth$clock3 = (_metadata2 = metadata) === null || _metadata2 === void 0 ? void 0 : _metadata2[clockSkew]) !== null && _metadata$oauth$clock3 !== void 0 ? _metadata$oauth$clock3 : 0;
        client[clockTolerance] = (_metadata$oauth$clock4 = (_metadata3 = metadata) === null || _metadata3 === void 0 ? void 0 : _metadata3[clockTolerance]) !== null && _metadata$oauth$clock4 !== void 0 ? _metadata$oauth$clock4 : 30;
        let auth;
        if (clientAuthentication) {
            auth = clientAuthentication;
        } else {
            if (typeof client.client_secret === "string" && client.client_secret.length) {
                auth = ClientSecretPost(client.client_secret);
            } else {
                auth = None();
            }
        }
        let c = Object.freeze(client);
        const clone = structuredClone(server);
        if (kEntraId in server) {
            clone[_expectedIssuer] = _ref => {
                let tid = _ref.claims.tid;
                return server.issuer.replace("{tenantid}", tid);
            };
        }
        let as = Object.freeze(clone);
        props || (props = new WeakMap);
        props.set(this, {
            __proto__: null,
            as: as,
            c: c,
            auth: auth,
            tlsOnly: true,
            jwksCache: {}
        });
    }
    serverMetadata() {
        const metadata = structuredClone(int(this).as);
        addServerHelpers(metadata);
        return metadata;
    }
    clientMetadata() {
        const metadata = structuredClone(int(this).c);
        return metadata;
    }
    get timeout() {
        return int(this).timeout;
    }
    set timeout(value) {
        int(this).timeout = value;
    }
    get [customFetch$1]() {
        return int(this).fetch;
    }
    set [customFetch$1](value) {
        int(this).fetch = value;
    }
}

Object.freeze(Configuration.prototype);

function getHelpers(response) {
    let exp = undefined;
    if (response.expires_in !== undefined) {
        const now = new Date;
        now.setSeconds(now.getSeconds() + response.expires_in);
        exp = now.getTime();
    }
    return {
        expiresIn: {
            __proto__: null,
            value() {
                if (exp) {
                    const now = Date.now();
                    if (exp > now) {
                        return Math.floor((exp - now) / 1e3);
                    }
                    return 0;
                }
                return undefined;
            }
        },
        claims: {
            __proto__: null,
            value() {
                try {
                    return getValidatedIdTokenClaims(this);
                } catch (_unused) {
                    return undefined;
                }
            }
        }
    };
}

function addHelpers(response) {
    Object.defineProperties(response, getHelpers(response));
}

async function handleRetryAfter(response, currentInterval, signal) {
    var _response$headers$get;
    let throwIfInvalid = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
    const retryAfter = (_response$headers$get = response.headers.get("retry-after")) === null || _response$headers$get === void 0 ? void 0 : _response$headers$get.trim();
    if (retryAfter === undefined) return;
    let delaySeconds;
    if (/^\d+$/.test(retryAfter)) {
        delaySeconds = parseInt(retryAfter, 10);
    } else {
        const retryDate = new Date(retryAfter);
        if (Number.isFinite(retryDate.getTime())) {
            const now = new Date;
            const delayMs = retryDate.getTime() - now.getTime();
            if (delayMs > 0) {
                delaySeconds = Math.ceil(delayMs / 1e3);
            }
        }
    }
    if (throwIfInvalid && !Number.isFinite(delaySeconds)) {
        throw new OperationProcessingError("invalid Retry-After header value", {
            cause: response
        });
    }
    if (delaySeconds > currentInterval) {
        await wait(delaySeconds - currentInterval, signal);
    }
}

function wait(duration, signal) {
    return new Promise((resolve, reject) => {
        const waitStep = remaining => {
            try {
                signal.throwIfAborted();
            } catch (err) {
                reject(err);
                return;
            }
            if (remaining <= 0) {
                resolve();
                return;
            }
            const currentWait = Math.min(remaining, 5);
            setTimeout(() => waitStep(remaining - currentWait), currentWait * 1e3);
        };
        waitStep(duration);
    });
}

function pollRequestSignal(pollingSignal, timeout) {
    const timeoutSignal = signal(timeout);
    if (!timeoutSignal) {
        return {
            signal: pollingSignal,
            cleanup() {}
        };
    }
    const controller = new AbortController;
    const abort = event => {
        const source = event.target;
        controller.abort(source.reason);
    };
    if (pollingSignal.aborted) {
        controller.abort(pollingSignal.reason);
    } else if (timeoutSignal.aborted) {
        controller.abort(timeoutSignal.reason);
    } else {
        pollingSignal.addEventListener("abort", abort, {
            once: true
        });
        timeoutSignal.addEventListener("abort", abort, {
            once: true
        });
    }
    return {
        signal: controller.signal,
        cleanup() {
            pollingSignal.removeEventListener("abort", abort);
            timeoutSignal.removeEventListener("abort", abort);
        }
    };
}

async function initiateBackchannelAuthentication(config, parameters) {
    checkConfig(config);
    const _int3 = int(config), as = _int3.as, c = _int3.c, auth = _int3.auth, fetch = _int3.fetch, tlsOnly = _int3.tlsOnly, timeout = _int3.timeout;
    return backchannelAuthenticationRequest(as, c, auth, parameters, {
        [customFetch$2]: fetch,
        [allowInsecureRequests$1]: !tlsOnly,
        headers: new Headers(headers),
        signal: signal(timeout)
    }).then(response => processBackchannelAuthenticationResponse(as, c, response)).catch(errorHandler);
}

async function pollBackchannelAuthenticationGrant(config, backchannelAuthenticationResponse, parameters, options) {
    var _backchannelAuthentic, _options$signal2;
    checkConfig(config);
    parameters = new URLSearchParams(parameters);
    let interval = (_backchannelAuthentic = backchannelAuthenticationResponse.interval) !== null && _backchannelAuthentic !== void 0 ? _backchannelAuthentic : 5;
    const pollingSignal = (_options$signal2 = options === null || options === void 0 ? void 0 : options.signal) !== null && _options$signal2 !== void 0 ? _options$signal2 : AbortSignal.timeout(backchannelAuthenticationResponse.expires_in * 1e3);
    try {
        await wait(interval, pollingSignal);
    } catch (err) {
        errorHandler(err);
    }
    const _int4 = int(config), as = _int4.as, c = _int4.c, auth = _int4.auth, fetch = _int4.fetch, tlsOnly = _int4.tlsOnly, nonRepudiation = _int4.nonRepudiation, timeout = _int4.timeout, decrypt = _int4.decrypt;
    const retryPoll = (updatedInterval, flag) => pollBackchannelAuthenticationGrant(config, _objectSpread2(_objectSpread2({}, backchannelAuthenticationResponse), {}, {
        interval: updatedInterval
    }), parameters, _objectSpread2(_objectSpread2({}, options), {}, {
        signal: pollingSignal,
        flag: flag
    }));
    const requestSignal = pollRequestSignal(pollingSignal, timeout);
    const response = await backchannelAuthenticationGrantRequest(as, c, auth, backchannelAuthenticationResponse.auth_req_id, {
        [customFetch$2]: fetch,
        [allowInsecureRequests$1]: !tlsOnly,
        additionalParameters: parameters,
        DPoP: options === null || options === void 0 ? void 0 : options.DPoP,
        headers: new Headers(headers),
        signal: requestSignal.signal
    }).catch(errorHandler).finally(requestSignal.cleanup);
    if (response.status === 503 && response.headers.has("retry-after")) {
        var _response$body2;
        await handleRetryAfter(response, interval, pollingSignal, true);
        await ((_response$body2 = response.body) === null || _response$body2 === void 0 ? void 0 : _response$body2.cancel());
        return retryPoll(interval);
    }
    const p = processBackchannelAuthenticationGrantResponse(as, c, response, {
        [jweDecrypt]: decrypt
    });
    let result;
    try {
        result = await p;
    } catch (err) {
        if (retryable(err, options)) {
            return retryPoll(interval, retry);
        }
        if (err instanceof ResponseBodyError) {
            switch (err.error) {
              case "slow_down":
                interval += 5;

              case "authorization_pending":
                await handleRetryAfter(err.response, interval, pollingSignal);
                return retryPoll(interval);
            }
        }
        errorHandler(err);
    }
    result.id_token && await (nonRepudiation === null || nonRepudiation === void 0 ? void 0 : nonRepudiation(response));
    addHelpers(result);
    return result;
}

function allowInsecureRequests(config) {
    int(config).tlsOnly = false;
}

function stripParams(url) {
    url = new URL(url);
    url.search = "";
    url.hash = "";
    return url.href;
}

function webInstanceOf(input, toStringTag) {
    try {
        return Object.getPrototypeOf(input)[Symbol.toStringTag] === toStringTag;
    } catch (_unused2) {
        return false;
    }
}

async function authorizationCodeGrant(config, currentUrl, checks, tokenEndpointParameters, options) {
    checkConfig(config);
    if ((options === null || options === void 0 ? void 0 : options.flag) !== retry && !(currentUrl instanceof URL) && !webInstanceOf(currentUrl, "Request")) {
        throw CodedTypeError('"currentUrl" must be an instance of URL, or Request', ERR_INVALID_ARG_TYPE);
    }
    let authResponse;
    let redirectUri;
    const _int0 = int(config), as = _int0.as, c = _int0.c, auth = _int0.auth, fetch = _int0.fetch, tlsOnly = _int0.tlsOnly, jarm = _int0.jarm, hybrid = _int0.hybrid, nonRepudiation = _int0.nonRepudiation, timeout = _int0.timeout, decrypt = _int0.decrypt, implicit = _int0.implicit;
    if ((options === null || options === void 0 ? void 0 : options.flag) === retry) {
        authResponse = options.authResponse;
        redirectUri = options.redirectUri;
    } else {
        if (!(currentUrl instanceof URL)) {
            const request = currentUrl;
            currentUrl = new URL(currentUrl.url);
            switch (request.method) {
              case "GET":
                break;

              case "POST":
                const params = new URLSearchParams(await formPostResponse(request));
                if (hybrid) {
                    currentUrl.hash = params.toString();
                } else {
                    for (const _ref2 of params.entries()) {
                        var _ref3 = _slicedToArray(_ref2, 2);
                        const k = _ref3[0];
                        const v = _ref3[1];
                        currentUrl.searchParams.append(k, v);
                    }
                }
                break;

              default:
                throw CodedTypeError("unexpected Request HTTP method", ERR_INVALID_ARG_VALUE);
            }
        }
        redirectUri = stripParams(currentUrl);
        switch (true) {
          case !!jarm:
            authResponse = await jarm(currentUrl, checks === null || checks === void 0 ? void 0 : checks.expectedState);
            break;

          case !!hybrid:
            authResponse = await hybrid(currentUrl, checks === null || checks === void 0 ? void 0 : checks.expectedNonce, checks === null || checks === void 0 ? void 0 : checks.expectedState, checks === null || checks === void 0 ? void 0 : checks.maxAge);
            break;

          case !!implicit:
            throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");

          default:
            try {
                authResponse = validateAuthResponse(as, c, currentUrl.searchParams, checks === null || checks === void 0 ? void 0 : checks.expectedState);
            } catch (err) {
                errorHandler(err);
            }
        }
    }
    const response = await authorizationCodeGrantRequest(as, c, auth, authResponse, redirectUri, (checks === null || checks === void 0 ? void 0 : checks.pkceCodeVerifier) || nopkce, {
        additionalParameters: tokenEndpointParameters,
        [customFetch$2]: fetch,
        [allowInsecureRequests$1]: !tlsOnly,
        DPoP: options === null || options === void 0 ? void 0 : options.DPoP,
        headers: new Headers(headers),
        signal: signal(timeout)
    }).catch(errorHandler);
    if (typeof (checks === null || checks === void 0 ? void 0 : checks.expectedNonce) === "string" || typeof (checks === null || checks === void 0 ? void 0 : checks.maxAge) === "number") {
        checks.idTokenExpected = true;
    }
    const p = processAuthorizationCodeResponse(as, c, response, {
        expectedNonce: checks === null || checks === void 0 ? void 0 : checks.expectedNonce,
        maxAge: checks === null || checks === void 0 ? void 0 : checks.maxAge,
        requireIdToken: checks === null || checks === void 0 ? void 0 : checks.idTokenExpected,
        [jweDecrypt]: decrypt
    });
    let result;
    try {
        result = await p;
    } catch (err) {
        if (retryable(err, options)) {
            return authorizationCodeGrant(config, undefined, checks, tokenEndpointParameters, _objectSpread2(_objectSpread2({}, options), {}, {
                flag: retry,
                authResponse: authResponse,
                redirectUri: redirectUri
            }));
        }
        errorHandler(err);
    }
    result.id_token && await (nonRepudiation === null || nonRepudiation === void 0 ? void 0 : nonRepudiation(response));
    addHelpers(result);
    return result;
}

async function refreshTokenGrant(config, refreshToken, parameters, options) {
    checkConfig(config);
    parameters = new URLSearchParams(parameters);
    const _int11 = int(config), as = _int11.as, c = _int11.c, auth = _int11.auth, fetch = _int11.fetch, tlsOnly = _int11.tlsOnly, nonRepudiation = _int11.nonRepudiation, timeout = _int11.timeout, decrypt = _int11.decrypt;
    const response = await refreshTokenGrantRequest(as, c, auth, refreshToken, {
        [customFetch$2]: fetch,
        [allowInsecureRequests$1]: !tlsOnly,
        additionalParameters: parameters,
        DPoP: options === null || options === void 0 ? void 0 : options.DPoP,
        headers: new Headers(headers),
        signal: signal(timeout)
    }).catch(errorHandler);
    const p = processRefreshTokenResponse(as, c, response, {
        [jweDecrypt]: decrypt
    });
    let result;
    try {
        result = await p;
    } catch (err) {
        if (retryable(err, options)) {
            return refreshTokenGrant(config, refreshToken, parameters, _objectSpread2(_objectSpread2({}, options), {}, {
                flag: retry
            }));
        }
        errorHandler(err);
    }
    result.id_token && await (nonRepudiation === null || nonRepudiation === void 0 ? void 0 : nonRepudiation(response));
    addHelpers(result);
    return result;
}

async function clientCredentialsGrant(config, parameters, options) {
    checkConfig(config);
    parameters = new URLSearchParams(parameters);
    const _int12 = int(config), as = _int12.as, c = _int12.c, auth = _int12.auth, fetch = _int12.fetch, tlsOnly = _int12.tlsOnly, timeout = _int12.timeout;
    const response = await clientCredentialsGrantRequest(as, c, auth, parameters, {
        [customFetch$2]: fetch,
        [allowInsecureRequests$1]: !tlsOnly,
        DPoP: options === null || options === void 0 ? void 0 : options.DPoP,
        headers: new Headers(headers),
        signal: signal(timeout)
    }).catch(errorHandler);
    const p = processClientCredentialsResponse(as, c, response);
    let result;
    try {
        result = await p;
    } catch (err) {
        if (retryable(err, options)) {
            return clientCredentialsGrant(config, parameters, _objectSpread2(_objectSpread2({}, options), {}, {
                flag: retry
            }));
        }
        errorHandler(err);
    }
    addHelpers(result);
    return result;
}

function buildAuthorizationUrl(config, parameters) {
    checkConfig(config);
    const _int13 = int(config), as = _int13.as, c = _int13.c, tlsOnly = _int13.tlsOnly, hybrid = _int13.hybrid, jarm = _int13.jarm, implicit = _int13.implicit;
    const authorizationEndpoint = resolveEndpoint(as, "authorization_endpoint", false, tlsOnly);
    parameters = new URLSearchParams(parameters);
    if (!parameters.has("client_id")) {
        parameters.set("client_id", c.client_id);
    }
    if (!parameters.has("request_uri") && !parameters.has("request")) {
        if (!parameters.has("response_type")) {
            parameters.set("response_type", hybrid ? "code id_token" : implicit ? "id_token" : "code");
        }
        if (implicit && !parameters.has("nonce")) {
            throw CodedTypeError("response_type=id_token clients must provide a nonce parameter in their authorization request parameters", ERR_INVALID_ARG_VALUE);
        }
        if (jarm) {
            parameters.set("response_mode", "jwt");
        }
    }
    for (const _ref4 of parameters.entries()) {
        var _ref5 = _slicedToArray(_ref4, 2);
        const k = _ref5[0];
        const v = _ref5[1];
        authorizationEndpoint.searchParams.append(k, v);
    }
    return authorizationEndpoint;
}

async function buildAuthorizationUrlWithPAR(config, parameters, options) {
    checkConfig(config);
    const authorizationEndpoint = buildAuthorizationUrl(config, parameters);
    const _int15 = int(config), as = _int15.as, c = _int15.c, auth = _int15.auth, fetch = _int15.fetch, tlsOnly = _int15.tlsOnly, timeout = _int15.timeout;
    const response = await pushedAuthorizationRequest(as, c, auth, authorizationEndpoint.searchParams, {
        [customFetch$2]: fetch,
        [allowInsecureRequests$1]: !tlsOnly,
        DPoP: options === null || options === void 0 ? void 0 : options.DPoP,
        headers: new Headers(headers),
        signal: signal(timeout)
    }).catch(errorHandler);
    const p = processPushedAuthorizationResponse(as, c, response);
    let result;
    try {
        result = await p;
    } catch (err) {
        if (retryable(err, options)) {
            return buildAuthorizationUrlWithPAR(config, parameters, _objectSpread2(_objectSpread2({}, options), {}, {
                flag: retry
            }));
        }
        errorHandler(err);
    }
    return buildAuthorizationUrl(config, {
        request_uri: result.request_uri
    });
}

function buildEndSessionUrl(config, parameters) {
    checkConfig(config);
    const _int16 = int(config), as = _int16.as, c = _int16.c, tlsOnly = _int16.tlsOnly;
    const endSessionEndpoint = resolveEndpoint(as, "end_session_endpoint", false, tlsOnly);
    parameters = new URLSearchParams(parameters);
    if (!parameters.has("client_id")) {
        parameters.set("client_id", c.client_id);
    }
    for (const _ref6 of parameters.entries()) {
        var _ref7 = _slicedToArray(_ref6, 2);
        const k = _ref7[0];
        const v = _ref7[1];
        endSessionEndpoint.searchParams.append(k, v);
    }
    return endSessionEndpoint;
}

function checkConfig(input) {
    if (!(input instanceof Configuration)) {
        throw CodedTypeError('"config" must be an instance of Configuration', ERR_INVALID_ARG_TYPE);
    }
    if (Object.getPrototypeOf(input) !== Configuration.prototype) {
        throw CodedTypeError("subclassing Configuration is not allowed", ERR_INVALID_ARG_VALUE);
    }
}

function signal(timeout) {
    return timeout ? AbortSignal.timeout(timeout * 1e3) : undefined;
}

async function fetchUserInfo(config, accessToken, expectedSubject, options) {
    checkConfig(config);
    const _int17 = int(config), as = _int17.as, c = _int17.c, fetch = _int17.fetch, tlsOnly = _int17.tlsOnly, nonRepudiation = _int17.nonRepudiation, timeout = _int17.timeout, decrypt = _int17.decrypt;
    const response = await userInfoRequest(as, c, accessToken, {
        [customFetch$2]: fetch,
        [allowInsecureRequests$1]: !tlsOnly,
        DPoP: options === null || options === void 0 ? void 0 : options.DPoP,
        headers: new Headers(headers),
        signal: signal(timeout)
    }).catch(errorHandler);
    let exec = processUserInfoResponse(as, c, expectedSubject, response, {
        [jweDecrypt]: decrypt
    });
    let result;
    try {
        result = await exec;
    } catch (err) {
        if (retryable(err, options)) {
            return fetchUserInfo(config, accessToken, expectedSubject, _objectSpread2(_objectSpread2({}, options), {}, {
                flag: retry
            }));
        }
        errorHandler(err);
    }
    getContentType(response) === "application/jwt" && await (nonRepudiation === null || nonRepudiation === void 0 ? void 0 : nonRepudiation(response));
    return result;
}

function retryable(err, options) {
    if (options !== null && options !== void 0 && options.DPoP && options.flag !== retry) {
        return isDPoPNonceError(err);
    }
    return false;
}

const retry = Symbol();

async function genericGrantRequest(config, grantType, parameters, options) {
    checkConfig(config);
    const _int19 = int(config), as = _int19.as, c = _int19.c, auth = _int19.auth, fetch = _int19.fetch, tlsOnly = _int19.tlsOnly, timeout = _int19.timeout, decrypt = _int19.decrypt, nonRepudiation = _int19.nonRepudiation;
    const response = await genericTokenEndpointRequest(as, c, auth, grantType, new URLSearchParams(parameters), {
        [customFetch$2]: fetch,
        [allowInsecureRequests$1]: !tlsOnly,
        DPoP: options === null || options === void 0 ? void 0 : options.DPoP,
        headers: new Headers(headers),
        signal: signal(timeout)
    }).catch(errorHandler);
    let recognizedTokenTypes;
    if (grantType === "urn:ietf:params:oauth:grant-type:token-exchange") {
        recognizedTokenTypes = {
            n_a: () => {}
        };
    }
    const p = processGenericTokenEndpointResponse(as, c, response, {
        [jweDecrypt]: decrypt,
        recognizedTokenTypes: recognizedTokenTypes
    });
    let result;
    try {
        result = await p;
    } catch (err) {
        if (retryable(err, options)) {
            return genericGrantRequest(config, grantType, parameters, _objectSpread2(_objectSpread2({}, options), {}, {
                flag: retry
            }));
        }
        errorHandler(err);
    }
    result.id_token && await (nonRepudiation === null || nonRepudiation === void 0 ? void 0 : nonRepudiation(response));
    addHelpers(result);
    return result;
}

async function tokenRevocation(config, token, parameters) {
    checkConfig(config);
    const _int20 = int(config), as = _int20.as, c = _int20.c, auth = _int20.auth, fetch = _int20.fetch, tlsOnly = _int20.tlsOnly, timeout = _int20.timeout;
    return revocationRequest(as, c, auth, token, {
        [customFetch$2]: fetch,
        [allowInsecureRequests$1]: !tlsOnly,
        additionalParameters: new URLSearchParams(parameters),
        headers: new Headers(headers),
        signal: signal(timeout)
    }).then(processRevocationResponse).catch(errorHandler);
}

async function getSigKey(entry, key, usage) {
    if (key instanceof Uint8Array) {
        return crypto.subtle.importKey("raw", key, entry.subtle, false, [ usage ]);
    }
    checkCryptoKey(key, entry.subtle, usage);
    if (entry.minRsaBits) checkModulusLength(entry.alg, key);
    return key;
}

async function sign(entry, key, data) {
    const cryptoKey = await getSigKey(entry, key, "sign");
    const signature = await crypto.subtle.sign(entry.signing, cryptoKey, data);
    return new Uint8Array(signature);
}

async function verify(entry, key, signature, data) {
    const cryptoKey = await getSigKey(entry, key, "verify");
    try {
        return await crypto.subtle.verify(entry.signing, cryptoKey, signature, data);
    } catch (_unused) {
        return false;
    }
}

const sig = [ [ "verify" ], [ "sign" ] ];

function hmac(bits) {
    const subtle = {
        name: "HMAC",
        hash: "SHA-".concat(bits)
    };
    return {
        kty: [ "oct" ],
        secret: true,
        subtle: subtle,
        signing: subtle,
        usages: sig
    };
}

function rsa(bits, saltLength) {
    const name = saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5";
    const subtle = {
        name: name,
        hash: "SHA-".concat(bits)
    };
    return {
        kty: [ "RSA" ],
        subtle: subtle,
        signing: saltLength ? _objectSpread2(_objectSpread2({}, subtle), {}, {
            saltLength: saltLength
        }) : subtle,
        usages: sig,
        minRsaBits: 2048
    };
}

function ecdsa(crv, bits) {
    return {
        kty: [ "EC" ],
        crv: crv,
        subtle: {
            name: "ECDSA",
            namedCurve: crv
        },
        signing: {
            name: "ECDSA",
            hash: "SHA-".concat(bits)
        },
        usages: sig
    };
}

function eddsa() {
    const subtle = {
        name: "Ed25519"
    };
    return {
        kty: [ "OKP" ],
        crv: "Ed25519",
        subtle: subtle,
        signing: subtle,
        usages: sig
    };
}

function mldsa(bits) {
    const name = "ML-DSA-".concat(bits);
    const subtle = {
        name: name
    };
    return {
        kty: [ "AKP" ],
        subtle: subtle,
        signing: subtle,
        usages: sig
    };
}

const JWS = table({
    HS256: hmac(256),
    HS384: hmac(384),
    HS512: hmac(512),
    RS256: rsa(256),
    RS384: rsa(384),
    RS512: rsa(512),
    PS256: rsa(256, 32),
    PS384: rsa(384, 48),
    PS512: rsa(512, 64),
    ES256: ecdsa("P-256", 256),
    ES384: ecdsa("P-384", 384),
    ES512: ecdsa("P-521", 512),
    EdDSA: eddsa(),
    Ed25519: eddsa(),
    "ML-DSA-44": mldsa(44),
    "ML-DSA-65": mldsa(65),
    "ML-DSA-87": mldsa(87)
});

function jwsAlgorithm(alg) {
    const entry = typeof alg === "string" ? JWS[alg] : undefined;
    if (!entry) {
        throw new JOSENotSupported("alg ".concat(alg, " is not supported either by JOSE or your javascript runtime"));
    }
    return entry;
}

function prepareVerify(options) {
    return [ options && validateAlgorithms("algorithms", options.algorithms), options === null || options === void 0 ? void 0 : options.crit ];
}

function parseProtectedHeader(encodedProtected) {
    let parsedProtected = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : encodedProtected === undefined ? {} : parseJoseHeader(encodedProtected, JWSInvalid, "JWS Protected Header is invalid");
    return parsedProtected;
}

function validateJwsHeaders(parsedProt, joseHeader, shared) {
    const b64 = validateB64(parsedProt, validateCrit(JWSInvalid, JWS_RECOGNIZED, shared[1], parsedProt, joseHeader));
    const alg = joseHeader.alg;
    if (typeof alg !== "string" || !alg) {
        throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
    }
    if (shared[0] && !shared[0].has(alg)) {
        throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
    }
    return [ b64, alg ];
}

function encodeCompactUnencodedPayload(payload) {
    try {
        return encode$1(payload);
    } catch (_unused) {
        throw new JWSInvalid("JWS Compact Serialization payload must use only ASCII characters");
    }
}

async function verifyPrepared(jws, shared, key, encodedProtected, parsedProt, alg, signingPayload) {
    var _, _shared$_;
    let resolvedKey = false;
    if (typeof key === "function") {
        key = await key(parsedProt, jws);
        resolvedKey = true;
    }
    const b64 = typeof signingPayload === "string";
    const entry = jwsAlgorithm(alg);
    const data = concat(encodedProtected !== undefined ? encode$1(encodedProtected) : new Uint8Array, encode$1("."), b64 ? (_shared$_ = shared[_ = 2]) !== null && _shared$_ !== void 0 ? _shared$_ : shared[_] = encodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload);
    const signature = decodeBase64url(jws.signature, "signature", JWSInvalid);
    const k = await prepareKey(entry, key, "verify");
    if (!await verify(entry, k, signature, data)) {
        throw new JWSSignatureVerificationFailed;
    }
    const payload = b64 ? decodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload;
    return [ payload, parsedProt, b64, k, resolvedKey ];
}

async function verifyCompact(jws, shared, key) {
    if (jws instanceof Uint8Array) {
        jws = decoder.decode(jws);
    }
    if (typeof jws !== "string") {
        throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
    }
    const _jws$split = jws.split("."), protectedHeader = _jws$split[0], payload = _jws$split[1], signature = _jws$split[2], length = _jws$split.length;
    if (length !== 3) {
        throw new JWSInvalid("Invalid Compact JWS");
    }
    const compactJws = {
        payload: payload,
        protected: protectedHeader,
        signature: signature
    };
    const parsedProt = parseProtectedHeader(protectedHeader);
    const _validateJwsHeaders = validateJwsHeaders(parsedProt, parsedProt, shared), _validateJwsHeaders2 = _slicedToArray(_validateJwsHeaders, 2), b64 = _validateJwsHeaders2[0], alg = _validateJwsHeaders2[1];
    const signingPayload = b64 ? payload : encodeCompactUnencodedPayload(payload);
    return verifyPrepared(compactJws, shared, key, protectedHeader, parsedProt, alg, signingPayload);
}

const epoch = date => Math.floor(date.getTime() / 1e3);

const multipliers = {
    s: 1,
    m: 60,
    h: 3600,
    d: 86400,
    w: 604800,
    y: 31557600
};

const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;

const checkFailed = "check_failed";

function invalidDuration() {
    throw new TypeError("Invalid time period format");
}

function secs(str) {
    if (typeof str !== "string") {
        invalidDuration();
    }
    const matched = REGEX.exec(str);
    if (!matched || matched[4] && matched[1]) {
        invalidDuration();
    }
    const value = parseFloat(matched[2]);
    const numericDate = Math.round(value * multipliers[matched[3][0].toLowerCase()]);
    if (!Number.isFinite(numericDate)) {
        invalidDuration();
    }
    if (matched[1] === "-" || matched[4] === "ago") {
        return -numericDate;
    }
    return numericDate;
}

function validateInput(label, input) {
    if (!Number.isFinite(input)) {
        throw new TypeError("Invalid ".concat(label, " input"));
    }
    return input;
}

function validateStringClaim(claim, value) {
    if (typeof value !== "string") {
        throw new TypeError('"'.concat(claim, '" claim must be a string'));
    }
}

function validateAudienceClaim(value) {
    if (typeof value !== "string" && (!Array.isArray(value) || Array.from(value).some(member => typeof member !== "string"))) {
        throw new TypeError('"aud" claim must be a string or an array of strings');
    }
}

function numericDate(value, label) {
    if (typeof value === "number") return validateInput(label, value);
    if (value instanceof Date) return validateInput(label, epoch(value));
    return epoch(new Date) + secs(value);
}

const normalizeTyp = value => {
    const normalized = value.toLowerCase();
    return value.includes("/") ? normalized : "application/".concat(normalized);
};

const checkAudiencePresence = (audPayload, audOption) => {
    if (typeof audPayload === "string") {
        return audOption.includes(audPayload);
    }
    if (Array.isArray(audPayload)) {
        return audOption.some(aud => audPayload.includes(aud));
    }
    return false;
};

function validateNumericDate(payload, claim) {
    let required = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
    const value = payload[claim];
    if (value === undefined && !required) return undefined;
    if (typeof value !== "number") {
        throw new JWTClaimValidationFailed('"'.concat(claim, '" claim must be a number'), payload, claim, "invalid");
    }
    return value;
}

function unexpectedClaim(payload, claim) {
    throw new JWTClaimValidationFailed('unexpected "'.concat(claim, '" claim value'), payload, claim, checkFailed);
}

function validateClaimsSet(protectedHeader, encodedPayload) {
    let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    let payload;
    try {
        payload = JSON.parse(strictDecoder.decode(encodedPayload));
    } catch (_unused) {}
    if (!isObject(payload)) {
        throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
    }
    const typ = options.typ;
    if (typ !== undefined && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
        throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", checkFailed);
    }
    const _options$requiredClai = options.requiredClaims, requiredClaims = _options$requiredClai === void 0 ? [] : _options$requiredClai, issuer = options.issuer, subject = options.subject, audience = options.audience, maxTokenAge = options.maxTokenAge;
    const presenceCheck = [ ...requiredClaims ];
    if (maxTokenAge !== undefined) presenceCheck.push("iat");
    if (audience !== undefined) presenceCheck.push("aud");
    if (subject !== undefined) presenceCheck.push("sub");
    if (issuer !== undefined) presenceCheck.push("iss");
    for (const claim of new Set(presenceCheck.reverse())) {
        if (!Object.hasOwn(payload, claim)) {
            throw new JWTClaimValidationFailed('missing required "'.concat(claim, '" claim'), payload, claim, "missing");
        }
    }
    if (issuer !== undefined && !(Array.isArray(issuer) ? issuer : [ issuer ]).includes(payload.iss)) {
        unexpectedClaim(payload, "iss");
    }
    if (subject !== undefined && payload.sub !== subject) {
        unexpectedClaim(payload, "sub");
    }
    if (audience !== undefined && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [ audience ] : audience)) {
        unexpectedClaim(payload, "aud");
    }
    const clockTolerance = options.clockTolerance;
    let tolerance = 0;
    if (typeof clockTolerance === "string") {
        tolerance = secs(clockTolerance);
    } else if (clockTolerance !== undefined) {
        if (typeof clockTolerance !== "number") {
            throw new TypeError("Invalid clockTolerance option type");
        }
        tolerance = clockTolerance;
    }
    validateInput("clockTolerance option", tolerance);
    const currentDate = options.currentDate;
    const now = validateInput("currentDate option", epoch(currentDate === undefined ? new Date : currentDate));
    const iat = validateNumericDate(payload, "iat", maxTokenAge !== undefined);
    const nbf = validateNumericDate(payload, "nbf");
    if (nbf !== undefined) {
        if (nbf > now + tolerance) {
            throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", checkFailed);
        }
    }
    const exp = validateNumericDate(payload, "exp");
    if (exp !== undefined) {
        if (exp <= now - tolerance) {
            throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", checkFailed);
        }
    }
    if (maxTokenAge !== undefined) {
        const age = now - iat;
        const max = validateInput("maxTokenAge option", typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge));
        if (age - tolerance > max) {
            throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", checkFailed);
        }
        if (age < -tolerance) {
            throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", checkFailed);
        }
    }
    return payload;
}

let producerPayloads;

function producerPayload(producer) {
    return producerPayloads.get(producer);
}

function jwtData(producer) {
    const payload = producerPayload(producer);
    for (const claim of [ "iat", "nbf", "exp" ]) {
        const value = payload[claim];
        if (typeof value === "number" && !Number.isFinite(value)) {
            throw new TypeError('"'.concat(claim, '" claim must be a finite number'));
        }
    }
    return encoder.encode(JSON.stringify(payload));
}

class JWTClaimsBuilder {
    constructor() {
        let payload = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        if (!isObject(payload)) {
            throw new TypeError("JWT Claims Set MUST be an object");
        }
        (producerPayloads || (producerPayloads = new WeakMap)).set(this, structuredClone(payload));
    }
    setIssuer(value) {
        validateStringClaim("iss", value);
        producerPayload(this).iss = value;
        return this;
    }
    setSubject(value) {
        validateStringClaim("sub", value);
        producerPayload(this).sub = value;
        return this;
    }
    setAudience(value) {
        validateAudienceClaim(value);
        producerPayload(this).aud = value;
        return this;
    }
    setJti(value) {
        validateStringClaim("jti", value);
        producerPayload(this).jti = value;
        return this;
    }
    setNotBefore(value) {
        producerPayload(this).nbf = numericDate(value, "setNotBefore");
        return this;
    }
    setExpirationTime(value) {
        producerPayload(this).exp = numericDate(value, "setExpirationTime");
        return this;
    }
    setIssuedAt(value) {
        const payload = producerPayload(this);
        if (value === undefined) {
            payload.iat = epoch(new Date);
        } else if (typeof value === "string") {
            payload.iat = validateInput("setIssuedAt", epoch(new Date) + secs(value));
        } else {
            payload.iat = numericDate(value, "setIssuedAt");
        }
        return this;
    }
}

async function jwtVerify(jwt, key, options) {
    const verified = await verifyCompact(jwt, prepareVerify(options), key);
    if (!verified[2]) {
        throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
    }
    const payload = validateClaimsSet(verified[1], verified[0], options);
    const result = {
        payload: payload,
        protectedHeader: verified[1]
    };
    if (typeof key === "function") {
        return _objectSpread2(_objectSpread2({}, result), {}, {
            key: verified[3]
        });
    }
    return result;
}

function serializeProtectedHeader(protectedHeader) {
    if (protectedHeader === undefined) return [ undefined, "" ];
    const normalized = serializeJoseHeader(JWSInvalid, protectedHeader);
    return [ normalized[0], encode(normalized[1]) ];
}

function validateSignatureHeader(protectedHeader, joseHeader, crit) {
    validateCritDuplicates(JWSInvalid, protectedHeader);
    return validateB64(protectedHeader, validateCrit(JWSInvalid, JWS_RECOGNIZED, crit, protectedHeader, joseHeader));
}

function signatureAlgorithm(joseHeader) {
    const alg = joseHeader.alg;
    if (typeof alg !== "string" || !alg) {
        throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
    }
    return jwsAlgorithm(alg);
}

async function signSignature(protectedHeader, payload, entry, key) {
    const data = concat(encode$1(protectedHeader), encode$1("."), payload);
    const k = await prepareKey(entry, key, "sign");
    return encode(await sign(entry, k, data));
}

async function createCompactSignature(payload, inputProtectedHeader, inputCrit, key, rejectUnencoded) {
    const _serializeProtectedHe3 = serializeProtectedHeader(inputProtectedHeader), _serializeProtectedHe4 = _slicedToArray(_serializeProtectedHe3, 2), protectedHeader = _serializeProtectedHe4[0], protectedHeaderString = _serializeProtectedHe4[1];
    if (!protectedHeader) {
        throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
    }
    const b64 = validateSignatureHeader(protectedHeader, protectedHeader, inputCrit);
    if (!b64) rejectUnencoded();
    const entry = signatureAlgorithm(protectedHeader);
    const encodedPayload = encode(payload);
    const signature = await signSignature(protectedHeaderString, encode$1(encodedPayload), entry, key);
    return "".concat(protectedHeaderString, ".").concat(encodedPayload, ".").concat(signature);
}

const SignJWT_base = JWTClaimsBuilder;

var _protectedHeader = new WeakMap;

class SignJWT extends SignJWT_base {
    constructor() {
        super(...arguments);
        _classPrivateFieldInitSpec(this, _protectedHeader, void 0);
    }
    setProtectedHeader(protectedHeader) {
        assertNotSet(_classPrivateFieldGet2(_protectedHeader, this), "setProtectedHeader");
        _classPrivateFieldSet2(_protectedHeader, this, protectedHeader);
        return this;
    }
    async sign(key, options) {
        return createCompactSignature(jwtData(this), _classPrivateFieldGet2(_protectedHeader, this), options === null || options === void 0 ? void 0 : options.crit, key, () => {
            throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
        });
    }
}

const algArgument = '"alg" (Algorithm)';

function unsupportedAlg() {
    let source = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'JWK "alg" (Algorithm) Parameter';
    throw new JOSENotSupported("Invalid or unsupported ".concat(source, " value"));
}

function keyAlgorithm(alg, source) {
    var _ref, _JWS$alg;
    return (_ref = typeof alg === "string" ? (_JWS$alg = JWS[alg]) !== null && _JWS$alg !== void 0 ? _JWS$alg : JWE[alg] : undefined) !== null && _ref !== void 0 ? _ref : unsupportedAlg(source);
}

function validateExtractableOption(extractable) {
    if (extractable !== undefined && typeof extractable !== "boolean") {
        throw new TypeError('"extractable" option must be a boolean');
    }
    return extractable;
}

const bytesEqual = (a, b) => {
    if (a.byteLength !== b.length) return false;
    for (let i = 0; i < a.byteLength; i++) {
        if (a[i] !== b[i]) return false;
    }
    return true;
};

const createASN1State = data => ({
    data: data,
    pos: 0
});

const readByte = state => {
    const byte = state.data[state.pos++];
    if (byte === undefined) {
        throw new Error("Unexpected end of ASN.1 input");
    }
    return byte;
};

const parseLength = state => {
    const first = readByte(state);
    if (first & 128) {
        const lengthOfLen = first & 127;
        let length = 0;
        for (let i = 0; i < lengthOfLen; i++) {
            length = length << 8 | readByte(state);
        }
        return length;
    }
    return first;
};

const expectTag = (state, expectedTag, errorMessage) => {
    if (readByte(state) !== expectedTag) {
        throw new Error(errorMessage);
    }
};

const getSubarray = (state, length) => {
    if (length < 0 || state.pos + length > state.data.length) {
        throw new Error("Unexpected end of ASN.1 input");
    }
    const result = state.data.subarray(state.pos, state.pos + length);
    state.pos += length;
    return result;
};

const parseAlgorithmOID = state => {
    expectTag(state, 6, "Expected algorithm OID");
    const oidLen = parseLength(state);
    return getSubarray(state, oidLen);
};

function parseKeyHeader(state, keyFormat) {
    expectTag(state, 48, "Invalid ".concat(keyFormat === "spki" ? "SPKI" : "PKCS#8", " structure"));
    parseLength(state);
    if (keyFormat === "pkcs8") {
        expectTag(state, 2, "Expected version field");
        const length = parseLength(state);
        state.pos += length;
    }
    expectTag(state, 48, "Expected algorithm identifier");
    parseLength(state);
}

const parseECAlgorithmIdentifier = state => {
    const algOid = parseAlgorithmOID(state);
    if (bytesEqual(algOid, [ 43, 101, 110 ])) {
        return "X25519";
    }
    if (!bytesEqual(algOid, [ 42, 134, 72, 206, 61, 2, 1 ])) {
        throw new Error("Unsupported key algorithm");
    }
    expectTag(state, 6, "Expected curve OID");
    const curveOidLen = parseLength(state);
    const curveOid = getSubarray(state, curveOidLen);
    if (bytesEqual(curveOid, [ 42, 134, 72, 206, 61, 3, 1, 7 ])) return "P-256";
    if (bytesEqual(curveOid, [ 43, 129, 4, 0, 34 ])) return "P-384";
    if (bytesEqual(curveOid, [ 43, 129, 4, 0, 35 ])) return "P-521";
    throw new Error("Unsupported named curve");
};

const genericImport = async (keyFormat, keyData, alg, options) => {
    const extractable = validateExtractableOption(options === null || options === void 0 ? void 0 : options.extractable);
    const entry = keyAlgorithm(alg, algArgument);
    if (entry.secret) {
        unsupportedAlg(algArgument);
    }
    const isPublic = keyFormat === "spki";
    let algorithm;
    if (entry.resolve) {
        try {
            const state = createASN1State(keyData);
            parseKeyHeader(state, keyFormat);
            algorithm = entry.resolve({
                crv: parseECAlgorithmIdentifier(state)
            });
        } catch (_unused) {
            throw new JOSENotSupported("Invalid or unsupported key format");
        }
    } else {
        algorithm = entry.subtle;
    }
    return crypto.subtle.importKey(keyFormat, keyData, algorithm, extractable !== null && extractable !== void 0 ? extractable : isPublic, entry.usages[isPublic ? 0 : 1]);
};

const processPEMData = (pem, pattern) => decodeBase64(pem.replace(pattern, ""));

const fromPKCS8 = (pem, alg, options) => {
    const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);
    return genericImport("pkcs8", keyData, alg, options);
};

function isUsableJWK(jwk, entry, alg, kid) {
    const _snapshotJwk = snapshotJwk(jwk), kty = _snapshotJwk.kty, key_ops = _snapshotJwk.key_ops, ext = _snapshotJwk.ext, jwkKid = _snapshotJwk.kid, jwkAlg = _snapshotJwk.alg, use = _snapshotJwk.use, crv = _snapshotJwk.crv;
    const keyOps = Array.isArray(key_ops) ? [ ...key_ops ] : key_ops;
    return (ext === undefined || typeof ext === "boolean") && (keyOps === undefined || Array.isArray(keyOps) && keyOps.every((operation, index) => typeof operation === "string" && keyOps.indexOf(operation) === index) && keyOps.includes("verify")) && entry.kty.includes(kty) && (kid === undefined || typeof kid === "string" && kid === jwkKid) && (jwkAlg === undefined ? kty !== "AKP" : alg === jwkAlg) && (use === undefined || use === "sig") && (!entry.crv || crv === entry.crv);
}

async function importWithAlgCache(cache, jwk, entry) {
    const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);
    const alg = entry.alg;
    if (cached[alg] === undefined) {
        const key = await jwkToKey(entry, _objectSpread2(_objectSpread2({}, jwk), {}, {
            alg: alg,
            ext: true
        }));
        if (key.type !== "public") {
            throw new JWKSInvalid("JSON Web Key Set members must be public keys");
        }
        cached[alg] = key;
    }
    return cached[alg];
}

function createLocalJWKSet(jwks) {
    let snapshot;
    try {
        snapshot = structuredClone(jwks);
    } catch (_unused) {}
    if (!isJwkSet(snapshot)) {
        throw new JWKSInvalid("JSON Web Key Set malformed");
    }
    const cached = new WeakMap;
    const localJWKSet = async (protectedHeader, token) => {
        const _protectedHeader$toke = _objectSpread2(_objectSpread2({}, protectedHeader), token === null || token === void 0 ? void 0 : token.header), alg = _protectedHeader$toke.alg, kid = _protectedHeader$toke.kid;
        const entry = typeof alg === "string" ? JWS[alg] : undefined;
        if (!entry || entry.secret) {
            throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
        }
        const candidates = snapshot.keys.filter(jwk => isUsableJWK(jwk, entry, alg, kid));
        const jwk = candidates[0], length = candidates.length;
        if (!length) {
            throw new JWKSNoMatchingKey;
        }
        if (length !== 1) {
            const error = new JWKSMultipleMatchingKeys;
            error[Symbol.asyncIterator] = _wrapAsyncGenerator(function*() {
                for (const jwk of candidates) {
                    try {
                        yield yield _awaitAsyncGenerator(importWithAlgCache(cached, jwk, entry));
                    } catch (_unused2) {}
                }
            });
            throw error;
        }
        return importWithAlgCache(cached, jwk, entry);
    };
    return Object.defineProperty(localJWKSet, "jwks", {
        value: () => structuredClone(snapshot)
    });
}

var _navigator$userAgent, _navigator$userAgent$;

function isCloudflareWorkers() {
    return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel";
}

let USER_AGENT;

if (typeof navigator === "undefined" || !((_navigator$userAgent = navigator.userAgent) !== null && _navigator$userAgent !== void 0 && (_navigator$userAgent$ = _navigator$userAgent.startsWith) !== null && _navigator$userAgent$ !== void 0 && _navigator$userAgent$.call(_navigator$userAgent, "Mozilla/5.0 "))) {
    const NAME = "jose";
    const VERSION = "v6.2.10";
    USER_AGENT = "".concat(NAME, "/").concat(VERSION);
}

const customFetch = Symbol();

async function fetchJwks(url, headers, signal) {
    let fetchImpl = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : fetch;
    const response = await fetchImpl(url, {
        method: "GET",
        signal: signal,
        redirect: "manual",
        headers: headers
    }).catch(err => {
        if (err.name === "TimeoutError") {
            throw new JWKSTimeout;
        }
        throw err;
    });
    if (response.status !== 200) {
        throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
    }
    try {
        return await response.json();
    } catch (_unused) {
        throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON");
    }
}

const jwksCache = Symbol();

function isFreshFor(timestamp, duration) {
    return Number.isFinite(timestamp) && Date.now() < timestamp + duration;
}

function validateDuration(value, fallback, option) {
    if (Number.isNaN(value)) {
        throw new TypeError('"'.concat(option, '" option must not be NaN'));
    }
    return typeof value === "number" ? value : fallback;
}

function createRemoteJWKSet(url, options) {
    if (!(url instanceof URL)) {
        throw new TypeError("url must be an instance of URL");
    }
    const href = new URL(url.href).href;
    const opts = options !== null && options !== void 0 ? options : {};
    const timeoutOption = opts.timeoutDuration;
    if (typeof timeoutOption === "number" && (!Number.isInteger(timeoutOption) || timeoutOption < 0)) {
        throw new TypeError('"timeoutDuration" option must be a non-negative integer');
    }
    const timeoutDuration = typeof timeoutOption === "number" ? timeoutOption : 5e3;
    const cooldownDuration = validateDuration(opts.cooldownDuration, 3e4, "cooldownDuration");
    const cacheMaxAge = validateDuration(opts.cacheMaxAge, 6e5, "cacheMaxAge");
    const headers = new Headers(opts.headers);
    if (USER_AGENT && !headers.has("User-Agent")) {
        headers.set("User-Agent", USER_AGENT);
    }
    if (!headers.has("accept")) {
        headers.set("accept", "application/json, application/jwk-set+json");
    }
    const fetchImpl = opts[customFetch];
    const cache = opts[jwksCache];
    let jwksTimestamp;
    let pendingFetch;
    let reloadSequence = 0;
    let appliedSequence = 0;
    let local;
    if (cache && typeof cache === "object") {
        const uat = cache.uat, jwks = cache.jwks;
        if (isFreshFor(uat, cacheMaxAge) && isJwkSet(jwks)) {
            jwksTimestamp = uat;
            local = createLocalJWKSet(jwks);
        }
    }
    const reload = async () => {
        if (pendingFetch && isCloudflareWorkers()) {
            pendingFetch = undefined;
        }
        if (!pendingFetch) {
            const sequence = ++reloadSequence;
            const current = pendingFetch = fetchJwks(href, headers, AbortSignal.timeout(timeoutDuration), fetchImpl).then(json => {
                const next = createLocalJWKSet(json);
                if (sequence <= appliedSequence) {
                    return;
                }
                local = next;
                const updatedAt = Date.now();
                if (cache) {
                    cache.uat = updatedAt;
                    cache.jwks = json;
                }
                jwksTimestamp = updatedAt;
                appliedSequence = sequence;
            }).finally(() => {
                if (pendingFetch === current) {
                    pendingFetch = undefined;
                }
            });
        }
        await pendingFetch;
    };
    const remoteJWKSet = async (protectedHeader, token) => {
        if (!local || !isFreshFor(jwksTimestamp, cacheMaxAge)) {
            await reload();
        }
        try {
            return await local(protectedHeader, token);
        } catch (err) {
            if (err instanceof JWKSNoMatchingKey && !isFreshFor(jwksTimestamp, cooldownDuration)) {
                await reload();
                return local(protectedHeader, token);
            }
            throw err;
        }
    };
    return Object.defineProperties(remoteJWKSet, {
        coolingDown: {
            get: () => isFreshFor(jwksTimestamp, cooldownDuration),
            enumerable: true
        },
        fresh: {
            get: () => isFreshFor(jwksTimestamp, cacheMaxAge),
            enumerable: true
        },
        reload: {
            value: reload,
            enumerable: true
        },
        reloading: {
            get: () => !!pendingFetch,
            enumerable: true
        },
        jwks: {
            value: () => {
                var _local;
                return (_local = local) === null || _local === void 0 ? void 0 : _local.jwks();
            },
            enumerable: true
        }
    });
}

async function importPKCS8(pkcs8, alg, options) {
    if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) {
        throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
    }
    return fromPKCS8(pkcs8, alg, options);
}

function decodeJwt(jwt) {
    if (typeof jwt !== "string") throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
    const _jwt$split = jwt.split("."), payload = _jwt$split[1], length = _jwt$split.length;
    if (length === 5) throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
    if (length !== 3) throw new JWTInvalid("Invalid JWT");
    if (!payload) throw new JWTInvalid("JWTs must contain a payload");
    let decoded;
    try {
        decoded = decode(payload);
    } catch (_unused) {
        throw new JWTInvalid("Failed to base64url decode the payload");
    }
    let result;
    try {
        result = JSON.parse(strictDecoder.decode(decoded));
    } catch (_unused2) {
        throw new JWTInvalid("Failed to parse the decoded payload as JSON");
    }
    if (!isObject(result)) throw new JWTInvalid("Invalid JWT Claims Set");
    return result;
}

const _excluded = [ "mfaToken" ], _excluded2 = [ "mfaToken" ];

var _baseUrl, _clientId, _clientSecret, _customFetch, _telemetryConfig, _getConfiguration, _createCaptureConfiguration, _Class0_brand, _baseUrl2, _clientId2, _clientAuthOptions, _customFetch2, _telemetryConfig2, _grantRequest, _Class10_brand, _baseUrl3, _domain, _clientId3, _customFetch3, _telemetryConfig3, _clientAuthOptions2, _grantRequest2, _Class13_brand, _baseUrl4, _clientId4, _customFetch4, _telemetryConfig4, _Class15_brand, _domain2, _baseUrl5, _clientId5, _clientSecret2, _clientAssertionSigningKey, _clientAssertionSigningAlg, _useMtls, _customFetch5, _Class17_brand, _entries, _ttlMs, _maxEntries, _configuration, _optionalConfiguration, _serverMetadata, _clientAuthPromise, _options2, _customFetch6, _telemetryConfig5, _jwks, _discoveryCache, _inFlightDiscovery, _jwksCache, _Class19_brand;

function extractHttpMetadata(cause) {
    if (typeof cause !== "object" || cause === null) {
        return {};
    }
    const c = cause;
    return {
        statusCode: typeof c.statusCode === "number" ? c.statusCode : void 0,
        headers: c.headers instanceof Headers ? c.headers : void 0,
        body: typeof c.body === "string" ? c.body : void 0
    };
}

function toOAuth2Error(e) {
    var _err$error, _err$error_descriptio;
    if (typeof e !== "object" || e === null) {
        return {
            error: "unknown_error",
            error_description: String(e)
        };
    }
    const err = e;
    let headers;
    if (err.response instanceof Response) {
        try {
            headers = new Headers(err.response.headers);
            headers.delete("set-cookie");
        } catch (_unused) {
            headers = void 0;
        }
    }
    const base = {
        error: (_err$error = err.error) !== null && _err$error !== void 0 ? _err$error : "",
        error_description: (_err$error_descriptio = err.error_description) !== null && _err$error_descriptio !== void 0 ? _err$error_descriptio : "",
        message: err.message,
        statusCode: typeof err.status === "number" ? err.status : void 0,
        headers: headers
    };
    if (err.error === "mfa_required" && err.cause) {
        base.mfa_token = typeof err.cause.mfa_token === "string" ? err.cause.mfa_token : void 0;
        const req = err.cause.mfa_requirements;
        if (typeof req === "object" && req !== null) {
            base.mfa_requirements = req;
        }
    }
    return base;
}

var NotSupportedError = class NotSupportedError extends Error {
    constructor(code, message) {
        super(message);
        _defineProperty(this, "code", void 0);
        this.name = "NotSupportedError";
        this.code = code;
    }
};

var ApiError = class ApiError extends Error {
    constructor(code, message, cause) {
        super(message);
        _defineProperty(this, "cause", void 0);
        _defineProperty(this, "code", void 0);
        _defineProperty(this, "statusCode", void 0);
        _defineProperty(this, "headers", void 0);
        _defineProperty(this, "body", void 0);
        this.code = code;
        this.cause = cause && {
            error: cause.error,
            error_description: cause.error_description,
            message: cause.message,
            mfa_token: cause.mfa_token,
            mfa_requirements: cause.mfa_requirements
        };
        const meta = extractHttpMetadata(cause);
        this.statusCode = meta.statusCode;
        this.headers = meta.headers;
        this.body = meta.body;
    }
};

var TokenByCodeError = class extends ApiError {
    constructor(message, cause) {
        super("token_by_code_error", message, cause);
        this.name = "TokenByCodeError";
    }
};

var TokenByClientCredentialsError = class extends ApiError {
    constructor(message, cause) {
        super("token_by_client_credentials_error", message, cause);
        this.name = "TokenByClientCredentialsError";
    }
};

var TokenByRefreshTokenError = class extends ApiError {
    constructor(message, cause) {
        super("token_by_refresh_token_error", message, cause);
        this.name = "TokenByRefreshTokenError";
    }
};

var TokenByPasswordError = class extends ApiError {
    constructor(message, cause) {
        super("token_by_password_error", message, cause);
        this.name = "TokenByPasswordError";
    }
};

var TokenForConnectionError = class extends ApiError {
    constructor(message, cause) {
        super("token_for_connection_error", message, cause);
        this.name = "TokenForConnectionErrorCode";
    }
};

var TokenExchangeError = class extends ApiError {
    constructor(message, cause) {
        super("token_exchange_error", message, cause);
        this.name = "TokenExchangeError";
    }
};

var TokenRevocationError = class extends ApiError {
    constructor(message, cause) {
        super("token_revocation_error", message, cause);
        this.name = "TokenRevocationError";
    }
};

var UserInfoError = class extends ApiError {
    constructor(message, cause) {
        super("user_info_error", message, cause);
        this.name = "UserInfoError";
    }
};

var VerifyLogoutTokenError = class VerifyLogoutTokenError extends Error {
    constructor(message) {
        super(message);
        _defineProperty(this, "code", "verify_logout_token_error");
        this.name = "VerifyLogoutTokenError";
    }
};

var BackchannelAuthenticationError = class BackchannelAuthenticationError extends ApiError {
    constructor(cause) {
        super("backchannel_authentication_error", "There was an error when trying to use Client-Initiated Backchannel Authentication.", cause);
        _defineProperty(this, "code", "backchannel_authentication_error");
        this.name = "BackchannelAuthenticationError";
    }
};

var BuildAuthorizationUrlError = class extends ApiError {
    constructor(cause) {
        super("build_authorization_url_error", "There was an error when trying to build the authorization URL.", cause);
        this.name = "BuildAuthorizationUrlError";
    }
};

var BuildLinkUserUrlError = class extends ApiError {
    constructor(cause) {
        super("build_link_user_url_error", "There was an error when trying to build the Link User URL.", cause);
        this.name = "BuildLinkUserUrlError";
    }
};

var BuildUnlinkUserUrlError = class extends ApiError {
    constructor(cause) {
        super("build_unlink_user_url_error", "There was an error when trying to build the Unlink User URL.", cause);
        this.name = "BuildUnlinkUserUrlError";
    }
};

var MissingClientAuthError = class MissingClientAuthError extends Error {
    constructor() {
        super("The client secret or client assertion signing key must be provided.");
        _defineProperty(this, "code", "missing_client_auth_error");
        this.name = "MissingClientAuthError";
    }
};

var OrganizationValidationError = class OrganizationValidationError extends Error {
    constructor(message) {
        super(message);
        _defineProperty(this, "code", "organization_validation_error");
        this.name = "OrganizationValidationError";
    }
};

var MissingCapturedResponseError = class MissingCapturedResponseError extends Error {
    constructor(message) {
        super(message || "fullResponse: true requested but no HTTP Response was captured. This is a bug in CapturingFetch.");
        _defineProperty(this, "code", "missing_captured_response_error");
        this.name = "MissingCapturedResponseError";
    }
};

function filterSensitiveHeaders(source) {
    try {
        const filtered = new Headers(source);
        filtered.delete("set-cookie");
        return filtered;
    } catch (_unused2) {
        return new Headers;
    }
}

function attachHttpMetadata(err, e, captured) {
    var _errObj$response;
    const errObj = typeof e === "object" && e !== null ? e : void 0;
    const res = (_errObj$response = errObj === null || errObj === void 0 ? void 0 : errObj.response) !== null && _errObj$response !== void 0 ? _errObj$response : captured;
    const status = typeof (errObj === null || errObj === void 0 ? void 0 : errObj.status) === "number" ? errObj.status : res === null || res === void 0 ? void 0 : res.status;
    if (typeof status === "number") err.statusCode = status;
    if (res !== null && res !== void 0 && res.headers) {
        err.headers = filterSensitiveHeaders(res.headers);
    }
}

function stripUndefinedProperties(value) {
    return Object.entries(value).filter(_ref => {
        let _ref2 = _slicedToArray(_ref, 2), value2 = _ref2[1];
        return typeof value2 !== "undefined";
    }).reduce((acc, curr) => _objectSpread2(_objectSpread2({}, acc), {}, {
        [curr[0]]: curr[1]
    }), {});
}

function assertValidOrganization(organization) {
    if (!organization.trim()) {
        throw new OrganizationValidationError("organization must not be blank");
    }
}

function validateOrganizationClaim(claims, organization) {
    if (!claims) {
        return;
    }
    const org = organization.trim();
    if (org.startsWith("org_")) {
        const actual = claims.org_id;
        if (typeof actual !== "string") {
            throw new OrganizationValidationError("Organization Id (org_id) claim must be a string present in the ID token");
        }
        if (actual !== org) {
            throw new OrganizationValidationError('Organization Id (org_id) claim value mismatch in the ID token; expected "'.concat(org, '", found "').concat(actual, '"'));
        }
    } else {
        const actual = claims.org_name;
        if (typeof actual !== "string") {
            throw new OrganizationValidationError("Organization Name (org_name) claim must be a string present in the ID token");
        }
        if (actual.toLowerCase() !== org.toLowerCase()) {
            throw new OrganizationValidationError('Organization Name (org_name) claim value mismatch in the ID token; expected "'.concat(org, '", found "').concat(actual, '"'));
        }
    }
}

var MfaError$1 = class MfaError extends Error {
    constructor(code, message, cause) {
        super(message);
        _defineProperty(this, "cause", void 0);
        _defineProperty(this, "code", void 0);
        _defineProperty(this, "statusCode", void 0);
        _defineProperty(this, "headers", void 0);
        _defineProperty(this, "body", void 0);
        this.code = code;
        this.cause = cause && {
            error: cause.error,
            error_description: cause.error_description,
            message: cause.message
        };
        const meta = extractHttpMetadata(cause);
        this.statusCode = meta.statusCode;
        this.headers = meta.headers;
        this.body = meta.body;
    }
};

var MfaListAuthenticatorsError$1 = class extends MfaError$1 {
    constructor(message, cause) {
        super("mfa_list_authenticators_error", message, cause);
        this.name = "MfaListAuthenticatorsError";
    }
};

var MfaEnrollmentError$1 = class extends MfaError$1 {
    constructor(message, cause) {
        super("mfa_enrollment_error", message, cause);
        this.name = "MfaEnrollmentError";
    }
};

var MfaDeleteAuthenticatorError = class extends MfaError$1 {
    constructor(message, cause) {
        super("mfa_delete_authenticator_error", message, cause);
        this.name = "MfaDeleteAuthenticatorError";
    }
};

var MfaChallengeError$1 = class extends MfaError$1 {
    constructor(message, cause) {
        super("mfa_challenge_error", message, cause);
        this.name = "MfaChallengeError";
    }
};

var MfaVerifyError$1 = class extends MfaError$1 {
    constructor(message, cause) {
        super("mfa_verify_error", message, cause);
        this.name = "MfaVerifyError";
    }
};

function transformAuthenticatorResponse(api) {
    return {
        id: api.id,
        authenticatorType: api.authenticator_type,
        active: api.active,
        name: api.name,
        oobChannels: api.oob_channels,
        type: api.type
    };
}

function transformEnrollmentResponse(api) {
    if (api.authenticator_type === "otp") {
        return {
            authenticatorType: "otp",
            secret: api.secret,
            barcodeUri: api.barcode_uri,
            recoveryCodes: api.recovery_codes,
            id: api.id
        };
    }
    if (api.authenticator_type === "oob") {
        return {
            authenticatorType: "oob",
            oobChannel: api.oob_channel,
            oobCode: api.oob_code,
            bindingMethod: api.binding_method,
            id: api.id,
            barcodeUri: api.barcode_uri,
            recoveryCodes: api.recovery_codes
        };
    }
    throw new Error("Unexpected authenticator type: ".concat(api.authenticator_type));
}

function transformChallengeResponse(api) {
    const result = {
        challengeType: api.challenge_type
    };
    if (api.oob_code !== void 0) {
        result.oobCode = api.oob_code;
    }
    if (api.binding_method !== void 0) {
        result.bindingMethod = api.binding_method;
    }
    return result;
}

var TokenResponse = class _TokenResponse {
    constructor(accessToken, expiresAt, idToken, refreshToken, scope, claims, authorizationDetails) {
        _defineProperty(this, "accessToken", void 0);
        _defineProperty(this, "idToken", void 0);
        _defineProperty(this, "refreshToken", void 0);
        _defineProperty(this, "expiresAt", void 0);
        _defineProperty(this, "scope", void 0);
        _defineProperty(this, "claims", void 0);
        _defineProperty(this, "authorizationDetails", void 0);
        _defineProperty(this, "tokenType", void 0);
        _defineProperty(this, "issuedTokenType", void 0);
        _defineProperty(this, "recoveryCode", void 0);
        _defineProperty(this, "act", void 0);
        this.accessToken = accessToken;
        this.idToken = idToken;
        this.refreshToken = refreshToken;
        this.expiresAt = expiresAt;
        this.scope = scope;
        this.claims = claims;
        this.authorizationDetails = authorizationDetails;
    }
    static fromTokenEndpointResponse(response) {
        const claims = response.id_token ? response.claims() : void 0;
        const tokenResponse = new _TokenResponse(response.access_token, Math.floor(Date.now() / 1e3) + Number(response.expires_in), response.id_token, response.refresh_token, response.scope, claims, response.authorization_details);
        tokenResponse.tokenType = response.token_type;
        tokenResponse.issuedTokenType = response.issued_token_type;
        return tokenResponse;
    }
};

function createTelemetryFetch(baseFetch, config) {
    if (config.enabled === false) {
        return baseFetch;
    }
    const telemetryData = {
        name: config.name,
        version: config.version
    };
    const headerValue = btoa(JSON.stringify(telemetryData));
    return async (input, init) => {
        const headers = input instanceof Request ? new Headers(input.headers) : new Headers;
        if (init !== null && init !== void 0 && init.headers) {
            const initHeaders = new Headers(init.headers);
            initHeaders.forEach((value, key) => {
                headers.set(key, value);
            });
        }
        headers.set("Auth0-Client", headerValue);
        return baseFetch(input, _objectSpread2(_objectSpread2({}, init), {}, {
            headers: headers
        }));
    };
}

function getTelemetryConfig(config) {
    var _config$name, _config$version;
    if ((config === null || config === void 0 ? void 0 : config.enabled) === false) {
        return config;
    }
    return {
        enabled: true,
        name: (_config$name = config === null || config === void 0 ? void 0 : config.name) !== null && _config$name !== void 0 ? _config$name : "@auth0/auth0-auth-js",
        version: (_config$version = config === null || config === void 0 ? void 0 : config.version) !== null && _config$version !== void 0 ? _config$version : "1.15.0"
    };
}

function combineSignals(callerSignal, initSignal) {
    if (!callerSignal) {
        return {
            signal: initSignal !== null && initSignal !== void 0 ? initSignal : void 0
        };
    }
    if (!initSignal) {
        return {
            signal: callerSignal
        };
    }
    if (typeof AbortSignal !== "undefined" && typeof AbortSignal.any === "function") {
        return {
            signal: AbortSignal.any([ callerSignal, initSignal ])
        };
    }
    const controller = new AbortController;
    const sources = [ callerSignal, initSignal ];
    const alreadyAborted = sources.find(s => s.aborted);
    if (alreadyAborted) {
        controller.abort(alreadyAborted.reason);
        return {
            signal: controller.signal
        };
    }
    const listeners = [];
    const cleanup = () => {
        sources.forEach((s, i) => {
            const listener = listeners[i];
            if (listener) s.removeEventListener("abort", listener);
        });
    };
    sources.forEach((source, i) => {
        const listener = () => {
            cleanup();
            controller.abort(source.reason);
        };
        listeners[i] = listener;
        source.addEventListener("abort", listener, {
            once: true
        });
    });
    return {
        signal: controller.signal,
        cleanup: cleanup
    };
}

function createCapturingFetch(baseFetch) {
    let capturedResponse;
    const wrappedFetch = async (input, init) => {
        const response = await baseFetch(input, init);
        capturedResponse = response.clone();
        return response;
    };
    const capturingFetch = wrappedFetch;
    capturingFetch.getCapturedResponse = () => capturedResponse;
    return capturingFetch;
}

function composeRequestFetch(baseFetch, requestOptions, telemetryConfig) {
    if (!requestOptions) {
        return baseFetch;
    }
    const signal = requestOptions.signal, headers = requestOptions.headers, perRequestFetch = requestOptions.customFetch;
    const base = perRequestFetch ? createTelemetryFetch(perRequestFetch, telemetryConfig) : baseFetch;
    if (!signal && !headers) {
        return base;
    }
    return async (input, init) => {
        const mergedHeaders = headers ? new Headers(input instanceof Request ? input.headers : void 0) : void 0;
        if (mergedHeaders && init !== null && init !== void 0 && init.headers) {
            new Headers(init.headers).forEach((value, key) => mergedHeaders.set(key, value));
        }
        if (headers) {
            for (const _ref3 of Object.entries(headers)) {
                var _ref4 = _slicedToArray(_ref3, 2);
                const key = _ref4[0];
                const value = _ref4[1];
                const lowerKey = key.toLowerCase();
                if (lowerKey === "authorization" || lowerKey === "auth0-client") {
                    continue;
                }
                mergedHeaders.set(key, value);
            }
        }
        const combined = combineSignals(signal, init === null || init === void 0 ? void 0 : init.signal);
        try {
            return await base(input, _objectSpread2(_objectSpread2(_objectSpread2({}, init), mergedHeaders && {
                headers: mergedHeaders
            }), {}, {
                signal: combined.signal
            }));
        } finally {
            var _combined$cleanup;
            (_combined$cleanup = combined.cleanup) === null || _combined$cleanup === void 0 || _combined$cleanup.call(combined);
        }
    };
}

var GRANT_TYPE_MAP = {
    otp: "http://auth0.com/oauth/grant-type/mfa-otp",
    oob: "http://auth0.com/oauth/grant-type/mfa-oob",
    "recovery-code": "http://auth0.com/oauth/grant-type/mfa-recovery-code"
};

var MfaClient = (_baseUrl = new WeakMap, _clientId = new WeakMap, _clientSecret = new WeakMap, 
_customFetch = new WeakMap, _telemetryConfig = new WeakMap, _getConfiguration = new WeakMap, 
_createCaptureConfiguration = new WeakMap, _Class0_brand = new WeakSet, class MfaClient {
    constructor(options) {
        var _options$customFetch, _options$telemetryCon;
        _classPrivateMethodInitSpec(this, _Class0_brand);
        _classPrivateFieldInitSpec(this, _baseUrl, void 0);
        _classPrivateFieldInitSpec(this, _clientId, void 0);
        _classPrivateFieldInitSpec(this, _clientSecret, void 0);
        _classPrivateFieldInitSpec(this, _customFetch, void 0);
        _classPrivateFieldInitSpec(this, _telemetryConfig, void 0);
        _classPrivateFieldInitSpec(this, _getConfiguration, void 0);
        _classPrivateFieldInitSpec(this, _createCaptureConfiguration, void 0);
        _classPrivateFieldSet2(_baseUrl, this, "https://".concat(options.domain));
        _classPrivateFieldSet2(_clientId, this, options.clientId);
        _classPrivateFieldSet2(_clientSecret, this, options.clientSecret);
        _classPrivateFieldSet2(_customFetch, this, (_options$customFetch = options.customFetch) !== null && _options$customFetch !== void 0 ? _options$customFetch : function() {
            return fetch(...arguments);
        });
        _classPrivateFieldSet2(_telemetryConfig, this, (_options$telemetryCon = options.telemetryConfig) !== null && _options$telemetryCon !== void 0 ? _options$telemetryCon : getTelemetryConfig());
        _classPrivateFieldSet2(_getConfiguration, this, options.getConfiguration);
        _classPrivateFieldSet2(_createCaptureConfiguration, this, options.createCaptureConfiguration);
    }
    async listAuthenticators(options, requestOptions) {
        const url = "".concat(_classPrivateFieldGet2(_baseUrl, this), "/mfa/authenticators");
        const mfaToken = options.mfaToken;
        const response = await _assertClassBrand(_Class0_brand, this, _fetchFor).call(this, requestOptions)(url, {
            method: "GET",
            headers: {
                Authorization: "Bearer ".concat(mfaToken),
                "Content-Type": "application/json"
            }
        });
        if (!response.ok) {
            const bodyText = await response.clone().text();
            const statusCode = response.status;
            const headers = filterSensitiveHeaders(response.headers);
            let error;
            try {
                error = JSON.parse(bodyText);
            } catch (_unused3) {
                throw new MfaListAuthenticatorsError$1("Failed to list authenticators", {
                    error: "unknown_error",
                    error_description: "Failed to list authenticators",
                    statusCode: statusCode,
                    headers: headers,
                    body: bodyText
                });
            }
            throw new MfaListAuthenticatorsError$1(error.error_description || "Failed to list authenticators", _objectSpread2(_objectSpread2({}, error), {}, {
                statusCode: statusCode,
                headers: headers,
                body: bodyText
            }));
        }
        const apiResponse = await response.json();
        return apiResponse.map(transformAuthenticatorResponse);
    }
    async enrollAuthenticator(options, requestOptions) {
        const url = "".concat(_classPrivateFieldGet2(_baseUrl, this), "/mfa/associate");
        const mfaToken = options.mfaToken, sdkParams = _objectWithoutProperties(options, _excluded);
        const apiParams = {
            authenticator_types: sdkParams.authenticatorTypes
        };
        if ("oobChannels" in sdkParams) {
            apiParams.oob_channels = sdkParams.oobChannels;
        }
        if ("phoneNumber" in sdkParams && sdkParams.phoneNumber) {
            apiParams.phone_number = sdkParams.phoneNumber;
        }
        if ("email" in sdkParams && sdkParams.email) {
            apiParams.email = sdkParams.email;
        }
        const response = await _assertClassBrand(_Class0_brand, this, _fetchFor).call(this, requestOptions)(url, {
            method: "POST",
            headers: {
                Authorization: "Bearer ".concat(mfaToken),
                "Content-Type": "application/json"
            },
            body: JSON.stringify(apiParams)
        });
        if (!response.ok) {
            const bodyText = await response.clone().text();
            const statusCode = response.status;
            const headers = filterSensitiveHeaders(response.headers);
            let error;
            try {
                error = JSON.parse(bodyText);
            } catch (_unused4) {
                throw new MfaEnrollmentError$1("Failed to enroll authenticator", {
                    error: "unknown_error",
                    error_description: "Failed to enroll authenticator",
                    statusCode: statusCode,
                    headers: headers,
                    body: bodyText
                });
            }
            throw new MfaEnrollmentError$1(error.error_description || "Failed to enroll authenticator", _objectSpread2(_objectSpread2({}, error), {}, {
                statusCode: statusCode,
                headers: headers,
                body: bodyText
            }));
        }
        const apiResponse = await response.json();
        return transformEnrollmentResponse(apiResponse);
    }
    async deleteAuthenticator(options, requestOptions) {
        const authenticatorId = options.authenticatorId, mfaToken = options.mfaToken;
        const url = "".concat(_classPrivateFieldGet2(_baseUrl, this), "/mfa/authenticators/").concat(encodeURIComponent(authenticatorId));
        const response = await _assertClassBrand(_Class0_brand, this, _fetchFor).call(this, requestOptions)(url, {
            method: "DELETE",
            headers: {
                Authorization: "Bearer ".concat(mfaToken),
                "Content-Type": "application/json"
            }
        });
        if (!response.ok) {
            const bodyText = await response.clone().text();
            const statusCode = response.status;
            const headers = filterSensitiveHeaders(response.headers);
            let error;
            try {
                error = JSON.parse(bodyText);
            } catch (_unused5) {
                throw new MfaDeleteAuthenticatorError("Failed to delete authenticator", {
                    error: "unknown_error",
                    error_description: "Failed to delete authenticator",
                    statusCode: statusCode,
                    headers: headers,
                    body: bodyText
                });
            }
            throw new MfaDeleteAuthenticatorError(error.error_description || "Failed to delete authenticator", _objectSpread2(_objectSpread2({}, error), {}, {
                statusCode: statusCode,
                headers: headers,
                body: bodyText
            }));
        }
    }
    async challengeAuthenticator(options, requestOptions) {
        const url = "".concat(_classPrivateFieldGet2(_baseUrl, this), "/mfa/challenge");
        const mfaToken = options.mfaToken, challengeParams = _objectWithoutProperties(options, _excluded2);
        const body = {
            mfa_token: mfaToken,
            client_id: _classPrivateFieldGet2(_clientId, this),
            challenge_type: challengeParams.challengeType
        };
        if (_classPrivateFieldGet2(_clientSecret, this)) {
            body.client_secret = _classPrivateFieldGet2(_clientSecret, this);
        }
        if (challengeParams.authenticatorId) {
            body.authenticator_id = challengeParams.authenticatorId;
        }
        const response = await _assertClassBrand(_Class0_brand, this, _fetchFor).call(this, requestOptions)(url, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(body)
        });
        if (!response.ok) {
            const bodyText = await response.clone().text();
            const statusCode = response.status;
            const headers = filterSensitiveHeaders(response.headers);
            let error;
            try {
                error = JSON.parse(bodyText);
            } catch (_unused6) {
                throw new MfaChallengeError$1("Failed to challenge authenticator", {
                    error: "unknown_error",
                    error_description: "Failed to challenge authenticator",
                    statusCode: statusCode,
                    headers: headers,
                    body: bodyText
                });
            }
            throw new MfaChallengeError$1(error.error_description || "Failed to challenge authenticator", _objectSpread2(_objectSpread2({}, error), {}, {
                statusCode: statusCode,
                headers: headers,
                body: bodyText
            }));
        }
        const apiResponse = await response.json();
        return transformChallengeResponse(apiResponse);
    }
    async verify(options, requestOptions) {
        if (!_classPrivateFieldGet2(_getConfiguration, this)) {
            throw new Error("MFA verify requires a configuration provider (getConfiguration was not set)");
        }
        const params = {
            mfa_token: options.mfaToken
        };
        if (options.audience) {
            params.audience = options.audience;
        }
        if (options.factorType === "otp") {
            params.otp = options.otp;
        } else if (options.factorType === "oob") {
            params.oob_code = options.oobCode;
            if (options.bindingCode) {
                params.binding_code = options.bindingCode;
            }
        } else if (options.factorType === "recovery-code") {
            params.recovery_code = options.recoveryCode;
        }
        if (options.fullResponse) {
            var _baseConfiguration$cl;
            if (!_classPrivateFieldGet2(_createCaptureConfiguration, this)) {
                throw new Error("MFA verify fullResponse requires a capture-config factory (createCaptureConfiguration was not set)");
            }
            const baseConfiguration = await _classPrivateFieldGet2(_getConfiguration, this).call(this, requestOptions);
            const baseFetch = (_baseConfiguration$cl = baseConfiguration[customFetch$1]) !== null && _baseConfiguration$cl !== void 0 ? _baseConfiguration$cl : fetch;
            const capturingFetch = createCapturingFetch(baseFetch);
            const captureConfiguration = await _classPrivateFieldGet2(_createCaptureConfiguration, this).call(this, capturingFetch);
            try {
                const tokenEndpointResponse = await genericGrantRequest(captureConfiguration, GRANT_TYPE_MAP[options.factorType], params);
                const tokenResponse = TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
                if (tokenEndpointResponse.recovery_code) {
                    tokenResponse.recoveryCode = tokenEndpointResponse.recovery_code;
                }
                const capturedResponse = capturingFetch.getCapturedResponse();
                if (!capturedResponse) {
                    throw new MissingCapturedResponseError;
                }
                return {
                    data: tokenResponse,
                    response: capturedResponse
                };
            } catch (e) {
                var _rawErr$error, _ref5, _rawErr$error_descrip;
                if (e instanceof MissingCapturedResponseError) throw e;
                if (e instanceof MfaVerifyError$1) throw e;
                const rawErr = e;
                const mfaErr = new MfaVerifyError$1(rawErr.error_description || rawErr.message || "Failed to verify MFA challenge", {
                    error: (_rawErr$error = rawErr.error) !== null && _rawErr$error !== void 0 ? _rawErr$error : "mfa_verify_error",
                    error_description: (_ref5 = (_rawErr$error_descrip = rawErr.error_description) !== null && _rawErr$error_descrip !== void 0 ? _rawErr$error_descrip : rawErr.message) !== null && _ref5 !== void 0 ? _ref5 : "Failed to verify MFA challenge"
                });
                attachHttpMetadata(mfaErr, e, capturingFetch.getCapturedResponse());
                throw mfaErr;
            }
        }
        const configuration = await _classPrivateFieldGet2(_getConfiguration, this).call(this, requestOptions);
        try {
            const tokenEndpointResponse = await genericGrantRequest(configuration, GRANT_TYPE_MAP[options.factorType], params);
            const tokenResponse = TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
            if (tokenEndpointResponse.recovery_code) {
                tokenResponse.recoveryCode = tokenEndpointResponse.recovery_code;
            }
            return tokenResponse;
        } catch (e) {
            var _rawErr$error2, _ref6, _rawErr$error_descrip2;
            if (e instanceof MfaVerifyError$1) {
                throw e;
            }
            const rawErr = e;
            const mfaErr = new MfaVerifyError$1(rawErr.error_description || rawErr.message || "Failed to verify MFA challenge", {
                error: (_rawErr$error2 = rawErr.error) !== null && _rawErr$error2 !== void 0 ? _rawErr$error2 : "mfa_verify_error",
                error_description: (_ref6 = (_rawErr$error_descrip2 = rawErr.error_description) !== null && _rawErr$error_descrip2 !== void 0 ? _rawErr$error_descrip2 : rawErr.message) !== null && _ref6 !== void 0 ? _ref6 : "Failed to verify MFA challenge"
            });
            attachHttpMetadata(mfaErr, e);
            throw mfaErr;
        }
    }
});

function _fetchFor(requestOptions) {
    return composeRequestFetch(_classPrivateFieldGet2(_customFetch, this), requestOptions, _classPrivateFieldGet2(_telemetryConfig, this));
}

var PasskeyError$1 = class PasskeyError extends Error {
    constructor(code, message, cause) {
        super(message);
        _defineProperty(this, "cause", void 0);
        _defineProperty(this, "code", void 0);
        _defineProperty(this, "statusCode", void 0);
        _defineProperty(this, "headers", void 0);
        _defineProperty(this, "body", void 0);
        this.code = code;
        this.cause = cause && {
            error: cause.error,
            error_description: cause.error_description,
            message: cause.message
        };
        const meta = extractHttpMetadata(cause);
        this.statusCode = meta.statusCode;
        this.headers = meta.headers;
        this.body = meta.body;
    }
};

var PasskeyRegisterError = class extends PasskeyError$1 {
    constructor(message, cause) {
        super("passkey_register_error", message, cause);
        this.name = "PasskeyRegisterError";
    }
};

var PasskeyChallengeError = class extends PasskeyError$1 {
    constructor(message, cause) {
        super("passkey_challenge_error", message, cause);
        this.name = "PasskeyChallengeError";
    }
};

var PasskeyGetTokenError = class extends PasskeyError$1 {
    constructor(message, cause) {
        super("passkey_get_token_error", message, cause);
        this.name = "PasskeyGetTokenError";
        this.cause = cause && {
            error: cause.error,
            error_description: cause.error_description,
            message: cause.message,
            mfa_token: cause.mfa_token,
            mfa_requirements: cause.mfa_requirements
        };
    }
};

function buildClientAuthBody(options) {
    if (options.useMtls) {
        return {};
    }
    if (options.clientSecret) {
        return {
            client_secret: options.clientSecret
        };
    }
    return {};
}

function transformSignupChallengeResponse(api) {
    return {
        authSession: api.auth_session,
        authnParamsPublicKey: _objectSpread2({}, api.authn_params_public_key)
    };
}

function transformLoginChallengeResponse(api) {
    return {
        authSession: api.auth_session,
        authnParamsPublicKey: _objectSpread2({}, api.authn_params_public_key)
    };
}

var PASSKEY_GRANT_TYPE = "urn:okta:params:oauth:grant-type:webauthn";

var PasskeyClient = (_baseUrl2 = new WeakMap, _clientId2 = new WeakMap, _clientAuthOptions = new WeakMap, 
_customFetch2 = new WeakMap, _telemetryConfig2 = new WeakMap, _grantRequest = new WeakMap, 
_Class10_brand = new WeakSet, class PasskeyClient {
    constructor(options) {
        var _options$customFetch2, _options$telemetryCon2;
        _classPrivateMethodInitSpec(this, _Class10_brand);
        _classPrivateFieldInitSpec(this, _baseUrl2, void 0);
        _classPrivateFieldInitSpec(this, _clientId2, void 0);
        _classPrivateFieldInitSpec(this, _clientAuthOptions, void 0);
        _classPrivateFieldInitSpec(this, _customFetch2, void 0);
        _classPrivateFieldInitSpec(this, _telemetryConfig2, void 0);
        _classPrivateFieldInitSpec(this, _grantRequest, void 0);
        _classPrivateFieldSet2(_baseUrl2, this, "https://".concat(options.domain));
        _classPrivateFieldSet2(_clientId2, this, options.clientId);
        _classPrivateFieldSet2(_clientAuthOptions, this, {
            clientSecret: options.clientSecret,
            useMtls: options.useMtls
        });
        _classPrivateFieldSet2(_customFetch2, this, (_options$customFetch2 = options.customFetch) !== null && _options$customFetch2 !== void 0 ? _options$customFetch2 : function() {
            return fetch(...arguments);
        });
        _classPrivateFieldSet2(_telemetryConfig2, this, (_options$telemetryCon2 = options.telemetryConfig) !== null && _options$telemetryCon2 !== void 0 ? _options$telemetryCon2 : getTelemetryConfig());
        _classPrivateFieldSet2(_grantRequest, this, options.grantRequest);
    }
    async register(options, requestOptions) {
        const url = "".concat(_classPrivateFieldGet2(_baseUrl2, this), "/passkey/register");
        const userProfile = _objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({}, options.email && {
            email: options.email
        }), options.name && {
            name: options.name
        }), options.phoneNumber && {
            phone_number: options.phoneNumber
        }), options.username && {
            username: options.username
        }), options.givenName && {
            given_name: options.givenName
        }), options.familyName && {
            family_name: options.familyName
        }), options.nickname && {
            nickname: options.nickname
        }), options.picture && {
            picture: options.picture
        });
        const body = _objectSpread2(_objectSpread2({
            client_id: _classPrivateFieldGet2(_clientId2, this)
        }, buildClientAuthBody(_classPrivateFieldGet2(_clientAuthOptions, this))), {}, {
            user_profile: userProfile
        });
        if (options.realm) body.realm = options.realm;
        if (options.organization) body.organization = options.organization;
        if (options.userMetadata) body.user_metadata = options.userMetadata;
        const response = await _assertClassBrand(_Class10_brand, this, _fetchFor2).call(this, requestOptions)(url, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(body)
        });
        if (!response.ok) {
            const error = await _assertClassBrand(_Class10_brand, this, _parseErrorResponse).call(this, response);
            const err = new PasskeyRegisterError(error.error_description || "Failed to request signup challenge", error);
            err.statusCode = response.status;
            err.headers = filterSensitiveHeaders(response.headers);
            throw err;
        }
        const apiResponse = await response.json();
        return transformSignupChallengeResponse(apiResponse);
    }
    async challenge(options, requestOptions) {
        const url = "".concat(_classPrivateFieldGet2(_baseUrl2, this), "/passkey/challenge");
        const body = _objectSpread2({
            client_id: _classPrivateFieldGet2(_clientId2, this)
        }, buildClientAuthBody(_classPrivateFieldGet2(_clientAuthOptions, this)));
        if (options !== null && options !== void 0 && options.realm) body.realm = options.realm;
        if (options !== null && options !== void 0 && options.organization) body.organization = options.organization;
        const response = await _assertClassBrand(_Class10_brand, this, _fetchFor2).call(this, requestOptions)(url, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(body)
        });
        if (!response.ok) {
            const error = await _assertClassBrand(_Class10_brand, this, _parseErrorResponse).call(this, response);
            const err = new PasskeyChallengeError(error.error_description || "Failed to request login challenge", error);
            err.statusCode = response.status;
            err.headers = filterSensitiveHeaders(response.headers);
            throw err;
        }
        const apiResponse = await response.json();
        return transformLoginChallengeResponse(apiResponse);
    }
    async getTokenByPasskey(options, requestOptions) {
        if (options.organization !== void 0) {
            assertValidOrganization(options.organization);
        }
        const params = new URLSearchParams({
            auth_session: options.authSession,
            authn_response: JSON.stringify(options.credential)
        });
        if (options.realm) params.append("realm", options.realm);
        if (options.scope) params.append("scope", options.scope);
        if (options.audience) params.append("audience", options.audience);
        if (options.organization) params.append("organization", options.organization);
        let tokenResponse;
        try {
            tokenResponse = await _classPrivateFieldGet2(_grantRequest, this).call(this, PASSKEY_GRANT_TYPE, params, requestOptions, options.fullResponse);
        } catch (e) {
            if (e instanceof MissingCapturedResponseError) throw e;
            const apiError = toOAuth2Error(e);
            const err = new PasskeyGetTokenError(apiError.error_description || "Failed to exchange passkey credential for tokens.", apiError);
            attachHttpMetadata(err, e);
            throw err;
        }
        if (options.fullResponse) {
            const envelope = tokenResponse;
            if (options.organization) {
                validateOrganizationClaim(envelope.data.claims, options.organization);
            }
            return envelope;
        }
        const bare = tokenResponse;
        if (options.organization) {
            validateOrganizationClaim(bare.claims, options.organization);
        }
        return bare;
    }
});

function _fetchFor2(requestOptions) {
    return composeRequestFetch(_classPrivateFieldGet2(_customFetch2, this), requestOptions, _classPrivateFieldGet2(_telemetryConfig2, this));
}

async function _parseErrorResponse(response) {
    const bodyText = await response.clone().text();
    try {
        const parsed = JSON.parse(bodyText);
        return _objectSpread2(_objectSpread2({}, parsed), {}, {
            statusCode: response.status,
            headers: response.headers,
            body: bodyText
        });
    } catch (_unused0) {
        return {
            error: "unknown_error",
            error_description: "HTTP ".concat(response.status, " ").concat(response.statusText),
            statusCode: response.status,
            headers: response.headers,
            body: bodyText
        };
    }
}

var PasswordlessError = class PasswordlessError extends Error {
    constructor(code, message, cause) {
        super(message);
        _defineProperty(this, "cause", void 0);
        _defineProperty(this, "code", void 0);
        _defineProperty(this, "statusCode", void 0);
        _defineProperty(this, "headers", void 0);
        _defineProperty(this, "body", void 0);
        Object.setPrototypeOf(this, new.target.prototype);
        this.code = code;
        this.cause = cause && (cause.error || cause.error_description) ? {
            error: cause.error,
            error_description: cause.error_description,
            message: cause.message,
            mfa_token: cause.mfa_token,
            mfa_requirements: cause.mfa_requirements
        } : void 0;
        const meta = extractHttpMetadata(cause);
        this.statusCode = meta.statusCode;
        this.headers = meta.headers;
        this.body = meta.body;
    }
};

var PasswordlessStartError = class extends PasswordlessError {
    constructor(message, cause) {
        super("passwordless_start_error", message, cause);
        this.name = "PasswordlessStartError";
    }
};

var PasswordlessVerifyError = class extends PasswordlessError {
    constructor(message, cause) {
        super("passwordless_verify_error", message, cause);
        this.name = "PasswordlessVerifyError";
    }
};

var PasswordlessDbGetTokenError = class extends PasswordlessError {
    constructor(message, cause) {
        super("passwordless_db_get_token_error", message, cause);
        this.name = "PasswordlessDbGetTokenError";
    }
};

var PasswordlessChallengeError = class PasswordlessChallengeError extends PasswordlessError {
    constructor(message, statusCode, cause, validationErrors, headers) {
        super("passwordless_challenge_error", message, cause);
        _defineProperty(this, "statusCode", void 0);
        _defineProperty(this, "validationErrors", void 0);
        this.name = "PasswordlessChallengeError";
        this.statusCode = statusCode;
        this.validationErrors = validationErrors;
        this.headers = headers !== null && headers !== void 0 ? headers : this.headers;
    }
};

var DEFAULT_CLIENT_ASSERTION_ALG = "RS256";

var CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";

var CLIENT_ASSERTION_EXPIRY_SECONDS = 120;

function isE164PhoneNumber(phoneNumber) {
    return /^\+[1-9]\d{1,14}$/.test(phoneNumber);
}

async function buildClientAuthBody2(options, clientId, domain) {
    if (options.useMtls) {
        return {};
    }
    if (options.clientAssertionSigningKey) {
        var _options$clientAssert;
        const alg = (_options$clientAssert = options.clientAssertionSigningAlg) !== null && _options$clientAssert !== void 0 ? _options$clientAssert : DEFAULT_CLIENT_ASSERTION_ALG;
        const privateKey = options.clientAssertionSigningKey instanceof CryptoKey ? options.clientAssertionSigningKey : await importPKCS8(options.clientAssertionSigningKey, alg);
        const clientAssertion = await new SignJWT({}).setProtectedHeader({
            alg: alg
        }).setIssuer(clientId).setSubject(clientId).setAudience("https://".concat(domain, "/")).setJti(crypto.randomUUID()).setIssuedAt().setExpirationTime("".concat(CLIENT_ASSERTION_EXPIRY_SECONDS, "s")).sign(privateKey);
        return {
            client_assertion: clientAssertion,
            client_assertion_type: CLIENT_ASSERTION_TYPE
        };
    }
    if (options.clientSecret) {
        return {
            client_secret: options.clientSecret
        };
    }
    throw new MissingClientAuthError;
}

function transformSendEmailRequest(options) {
    var _options$send;
    const send = (_options$send = options.send) !== null && _options$send !== void 0 ? _options$send : "code";
    const wire = {
        email: options.email,
        connection: "email",
        send: send
    };
    if (send === "link" && options.authParams) {
        wire.authParams = options.authParams;
    }
    return wire;
}

function transformSendSmsRequest(options) {
    return {
        phone_number: options.phoneNumber,
        connection: "sms"
    };
}

function transformChallengeEmailRequest(options) {
    var _options$allowSignup;
    return {
        email: options.email,
        connection: options.connection,
        allow_signup: (_options$allowSignup = options.allowSignup) !== null && _options$allowSignup !== void 0 ? _options$allowSignup : false
    };
}

function transformChallengePhoneRequest(options) {
    var _options$allowSignup2;
    const body = {
        phone_number: options.phoneNumber,
        connection: options.connection,
        allow_signup: (_options$allowSignup2 = options.allowSignup) !== null && _options$allowSignup2 !== void 0 ? _options$allowSignup2 : false
    };
    if (options.deliveryMethod) {
        body.delivery_method = options.deliveryMethod;
    }
    return body;
}

var PASSWORDLESS_OTP_GRANT_TYPE = "http://auth0.com/oauth/grant-type/passwordless/otp";

var PasswordlessClient = (_baseUrl3 = new WeakMap, _domain = new WeakMap, _clientId3 = new WeakMap, 
_customFetch3 = new WeakMap, _telemetryConfig3 = new WeakMap, _clientAuthOptions2 = new WeakMap, 
_grantRequest2 = new WeakMap, _Class13_brand = new WeakSet, class PasswordlessClient {
    constructor(options) {
        var _options$customFetch3, _options$telemetryCon3;
        _classPrivateMethodInitSpec(this, _Class13_brand);
        _classPrivateFieldInitSpec(this, _baseUrl3, void 0);
        _classPrivateFieldInitSpec(this, _domain, void 0);
        _classPrivateFieldInitSpec(this, _clientId3, void 0);
        _classPrivateFieldInitSpec(this, _customFetch3, void 0);
        _classPrivateFieldInitSpec(this, _telemetryConfig3, void 0);
        _classPrivateFieldInitSpec(this, _clientAuthOptions2, void 0);
        _classPrivateFieldInitSpec(this, _grantRequest2, void 0);
        _classPrivateFieldSet2(_domain, this, options.domain);
        _classPrivateFieldSet2(_baseUrl3, this, "https://".concat(options.domain));
        _classPrivateFieldSet2(_clientId3, this, options.clientId);
        _classPrivateFieldSet2(_customFetch3, this, (_options$customFetch3 = options.customFetch) !== null && _options$customFetch3 !== void 0 ? _options$customFetch3 : function() {
            return fetch(...arguments);
        });
        _classPrivateFieldSet2(_telemetryConfig3, this, (_options$telemetryCon3 = options.telemetryConfig) !== null && _options$telemetryCon3 !== void 0 ? _options$telemetryCon3 : getTelemetryConfig());
        _classPrivateFieldSet2(_clientAuthOptions2, this, {
            clientSecret: options.clientSecret,
            clientAssertionSigningKey: options.clientAssertionSigningKey,
            clientAssertionSigningAlg: options.clientAssertionSigningAlg,
            useMtls: options.useMtls
        });
        _classPrivateFieldSet2(_grantRequest2, this, options.grantRequest);
    }
    async sendEmail(options, requestOptions) {
        const response = await _assertClassBrand(_Class13_brand, this, _start).call(this, transformSendEmailRequest(options), "Failed to send passwordless email", options.language, requestOptions);
        if (options.fullResponse) {
            return {
                data: void 0,
                response: response
            };
        }
    }
    async sendSms(options, requestOptions) {
        if (!isE164PhoneNumber(options.phoneNumber)) {
            throw new PasswordlessStartError("Phone number must be in E.164 format (e.g. +14155550100).");
        }
        const response = await _assertClassBrand(_Class13_brand, this, _start).call(this, transformSendSmsRequest(options), "Failed to send passwordless SMS", options.language, requestOptions);
        if (options.fullResponse) {
            return {
                data: void 0,
                response: response
            };
        }
    }
    async challengeWithEmail(options, requestOptions) {
        const wireBody = transformChallengeEmailRequest(options);
        return _assertClassBrand(_Class13_brand, this, _challenge).call(this, wireBody, "Failed to request email OTP challenge", requestOptions);
    }
    async challengeWithPhoneNumber(options, requestOptions) {
        if (!isE164PhoneNumber(options.phoneNumber)) {
            throw new PasswordlessChallengeError("Phone number must be in E.164 format (e.g. +14155550100).", 0, void 0, void 0);
        }
        const wireBody = transformChallengePhoneRequest(options);
        return _assertClassBrand(_Class13_brand, this, _challenge).call(this, wireBody, "Failed to request phone OTP challenge", requestOptions);
    }
    async getTokenByPasswordlessDbConnection(options, requestOptions) {
        const params = new URLSearchParams({
            auth_session: options.authSession,
            otp: options.otp
        });
        if (options.scope) {
            params.append("scope", options.scope);
        }
        if (options.audience) {
            params.append("audience", options.audience);
        }
        if (!_classPrivateFieldGet2(_grantRequest2, this)) {
            throw new PasswordlessDbGetTokenError("Missing grant request delegate.", toOAuth2Error(new Error("missing grantRequest")));
        }
        try {
            const result = await _classPrivateFieldGet2(_grantRequest2, this).call(this, PASSWORDLESS_OTP_GRANT_TYPE, params, requestOptions, options.fullResponse);
            return result;
        } catch (e) {
            if (e instanceof MissingCapturedResponseError) throw e;
            const err = new PasswordlessDbGetTokenError("There was an error while trying to request a token.", toOAuth2Error(e));
            const annotated = e;
            err.statusCode = annotated._statusCode;
            err.headers = annotated._headers;
            throw err;
        }
    }
});

function _fetchFor3(requestOptions) {
    return composeRequestFetch(_classPrivateFieldGet2(_customFetch3, this), requestOptions, _classPrivateFieldGet2(_telemetryConfig3, this));
}

async function _start(wireBody, failureMessage, language, requestOptions) {
    var _errorBody;
    const clientAuthBody = await buildClientAuthBody2(_classPrivateFieldGet2(_clientAuthOptions2, this), _classPrivateFieldGet2(_clientId3, this), _classPrivateFieldGet2(_domain, this));
    const finalBody = _objectSpread2(_objectSpread2({
        client_id: _classPrivateFieldGet2(_clientId3, this)
    }, wireBody), clientAuthBody);
    let response;
    try {
        response = await _assertClassBrand(_Class13_brand, this, _fetchFor3).call(this, requestOptions)("".concat(_classPrivateFieldGet2(_baseUrl3, this), "/passwordless/start"), {
            method: "POST",
            headers: _objectSpread2({
                "Content-Type": "application/json"
            }, language ? {
                "x-request-language": language
            } : {}),
            body: JSON.stringify(finalBody)
        });
    } catch (_unused1) {
        throw new PasswordlessStartError("".concat(failureMessage, ": a network error occurred."));
    }
    if (response.ok) {
        return response;
    }
    const bodyText = await response.clone().text();
    let errorBody;
    if (response.status !== 204) {
        try {
            errorBody = JSON.parse(bodyText);
        } catch (_unused10) {
            errorBody = void 0;
        }
    }
    const startErr = new PasswordlessStartError(((_errorBody = errorBody) === null || _errorBody === void 0 ? void 0 : _errorBody.error_description) || failureMessage, errorBody);
    startErr.statusCode = response.status;
    startErr.headers = filterSensitiveHeaders(response.headers);
    startErr.body = bodyText;
    throw startErr;
}

async function _challenge(wireBody, failureMessage, requestOptions) {
    var _errorBody2, _errorBody3;
    const clientAuthBody = await buildClientAuthBody2(_classPrivateFieldGet2(_clientAuthOptions2, this), _classPrivateFieldGet2(_clientId3, this), _classPrivateFieldGet2(_domain, this));
    const finalBody = _objectSpread2(_objectSpread2({
        client_id: _classPrivateFieldGet2(_clientId3, this)
    }, wireBody), clientAuthBody);
    let response;
    try {
        response = await _assertClassBrand(_Class13_brand, this, _fetchFor3).call(this, requestOptions)("".concat(_classPrivateFieldGet2(_baseUrl3, this), "/otp/challenge"), {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(finalBody)
        });
    } catch (_unused11) {
        throw new PasswordlessChallengeError("challenge error: a network error occurred.", 0, void 0, void 0);
    }
    if (response.ok) {
        let responseBody;
        try {
            responseBody = await response.json();
        } catch (_unused12) {
            throw new PasswordlessChallengeError("".concat(failureMessage, ": could not parse the response body."), response.status, void 0, void 0, filterSensitiveHeaders(response.headers));
        }
        return {
            authSession: responseBody.auth_session
        };
    }
    const bodyText = await response.clone().text();
    let errorBody;
    try {
        errorBody = JSON.parse(bodyText);
    } catch (_unused13) {
        errorBody = void 0;
    }
    const cause = errorBody ? _objectSpread2(_objectSpread2({}, errorBody), {}, {
        statusCode: response.status,
        headers: response.headers,
        body: bodyText
    }) : {
        error: "",
        error_description: "",
        statusCode: response.status,
        headers: response.headers,
        body: bodyText
    };
    throw new PasswordlessChallengeError(((_errorBody2 = errorBody) === null || _errorBody2 === void 0 ? void 0 : _errorBody2.error_description) || failureMessage, response.status, cause, (_errorBody3 = errorBody) === null || _errorBody3 === void 0 ? void 0 : _errorBody3.validation_errors, filterSensitiveHeaders(response.headers));
}

var DatabaseError = class DatabaseError extends Error {
    constructor(code, message, cause) {
        super(message);
        _defineProperty(this, "cause", void 0);
        _defineProperty(this, "code", void 0);
        _defineProperty(this, "statusCode", void 0);
        _defineProperty(this, "headers", void 0);
        _defineProperty(this, "body", void 0);
        Object.setPrototypeOf(this, new.target.prototype);
        this.code = code;
        this.cause = cause && {
            error: cause.error,
            error_description: cause.error_description,
            message: cause.message
        };
        const meta = extractHttpMetadata(cause);
        this.statusCode = meta.statusCode;
        this.headers = meta.headers;
        this.body = meta.body;
    }
};

var SignUpError = class extends DatabaseError {
    constructor(message, cause) {
        super("signup_error", message, cause);
        this.name = "SignUpError";
    }
};

var ChangePasswordError = class extends DatabaseError {
    constructor(message, cause) {
        super("change_password_error", message, cause);
        this.name = "ChangePasswordError";
    }
};

function requireFields(options, keys, ErrorClass) {
    for (const key of keys) {
        if (options[key] === null || options[key] === void 0 || options[key] === "") {
            throw new ErrorClass('Required parameter "'.concat(String(key), '" was null, undefined, or empty.'));
        }
    }
}

function transformSignUpRequest(options) {
    const wire = {
        email: options.email,
        password: options.password,
        connection: options.connection
    };
    if (options.username !== void 0) wire.username = options.username;
    if (options.givenName !== void 0) wire.given_name = options.givenName;
    if (options.familyName !== void 0) wire.family_name = options.familyName;
    if (options.name !== void 0) wire.name = options.name;
    if (options.nickname !== void 0) wire.nickname = options.nickname;
    if (options.picture !== void 0) wire.picture = options.picture;
    if (options.userMetadata !== void 0) wire.user_metadata = options.userMetadata;
    return wire;
}

function transformChangePasswordRequest(options) {
    const wire = {
        connection: options.connection
    };
    if (options.email !== void 0) wire.email = options.email;
    if (options.username !== void 0) wire.username = options.username;
    if (options.organization !== void 0) wire.organization = options.organization;
    return wire;
}

function normalizeSignUpResult(raw) {
    var _ref7, _raw$_id;
    const id = (_ref7 = (_raw$_id = raw._id) !== null && _raw$_id !== void 0 ? _raw$_id : raw.user_id) !== null && _ref7 !== void 0 ? _ref7 : raw.id;
    return {
        id: id,
        email: typeof raw.email === "string" ? raw.email : "",
        emailVerified: Boolean(raw.email_verified),
        username: raw.username,
        givenName: raw.given_name,
        familyName: raw.family_name,
        name: raw.name,
        nickname: raw.nickname,
        picture: raw.picture,
        userMetadata: raw.user_metadata
    };
}

async function parseErrorBody(response) {
    let raw;
    try {
        raw = await response.json();
    } catch (_unused7) {
        return void 0;
    }
    if (typeof raw.error === "string") {
        return raw;
    }
    if (typeof raw.code === "string") {
        return {
            error: raw.code,
            error_description: typeof raw.description === "string" ? raw.description : ""
        };
    }
    return void 0;
}

var DatabaseClient = (_baseUrl4 = new WeakMap, _clientId4 = new WeakMap, _customFetch4 = new WeakMap, 
_telemetryConfig4 = new WeakMap, _Class15_brand = new WeakSet, class DatabaseClient {
    constructor(options) {
        var _options$customFetch4, _options$telemetryCon4;
        _classPrivateMethodInitSpec(this, _Class15_brand);
        _classPrivateFieldInitSpec(this, _baseUrl4, void 0);
        _classPrivateFieldInitSpec(this, _clientId4, void 0);
        _classPrivateFieldInitSpec(this, _customFetch4, void 0);
        _classPrivateFieldInitSpec(this, _telemetryConfig4, void 0);
        _classPrivateFieldSet2(_baseUrl4, this, "https://".concat(options.domain));
        _classPrivateFieldSet2(_clientId4, this, options.clientId);
        _classPrivateFieldSet2(_customFetch4, this, (_options$customFetch4 = options.customFetch) !== null && _options$customFetch4 !== void 0 ? _options$customFetch4 : function() {
            return fetch(...arguments);
        });
        _classPrivateFieldSet2(_telemetryConfig4, this, (_options$telemetryCon4 = options.telemetryConfig) !== null && _options$telemetryCon4 !== void 0 ? _options$telemetryCon4 : getTelemetryConfig());
    }
    async signUp(options, requestOptions) {
        var _options$clientId;
        requireFields(options, [ "email", "password", "connection" ], SignUpError);
        const body = _objectSpread2({
            client_id: (_options$clientId = options.clientId) !== null && _options$clientId !== void 0 ? _options$clientId : _classPrivateFieldGet2(_clientId4, this)
        }, transformSignUpRequest(options));
        const response = await _assertClassBrand(_Class15_brand, this, _post).call(this, "/dbconnections/signup", body, SignUpError, "Failed to sign up", requestOptions);
        if (options.fullResponse) {
            const clone = response.clone();
            const raw2 = await response.json();
            return {
                data: normalizeSignUpResult(raw2),
                response: clone
            };
        }
        const raw = await response.json();
        return normalizeSignUpResult(raw);
    }
    async changePassword(options, requestOptions) {
        var _options$clientId2;
        requireFields(options, [ "connection" ], ChangePasswordError);
        if (!options.email && !options.username) {
            throw new ChangePasswordError('Either "email" or "username" is required.');
        }
        const body = _objectSpread2({
            client_id: (_options$clientId2 = options.clientId) !== null && _options$clientId2 !== void 0 ? _options$clientId2 : _classPrivateFieldGet2(_clientId4, this)
        }, transformChangePasswordRequest(options));
        const response = await _assertClassBrand(_Class15_brand, this, _post).call(this, "/dbconnections/change_password", body, ChangePasswordError, "Failed to request a password change", requestOptions);
        if (options.fullResponse) {
            const clone = response.clone();
            const text = await response.text();
            return {
                data: text,
                response: clone
            };
        }
        return response.text();
    }
});

async function _post(path, body, ErrorClass, failureMessage, requestOptions) {
    const requestFetch = composeRequestFetch(_classPrivateFieldGet2(_customFetch4, this), requestOptions, _classPrivateFieldGet2(_telemetryConfig4, this));
    let response;
    try {
        response = await requestFetch("".concat(_classPrivateFieldGet2(_baseUrl4, this)).concat(path), {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(body)
        });
    } catch (_unused14) {
        throw new ErrorClass("".concat(failureMessage, ": a network error occurred."));
    }
    if (response.ok) {
        return response;
    }
    const bodyText = await response.clone().text();
    const errorBody = await parseErrorBody(response.clone());
    const err = new ErrorClass((errorBody === null || errorBody === void 0 ? void 0 : errorBody.error_description) || failureMessage, errorBody !== null && errorBody !== void 0 ? errorBody : {
        error: "unknown_error",
        error_description: failureMessage
    });
    err.statusCode = response.status;
    err.headers = filterSensitiveHeaders(response.headers);
    err.body = bodyText;
    throw err;
}

var AnonymousSessionError = class AnonymousSessionError extends Error {
    constructor(code, message, cause) {
        super(message);
        _defineProperty(this, "code", void 0);
        _defineProperty(this, "cause", void 0);
        this.name = "AnonymousSessionError";
        this.code = code;
        this.cause = cause && {
            error: cause.error,
            error_description: cause.error_description,
            message: cause.message
        };
    }
};

var DEFAULT_CLIENT_ASSERTION_ALG2 = "RS256";

var CLIENT_ASSERTION_TYPE2 = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";

var CLIENT_ASSERTION_EXPIRY_SECONDS2 = 120;

async function buildClientAuthBody3(options, clientId, domain) {
    if (options.useMtls) {
        return {};
    }
    if (options.clientAssertionSigningKey) {
        var _options$clientAssert2;
        const alg = (_options$clientAssert2 = options.clientAssertionSigningAlg) !== null && _options$clientAssert2 !== void 0 ? _options$clientAssert2 : DEFAULT_CLIENT_ASSERTION_ALG2;
        const privateKey = options.clientAssertionSigningKey instanceof CryptoKey ? options.clientAssertionSigningKey : await importPKCS8(options.clientAssertionSigningKey, alg);
        const clientAssertion = await new SignJWT({}).setProtectedHeader({
            alg: alg
        }).setIssuer(clientId).setSubject(clientId).setAudience("https://".concat(domain, "/")).setJti(crypto.randomUUID()).setIssuedAt().setExpirationTime("".concat(CLIENT_ASSERTION_EXPIRY_SECONDS2, "s")).sign(privateKey);
        return {
            client_assertion: clientAssertion,
            client_assertion_type: CLIENT_ASSERTION_TYPE2
        };
    }
    if (options.clientSecret) {
        return {
            client_secret: options.clientSecret
        };
    }
    return {};
}

var SESSION_INVALIDATION_CODES = new Set([ "session_expired", "invalid_session_token" ]);

function parseTokenResponse(apiResponse) {
    const now = Math.floor(Date.now() / 1e3);
    if (typeof apiResponse.access_token !== "string" || !apiResponse.access_token) {
        throw new AnonymousSessionError("server_error", "access_token missing or invalid in anonymous token response");
    }
    const expiresIn = apiResponse.expires_in;
    if (typeof expiresIn !== "number" || !Number.isFinite(expiresIn)) {
        throw new AnonymousSessionError("server_error", "expires_in missing or invalid in anonymous token response");
    }
    return {
        accessToken: apiResponse.access_token,
        expiresAt: now + expiresIn,
        scope: apiResponse.scope,
        sessionToken: apiResponse.session_token,
        sessionTokenExpiresAt: typeof apiResponse.session_expires_in === "number" && Number.isFinite(apiResponse.session_expires_in) ? now + apiResponse.session_expires_in : void 0
    };
}

async function parseErrorResponse(response) {
    const fallback = "Request failed with status ".concat(response.status);
    let parsed = {};
    try {
        parsed = await response.json();
    } catch (_unused8) {}
    return {
        error: typeof parsed.error === "string" ? parsed.error : "server_error",
        error_description: typeof parsed.error_description === "string" ? parsed.error_description : fallback
    };
}

var AnonymousSessionClient = (_domain2 = new WeakMap, _baseUrl5 = new WeakMap, _clientId5 = new WeakMap, 
_clientSecret2 = new WeakMap, _clientAssertionSigningKey = new WeakMap, _clientAssertionSigningAlg = new WeakMap, 
_useMtls = new WeakMap, _customFetch5 = new WeakMap, _Class17_brand = new WeakSet, 
class AnonymousSessionClient {
    constructor(_options) {
        var _options$customFetch5;
        _classPrivateMethodInitSpec(this, _Class17_brand);
        _classPrivateFieldInitSpec(this, _domain2, void 0);
        _classPrivateFieldInitSpec(this, _baseUrl5, void 0);
        _classPrivateFieldInitSpec(this, _clientId5, void 0);
        _classPrivateFieldInitSpec(this, _clientSecret2, void 0);
        _classPrivateFieldInitSpec(this, _clientAssertionSigningKey, void 0);
        _classPrivateFieldInitSpec(this, _clientAssertionSigningAlg, void 0);
        _classPrivateFieldInitSpec(this, _useMtls, void 0);
        _classPrivateFieldInitSpec(this, _customFetch5, void 0);
        _classPrivateFieldSet2(_domain2, this, _options.domain);
        _classPrivateFieldSet2(_baseUrl5, this, "https://".concat(_options.domain));
        _classPrivateFieldSet2(_clientId5, this, _options.clientId);
        _classPrivateFieldSet2(_clientSecret2, this, _options.clientSecret);
        _classPrivateFieldSet2(_clientAssertionSigningKey, this, _options.clientAssertionSigningKey);
        _classPrivateFieldSet2(_clientAssertionSigningAlg, this, _options.clientAssertionSigningAlg);
        _classPrivateFieldSet2(_useMtls, this, _options.useMtls);
        _classPrivateFieldSet2(_customFetch5, this, (_options$customFetch5 = _options.customFetch) !== null && _options$customFetch5 !== void 0 ? _options$customFetch5 : function() {
            return fetch(...arguments);
        });
    }
    async createSession(options) {
        const body = {
            client_id: _classPrivateFieldGet2(_clientId5, this)
        };
        if (options !== null && options !== void 0 && options.audience) {
            body.audience = options.audience;
        }
        if (options !== null && options !== void 0 && options.scope) {
            body.scope = options.scope;
        }
        if (options !== null && options !== void 0 && options.metadata) {
            body.metadata = options.metadata;
        }
        const tokens = await _assertClassBrand(_Class17_brand, this, _postAnonymousToken).call(this, body);
        if (!tokens.sessionToken) {
            throw new AnonymousSessionError("server_error", "session_token missing from create session response");
        }
        return {
            sessionToken: tokens.sessionToken,
            accessToken: tokens.accessToken,
            expiresAt: tokens.expiresAt,
            sessionTokenExpiresAt: tokens.sessionTokenExpiresAt,
            scope: tokens.scope
        };
    }
    async getAccessToken(options) {
        if (!(options !== null && options !== void 0 && options.sessionToken)) {
            return this.createSession({
                audience: options === null || options === void 0 ? void 0 : options.audience,
                scope: options === null || options === void 0 ? void 0 : options.scope
            });
        }
        try {
            return await _assertClassBrand(_Class17_brand, this, _mintToken).call(this, options.sessionToken, options);
        } catch (e) {
            if (e instanceof AnonymousSessionError && SESSION_INVALIDATION_CODES.has(e.code)) {
                const fresh = await this.createSession({
                    audience: options === null || options === void 0 ? void 0 : options.audience,
                    scope: options === null || options === void 0 ? void 0 : options.scope
                });
                return _objectSpread2(_objectSpread2({}, fresh), {}, {
                    sessionReplaced: true
                });
            }
            throw e;
        }
    }
    async logout() {
        const url = "".concat(_classPrivateFieldGet2(_baseUrl5, this), "/anonymous/logout");
        const body = {
            client_id: _classPrivateFieldGet2(_clientId5, this)
        };
        const response = await _classPrivateFieldGet2(_customFetch5, this).call(this, url, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            credentials: "include",
            redirect: "error",
            body: JSON.stringify(body)
        });
        if (!response.ok) {
            const errorBody = await parseErrorResponse(response);
            throw new AnonymousSessionError(errorBody.error, errorBody.error_description || "Failed to end anonymous session", errorBody);
        }
    }
});

async function _mintToken(sessionToken, options) {
    const body = {
        client_id: _classPrivateFieldGet2(_clientId5, this),
        session_token: sessionToken
    };
    if (options !== null && options !== void 0 && options.audience) {
        body.audience = options.audience;
    }
    if (options !== null && options !== void 0 && options.scope) {
        body.scope = options.scope;
    }
    const tokens = await _assertClassBrand(_Class17_brand, this, _postAnonymousToken).call(this, body);
    return {
        sessionToken: sessionToken,
        accessToken: tokens.accessToken,
        expiresAt: tokens.expiresAt,
        sessionTokenExpiresAt: tokens.sessionTokenExpiresAt,
        scope: tokens.scope,
        sessionReplaced: false
    };
}

async function _postAnonymousToken(body) {
    const url = "".concat(_classPrivateFieldGet2(_baseUrl5, this), "/anonymous/token");
    const authFields = await buildClientAuthBody3({
        clientSecret: _classPrivateFieldGet2(_clientSecret2, this),
        clientAssertionSigningKey: _classPrivateFieldGet2(_clientAssertionSigningKey, this),
        clientAssertionSigningAlg: _classPrivateFieldGet2(_clientAssertionSigningAlg, this),
        useMtls: _classPrivateFieldGet2(_useMtls, this)
    }, _classPrivateFieldGet2(_clientId5, this), _classPrivateFieldGet2(_domain2, this));
    Object.assign(body, authFields);
    const response = await _classPrivateFieldGet2(_customFetch5, this).call(this, url, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        credentials: "include",
        redirect: "error",
        body: JSON.stringify(body)
    });
    if (!response.ok) {
        const errorBody = await parseErrorResponse(response);
        throw new AnonymousSessionError(errorBody.error, errorBody.error_description || "Anonymous token request failed", errorBody);
    }
    let apiResponse;
    try {
        apiResponse = await response.json();
    } catch (_unused15) {
        throw new AnonymousSessionError("server_error", "Invalid response from anonymous token endpoint");
    }
    return parseTokenResponse(apiResponse);
}

var LruCache = (_entries = new WeakMap, _ttlMs = new WeakMap, _maxEntries = new WeakMap, 
class LruCache {
    constructor(maxEntries, ttlMs) {
        _classPrivateFieldInitSpec(this, _entries, new Map);
        _classPrivateFieldInitSpec(this, _ttlMs, void 0);
        _classPrivateFieldInitSpec(this, _maxEntries, void 0);
        _classPrivateFieldSet2(_maxEntries, this, Math.max(1, Math.floor(maxEntries)));
        _classPrivateFieldSet2(_ttlMs, this, Math.max(0, Math.floor(ttlMs)));
    }
    get(key) {
        const entry = _classPrivateFieldGet2(_entries, this).get(key);
        if (!entry) {
            return;
        }
        if (Date.now() >= entry.expiresAt) {
            _classPrivateFieldGet2(_entries, this).delete(key);
            return;
        }
        _classPrivateFieldGet2(_entries, this).delete(key);
        _classPrivateFieldGet2(_entries, this).set(key, entry);
        return entry.value;
    }
    set(key, value, ttlMs) {
        if (_classPrivateFieldGet2(_entries, this).has(key)) {
            _classPrivateFieldGet2(_entries, this).delete(key);
        }
        const effectiveTtl = ttlMs != null && Number.isFinite(ttlMs) && ttlMs > 0 ? ttlMs : _classPrivateFieldGet2(_ttlMs, this);
        _classPrivateFieldGet2(_entries, this).set(key, {
            value: value,
            expiresAt: Date.now() + effectiveTtl
        });
        while (_classPrivateFieldGet2(_entries, this).size > _classPrivateFieldGet2(_maxEntries, this)) {
            const oldestKey = _classPrivateFieldGet2(_entries, this).keys().next().value;
            if (oldestKey === void 0) {
                break;
            }
            _classPrivateFieldGet2(_entries, this).delete(oldestKey);
        }
    }
});

var globalCaches = new Map;

function getGlobalCache(key) {
    return globalCaches.get(key);
}

function getGlobalCacheKey(maxEntries, ttlMs) {
    return "".concat(maxEntries, ":").concat(ttlMs);
}

function resolveCacheConfig(options) {
    const ttlSeconds = typeof (options === null || options === void 0 ? void 0 : options.ttl) === "number" ? options.ttl : 600;
    const maxEntries = typeof (options === null || options === void 0 ? void 0 : options.maxEntries) === "number" && options.maxEntries > 0 ? options.maxEntries : 100;
    const ttlMs = ttlSeconds * 1e3;
    return {
        ttlMs: ttlMs,
        maxEntries: maxEntries
    };
}

var DiscoveryCacheFactory = class {
    static createDiscoveryCache(config) {
        const cacheKey = getGlobalCacheKey(config.maxEntries, config.ttlMs);
        let cache2 = getGlobalCache(cacheKey);
        if (!cache2) {
            cache2 = new LruCache(config.maxEntries, config.ttlMs);
            globalCaches.set(cacheKey, cache2);
        }
        return cache2;
    }
    static createJwksCache() {
        return {};
    }
};

var DEFAULT_SCOPES = "openid profile email offline_access";

var MAX_ARRAY_VALUES_PER_KEY = 20;

var PARAM_DENYLIST = Object.freeze(new Set([ "grant_type", "client_id", "client_secret", "client_assertion", "client_assertion_type", "subject_token", "subject_token_type", "requested_token_type", "actor_token", "actor_token_type", "audience", "aud", "resource", "resources", "resource_indicator", "scope", "connection", "login_hint", "organization", "assertion" ]));

function validateSubjectToken(token) {
    if (token == null) {
        throw new TokenExchangeError("subject_token is required");
    }
    if (typeof token !== "string") {
        throw new TokenExchangeError("subject_token must be a string");
    }
    if (token.trim().length === 0) {
        throw new TokenExchangeError("subject_token cannot be blank or whitespace");
    }
    if (token !== token.trim()) {
        throw new TokenExchangeError("subject_token must not include leading or trailing whitespace");
    }
    if (/^bearer\s+/i.test(token)) {
        throw new TokenExchangeError("subject_token must not include the 'Bearer ' prefix");
    }
}

function appendExtraParams(params, extra) {
    if (!extra) return;
    for (const _ref8 of Object.entries(extra)) {
        var _ref9 = _slicedToArray(_ref8, 2);
        const parameterKey = _ref9[0];
        const parameterValue = _ref9[1];
        if (PARAM_DENYLIST.has(parameterKey)) continue;
        if (Array.isArray(parameterValue)) {
            if (parameterValue.length > MAX_ARRAY_VALUES_PER_KEY) {
                throw new TokenExchangeError("Parameter '".concat(parameterKey, "' exceeds maximum array size of ").concat(MAX_ARRAY_VALUES_PER_KEY));
            }
            parameterValue.forEach(arrayItem => {
                params.append(parameterKey, arrayItem);
            });
        } else {
            params.append(parameterKey, parameterValue);
        }
    }
}

var GRANT_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN = "urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token";

var TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange";

var SUBJECT_TYPE_REFRESH_TOKEN = "urn:ietf:params:oauth:token-type:refresh_token";

var SUBJECT_TYPE_ACCESS_TOKEN = "urn:ietf:params:oauth:token-type:access_token";

var REQUESTED_TOKEN_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN = "http://auth0.com/oauth/token-type/federated-connection-access-token";

function createPasskeyFetch(customFetch4, grantType) {
    return (input, init) => {
        const body = init === null || init === void 0 ? void 0 : init.body;
        if (grantType !== PASSKEY_GRANT_TYPE || !(body instanceof URLSearchParams)) {
            return customFetch4(input, init);
        }
        const jsonBody = {};
        for (const _ref0 of body) {
            var _ref1 = _slicedToArray(_ref0, 2);
            const key = _ref1[0];
            const value = _ref1[1];
            jsonBody[key] = key === "authn_response" ? JSON.parse(value) : value;
        }
        const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers);
        headers.set("Content-Type", "application/json");
        return customFetch4(input, _objectSpread2(_objectSpread2({}, init), {}, {
            headers: headers,
            body: JSON.stringify(jsonBody)
        }));
    };
}

var AuthClient = (_configuration = new WeakMap, _optionalConfiguration = new WeakMap, 
_serverMetadata = new WeakMap, _clientAuthPromise = new WeakMap, _options2 = new WeakMap, 
_customFetch6 = new WeakMap, _telemetryConfig5 = new WeakMap, _jwks = new WeakMap, 
_discoveryCache = new WeakMap, _inFlightDiscovery = new WeakMap, _jwksCache = new WeakMap, 
_Class19_brand = new WeakSet, class AuthClient {
    constructor(_options3) {
        var _options3$customFetch;
        _classPrivateMethodInitSpec(this, _Class19_brand);
        _classPrivateFieldInitSpec(this, _configuration, void 0);
        _classPrivateFieldInitSpec(this, _optionalConfiguration, void 0);
        _classPrivateFieldInitSpec(this, _serverMetadata, void 0);
        _classPrivateFieldInitSpec(this, _clientAuthPromise, void 0);
        _classPrivateFieldInitSpec(this, _options2, void 0);
        _classPrivateFieldInitSpec(this, _customFetch6, void 0);
        _classPrivateFieldInitSpec(this, _telemetryConfig5, void 0);
        _classPrivateFieldInitSpec(this, _jwks, void 0);
        _classPrivateFieldInitSpec(this, _discoveryCache, void 0);
        _classPrivateFieldInitSpec(this, _inFlightDiscovery, void 0);
        _classPrivateFieldInitSpec(this, _jwksCache, void 0);
        _defineProperty(this, "mfa", void 0);
        _defineProperty(this, "passkey", void 0);
        _defineProperty(this, "passwordless", void 0);
        _defineProperty(this, "database", void 0);
        _defineProperty(this, "anonymous", void 0);
        _classPrivateFieldSet2(_options2, this, _options3);
        if (_options3.useMtls && !_options3.customFetch) {
            throw new NotSupportedError("mtls_without_custom_fetch_not_supported", "Using mTLS without a custom fetch implementation is not supported");
        }
        _classPrivateFieldSet2(_telemetryConfig5, this, getTelemetryConfig(_options3.telemetry));
        _classPrivateFieldSet2(_customFetch6, this, createTelemetryFetch((_options3$customFetch = _options3.customFetch) !== null && _options3$customFetch !== void 0 ? _options3$customFetch : function() {
            return fetch(...arguments);
        }, _classPrivateFieldGet2(_telemetryConfig5, this)));
        const cacheConfig = resolveCacheConfig(_options3.discoveryCache);
        _classPrivateFieldSet2(_discoveryCache, this, DiscoveryCacheFactory.createDiscoveryCache(cacheConfig));
        _classPrivateFieldSet2(_inFlightDiscovery, this, new Map);
        _classPrivateFieldSet2(_jwksCache, this, DiscoveryCacheFactory.createJwksCache());
        this.mfa = new MfaClient({
            domain: _classPrivateFieldGet2(_options2, this).domain,
            clientId: _classPrivateFieldGet2(_options2, this).clientId,
            clientSecret: _classPrivateFieldGet2(_options2, this).clientSecret,
            customFetch: _classPrivateFieldGet2(_customFetch6, this),
            telemetryConfig: _classPrivateFieldGet2(_telemetryConfig5, this),
            getConfiguration: async requestOptions => (await _assertClassBrand(_Class19_brand, this, _discoverForRequest).call(this, requestOptions)).configuration,
            createCaptureConfiguration: async capturingFetch => {
                const _await$_assertClassBr = await _assertClassBrand(_Class19_brand, this, _discover).call(this), serverMetadata = _await$_assertClassBr.serverMetadata;
                return _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, serverMetadata, capturingFetch);
            }
        });
        this.passkey = new PasskeyClient({
            domain: _classPrivateFieldGet2(_options2, this).domain,
            clientId: _classPrivateFieldGet2(_options2, this).clientId,
            clientSecret: _classPrivateFieldGet2(_options2, this).clientSecret,
            useMtls: _classPrivateFieldGet2(_options2, this).useMtls,
            customFetch: _classPrivateFieldGet2(_customFetch6, this),
            telemetryConfig: _classPrivateFieldGet2(_telemetryConfig5, this),
            grantRequest: async (grantType, params, requestOptions, capture) => {
                const _await$_assertClassBr2 = await _assertClassBrand(_Class19_brand, this, _discover).call(this), serverMetadata = _await$_assertClassBr2.serverMetadata;
                const requestFetch = _assertClassBrand(_Class19_brand, this, _buildRequestFetch).call(this, requestOptions);
                if (capture) {
                    const capturingFetch = createCapturingFetch(requestFetch);
                    const configuration2 = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, serverMetadata, capturingFetch);
                    configuration2[customFetch$1] = createPasskeyFetch(capturingFetch, grantType);
                    const tokenEndpointResponse2 = await genericGrantRequest(configuration2, grantType, params);
                    const data = TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse2);
                    const capturedResponse = capturingFetch.getCapturedResponse();
                    if (!capturedResponse) {
                        throw new MissingCapturedResponseError;
                    }
                    return {
                        data: data,
                        response: capturedResponse
                    };
                }
                const configuration = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, serverMetadata);
                configuration[customFetch$1] = createPasskeyFetch(requestFetch, grantType);
                const tokenEndpointResponse = await genericGrantRequest(configuration, grantType, params);
                return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
            }
        });
        this.passwordless = new PasswordlessClient({
            domain: _classPrivateFieldGet2(_options2, this).domain,
            clientId: _classPrivateFieldGet2(_options2, this).clientId,
            customFetch: _classPrivateFieldGet2(_customFetch6, this),
            telemetryConfig: _classPrivateFieldGet2(_telemetryConfig5, this),
            clientSecret: _classPrivateFieldGet2(_options2, this).clientSecret,
            clientAssertionSigningKey: _classPrivateFieldGet2(_options2, this).clientAssertionSigningKey,
            clientAssertionSigningAlg: _classPrivateFieldGet2(_options2, this).clientAssertionSigningAlg,
            useMtls: _classPrivateFieldGet2(_options2, this).useMtls,
            grantRequest: async (grantType, params, requestOptions, capture) => {
                const _await$_assertClassBr3 = await _assertClassBrand(_Class19_brand, this, _discoverForRequest).call(this, requestOptions), configuration = _await$_assertClassBr3.configuration;
                if (capture) {
                    var _configuration$client;
                    const baseFetch = (_configuration$client = configuration[customFetch$1]) !== null && _configuration$client !== void 0 ? _configuration$client : _classPrivateFieldGet2(_customFetch6, this);
                    const capturingFetch = createCapturingFetch(baseFetch);
                    const captureConfig = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch);
                    const tokenEndpointResponse = await genericGrantRequest(captureConfig, grantType, params);
                    const data = TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
                    const capturedResponse = capturingFetch.getCapturedResponse();
                    if (!capturedResponse) {
                        throw new MissingCapturedResponseError;
                    }
                    return {
                        data: data,
                        response: capturedResponse
                    };
                }
                try {
                    const tokenEndpointResponse = await genericGrantRequest(configuration, grantType, params);
                    return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
                } catch (e) {
                    const annotated = e;
                    const tmp = {};
                    attachHttpMetadata(tmp, e);
                    annotated._statusCode = tmp.statusCode;
                    annotated._headers = tmp.headers;
                    throw e;
                }
            }
        });
        this.database = new DatabaseClient({
            domain: _classPrivateFieldGet2(_options2, this).domain,
            clientId: _classPrivateFieldGet2(_options2, this).clientId,
            customFetch: _classPrivateFieldGet2(_customFetch6, this),
            telemetryConfig: _classPrivateFieldGet2(_telemetryConfig5, this)
        });
        this.anonymous = new AnonymousSessionClient({
            domain: _classPrivateFieldGet2(_options2, this).domain,
            clientId: _classPrivateFieldGet2(_options2, this).clientId,
            clientSecret: _classPrivateFieldGet2(_options2, this).clientSecret,
            clientAssertionSigningKey: _classPrivateFieldGet2(_options2, this).clientAssertionSigningKey,
            clientAssertionSigningAlg: _classPrivateFieldGet2(_options2, this).clientAssertionSigningAlg,
            useMtls: _classPrivateFieldGet2(_options2, this).useMtls,
            customFetch: _classPrivateFieldGet2(_customFetch6, this)
        });
    }
    async getServerMetadata() {
        const _await$_assertClassBr4 = await _assertClassBrand(_Class19_brand, this, _discover).call(this), serverMetadata = _await$_assertClassBr4.serverMetadata;
        return serverMetadata;
    }
    async buildAuthorizationUrl(options) {
        const _await$_assertClassBr5 = await _assertClassBrand(_Class19_brand, this, _discover).call(this), serverMetadata = _await$_assertClassBr5.serverMetadata;
        if (options !== null && options !== void 0 && options.pushedAuthorizationRequests && !serverMetadata.pushed_authorization_request_endpoint) {
            throw new NotSupportedError("par_not_supported_error", "The Auth0 tenant does not have pushed authorization requests enabled. Learn how to enable it here: https://auth0.com/docs/get-started/applications/configure-par");
        }
        try {
            return await _assertClassBrand(_Class19_brand, this, _buildAuthorizationUrl).call(this, options);
        } catch (e) {
            throw new BuildAuthorizationUrlError(e);
        }
    }
    async buildLinkUserUrl(options) {
        try {
            const result = await _assertClassBrand(_Class19_brand, this, _buildAuthorizationUrl).call(this, {
                authorizationParams: _objectSpread2(_objectSpread2({}, options.authorizationParams), {}, {
                    requested_connection: options.connection,
                    requested_connection_scope: options.connectionScope,
                    scope: "openid link_account offline_access",
                    id_token_hint: options.idToken
                })
            });
            return {
                linkUserUrl: result.authorizationUrl,
                codeVerifier: result.codeVerifier
            };
        } catch (e) {
            throw new BuildLinkUserUrlError(e);
        }
    }
    async buildUnlinkUserUrl(options) {
        try {
            const result = await _assertClassBrand(_Class19_brand, this, _buildAuthorizationUrl).call(this, {
                authorizationParams: _objectSpread2(_objectSpread2({}, options.authorizationParams), {}, {
                    requested_connection: options.connection,
                    scope: "openid unlink_account",
                    id_token_hint: options.idToken
                })
            });
            return {
                unlinkUserUrl: result.authorizationUrl,
                codeVerifier: result.codeVerifier
            };
        } catch (e) {
            throw new BuildUnlinkUserUrlError(e);
        }
    }
    async backchannelAuthentication(options, requestOptions) {
        var _configuration$client3;
        const _await$_assertClassBr6 = await _assertClassBrand(_Class19_brand, this, _discoverForRequest).call(this, requestOptions), configuration = _await$_assertClassBr6.configuration, serverMetadata = _await$_assertClassBr6.serverMetadata;
        const additionalParams = stripUndefinedProperties(_objectSpread2(_objectSpread2({}, _classPrivateFieldGet2(_options2, this).authorizationParams), options === null || options === void 0 ? void 0 : options.authorizationParams));
        const params = new URLSearchParams(_objectSpread2(_objectSpread2({
            scope: DEFAULT_SCOPES
        }, additionalParams), {}, {
            client_id: _classPrivateFieldGet2(_options2, this).clientId,
            binding_message: options.bindingMessage,
            login_hint: JSON.stringify({
                format: "iss_sub",
                iss: serverMetadata.issuer,
                sub: options.loginHint.sub
            })
        }));
        if (options.requestedExpiry) {
            params.append("requested_expiry", options.requestedExpiry.toString());
        }
        if (options.authorizationDetails) {
            params.append("authorization_details", JSON.stringify(options.authorizationDetails));
        }
        if (options.fullResponse) {
            var _configuration$client2;
            const capturingFetch2 = createCapturingFetch((_configuration$client2 = configuration[customFetch$1]) !== null && _configuration$client2 !== void 0 ? _configuration$client2 : _classPrivateFieldGet2(_customFetch6, this));
            const captureConfig2 = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch2);
            try {
                const backchannelAuthenticationResponse = await initiateBackchannelAuthentication(configuration, params);
                const tokenEndpointResponse = await pollBackchannelAuthenticationGrant(captureConfig2, backchannelAuthenticationResponse);
                const capturedResponse = capturingFetch2.getCapturedResponse();
                if (!capturedResponse) {
                    throw new MissingCapturedResponseError;
                }
                return {
                    data: TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse),
                    response: capturedResponse
                };
            } catch (e) {
                if (e instanceof MissingCapturedResponseError) throw e;
                const err = new BackchannelAuthenticationError(e);
                attachHttpMetadata(err, e, capturingFetch2.getCapturedResponse());
                throw err;
            }
        }
        const baseFetch = (_configuration$client3 = configuration[customFetch$1]) !== null && _configuration$client3 !== void 0 ? _configuration$client3 : _classPrivateFieldGet2(_customFetch6, this);
        const capturingFetch = createCapturingFetch(baseFetch);
        const captureConfig = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch);
        try {
            const backchannelAuthenticationResponse = await initiateBackchannelAuthentication(configuration, params);
            const tokenEndpointResponse = await pollBackchannelAuthenticationGrant(captureConfig, backchannelAuthenticationResponse);
            return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
        } catch (e) {
            const err = new BackchannelAuthenticationError(e);
            attachHttpMetadata(err, e, capturingFetch.getCapturedResponse());
            throw err;
        }
    }
    async initiateBackchannelAuthentication(options, requestOptions) {
        var _configuration$client4;
        const _await$_assertClassBr7 = await _assertClassBrand(_Class19_brand, this, _discoverForRequest).call(this, requestOptions), configuration = _await$_assertClassBr7.configuration, serverMetadata = _await$_assertClassBr7.serverMetadata;
        const additionalParams = stripUndefinedProperties(_objectSpread2(_objectSpread2({}, _classPrivateFieldGet2(_options2, this).authorizationParams), options === null || options === void 0 ? void 0 : options.authorizationParams));
        const params = new URLSearchParams(_objectSpread2(_objectSpread2({
            scope: DEFAULT_SCOPES
        }, additionalParams), {}, {
            client_id: _classPrivateFieldGet2(_options2, this).clientId,
            binding_message: options.bindingMessage,
            login_hint: JSON.stringify({
                format: "iss_sub",
                iss: serverMetadata.issuer,
                sub: options.loginHint.sub
            })
        }));
        if (options.requestedExpiry) {
            params.append("requested_expiry", options.requestedExpiry.toString());
        }
        if (options.authorizationDetails) {
            params.append("authorization_details", JSON.stringify(options.authorizationDetails));
        }
        const baseFetch = (_configuration$client4 = configuration[customFetch$1]) !== null && _configuration$client4 !== void 0 ? _configuration$client4 : _classPrivateFieldGet2(_customFetch6, this);
        const capturingFetch = createCapturingFetch(baseFetch);
        const captureConfig = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch);
        try {
            const backchannelAuthenticationResponse = await initiateBackchannelAuthentication(captureConfig, params);
            return {
                authReqId: backchannelAuthenticationResponse.auth_req_id,
                expiresIn: backchannelAuthenticationResponse.expires_in,
                interval: backchannelAuthenticationResponse.interval
            };
        } catch (e) {
            const err = new BackchannelAuthenticationError(e);
            const _cap = capturingFetch.getCapturedResponse();
            err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
            err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
            throw err;
        }
    }
    async backchannelAuthenticationGrant(_ref10, requestOptions) {
        var _configuration$client5;
        let authReqId = _ref10.authReqId;
        const _await$_assertClassBr8 = await _assertClassBrand(_Class19_brand, this, _discoverForRequest).call(this, requestOptions), configuration = _await$_assertClassBr8.configuration;
        const params = new URLSearchParams({
            auth_req_id: authReqId
        });
        const baseFetch = (_configuration$client5 = configuration[customFetch$1]) !== null && _configuration$client5 !== void 0 ? _configuration$client5 : _classPrivateFieldGet2(_customFetch6, this);
        const capturingFetch = createCapturingFetch(baseFetch);
        const captureConfig = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch);
        try {
            const tokenEndpointResponse = await genericGrantRequest(captureConfig, "urn:openid:params:grant-type:ciba", params);
            return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
        } catch (e) {
            const err = new BackchannelAuthenticationError(e);
            const _cap = capturingFetch.getCapturedResponse();
            err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
            err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
            throw err;
        }
    }
    async getTokenForConnection(options, requestOptions) {
        var _options$accessToken;
        if (options.refreshToken && options.accessToken) {
            throw new TokenForConnectionError("Either a refresh or access token should be specified, but not both.");
        }
        const subjectTokenValue = (_options$accessToken = options.accessToken) !== null && _options$accessToken !== void 0 ? _options$accessToken : options.refreshToken;
        if (!subjectTokenValue) {
            throw new TokenForConnectionError("Either a refresh or access token must be specified.");
        }
        try {
            return await this.exchangeToken(_objectSpread2({
                connection: options.connection,
                subjectToken: subjectTokenValue,
                subjectTokenType: options.accessToken ? SUBJECT_TYPE_ACCESS_TOKEN : SUBJECT_TYPE_REFRESH_TOKEN,
                loginHint: options.loginHint
            }, options.fullResponse ? {
                fullResponse: true
            } : {}), requestOptions);
        } catch (e) {
            if (e instanceof TokenExchangeError) {
                const fce = new TokenForConnectionError(e.message, e.cause);
                fce.statusCode = e.statusCode;
                fce.headers = e.headers;
                throw fce;
            }
            throw e;
        }
    }
    async exchangeToken(options, requestOptions) {
        if (options.fullResponse) {
            return "connection" in options ? _assertClassBrand(_Class19_brand, this, _exchangeTokenVaultToken).call(this, options, requestOptions, true) : _assertClassBrand(_Class19_brand, this, _exchangeProfileToken).call(this, options, requestOptions, true);
        }
        return "connection" in options ? _assertClassBrand(_Class19_brand, this, _exchangeTokenVaultToken).call(this, options, requestOptions) : _assertClassBrand(_Class19_brand, this, _exchangeProfileToken).call(this, options, requestOptions);
    }
    async getTokenByCode(url, options, requestOptions) {
        var _configuration$client7;
        const _await$_assertClassBr9 = await _assertClassBrand(_Class19_brand, this, _discoverForRequest).call(this, requestOptions), configuration = _await$_assertClassBr9.configuration;
        if (options.organization !== void 0) {
            assertValidOrganization(options.organization);
        }
        if (options.fullResponse) {
            var _configuration$client6;
            const baseFetch = (_configuration$client6 = configuration[customFetch$1]) !== null && _configuration$client6 !== void 0 ? _configuration$client6 : _classPrivateFieldGet2(_customFetch6, this);
            const capturingFetch = createCapturingFetch(baseFetch);
            const captureConfig = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch);
            let data, capturedResponse;
            try {
                const tokenEndpointResponse = await authorizationCodeGrant(captureConfig, url, {
                    pkceCodeVerifier: options.codeVerifier
                });
                data = TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
                capturedResponse = capturingFetch.getCapturedResponse();
                if (!capturedResponse) {
                    throw new MissingCapturedResponseError;
                }
            } catch (e) {
                if (e instanceof MissingCapturedResponseError) throw e;
                const err = new TokenByCodeError("There was an error while trying to request a token.", toOAuth2Error(e));
                const _cap = capturingFetch.getCapturedResponse();
                err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
                err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
                throw err;
            }
            if (options.organization) {
                validateOrganizationClaim(data.claims, options.organization);
            }
            return {
                data: data,
                response: capturedResponse
            };
        }
        const bareBaseFetch = (_configuration$client7 = configuration[customFetch$1]) !== null && _configuration$client7 !== void 0 ? _configuration$client7 : _classPrivateFieldGet2(_customFetch6, this);
        const bareCapturingFetch = createCapturingFetch(bareBaseFetch);
        const bareCaptureConfig = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), bareCapturingFetch);
        let tokenResponse;
        try {
            const tokenEndpointResponse = await authorizationCodeGrant(bareCaptureConfig, url, {
                pkceCodeVerifier: options.codeVerifier
            });
            tokenResponse = TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
        } catch (e) {
            const err = new TokenByCodeError("There was an error while trying to request a token.", toOAuth2Error(e));
            const _bareCap = bareCapturingFetch.getCapturedResponse();
            err.statusCode = _bareCap === null || _bareCap === void 0 ? void 0 : _bareCap.status;
            err.headers = _bareCap ? filterSensitiveHeaders(_bareCap.headers) : void 0;
            throw err;
        }
        if (options.organization) {
            validateOrganizationClaim(tokenResponse.claims, options.organization);
        }
        return tokenResponse;
    }
    async getTokenByMagicLinkCode(url, options, requestOptions) {
        var _configuration$client9;
        const _await$_assertClassBr0 = await _assertClassBrand(_Class19_brand, this, _discoverForRequest).call(this, requestOptions), configuration = _await$_assertClassBr0.configuration;
        if (options !== null && options !== void 0 && options.fullResponse) {
            var _configuration$client8;
            const baseFetch2 = (_configuration$client8 = configuration[customFetch$1]) !== null && _configuration$client8 !== void 0 ? _configuration$client8 : _classPrivateFieldGet2(_customFetch6, this);
            const capturingFetch2 = createCapturingFetch(baseFetch2);
            const captureConfig2 = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch2);
            try {
                const tokenEndpointResponse = await authorizationCodeGrant(captureConfig2, url, {
                    expectedState: options === null || options === void 0 ? void 0 : options.expectedState
                });
                const data = TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
                const capturedResponse = capturingFetch2.getCapturedResponse();
                if (!capturedResponse) {
                    throw new MissingCapturedResponseError;
                }
                return {
                    data: data,
                    response: capturedResponse
                };
            } catch (e) {
                if (e instanceof MissingCapturedResponseError) throw e;
                const message = e instanceof Error && e.message ? e.message : "There was an error while trying to request a token.";
                const err = new TokenByCodeError(message, e);
                const _cap = capturingFetch2.getCapturedResponse();
                err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
                err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
                throw err;
            }
        }
        const baseFetch = (_configuration$client9 = configuration[customFetch$1]) !== null && _configuration$client9 !== void 0 ? _configuration$client9 : _classPrivateFieldGet2(_customFetch6, this);
        const capturingFetch = createCapturingFetch(baseFetch);
        const captureConfig = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch);
        try {
            const tokenEndpointResponse = await authorizationCodeGrant(captureConfig, url, {
                expectedState: options === null || options === void 0 ? void 0 : options.expectedState
            });
            return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
        } catch (e) {
            const message = e instanceof Error && e.message ? e.message : "There was an error while trying to request a token.";
            const err = new TokenByCodeError(message, e);
            const _cap = capturingFetch.getCapturedResponse();
            err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
            err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
            throw err;
        }
    }
    async getTokenByRefreshToken(options, requestOptions) {
        var _configuration$client1;
        const _await$_assertClassBr1 = await _assertClassBrand(_Class19_brand, this, _discoverForRequest).call(this, requestOptions), configuration = _await$_assertClassBr1.configuration;
        const additionalParameters = new URLSearchParams;
        if (options.audience) {
            additionalParameters.append("audience", options.audience);
        }
        if (options.scope) {
            additionalParameters.append("scope", options.scope);
        }
        if (options.fullResponse) {
            var _configuration$client0;
            const baseFetch2 = (_configuration$client0 = configuration[customFetch$1]) !== null && _configuration$client0 !== void 0 ? _configuration$client0 : _classPrivateFieldGet2(_customFetch6, this);
            const capturingFetch2 = createCapturingFetch(baseFetch2);
            const captureConfig2 = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch2);
            try {
                const tokenEndpointResponse = await refreshTokenGrant(captureConfig2, options.refreshToken, additionalParameters);
                const data = TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
                const capturedResponse = capturingFetch2.getCapturedResponse();
                if (!capturedResponse) {
                    throw new MissingCapturedResponseError;
                }
                return {
                    data: data,
                    response: capturedResponse
                };
            } catch (e) {
                if (e instanceof MissingCapturedResponseError) throw e;
                const err = new TokenByRefreshTokenError("The access token has expired and there was an error while trying to refresh it.", toOAuth2Error(e));
                const _cap = capturingFetch2.getCapturedResponse();
                err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
                err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
                throw err;
            }
        }
        const baseFetch = (_configuration$client1 = configuration[customFetch$1]) !== null && _configuration$client1 !== void 0 ? _configuration$client1 : _classPrivateFieldGet2(_customFetch6, this);
        const capturingFetch = createCapturingFetch(baseFetch);
        const captureConfig = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch);
        try {
            const tokenEndpointResponse = await refreshTokenGrant(captureConfig, options.refreshToken, additionalParameters);
            return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
        } catch (e) {
            const err = new TokenByRefreshTokenError("The access token has expired and there was an error while trying to refresh it.", toOAuth2Error(e));
            const _cap = capturingFetch.getCapturedResponse();
            err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
            err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
            throw err;
        }
    }
    async revokeToken(options, requestOptions) {
        var _configuration$client10;
        const _await$_assertClassBr10 = await _assertClassBrand(_Class19_brand, this, _discoverForRequest).call(this, requestOptions), configuration = _await$_assertClassBr10.configuration;
        const params = {};
        if (options.tokenTypeHint) {
            params["token_type_hint"] = options.tokenTypeHint;
        }
        const baseFetch = (_configuration$client10 = configuration[customFetch$1]) !== null && _configuration$client10 !== void 0 ? _configuration$client10 : _classPrivateFieldGet2(_customFetch6, this);
        const capturingFetch = createCapturingFetch(baseFetch);
        const captureConfig = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch);
        try {
            await tokenRevocation(captureConfig, options.token, params);
        } catch (e) {
            const err = new TokenRevocationError("An error occurred while trying to revoke the token.", toOAuth2Error(e));
            const _cap = capturingFetch.getCapturedResponse();
            err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
            err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
            throw err;
        }
    }
    async getUserInfo(options, requestOptions) {
        const _await$_assertClassBr11 = await _assertClassBrand(_Class19_brand, this, _discoverForRequest).call(this, requestOptions, true), configuration = _await$_assertClassBr11.configuration;
        try {
            var _options$expectedSubj;
            return await fetchUserInfo(configuration, options.accessToken, (_options$expectedSubj = options.expectedSubject) !== null && _options$expectedSubj !== void 0 ? _options$expectedSubj : skipSubjectCheck);
        } catch (e) {
            throw new UserInfoError("There was an error while trying to retrieve the user info.", toOAuth2Error(e));
        }
    }
    async getTokenByPassword(options, requestOptions) {
        var _requestConfig$client2;
        const _await$_assertClassBr12 = await _assertClassBrand(_Class19_brand, this, _discoverForRequest).call(this, requestOptions), configuration = _await$_assertClassBr12.configuration;
        const params = new URLSearchParams({
            username: options.username,
            password: options.password
        });
        if (options.audience) {
            params.append("audience", options.audience);
        }
        if (options.scope) {
            params.append("scope", options.scope);
        }
        if (options.realm) {
            params.append("realm", options.realm);
        }
        let requestConfig = configuration;
        if (options.auth0ForwardedFor) {
            const clientAuth = await _assertClassBrand(_Class19_brand, this, _getClientAuth).call(this);
            requestConfig = new Configuration(configuration.serverMetadata(), _classPrivateFieldGet2(_options2, this).clientId, {
                client_secret: _classPrivateFieldGet2(_options2, this).clientSecret,
                use_mtls_endpoint_aliases: _classPrivateFieldGet2(_options2, this).useMtls
            }, clientAuth);
            const baseFetch2 = configuration[customFetch$1];
            requestConfig[customFetch$1] = (url, init) => baseFetch2(url, _objectSpread2(_objectSpread2({}, init), {}, {
                headers: _objectSpread2(_objectSpread2({}, init.headers), {}, {
                    "auth0-forwarded-for": options.auth0ForwardedFor
                })
            }));
        }
        if (options.fullResponse) {
            var _requestConfig$client;
            const baseFetch2 = (_requestConfig$client = requestConfig[customFetch$1]) !== null && _requestConfig$client !== void 0 ? _requestConfig$client : _classPrivateFieldGet2(_customFetch6, this);
            const capturingFetch2 = createCapturingFetch(baseFetch2);
            const captureConfig2 = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, requestConfig.serverMetadata(), capturingFetch2);
            try {
                const tokenEndpointResponse = await genericGrantRequest(captureConfig2, "password", params);
                const data = TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
                const capturedResponse = capturingFetch2.getCapturedResponse();
                if (!capturedResponse) {
                    throw new MissingCapturedResponseError;
                }
                return {
                    data: data,
                    response: capturedResponse
                };
            } catch (e) {
                if (e instanceof MissingCapturedResponseError) throw e;
                const err = new TokenByPasswordError("There was an error while trying to request a token.", toOAuth2Error(e));
                const _cap = capturingFetch2.getCapturedResponse();
                err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
                err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
                throw err;
            }
        }
        const baseFetch = (_requestConfig$client2 = requestConfig[customFetch$1]) !== null && _requestConfig$client2 !== void 0 ? _requestConfig$client2 : _classPrivateFieldGet2(_customFetch6, this);
        const capturingFetch = createCapturingFetch(baseFetch);
        const captureConfig = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, requestConfig.serverMetadata(), capturingFetch);
        try {
            const tokenEndpointResponse = await genericGrantRequest(captureConfig, "password", params);
            return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
        } catch (e) {
            const err = new TokenByPasswordError("There was an error while trying to request a token.", toOAuth2Error(e));
            const _cap = capturingFetch.getCapturedResponse();
            err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
            err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
            throw err;
        }
    }
    async getTokenByPasswordlessEmail(options, requestOptions) {
        const params = new URLSearchParams({
            username: options.email,
            otp: options.code,
            realm: "email"
        });
        if (options.audience) {
            params.append("audience", options.audience);
        }
        if (options.scope) {
            params.append("scope", options.scope);
        }
        return _assertClassBrand(_Class19_brand, this, _getTokenByPasswordlessOtp).call(this, params, requestOptions, options.fullResponse);
    }
    async getTokenByPasswordlessSms(options, requestOptions) {
        if (!isE164PhoneNumber(options.phoneNumber)) {
            throw new PasswordlessVerifyError("Phone number must be in E.164 format (e.g. +14155550100).");
        }
        const params = new URLSearchParams({
            username: options.phoneNumber,
            otp: options.code,
            realm: "sms"
        });
        if (options.audience) {
            params.append("audience", options.audience);
        }
        if (options.scope) {
            params.append("scope", options.scope);
        }
        return _assertClassBrand(_Class19_brand, this, _getTokenByPasswordlessOtp).call(this, params, requestOptions, options.fullResponse);
    }
    async getTokenByClientCredentials(options, requestOptions) {
        var _configuration$client12;
        const _await$_assertClassBr13 = await _assertClassBrand(_Class19_brand, this, _discoverForRequest).call(this, requestOptions), configuration = _await$_assertClassBr13.configuration;
        if (options.fullResponse) {
            var _configuration$client11;
            const baseFetch2 = (_configuration$client11 = configuration[customFetch$1]) !== null && _configuration$client11 !== void 0 ? _configuration$client11 : _classPrivateFieldGet2(_customFetch6, this);
            const capturingFetch2 = createCapturingFetch(baseFetch2);
            const captureConfig2 = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch2);
            const params = new URLSearchParams({
                audience: options.audience
            });
            if (options.organization) {
                params.append("organization", options.organization);
            }
            try {
                const tokenEndpointResponse = await clientCredentialsGrant(captureConfig2, params);
                const data = TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
                const capturedResponse = capturingFetch2.getCapturedResponse();
                if (!capturedResponse) {
                    throw new MissingCapturedResponseError;
                }
                return {
                    data: data,
                    response: capturedResponse
                };
            } catch (e) {
                if (e instanceof MissingCapturedResponseError) throw e;
                const err = new TokenByClientCredentialsError("There was an error while trying to request a token.", toOAuth2Error(e));
                const _cap = capturingFetch2.getCapturedResponse();
                err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
                err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
                throw err;
            }
        }
        const baseFetch = (_configuration$client12 = configuration[customFetch$1]) !== null && _configuration$client12 !== void 0 ? _configuration$client12 : _classPrivateFieldGet2(_customFetch6, this);
        const capturingFetch = createCapturingFetch(baseFetch);
        const captureConfig = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch);
        try {
            const params = new URLSearchParams({
                audience: options.audience
            });
            if (options.organization) {
                params.append("organization", options.organization);
            }
            const tokenEndpointResponse = await clientCredentialsGrant(captureConfig, params);
            return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
        } catch (e) {
            const err = new TokenByClientCredentialsError("There was an error while trying to request a token.", toOAuth2Error(e));
            const _cap = capturingFetch.getCapturedResponse();
            err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
            err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
            throw err;
        }
    }
    async buildLogoutUrl(options) {
        const _await$_assertClassBr14 = await _assertClassBrand(_Class19_brand, this, _discover).call(this), configuration = _await$_assertClassBr14.configuration, serverMetadata = _await$_assertClassBr14.serverMetadata;
        if (!serverMetadata.end_session_endpoint) {
            const url = new URL("https://".concat(_classPrivateFieldGet2(_options2, this).domain, "/v2/logout"));
            url.searchParams.set("returnTo", options.returnTo);
            url.searchParams.set("client_id", _classPrivateFieldGet2(_options2, this).clientId);
            if (options.federated) {
                url.searchParams.set("federated", "");
            }
            return url;
        }
        const params = {
            post_logout_redirect_uri: options.returnTo
        };
        if (options.federated) {
            params.federated = "";
        }
        return buildEndSessionUrl(configuration, params);
    }
    async verifyLogoutToken(options) {
        const _await$_assertClassBr15 = await _assertClassBrand(_Class19_brand, this, _discover).call(this), serverMetadata = _await$_assertClassBr15.serverMetadata;
        const cacheConfig = resolveCacheConfig(_classPrivateFieldGet2(_options2, this).discoveryCache);
        const jwksUri = serverMetadata.jwks_uri;
        _classPrivateFieldGet2(_jwks, this) || _classPrivateFieldSet2(_jwks, this, createRemoteJWKSet(new URL(jwksUri), {
            cacheMaxAge: cacheConfig.ttlMs,
            [customFetch]: _classPrivateFieldGet2(_customFetch6, this),
            [jwksCache]: _classPrivateFieldGet2(_jwksCache, this)
        }));
        const _await$jwtVerify = await jwtVerify(options.logoutToken, _classPrivateFieldGet2(_jwks, this), {
            issuer: serverMetadata.issuer,
            audience: _classPrivateFieldGet2(_options2, this).clientId,
            algorithms: [ "RS256" ],
            requiredClaims: [ "iat" ]
        }), payload = _await$jwtVerify.payload;
        if (!("sid" in payload) && !("sub" in payload)) {
            throw new VerifyLogoutTokenError('either "sid" or "sub" (or both) claims must be present');
        }
        if ("sid" in payload && typeof payload.sid !== "string") {
            throw new VerifyLogoutTokenError('"sid" claim must be a string');
        }
        if ("sub" in payload && typeof payload.sub !== "string") {
            throw new VerifyLogoutTokenError('"sub" claim must be a string');
        }
        if ("nonce" in payload) {
            throw new VerifyLogoutTokenError('"nonce" claim is prohibited');
        }
        if (!("events" in payload)) {
            throw new VerifyLogoutTokenError('"events" claim is missing');
        }
        if (typeof payload.events !== "object" || payload.events === null) {
            throw new VerifyLogoutTokenError('"events" claim must be an object');
        }
        if (!("http://schemas.openid.net/event/backchannel-logout" in payload.events)) {
            throw new VerifyLogoutTokenError('"http://schemas.openid.net/event/backchannel-logout" member is missing in the "events" claim');
        }
        if (typeof payload.events["http://schemas.openid.net/event/backchannel-logout"] !== "object") {
            throw new VerifyLogoutTokenError('"http://schemas.openid.net/event/backchannel-logout" member in the "events" claim must be an object');
        }
        return {
            sid: payload.sid,
            sub: payload.sub
        };
    }
});

function _getDiscoveryCacheKey() {
    const domain = _classPrivateFieldGet2(_options2, this).domain.toLowerCase();
    return "".concat(domain, "|mtls:").concat(_classPrivateFieldGet2(_options2, this).useMtls ? "1" : "0");
}

async function _createConfiguration(serverMetadata, fetchImpl) {
    let clientAuthOptional = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
    const clientAuth = await _assertClassBrand(_Class19_brand, this, _getClientAuth).call(this, clientAuthOptional);
    const configuration = new Configuration(serverMetadata, _classPrivateFieldGet2(_options2, this).clientId, {
        client_secret: _classPrivateFieldGet2(_options2, this).clientSecret,
        use_mtls_endpoint_aliases: _classPrivateFieldGet2(_options2, this).useMtls
    }, clientAuth);
    configuration[customFetch$1] = fetchImpl !== null && fetchImpl !== void 0 ? fetchImpl : _classPrivateFieldGet2(_customFetch6, this);
    return configuration;
}

function _buildRequestFetch(requestOptions) {
    return composeRequestFetch(_classPrivateFieldGet2(_customFetch6, this), requestOptions, _classPrivateFieldGet2(_telemetryConfig5, this));
}

async function _discoverForRequest(requestOptions) {
    let clientAuthOptional = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    const _await$_assertClassBr16 = await _assertClassBrand(_Class19_brand, this, _discover).call(this, clientAuthOptional), configuration = _await$_assertClassBr16.configuration, serverMetadata = _await$_assertClassBr16.serverMetadata;
    if (!requestOptions) {
        return {
            configuration: configuration,
            serverMetadata: serverMetadata
        };
    }
    const requestFetch = _assertClassBrand(_Class19_brand, this, _buildRequestFetch).call(this, requestOptions);
    const requestConfiguration = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, serverMetadata, requestFetch, clientAuthOptional);
    return {
        configuration: requestConfiguration,
        serverMetadata: serverMetadata
    };
}

async function _discover() {
    let clientAuthOptional = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    const instanceConfiguration = clientAuthOptional ? _classPrivateFieldGet2(_optionalConfiguration, this) : _classPrivateFieldGet2(_configuration, this);
    if (instanceConfiguration && _classPrivateFieldGet2(_serverMetadata, this)) {
        return {
            configuration: instanceConfiguration,
            serverMetadata: _classPrivateFieldGet2(_serverMetadata, this)
        };
    }
    const cacheKey = _assertClassBrand(_Class19_brand, this, _getDiscoveryCacheKey).call(this);
    if (!clientAuthOptional) {
        await _assertClassBrand(_Class19_brand, this, _getClientAuth).call(this, false);
    }
    const cached = _classPrivateFieldGet2(_discoveryCache, this).get(cacheKey);
    if (cached) {
        return _assertClassBrand(_Class19_brand, this, _configurationFromMetadata).call(this, cached.serverMetadata, clientAuthOptional);
    }
    const inFlight = _classPrivateFieldGet2(_inFlightDiscovery, this).get(cacheKey);
    if (inFlight) {
        const entry = await inFlight;
        return _assertClassBrand(_Class19_brand, this, _configurationFromMetadata).call(this, entry.serverMetadata, clientAuthOptional);
    }
    const discoveryPromise = (async () => {
        const configuration = await discovery(new URL("https://".concat(_classPrivateFieldGet2(_options2, this).domain)), _classPrivateFieldGet2(_options2, this).clientId, {
            use_mtls_endpoint_aliases: _classPrivateFieldGet2(_options2, this).useMtls
        }, None(), {
            [customFetch$1]: _classPrivateFieldGet2(_customFetch6, this)
        });
        const serverMetadata = configuration.serverMetadata();
        _classPrivateFieldGet2(_discoveryCache, this).set(cacheKey, {
            serverMetadata: serverMetadata
        });
        return {
            serverMetadata: serverMetadata
        };
    })();
    void discoveryPromise.catch(() => void 0);
    _classPrivateFieldGet2(_inFlightDiscovery, this).set(cacheKey, discoveryPromise);
    try {
        const _await$discoveryPromi = await discoveryPromise, serverMetadata = _await$discoveryPromi.serverMetadata;
        return _assertClassBrand(_Class19_brand, this, _configurationFromMetadata).call(this, serverMetadata, clientAuthOptional);
    } finally {
        _classPrivateFieldGet2(_inFlightDiscovery, this).delete(cacheKey);
    }
}

async function _configurationFromMetadata(serverMetadata, clientAuthOptional) {
    const configuration = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, serverMetadata, void 0, clientAuthOptional);
    _classPrivateFieldSet2(_serverMetadata, this, serverMetadata);
    if (clientAuthOptional) {
        _classPrivateFieldSet2(_optionalConfiguration, this, configuration);
    } else {
        _classPrivateFieldSet2(_configuration, this, configuration);
    }
    return {
        configuration: configuration,
        serverMetadata: serverMetadata
    };
}

async function _exchangeTokenVaultToken(options, requestOptions, capture) {
    var _options$subjectToken, _options$requestedTok, _configuration$client14;
    const _await$_assertClassBr17 = await _assertClassBrand(_Class19_brand, this, _discoverForRequest).call(this, requestOptions), configuration = _await$_assertClassBr17.configuration;
    if ("audience" in options || "resource" in options) {
        throw new TokenExchangeError("audience and resource parameters are not supported for Token Vault exchanges");
    }
    validateSubjectToken(options.subjectToken);
    const tokenRequestParams = new URLSearchParams({
        connection: options.connection,
        subject_token: options.subjectToken,
        subject_token_type: (_options$subjectToken = options.subjectTokenType) !== null && _options$subjectToken !== void 0 ? _options$subjectToken : SUBJECT_TYPE_ACCESS_TOKEN,
        requested_token_type: (_options$requestedTok = options.requestedTokenType) !== null && _options$requestedTok !== void 0 ? _options$requestedTok : REQUESTED_TOKEN_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN
    });
    if (options.loginHint) {
        tokenRequestParams.append("login_hint", options.loginHint);
    }
    if (options.scope) {
        tokenRequestParams.append("scope", options.scope);
    }
    appendExtraParams(tokenRequestParams, options.extra);
    if (capture) {
        var _configuration$client13;
        const baseFetch2 = (_configuration$client13 = configuration[customFetch$1]) !== null && _configuration$client13 !== void 0 ? _configuration$client13 : _classPrivateFieldGet2(_customFetch6, this);
        const capturingFetch2 = createCapturingFetch(baseFetch2);
        const captureConfig2 = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch2);
        try {
            const tokenEndpointResponse = await genericGrantRequest(captureConfig2, GRANT_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN, tokenRequestParams);
            const data = TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
            const capturedResponse = capturingFetch2.getCapturedResponse();
            if (!capturedResponse) {
                throw new MissingCapturedResponseError;
            }
            return {
                data: data,
                response: capturedResponse
            };
        } catch (e) {
            if (e instanceof MissingCapturedResponseError) throw e;
            const err = new TokenExchangeError("Failed to exchange token for connection '".concat(options.connection, "'."), toOAuth2Error(e));
            const _cap = capturingFetch2.getCapturedResponse();
            err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
            err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
            throw err;
        }
    }
    const baseFetch = (_configuration$client14 = configuration[customFetch$1]) !== null && _configuration$client14 !== void 0 ? _configuration$client14 : _classPrivateFieldGet2(_customFetch6, this);
    const capturingFetch = createCapturingFetch(baseFetch);
    const captureConfig = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch);
    try {
        const tokenEndpointResponse = await genericGrantRequest(captureConfig, GRANT_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN, tokenRequestParams);
        return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
    } catch (e) {
        const err = new TokenExchangeError("Failed to exchange token for connection '".concat(options.connection, "'."), toOAuth2Error(e));
        const _cap = capturingFetch.getCapturedResponse();
        err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
        err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
        throw err;
    }
}

function _finalizeProfileToken(tokenResponse, tokenEndpointResponse, options) {
    if (options.organization) {
        validateOrganizationClaim(tokenResponse.claims, options.organization);
    }
    if (options.actorToken) {
        var _tokenResponse$claims;
        if ((_tokenResponse$claims = tokenResponse.claims) !== null && _tokenResponse$claims !== void 0 && _tokenResponse$claims.act) {
            tokenResponse.act = tokenResponse.claims.act;
        } else {
            try {
                tokenResponse.act = decodeJwt(tokenEndpointResponse.access_token).act;
            } catch (_unused16) {}
        }
    }
    return tokenResponse;
}

async function _exchangeProfileToken(options, requestOptions, capture) {
    var _configuration$client16;
    const _await$_assertClassBr18 = await _assertClassBrand(_Class19_brand, this, _discoverForRequest).call(this, requestOptions), configuration = _await$_assertClassBr18.configuration;
    validateSubjectToken(options.subjectToken);
    if (options.organization !== void 0) {
        assertValidOrganization(options.organization);
    }
    if (options.actorToken !== void 0 && options.actorTokenType === void 0) {
        throw new TokenExchangeError("actorTokenType is required when actorToken is provided");
    }
    const tokenRequestParams = new URLSearchParams({
        subject_token_type: options.subjectTokenType,
        subject_token: options.subjectToken
    });
    if (options.audience) {
        tokenRequestParams.append("audience", options.audience);
    }
    if (options.scope) {
        tokenRequestParams.append("scope", options.scope);
    }
    if (options.requestedTokenType) {
        tokenRequestParams.append("requested_token_type", options.requestedTokenType);
    }
    if (options.organization) {
        tokenRequestParams.append("organization", options.organization);
    }
    if (options.actorToken) {
        tokenRequestParams.append("actor_token", options.actorToken);
    }
    if (options.actorTokenType) {
        tokenRequestParams.append("actor_token_type", options.actorTokenType);
    }
    appendExtraParams(tokenRequestParams, options.extra);
    if (capture) {
        var _configuration$client15;
        const baseFetch2 = (_configuration$client15 = configuration[customFetch$1]) !== null && _configuration$client15 !== void 0 ? _configuration$client15 : _classPrivateFieldGet2(_customFetch6, this);
        const capturingFetch2 = createCapturingFetch(baseFetch2);
        const captureConfig2 = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch2);
        let data, tokenEndpointResponse2, capturedResponse;
        try {
            tokenEndpointResponse2 = await genericGrantRequest(captureConfig2, TOKEN_EXCHANGE_GRANT_TYPE, tokenRequestParams);
            data = TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse2);
            capturedResponse = capturingFetch2.getCapturedResponse();
            if (!capturedResponse) {
                throw new MissingCapturedResponseError;
            }
        } catch (e) {
            if (e instanceof MissingCapturedResponseError) throw e;
            const err = new TokenExchangeError("Failed to exchange token of type '".concat(options.subjectTokenType, "'").concat(options.audience ? " for audience '".concat(options.audience, "'") : "", "."), toOAuth2Error(e));
            const _cap = capturingFetch2.getCapturedResponse();
            err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
            err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
            throw err;
        }
        _assertClassBrand(_Class19_brand, this, _finalizeProfileToken).call(this, data, tokenEndpointResponse2, options);
        return {
            data: data,
            response: capturedResponse
        };
    }
    const baseFetch = (_configuration$client16 = configuration[customFetch$1]) !== null && _configuration$client16 !== void 0 ? _configuration$client16 : _classPrivateFieldGet2(_customFetch6, this);
    const capturingFetch = createCapturingFetch(baseFetch);
    const captureConfig = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch);
    let tokenResponse;
    let tokenEndpointResponse;
    try {
        tokenEndpointResponse = await genericGrantRequest(captureConfig, TOKEN_EXCHANGE_GRANT_TYPE, tokenRequestParams);
        tokenResponse = TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
    } catch (e) {
        const err = new TokenExchangeError("Failed to exchange token of type '".concat(options.subjectTokenType, "'").concat(options.audience ? " for audience '".concat(options.audience, "'") : "", "."), toOAuth2Error(e));
        const _cap = capturingFetch.getCapturedResponse();
        err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
        err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
        throw err;
    }
    _assertClassBrand(_Class19_brand, this, _finalizeProfileToken).call(this, tokenResponse, tokenEndpointResponse, options);
    return tokenResponse;
}

async function _getTokenByPasswordlessOtp(params, requestOptions, capture) {
    var _configuration$client18;
    const _await$_assertClassBr19 = await _assertClassBrand(_Class19_brand, this, _discoverForRequest).call(this, requestOptions), configuration = _await$_assertClassBr19.configuration;
    if (capture) {
        var _configuration$client17;
        const baseFetch2 = (_configuration$client17 = configuration[customFetch$1]) !== null && _configuration$client17 !== void 0 ? _configuration$client17 : _classPrivateFieldGet2(_customFetch6, this);
        const capturingFetch2 = createCapturingFetch(baseFetch2);
        const captureConfig2 = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch2);
        try {
            const tokenEndpointResponse = await genericGrantRequest(captureConfig2, "http://auth0.com/oauth/grant-type/passwordless/otp", params);
            const data = TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
            const capturedResponse = capturingFetch2.getCapturedResponse();
            if (!capturedResponse) {
                throw new MissingCapturedResponseError;
            }
            return {
                data: data,
                response: capturedResponse
            };
        } catch (e) {
            if (e instanceof MissingCapturedResponseError) throw e;
            const err = new PasswordlessVerifyError("There was an error while trying to request a token.", toOAuth2Error(e));
            const _cap = capturingFetch2.getCapturedResponse();
            err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
            err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
            throw err;
        }
    }
    const baseFetch = (_configuration$client18 = configuration[customFetch$1]) !== null && _configuration$client18 !== void 0 ? _configuration$client18 : _classPrivateFieldGet2(_customFetch6, this);
    const capturingFetch = createCapturingFetch(baseFetch);
    const captureConfig = await _assertClassBrand(_Class19_brand, this, _createConfiguration).call(this, configuration.serverMetadata(), capturingFetch);
    try {
        const tokenEndpointResponse = await genericGrantRequest(captureConfig, "http://auth0.com/oauth/grant-type/passwordless/otp", params);
        return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);
    } catch (e) {
        const err = new PasswordlessVerifyError("There was an error while trying to request a token.", toOAuth2Error(e));
        const _cap = capturingFetch.getCapturedResponse();
        err.statusCode = _cap === null || _cap === void 0 ? void 0 : _cap.status;
        err.headers = _cap ? filterSensitiveHeaders(_cap.headers) : void 0;
        throw err;
    }
}

async function _getClientAuth() {
    let optional = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    const hasCredentials = !!_classPrivateFieldGet2(_options2, this).clientSecret || !!_classPrivateFieldGet2(_options2, this).clientAssertionSigningKey || !!_classPrivateFieldGet2(_options2, this).useMtls;
    if (optional && !hasCredentials) {
        return None();
    }
    if (!_classPrivateFieldGet2(_clientAuthPromise, this)) {
        _classPrivateFieldSet2(_clientAuthPromise, this, (async () => {
            if (!_classPrivateFieldGet2(_options2, this).clientSecret && !_classPrivateFieldGet2(_options2, this).clientAssertionSigningKey && !_classPrivateFieldGet2(_options2, this).useMtls) {
                throw new MissingClientAuthError;
            }
            if (_classPrivateFieldGet2(_options2, this).useMtls) {
                return TlsClientAuth();
            }
            let clientPrivateKey = _classPrivateFieldGet2(_options2, this).clientAssertionSigningKey;
            if (clientPrivateKey && !(clientPrivateKey instanceof CryptoKey)) {
                clientPrivateKey = await importPKCS8(clientPrivateKey, _classPrivateFieldGet2(_options2, this).clientAssertionSigningAlg || "RS256");
            }
            return clientPrivateKey ? PrivateKeyJwt(clientPrivateKey) : ClientSecretPost(_classPrivateFieldGet2(_options2, this).clientSecret);
        })().catch(error => {
            _classPrivateFieldSet2(_clientAuthPromise, this, void 0);
            throw error;
        }));
    }
    return _classPrivateFieldGet2(_clientAuthPromise, this);
}

async function _buildAuthorizationUrl(options) {
    const _await$_assertClassBr20 = await _assertClassBrand(_Class19_brand, this, _discover).call(this), configuration = _await$_assertClassBr20.configuration;
    const codeChallengeMethod = "S256";
    const codeVerifier = randomPKCECodeVerifier();
    const codeChallenge = await calculatePKCECodeChallenge(codeVerifier);
    const additionalParams = stripUndefinedProperties(_objectSpread2(_objectSpread2({}, _classPrivateFieldGet2(_options2, this).authorizationParams), options === null || options === void 0 ? void 0 : options.authorizationParams));
    const params = new URLSearchParams(_objectSpread2(_objectSpread2({
        scope: DEFAULT_SCOPES
    }, additionalParams), {}, {
        client_id: _classPrivateFieldGet2(_options2, this).clientId,
        code_challenge: codeChallenge,
        code_challenge_method: codeChallengeMethod
    }));
    const authorizationUrl = options !== null && options !== void 0 && options.pushedAuthorizationRequests ? await buildAuthorizationUrlWithPAR(configuration, params) : await buildAuthorizationUrl(configuration, params);
    return {
        authorizationUrl: authorizationUrl,
        codeVerifier: codeVerifier
    };
}

var cache = new LruCache(1e3, 6e4);

async function isFederatedDomain$1(auth0Domain, emailDomain, options) {
    const normalizedDomain = emailDomain.toLowerCase();
    const bareAuth0Domain = auth0Domain.replace(/^https?:\/\//, "");
    const key = "".concat(bareAuth0Domain, "|").concat(normalizedDomain);
    const cached = cache.get(key);
    if (cached !== void 0) return cached;
    try {
        var _options$customFetch6;
        const url = new URL("https://".concat(bareAuth0Domain, "/.well-known/webfinger"));
        url.searchParams.set("resource", "urn:auth0:discovery:domain:".concat(normalizedDomain));
        url.searchParams.set("rel", "http://openid.net/specs/connect/1.0/issuer");
        let fetchFn = (_options$customFetch6 = options === null || options === void 0 ? void 0 : options.customFetch) !== null && _options$customFetch6 !== void 0 ? _options$customFetch6 : globalThis.fetch;
        if (options !== null && options !== void 0 && options.telemetry && options.telemetry.enabled !== false) {
            fetchFn = createTelemetryFetch(fetchFn, options.telemetry);
        }
        const res = await fetchFn(url.toString());
        if (res.ok) {
            cache.set(key, true);
            return true;
        }
        if (res.status === 404) {
            cache.set(key, false, 15e3);
            return false;
        }
        if (res.status === 429) {
            console.warn("[Auth0] isFederatedDomain: rate limit hit (429)");
            return false;
        }
        return false;
    } catch (_unused9) {
        return false;
    }
}

class MfaError extends GenericError {
    constructor(error, error_description) {
        super(error, error_description);
        Object.setPrototypeOf(this, MfaError.prototype);
    }
    static fromPayload(_ref) {
        let error = _ref.error, error_description = _ref.error_description;
        return new MfaError(error, error_description);
    }
}

class MfaListAuthenticatorsError extends MfaError {
    constructor(error, error_description) {
        super(error, error_description);
        Object.setPrototypeOf(this, MfaListAuthenticatorsError.prototype);
    }
}

class MfaEnrollmentError extends MfaError {
    constructor(error, error_description) {
        super(error, error_description);
        Object.setPrototypeOf(this, MfaEnrollmentError.prototype);
    }
}

class MfaChallengeError extends MfaError {
    constructor(error, error_description) {
        super(error, error_description);
        Object.setPrototypeOf(this, MfaChallengeError.prototype);
    }
}

class MfaVerifyError extends MfaError {
    constructor(error, error_description) {
        super(error, error_description);
        Object.setPrototypeOf(this, MfaVerifyError.prototype);
    }
}

class MfaEnrollmentFactorsError extends MfaError {
    constructor(error, error_description) {
        super(error, error_description);
        Object.setPrototypeOf(this, MfaEnrollmentFactorsError.prototype);
    }
}

const DEFAULT_TTL_MS = 10 * 60 * 1e3;

class MfaContextManager {
    constructor() {
        let ttlMs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_TTL_MS;
        this.contexts = new Map;
        this.ttlMs = ttlMs;
    }
    set(mfaToken, context) {
        this.cleanup();
        this.contexts.set(mfaToken, Object.assign(Object.assign({}, context), {
            createdAt: Date.now()
        }));
    }
    get(mfaToken) {
        const context = this.contexts.get(mfaToken);
        if (!context) {
            return undefined;
        }
        if (Date.now() - context.createdAt > this.ttlMs) {
            this.contexts.delete(mfaToken);
            return undefined;
        }
        return context;
    }
    remove(mfaToken) {
        this.contexts.delete(mfaToken);
    }
    cleanup() {
        const now = Date.now();
        for (const _ref of this.contexts) {
            var _ref2 = _slicedToArray(_ref, 2);
            const key = _ref2[0];
            const value = _ref2[1];
            if (now - value.createdAt > this.ttlMs) {
                this.contexts.delete(key);
            }
        }
    }
    get size() {
        return this.contexts.size;
    }
}

class MfaApiClient {
    constructor(authJsMfaClient, auth0Client) {
        this.authJsMfaClient = authJsMfaClient;
        this.auth0Client = auth0Client;
        this.contextManager = new MfaContextManager;
    }
    setMFAAuthDetails(mfaToken, scope, audience, mfaRequirements) {
        this.contextManager.set(mfaToken, {
            scope: scope,
            audience: audience,
            mfaRequirements: mfaRequirements
        });
    }
    async getAuthenticators(mfaToken) {
        var _a, _b, _c;
        const context = this.contextManager.get(mfaToken);
        if (!context) {
            throw new MfaListAuthenticatorsError("invalid_request", "MFA context not found for this MFA token");
        }
        const challengeTypes = (_b = (_a = context.mfaRequirements) === null || _a === void 0 ? void 0 : _a.challenge) === null || _b === void 0 ? void 0 : _b.map(c => c.type);
        try {
            const allAuthenticators = await this.authJsMfaClient.listAuthenticators({
                mfaToken: mfaToken
            });
            if (!challengeTypes || challengeTypes.length === 0) {
                return allAuthenticators;
            }
            return allAuthenticators.filter(auth => {
                if (!auth.type) return false;
                return challengeTypes.includes(auth.type);
            });
        } catch (error) {
            if (error instanceof MfaListAuthenticatorsError$1) {
                throw new MfaListAuthenticatorsError((_c = error.cause) === null || _c === void 0 ? void 0 : _c.error, error.message);
            }
            throw error;
        }
    }
    async enroll(params) {
        var _a;
        const authJsParams = getAuthJsEnrollParams(params);
        try {
            return await this.authJsMfaClient.enrollAuthenticator(authJsParams);
        } catch (error) {
            if (error instanceof MfaEnrollmentError$1) {
                throw new MfaEnrollmentError((_a = error.cause) === null || _a === void 0 ? void 0 : _a.error, error.message);
            }
            throw error;
        }
    }
    async challenge(params) {
        var _a;
        try {
            const authJsParams = {
                challengeType: params.challengeType,
                mfaToken: params.mfaToken
            };
            if (params.authenticatorId) {
                authJsParams.authenticatorId = params.authenticatorId;
            }
            return await this.authJsMfaClient.challengeAuthenticator(authJsParams);
        } catch (error) {
            if (error instanceof MfaChallengeError$1) {
                throw new MfaChallengeError((_a = error.cause) === null || _a === void 0 ? void 0 : _a.error, error.message);
            }
            throw error;
        }
    }
    async getEnrollmentFactors(mfaToken) {
        const context = this.contextManager.get(mfaToken);
        if (!context || !context.mfaRequirements) {
            throw new MfaEnrollmentFactorsError("mfa_context_not_found", "MFA context not found for this MFA token. Please retry the original request to get a new MFA token.");
        }
        if (!context.mfaRequirements.enroll || context.mfaRequirements.enroll.length === 0) {
            return [];
        }
        return context.mfaRequirements.enroll;
    }
    async verify(params) {
        const context = this.contextManager.get(params.mfaToken);
        if (!context) {
            throw new MfaVerifyError("mfa_context_not_found", "MFA context not found for this MFA token. Please retry the original request to get a new MFA token.");
        }
        const grantType = getGrantType(params);
        if (!grantType) {
            throw new MfaVerifyError("invalid_request", "Unable to determine grant type. Provide one of: otp, oobCode, or recoveryCode.");
        }
        const scope = context.scope;
        const audience = context.audience;
        try {
            const result = await this.auth0Client._requestTokenForMfa({
                grant_type: grantType,
                mfaToken: params.mfaToken,
                scope: scope,
                audience: audience,
                otp: params.otp,
                oob_code: params.oobCode,
                binding_code: params.bindingCode,
                recovery_code: params.recoveryCode
            });
            this.contextManager.remove(params.mfaToken);
            return result;
        } catch (error) {
            if (error instanceof MfaVerifyError) {
                throw new MfaVerifyError(error.error, error.error_description);
            }
            throw error;
        }
    }
}

class PasskeyError extends Error {
    constructor(code, message, cause) {
        super(message);
        this.name = "PasskeyError";
        this.code = code;
        this.cause = cause;
        Object.setPrototypeOf(this, PasskeyError.prototype);
    }
}

var _PasskeyApiClient_passkeyClient, _PasskeyApiClient_auth0Client;

class PasskeyApiClient {
    constructor(passkeyClient, auth0Client) {
        _PasskeyApiClient_passkeyClient.set(this, void 0);
        _PasskeyApiClient_auth0Client.set(this, void 0);
        __classPrivateFieldSet(this, _PasskeyApiClient_passkeyClient, passkeyClient, "f");
        __classPrivateFieldSet(this, _PasskeyApiClient_auth0Client, auth0Client, "f");
    }
    async signup(options) {
        if (!window.PublicKeyCredential) {
            throw new PasskeyError("passkey_not_supported", "WebAuthn is not supported in this browser.");
        }
        const scope = options.scope, audience = options.audience, challengeOptions = __rest(options, [ "scope", "audience" ]);
        const challenge = await __classPrivateFieldGet(this, _PasskeyApiClient_passkeyClient, "f").register(challengeOptions);
        const publicKeyOptions = prepareCreationOptions(challenge.authnParamsPublicKey);
        const credential = await navigator.credentials.create({
            publicKey: publicKeyOptions
        });
        if (!credential) {
            throw new PasskeyError("passkey_cancelled", "Passkey creation was cancelled or no credential was returned.");
        }
        const serialized = serializeCreationCredential(credential);
        return __classPrivateFieldGet(this, _PasskeyApiClient_auth0Client, "f")._requestTokenForPasskey({
            authSession: challenge.authSession,
            credential: serialized,
            realm: challengeOptions.realm,
            organization: challengeOptions.organization,
            scope: scope,
            audience: audience
        });
    }
    async login(options) {
        if (!window.PublicKeyCredential) {
            throw new PasskeyError("passkey_not_supported", "WebAuthn is not supported in this browser.");
        }
        const _a = options || {}, scope = _a.scope, audience = _a.audience, challengeOptions = __rest(_a, [ "scope", "audience" ]);
        const challenge = await __classPrivateFieldGet(this, _PasskeyApiClient_passkeyClient, "f").challenge(Object.keys(challengeOptions).length > 0 ? challengeOptions : undefined);
        const publicKeyOptions = prepareRequestOptions(challenge.authnParamsPublicKey);
        const credential = await navigator.credentials.get({
            publicKey: publicKeyOptions
        });
        if (!credential) {
            throw new PasskeyError("passkey_cancelled", "Passkey authentication was cancelled or no credential was returned.");
        }
        const serialized = serializeAssertionCredential(credential);
        return __classPrivateFieldGet(this, _PasskeyApiClient_auth0Client, "f")._requestTokenForPasskey({
            authSession: challenge.authSession,
            credential: serialized,
            realm: challengeOptions.realm,
            organization: challengeOptions.organization,
            scope: scope,
            audience: audience
        });
    }
    async getSignupChallenge(options) {
        if (!window.PublicKeyCredential) {
            throw new PasskeyError("passkey_not_supported", "WebAuthn is not supported in this browser.");
        }
        const challenge = await __classPrivateFieldGet(this, _PasskeyApiClient_passkeyClient, "f").register(options);
        return {
            authSession: challenge.authSession,
            publicKey: prepareCreationOptions(challenge.authnParamsPublicKey)
        };
    }
    async getLoginChallenge(options) {
        if (!window.PublicKeyCredential) {
            throw new PasskeyError("passkey_not_supported", "WebAuthn is not supported in this browser.");
        }
        const challenge = await __classPrivateFieldGet(this, _PasskeyApiClient_passkeyClient, "f").challenge(options);
        return {
            authSession: challenge.authSession,
            publicKey: prepareRequestOptions(challenge.authnParamsPublicKey)
        };
    }
    async getTokenWithPasskey(options) {
        if (!window.PublicKeyCredential) {
            throw new PasskeyError("passkey_not_supported", "WebAuthn is not supported in this browser.");
        }
        const authSession = options.authSession, credential = options.credential, realm = options.realm, organization = options.organization, scope = options.scope, audience = options.audience;
        const response = credential.response;
        let serialized;
        if (response instanceof AuthenticatorAttestationResponse) {
            serialized = serializeCreationCredential(credential);
        } else if (response instanceof AuthenticatorAssertionResponse) {
            serialized = serializeAssertionCredential(credential);
        } else {
            throw new PasskeyError("passkey_invalid_credential", "The provided credential is not a valid attestation or assertion response.");
        }
        return __classPrivateFieldGet(this, _PasskeyApiClient_auth0Client, "f")._requestTokenForPasskey({
            authSession: authSession,
            credential: serialized,
            realm: realm,
            organization: organization,
            scope: scope,
            audience: audience
        });
    }
}

_PasskeyApiClient_passkeyClient = new WeakMap, _PasskeyApiClient_auth0Client = new WeakMap;

function bufferToBase64url(buffer) {
    const bytes = new Uint8Array(buffer);
    const binary = Array.from(bytes, b => String.fromCharCode(b)).join("");
    return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}

function base64urlToBuffer(base64url) {
    const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/");
    const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
    const binary = atob(padded);
    const bytes = new Uint8Array(binary.length);
    for (let i = 0; i < binary.length; i++) {
        bytes[i] = binary.charCodeAt(i);
    }
    return bytes.buffer;
}

function prepareCreationOptions(publicKey) {
    return Object.assign(Object.assign({}, publicKey), {
        challenge: base64urlToBuffer(publicKey.challenge),
        user: Object.assign(Object.assign({}, publicKey.user), {
            id: base64urlToBuffer(publicKey.user.id)
        }),
        pubKeyCredParams: publicKey.pubKeyCredParams,
        authenticatorSelection: publicKey.authenticatorSelection
    });
}

function prepareRequestOptions(publicKey) {
    return Object.assign(Object.assign({}, publicKey), {
        challenge: base64urlToBuffer(publicKey.challenge)
    });
}

function serializeCreationCredential(credential) {
    var _a;
    const response = credential.response;
    return {
        id: credential.id,
        rawId: bufferToBase64url(credential.rawId),
        type: credential.type,
        authenticatorAttachment: (_a = credential.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined,
        response: {
            clientDataJSON: bufferToBase64url(response.clientDataJSON),
            attestationObject: bufferToBase64url(response.attestationObject)
        },
        clientExtensionResults: credential.getClientExtensionResults()
    };
}

function serializeAssertionCredential(credential) {
    var _a;
    const response = credential.response;
    return {
        id: credential.id,
        rawId: bufferToBase64url(credential.rawId),
        type: credential.type,
        authenticatorAttachment: (_a = credential.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined,
        response: {
            clientDataJSON: bufferToBase64url(response.clientDataJSON),
            authenticatorData: bufferToBase64url(response.authenticatorData),
            signature: bufferToBase64url(response.signature),
            userHandle: response.userHandle ? bufferToBase64url(response.userHandle) : undefined
        },
        clientExtensionResults: credential.getClientExtensionResults()
    };
}

class Auth0Client {
    resolveOnlineAccess(options) {
        if (options.refreshTokenMode !== "online") {
            return false;
        }
        if (options.useRefreshTokens !== true) {
            throw new InvalidConfigurationError('`refreshTokenMode: "online"` requires the refresh-token grant.', "Set `useRefreshTokens: true`.");
        }
        if (options.useDpop !== true) {
            throw new InvalidConfigurationError('`refreshTokenMode: "online"` requires DPoP, which is missing or disabled.', "Set `useDpop: true` (DPoP is mandatory for online access).");
        }
        return true;
    }
    warnEnterpriseConnectConfig(options) {
        var _a, _b;
        if (options.enterpriseConnect !== true) {
            return;
        }
        const scope = (_a = options.authorizationParams) === null || _a === void 0 ? void 0 : _a.scope;
        if (options.useRefreshTokens === true || typeof scope === "string" && scope.includes("offline_access")) {
            console.warn("Enterprise Connect issues no refresh token; `useRefreshTokens` and `offline_access` in `scope` have no effect.");
        }
        if ((_b = options.authorizationParams) === null || _b === void 0 ? void 0 : _b.organization) {
            console.warn("Enterprise Connect resolves the organization from the email domain (Home Realm Discovery); a static `organization` breaks multi-customer setups.");
        }
    }
    constructor(options) {
        this.userCache = (new InMemoryCache).enclosedCache;
        this.defaultOptions = {
            authorizationParams: {
                scope: DEFAULT_SCOPE
            },
            useRefreshTokensFallback: false,
            useFormData: true,
            refreshTokenMode: "offline"
        };
        this.onlineAccess = this.resolveOnlineAccess(options);
        this.warnEnterpriseConnectConfig(options);
        this.options = Object.assign(Object.assign(Object.assign({}, this.defaultOptions), options), {
            authorizationParams: Object.assign(Object.assign({}, this.defaultOptions.authorizationParams), options.authorizationParams)
        });
        typeof window !== "undefined" && validateCrypto();
        this.lockManager = getLockManager();
        if (options.cache && options.cacheLocation) {
            console.warn("Both `cache` and `cacheLocation` options have been specified in the Auth0Client configuration; ignoring `cacheLocation` and using `cache`.");
        }
        let cacheLocation;
        let cache;
        if (options.cache) {
            cache = options.cache;
        } else {
            cacheLocation = options.cacheLocation || CACHE_LOCATION_MEMORY;
            if (!cacheFactory(cacheLocation)) {
                throw new Error('Invalid cache location "'.concat(cacheLocation, '"'));
            }
            cache = cacheFactory(cacheLocation)();
        }
        this.httpTimeoutMs = options.httpTimeoutInSeconds ? options.httpTimeoutInSeconds * 1e3 : DEFAULT_FETCH_TIMEOUT_MS;
        this.cookieStorage = options.legacySameSiteCookie === false ? CookieStorage : CookieStorageWithLegacySameSite;
        this.orgHintCookieName = buildOrganizationHintCookieName(this.options.clientId);
        this.isAuthenticatedCookieName = buildIsAuthenticatedCookieName(this.options.clientId);
        this.sessionCheckExpiryDays = options.sessionCheckExpiryDays || DEFAULT_SESSION_CHECK_EXPIRY_DAYS;
        const transactionStorage = options.useCookiesForTransactions ? this.cookieStorage : SessionStorage;
        let sessionScope = "";
        if (this.onlineAccess) {
            sessionScope = ONLINE_ACCESS_SCOPE;
        } else if (this.options.useRefreshTokens) {
            sessionScope = "offline_access";
        }
        this.scope = injectDefaultScopes(this.options.authorizationParams.scope, "openid", sessionScope);
        this.transactionManager = new TransactionManager(transactionStorage, this.options.clientId, this.options.cookieDomain);
        this.nowProvider = this.options.nowProvider || DEFAULT_NOW_PROVIDER;
        this.cacheManager = new CacheManager(cache, !cache.allKeys ? new CacheKeyManifest(cache, this.options.clientId) : undefined, this.nowProvider);
        this.dpop = this.options.useDpop ? new Dpop(this.options.clientId) : undefined;
        this.domainUrl = getDomain(this.options.domain);
        this.tokenIssuer = getTokenIssuer(this.options.issuer, this.domainUrl);
        const myAccountApiIdentifier = "".concat(this.domainUrl, "/me/");
        const myAccountFetcher = this.createFetcher(Object.assign(Object.assign({}, this.options.useDpop && {
            dpopNonceId: "__auth0_my_account_api__"
        }), {
            getAccessToken: authParams => {
                var _a;
                return this.getTokenSilently({
                    authorizationParams: {
                        scope: (_a = authParams === null || authParams === void 0 ? void 0 : authParams.scope) === null || _a === void 0 ? void 0 : _a.join(" "),
                        audience: myAccountApiIdentifier
                    },
                    detailedResponse: true
                });
            }
        }));
        this.myAccount = new MyAccountApiClient(myAccountFetcher, myAccountApiIdentifier);
        this.authJsClient = new AuthClient({
            domain: this.options.domain,
            clientId: this.options.clientId
        });
        this.mfa = new MfaApiClient(this.authJsClient.mfa, this);
        this.passkey = new PasskeyApiClient(this.authJsClient.passkey, this);
        if (typeof window !== "undefined" && window.Worker && this.options.useRefreshTokens && cacheLocation === CACHE_LOCATION_MEMORY) {
            if (this.options.workerUrl) {
                this.worker = new Worker(this.options.workerUrl);
            } else {
                this.worker = new WorkerFactory;
            }
            this.worker.postMessage({
                type: "init",
                allowedBaseUrl: this.domainUrl
            });
        }
    }
    getConfiguration() {
        return Object.freeze({
            domain: this.options.domain,
            clientId: this.options.clientId
        });
    }
    _url(path) {
        const auth0ClientObj = this.options.auth0Client || DEFAULT_AUTH0_CLIENT;
        const strippedAuth0Client = stripAuth0Client(auth0ClientObj, true);
        const auth0Client = encodeURIComponent(btoa(JSON.stringify(strippedAuth0Client)));
        return "".concat(this.domainUrl).concat(path, "&auth0Client=").concat(auth0Client);
    }
    _authorizeUrl(authorizeOptions) {
        return this._url("/authorize?".concat(createQueryParams(authorizeOptions)));
    }
    async _verifyIdToken(id_token, nonce, organization) {
        const now = await this.nowProvider();
        return verify$1({
            iss: this.tokenIssuer,
            aud: this.options.clientId,
            id_token: id_token,
            nonce: nonce,
            organization: organization,
            leeway: this.options.leeway,
            max_age: parseNumber(this.options.authorizationParams.max_age),
            now: now
        });
    }
    _processOrgHint(organization) {
        if (organization) {
            this.cookieStorage.save(this.orgHintCookieName, organization, {
                daysUntilExpire: this.sessionCheckExpiryDays,
                cookieDomain: this.options.cookieDomain
            });
        } else {
            this.cookieStorage.remove(this.orgHintCookieName, {
                cookieDomain: this.options.cookieDomain
            });
        }
    }
    _extractSessionTransferToken(paramName) {
        const params = new URLSearchParams(window.location.search);
        return params.get(paramName) || undefined;
    }
    _clearSessionTransferTokenFromUrl(paramName) {
        try {
            const url = new URL(window.location.href);
            if (url.searchParams.has(paramName)) {
                url.searchParams.delete(paramName);
                window.history.replaceState({}, "", url.toString());
            }
        } catch (_a) {}
    }
    _applySessionTransferToken(authorizationParams) {
        const paramName = this.options.sessionTransferTokenQueryParamName;
        if (!paramName || authorizationParams.session_transfer_token) {
            return authorizationParams;
        }
        const token = this._extractSessionTransferToken(paramName);
        if (!token) return authorizationParams;
        this._clearSessionTransferTokenFromUrl(paramName);
        return Object.assign(Object.assign({}, authorizationParams), {
            session_transfer_token: token
        });
    }
    async _prepareAuthorizeUrl(authorizationParams, authorizeOptions, fallbackRedirectUri) {
        var _a;
        const state = encode$3(createRandomString());
        const nonce = encode$3(createRandomString());
        const code_verifier = createRandomString();
        const code_challengeBuffer = await sha256(code_verifier);
        const code_challenge = bufferToBase64UrlEncoded(code_challengeBuffer);
        const thumbprint = await ((_a = this.dpop) === null || _a === void 0 ? void 0 : _a.calculateThumbprint());
        const params = getAuthorizeParams(this.options, this.scope, authorizationParams, state, nonce, code_challenge, authorizationParams.redirect_uri || this.options.authorizationParams.redirect_uri || fallbackRedirectUri, authorizeOptions === null || authorizeOptions === void 0 ? void 0 : authorizeOptions.response_mode, thumbprint);
        const url = this._authorizeUrl(params);
        return {
            nonce: nonce,
            code_verifier: code_verifier,
            scope: params.scope,
            audience: params.audience || DEFAULT_AUDIENCE,
            redirect_uri: params.redirect_uri,
            state: state,
            url: url
        };
    }
    async loginWithPopup(options, config) {
        var _a;
        options = options || {};
        config = config || {};
        if (!config.popup) {
            config.popup = openPopup("");
            if (!config.popup) {
                throw new PopupOpenError;
            }
        }
        const authorizationParams = this._applySessionTransferToken(options.authorizationParams || {});
        const params = await this._prepareAuthorizeUrl(authorizationParams, {
            response_mode: "web_message"
        }, window.location.origin);
        config.popup.location.href = params.url;
        const codeResult = await runPopup(Object.assign(Object.assign({}, config), {
            timeoutInSeconds: config.timeoutInSeconds || this.options.authorizeTimeoutInSeconds || DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS
        }), new URL(params.url).origin);
        if (params.state !== codeResult.state) {
            throw new GenericError("state_mismatch", "Invalid state");
        }
        const organization = ((_a = options.authorizationParams) === null || _a === void 0 ? void 0 : _a.organization) || this.options.authorizationParams.organization;
        await this._requestToken({
            audience: params.audience,
            scope: params.scope,
            code_verifier: params.code_verifier,
            grant_type: "authorization_code",
            code: codeResult.code,
            redirect_uri: params.redirect_uri
        }, {
            nonceIn: params.nonce,
            organization: organization
        });
    }
    async getUser() {
        var _a;
        if (await this._isSessionCeilingReached()) {
            return undefined;
        }
        const cache = await this._getIdTokenFromCache();
        return (_a = cache === null || cache === void 0 ? void 0 : cache.decodedToken) === null || _a === void 0 ? void 0 : _a.user;
    }
    async getIdTokenClaims() {
        var _a;
        if (await this._isSessionCeilingReached()) {
            return undefined;
        }
        const cache = await this._getIdTokenFromCache();
        return (_a = cache === null || cache === void 0 ? void 0 : cache.decodedToken) === null || _a === void 0 ? void 0 : _a.claims;
    }
    async loginWithRedirect() {
        let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        var _a;
        const _b = patchOpenUrlWithOnRedirect(options), openUrl = _b.openUrl, fragment = _b.fragment, appState = _b.appState, urlOptions = __rest(_b, [ "openUrl", "fragment", "appState" ]);
        const organization = ((_a = urlOptions.authorizationParams) === null || _a === void 0 ? void 0 : _a.organization) || this.options.authorizationParams.organization;
        const authorizationParams = this._applySessionTransferToken(urlOptions.authorizationParams || {});
        const _c = await this._prepareAuthorizeUrl(authorizationParams), url = _c.url, transaction = __rest(_c, [ "url" ]);
        this.transactionManager.create(Object.assign(Object.assign(Object.assign({}, transaction), {
            appState: appState,
            response_type: exports.ResponseType.Code
        }), organization && {
            organization: organization
        }));
        const urlWithFragment = fragment ? "".concat(url, "#").concat(fragment) : url;
        if (openUrl) {
            await openUrl(urlWithFragment);
        } else {
            window.location.assign(urlWithFragment);
        }
    }
    async handleRedirectCallback() {
        let url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window.location.href;
        const queryStringFragments = url.split("?").slice(1);
        if (queryStringFragments.length === 0) {
            throw new Error("There are no query params available for parsing.");
        }
        const transaction = this.transactionManager.get();
        if (!transaction) {
            throw new GenericError("missing_transaction", "Invalid state");
        }
        this.transactionManager.remove();
        const authenticationResult = parseAuthenticationResult(queryStringFragments.join(""));
        if (transaction.response_type === exports.ResponseType.ConnectCode) {
            return this._handleConnectAccountRedirectCallback(authenticationResult, transaction);
        }
        return this._handleLoginRedirectCallback(authenticationResult, transaction);
    }
    async _handleLoginRedirectCallback(authenticationResult, transaction) {
        const code = authenticationResult.code, state = authenticationResult.state, error = authenticationResult.error, error_description = authenticationResult.error_description;
        if (error) {
            throw new AuthenticationError(error, error_description || error, state, transaction.appState);
        }
        if (!transaction.code_verifier || transaction.state && transaction.state !== state) {
            throw new GenericError("state_mismatch", "Invalid state");
        }
        const organization = transaction.organization;
        const nonceIn = transaction.nonce;
        const redirect_uri = transaction.redirect_uri;
        await this._requestToken(Object.assign({
            audience: transaction.audience,
            scope: transaction.scope,
            code_verifier: transaction.code_verifier,
            grant_type: "authorization_code",
            code: code
        }, redirect_uri ? {
            redirect_uri: redirect_uri
        } : {}), {
            nonceIn: nonceIn,
            organization: organization
        });
        return {
            appState: transaction.appState,
            response_type: exports.ResponseType.Code
        };
    }
    async _handleConnectAccountRedirectCallback(connectResult, transaction) {
        const connect_code = connectResult.connect_code, state = connectResult.state, error = connectResult.error, error_description = connectResult.error_description;
        if (error) {
            throw new ConnectError(error, error_description || error, transaction.connection, state, transaction.appState);
        }
        if (!connect_code) {
            throw new GenericError("missing_connect_code", "Missing connect code");
        }
        if (!transaction.code_verifier || !transaction.state || !transaction.auth_session || !transaction.redirect_uri || transaction.state !== state) {
            throw new GenericError("state_mismatch", "Invalid state");
        }
        const data = await this.myAccount.completeAccount({
            auth_session: transaction.auth_session,
            connect_code: connect_code,
            redirect_uri: transaction.redirect_uri,
            code_verifier: transaction.code_verifier
        });
        return Object.assign(Object.assign({}, data), {
            appState: transaction.appState,
            response_type: exports.ResponseType.ConnectCode
        });
    }
    async checkSession(options) {
        if (!this.cookieStorage.get(this.isAuthenticatedCookieName)) {
            if (!this.cookieStorage.get(OLD_IS_AUTHENTICATED_COOKIE_NAME)) {
                return;
            } else {
                this.cookieStorage.save(this.isAuthenticatedCookieName, true, {
                    daysUntilExpire: this.sessionCheckExpiryDays,
                    cookieDomain: this.options.cookieDomain
                });
                this.cookieStorage.remove(OLD_IS_AUTHENTICATED_COOKIE_NAME);
            }
        }
        try {
            await this.getTokenSilently(options);
        } catch (_) {}
    }
    async getTokenSilently() {
        let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        var _a, _b;
        const localOptions = Object.assign(Object.assign({
            cacheMode: "on"
        }, options), {
            authorizationParams: Object.assign(Object.assign(Object.assign({}, this.options.authorizationParams), options.authorizationParams), {
                scope: scopesToRequest(this.scope, (_a = options.authorizationParams) === null || _a === void 0 ? void 0 : _a.scope, ((_b = options.authorizationParams) === null || _b === void 0 ? void 0 : _b.audience) || this.options.authorizationParams.audience)
            })
        });
        const result = await this._getTokenSilently(localOptions);
        return options.detailedResponse ? result : result === null || result === void 0 ? void 0 : result.access_token;
    }
    async _getTokenSilently(options) {
        const cacheMode = options.cacheMode, getTokenOptions = __rest(options, [ "cacheMode" ]);
        if (await this._isSessionCeilingReached()) {
            return undefined;
        }
        if (cacheMode !== "off") {
            const entry = await this._getEntryFromCache({
                scope: getTokenOptions.authorizationParams.scope,
                audience: getTokenOptions.authorizationParams.audience || DEFAULT_AUDIENCE,
                clientId: this.options.clientId,
                cacheMode: cacheMode
            });
            if (entry) {
                return entry;
            }
        }
        if (cacheMode === "cache-only") {
            return;
        }
        const lockKey = buildGetTokenSilentlyLockKey(this.options.clientId, getTokenOptions.authorizationParams.audience || "default");
        try {
            return await this.lockManager.runWithLock(lockKey, 5e3, async () => {
                if (cacheMode !== "off") {
                    const entry = await this._getEntryFromCache({
                        scope: getTokenOptions.authorizationParams.scope,
                        audience: getTokenOptions.authorizationParams.audience || DEFAULT_AUDIENCE,
                        clientId: this.options.clientId
                    });
                    if (entry) {
                        return entry;
                    }
                }
                const authResult = this.options.useRefreshTokens ? await this._getTokenUsingRefreshToken(getTokenOptions) : await this._getTokenFromIFrame(getTokenOptions);
                const id_token = authResult.id_token, token_type = authResult.token_type, access_token = authResult.access_token, oauthTokenScope = authResult.oauthTokenScope, expires_in = authResult.expires_in;
                return Object.assign(Object.assign({
                    id_token: id_token,
                    token_type: token_type,
                    access_token: access_token
                }, oauthTokenScope ? {
                    scope: oauthTokenScope
                } : null), {
                    expires_in: expires_in
                });
            });
        } catch (error) {
            if (this._isInteractiveError(error) && this.options.interactiveErrorHandler === "popup") {
                return await this._handleInteractiveErrorWithPopup(getTokenOptions);
            }
            throw error;
        }
    }
    _isInteractiveError(error) {
        return error instanceof MfaRequiredError || error instanceof GenericError && this._isIframeMfaError(error);
    }
    _isIframeMfaError(error) {
        return error.error === "login_required" && error.error_description === MFA_STEP_UP_ERROR_DESCRIPTION;
    }
    async _handleInteractiveErrorWithPopup(options) {
        try {
            await this.loginWithPopup({
                authorizationParams: options.authorizationParams
            });
            const entry = await this._getEntryFromCache({
                scope: options.authorizationParams.scope,
                audience: options.authorizationParams.audience || DEFAULT_AUDIENCE,
                clientId: this.options.clientId
            });
            if (!entry) {
                throw new GenericError("interactive_handler_cache_miss", "Token not found in cache after interactive authentication");
            }
            return entry;
        } catch (error) {
            throw error;
        }
    }
    async getTokenWithPopup() {
        let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
        var _a, _b;
        const localOptions = Object.assign(Object.assign({}, options), {
            authorizationParams: Object.assign(Object.assign(Object.assign({}, this.options.authorizationParams), options.authorizationParams), {
                scope: scopesToRequest(this.scope, (_a = options.authorizationParams) === null || _a === void 0 ? void 0 : _a.scope, ((_b = options.authorizationParams) === null || _b === void 0 ? void 0 : _b.audience) || this.options.authorizationParams.audience)
            })
        });
        config = Object.assign(Object.assign({}, DEFAULT_POPUP_CONFIG_OPTIONS), config);
        await this.loginWithPopup(localOptions, config);
        const cache = await this.cacheManager.get(new CacheKey({
            scope: localOptions.authorizationParams.scope,
            audience: localOptions.authorizationParams.audience || DEFAULT_AUDIENCE,
            clientId: this.options.clientId
        }), undefined, this.options.useMrrt);
        return cache.access_token;
    }
    async isAuthenticated() {
        const user = await this.getUser();
        return !!user;
    }
    _buildLogoutUrl(options) {
        if (options.clientId !== null) {
            options.clientId = options.clientId || this.options.clientId;
        } else {
            delete options.clientId;
        }
        const _a = options.logoutParams || {}, federated = _a.federated, logoutOptions = __rest(_a, [ "federated" ]);
        const federatedQuery = federated ? "&federated" : "";
        const url = this._url("/v2/logout?".concat(createQueryParams(Object.assign({
            clientId: options.clientId
        }, logoutOptions))));
        return url + federatedQuery;
    }
    async revokeRefreshToken() {
        let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        if (!this.options.useRefreshTokens) {
            return;
        }
        const audience = options.audience || this.options.authorizationParams.audience;
        const resolvedAudience = audience || DEFAULT_AUDIENCE;
        const refreshTokens = await this.cacheManager.getRefreshTokensByAudience(resolvedAudience, this.options.clientId);
        await revokeToken({
            baseUrl: this.domainUrl,
            timeout: this.httpTimeoutMs,
            auth0Client: this.options.auth0Client,
            useFormData: this.options.useFormData,
            client_id: this.options.clientId,
            refreshTokens: refreshTokens,
            audience: resolvedAudience,
            onRefreshTokenRevoked: refreshToken => this.cacheManager.stripRefreshToken(refreshToken)
        }, this.worker);
        if (this.onlineAccess) {
            await this._clearLocalSession();
        }
    }
    async logout() {
        let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        var _a;
        if (this.options.enterpriseConnect && ((_a = options.logoutParams) === null || _a === void 0 ? void 0 : _a.federated) !== true) {
            console.warn("Enterprise Connect logout without `federated: true` leaves the enterprise IdP session alive; the next login may silently reuse the previous user.");
        }
        const _b = patchOpenUrlWithOnRedirect(options), openUrl = _b.openUrl, logoutOptions = __rest(_b, [ "openUrl" ]);
        await this._clearLocalSession(options.clientId);
        const url = this._buildLogoutUrl(logoutOptions);
        if (openUrl) {
            await openUrl(url);
        } else if (openUrl !== false) {
            window.location.assign(url);
        }
    }
    async _getTokenFromIFrame(options) {
        const iframeLockKey = buildIframeLockKey(this.options.clientId);
        try {
            return await this.lockManager.runWithLock(iframeLockKey, 5e3, async () => {
                const params = Object.assign(Object.assign({}, options.authorizationParams), {
                    prompt: "none"
                });
                const orgHint = this.cookieStorage.get(this.orgHintCookieName);
                if (orgHint && !params.organization) {
                    params.organization = orgHint;
                }
                const _await$this$_prepareA = await this._prepareAuthorizeUrl(params, {
                    response_mode: "web_message"
                }, window.location.origin), url = _await$this$_prepareA.url, stateIn = _await$this$_prepareA.state, nonceIn = _await$this$_prepareA.nonce, code_verifier = _await$this$_prepareA.code_verifier, redirect_uri = _await$this$_prepareA.redirect_uri, scope = _await$this$_prepareA.scope, audience = _await$this$_prepareA.audience;
                if (window.crossOriginIsolated) {
                    throw new GenericError("login_required", "The application is running in a Cross-Origin Isolated context, silently retrieving a token without refresh token is not possible.");
                }
                const authorizeTimeout = options.timeoutInSeconds || this.options.authorizeTimeoutInSeconds;
                let eventOrigin;
                try {
                    eventOrigin = new URL(this.domainUrl).origin;
                } catch (_a) {
                    eventOrigin = this.domainUrl;
                }
                const codeResult = await runIframe(url, eventOrigin, authorizeTimeout);
                if (stateIn !== codeResult.state) {
                    throw new GenericError("state_mismatch", "Invalid state");
                }
                const tokenResult = await this._requestToken(Object.assign(Object.assign({}, options.authorizationParams), {
                    code_verifier: code_verifier,
                    code: codeResult.code,
                    grant_type: "authorization_code",
                    redirect_uri: redirect_uri,
                    timeout: options.authorizationParams.timeout || this.httpTimeoutMs
                }), {
                    nonceIn: nonceIn,
                    organization: params.organization
                });
                return Object.assign(Object.assign({}, tokenResult), {
                    scope: scope,
                    oauthTokenScope: tokenResult.scope,
                    audience: audience
                });
            });
        } catch (e) {
            if (e.error === "login_required") {
                const shouldSkipLogoutForMfaStepUp = e instanceof GenericError && this._isIframeMfaError(e) && this.options.interactiveErrorHandler === "popup";
                if (!shouldSkipLogoutForMfaStepUp) {
                    this.logout({
                        openUrl: false
                    });
                }
            }
            throw e;
        }
    }
    async _getTokenUsingRefreshToken(options) {
        const cache = await this.cacheManager.get(new CacheKey({
            scope: options.authorizationParams.scope,
            audience: options.authorizationParams.audience || DEFAULT_AUDIENCE,
            clientId: this.options.clientId
        }), undefined, this.options.useMrrt);
        if ((!cache || !cache.refresh_token) && !this.worker) {
            if (this.options.useRefreshTokensFallback) {
                return await this._getTokenFromIFrame(options);
            }
            throw new MissingRefreshTokenError(options.authorizationParams.audience || DEFAULT_AUDIENCE, options.authorizationParams.scope);
        }
        const redirect_uri = options.authorizationParams.redirect_uri || this.options.authorizationParams.redirect_uri || window.location.origin;
        const timeout = typeof options.timeoutInSeconds === "number" ? options.timeoutInSeconds * 1e3 : null;
        const scopesToRequest = getScopeToRequest(this.options.useMrrt, options.authorizationParams, cache === null || cache === void 0 ? void 0 : cache.audience, cache === null || cache === void 0 ? void 0 : cache.scope);
        try {
            const tokenResult = await this._requestToken(Object.assign(Object.assign(Object.assign({}, options.authorizationParams), {
                grant_type: "refresh_token",
                refresh_token: cache && cache.refresh_token,
                redirect_uri: redirect_uri
            }), timeout && {
                timeout: timeout
            }), {
                scopesToRequest: scopesToRequest
            });
            await this._propagateRotatedRefreshToken(cache === null || cache === void 0 ? void 0 : cache.refresh_token, tokenResult.refresh_token);
            if (this.options.useMrrt) {
                const isRefreshMrrt = isRefreshWithMrrt(cache === null || cache === void 0 ? void 0 : cache.audience, cache === null || cache === void 0 ? void 0 : cache.scope, options.authorizationParams.audience, options.authorizationParams.scope);
                if (isRefreshMrrt) {
                    const missingScopes = getMissingScopes(scopesToRequest, tokenResult.scope, this.onlineAccess);
                    if (missingScopes) {
                        if (this.options.useRefreshTokensFallback) {
                            return await this._getTokenFromIFrame(options);
                        }
                        await this.cacheManager.remove(this.options.clientId, options.authorizationParams.audience, options.authorizationParams.scope);
                        throw new MissingScopesError(options.authorizationParams.audience || "default", missingScopes);
                    }
                }
            }
            return Object.assign(Object.assign({}, tokenResult), {
                scope: options.authorizationParams.scope,
                oauthTokenScope: tokenResult.scope,
                audience: options.authorizationParams.audience || DEFAULT_AUDIENCE
            });
        } catch (e) {
            if (e.message) {
                if (e.message.includes(USER_BLOCKED_ERROR_MESSAGE)) {
                    await this.logout({
                        openUrl: false
                    });
                    throw e;
                }
                if ((e.message.includes(MISSING_REFRESH_TOKEN_ERROR_MESSAGE) || e.message.includes(INVALID_REFRESH_TOKEN_ERROR_MESSAGE)) && this.options.useRefreshTokensFallback) {
                    return await this._getTokenFromIFrame(options);
                }
            }
            throw e;
        }
    }
    async _propagateRotatedRefreshToken(previousRefreshToken, newRefreshToken) {
        if (this.onlineAccess || !newRefreshToken || !previousRefreshToken) {
            return;
        }
        await this.cacheManager.updateEntry(previousRefreshToken, newRefreshToken, this.options.clientId, this.options.useMrrt);
    }
    async _saveEntryInCache(entry) {
        const _entry$decodedToken$c = entry.decodedToken.claims, session_expiry = _entry$decodedToken$c.session_expiry, iat = _entry$decodedToken$c.iat;
        if (session_expiry !== undefined) {
            if (typeof session_expiry !== "number") {
                throw new GenericError("invalid_token", "Invalid session_expiry: value must be a number.");
            }
            if (session_expiry >= 1e10) {
                throw new GenericError("invalid_token", "Invalid session_expiry: value appears to be in milliseconds; expected a Unix timestamp in seconds.");
            }
            if (iat === undefined || session_expiry <= iat) {
                throw new GenericError("invalid_token", "Invalid session_expiry: session ceiling is before or at the token issue time.");
            }
        }
        const id_token = entry.id_token, decodedToken = entry.decodedToken, entryWithoutIdToken = __rest(entry, [ "id_token", "decodedToken" ]);
        this.userCache.set(CACHE_KEY_ID_TOKEN_SUFFIX, {
            id_token: id_token,
            decodedToken: decodedToken
        });
        await this.cacheManager.setIdToken(this.options.clientId, entry.id_token, entry.decodedToken);
        await this.cacheManager.set(entryWithoutIdToken);
    }
    async _clearLocalSession() {
        let clientId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.options.clientId;
        var _a;
        if (clientId === null) {
            await this.cacheManager.clear();
        } else {
            await this.cacheManager.clear(clientId);
        }
        this.cookieStorage.remove(this.orgHintCookieName, {
            cookieDomain: this.options.cookieDomain
        });
        this.cookieStorage.remove(this.isAuthenticatedCookieName, {
            cookieDomain: this.options.cookieDomain
        });
        this.userCache.remove(CACHE_KEY_ID_TOKEN_SUFFIX);
        try {
            await ((_a = this.dpop) === null || _a === void 0 ? void 0 : _a.clear());
        } catch (_b) {}
        if (this.worker) {
            try {
                await sendMessage({
                    type: "clear"
                }, this.worker);
            } catch (_c) {}
        }
    }
    async _isSessionCeilingReached() {
        var _a, _b;
        const inMemory = this.userCache.get(CACHE_KEY_ID_TOKEN_SUFFIX);
        const idTokenEntry = inMemory !== null && inMemory !== void 0 ? inMemory : await this.cacheManager.getIdToken(new CacheKey({
            clientId: this.options.clientId
        }));
        const sessionExpiresAt = (_b = (_a = idTokenEntry === null || idTokenEntry === void 0 ? void 0 : idTokenEntry.decodedToken) === null || _a === void 0 ? void 0 : _a.claims) === null || _b === void 0 ? void 0 : _b.session_expiry;
        if (sessionExpiresAt === undefined) return false;
        const now = await this.nowProvider();
        const nowSeconds = Math.floor(now / 1e3);
        if (nowSeconds >= sessionExpiresAt - SESSION_EXPIRY_LEEWAY_SECONDS) {
            await this._clearLocalSession();
            return true;
        }
        return false;
    }
    async _getIdTokenFromCache() {
        const audience = this.options.authorizationParams.audience || DEFAULT_AUDIENCE;
        const scope = this.scope[audience];
        const cache = await this.cacheManager.getIdToken(new CacheKey({
            clientId: this.options.clientId,
            audience: audience,
            scope: scope
        }));
        const currentCache = this.userCache.get(CACHE_KEY_ID_TOKEN_SUFFIX);
        if (cache && cache.id_token === (currentCache === null || currentCache === void 0 ? void 0 : currentCache.id_token)) {
            return currentCache;
        }
        this.userCache.set(CACHE_KEY_ID_TOKEN_SUFFIX, cache);
        return cache;
    }
    async _getEntryFromCache(_ref) {
        let scope = _ref.scope, audience = _ref.audience, clientId = _ref.clientId, cacheMode = _ref.cacheMode;
        const entry = await this.cacheManager.get(new CacheKey({
            scope: scope,
            audience: audience,
            clientId: clientId
        }), 60, this.options.useMrrt, cacheMode);
        if (entry && entry.access_token) {
            const token_type = entry.token_type, access_token = entry.access_token, oauthTokenScope = entry.oauthTokenScope, expires_in = entry.expires_in;
            const cache = await this._getIdTokenFromCache();
            return cache && Object.assign(Object.assign({
                id_token: cache.id_token,
                token_type: token_type ? token_type : "Bearer",
                access_token: access_token
            }, oauthTokenScope ? {
                scope: oauthTokenScope
            } : null), {
                expires_in: expires_in
            });
        }
    }
    _storeMfaContext(e, scope, audience) {
        if (e instanceof MfaRequiredError) {
            this.mfa.setMFAAuthDetails(e.mfa_token, scope, audience, e.mfa_requirements);
        }
    }
    async _requestToken(options, additionalParameters) {
        var _a, _b, _c, _d, _e, _f;
        const _ref2 = additionalParameters || {}, nonceIn = _ref2.nonceIn, organization = _ref2.organization, scopesToRequest = _ref2.scopesToRequest;
        try {
            const authResult = await oauthToken(Object.assign(Object.assign({
                baseUrl: this.domainUrl,
                client_id: this.options.clientId,
                auth0Client: this.options.auth0Client,
                useFormData: this.options.useFormData,
                timeout: this.httpTimeoutMs,
                useMrrt: this.options.useMrrt,
                dpop: this.dpop,
                preserveRefreshToken: this.onlineAccess
            }, options), {
                scope: scopesToRequest || options.scope
            }), this.worker);
            let decodedToken = await this._verifyIdToken(authResult.id_token, nonceIn, organization);
            if (options.grant_type === "authorization_code") {
                const existingIdToken = await this._getIdTokenFromCache();
                if (((_b = (_a = existingIdToken === null || existingIdToken === void 0 ? void 0 : existingIdToken.decodedToken) === null || _a === void 0 ? void 0 : _a.claims) === null || _b === void 0 ? void 0 : _b.sub) && existingIdToken.decodedToken.claims.sub !== decodedToken.claims.sub) {
                    await this.cacheManager.clear(this.options.clientId);
                    this.userCache.remove(CACHE_KEY_ID_TOKEN_SUFFIX);
                }
            }
            if (options.grant_type !== "authorization_code") {
                const existingIdToken = await this._getIdTokenFromCache();
                const existingCeiling = (_d = (_c = existingIdToken === null || existingIdToken === void 0 ? void 0 : existingIdToken.decodedToken) === null || _c === void 0 ? void 0 : _c.claims) === null || _d === void 0 ? void 0 : _d.session_expiry;
                if (existingCeiling !== undefined) {
                    decodedToken = Object.assign(Object.assign({}, decodedToken), {
                        claims: Object.assign(Object.assign({}, decodedToken.claims), {
                            session_expiry: existingCeiling
                        })
                    });
                }
            }
            if (!authResult.refresh_token && this.onlineAccess) {
                authResult.refresh_token = (_e = options.refresh_token) !== null && _e !== void 0 ? _e : (_f = await this.cacheManager.get(new CacheKey({
                    scope: scopesToRequest || options.scope,
                    audience: options.audience || DEFAULT_AUDIENCE,
                    clientId: this.options.clientId
                }), undefined, this.options.useMrrt)) === null || _f === void 0 ? void 0 : _f.refresh_token;
            }
            await this._saveEntryInCache(Object.assign(Object.assign(Object.assign(Object.assign({}, authResult), {
                decodedToken: decodedToken,
                scope: options.scope,
                audience: options.audience || DEFAULT_AUDIENCE
            }), authResult.scope ? {
                oauthTokenScope: authResult.scope
            } : null), {
                client_id: this.options.clientId
            }));
            this.cookieStorage.save(this.isAuthenticatedCookieName, true, {
                daysUntilExpire: this.sessionCheckExpiryDays,
                cookieDomain: this.options.cookieDomain
            });
            this._processOrgHint(organization || decodedToken.claims.org_id);
            return Object.assign(Object.assign({}, authResult), {
                decodedToken: decodedToken
            });
        } catch (e) {
            if (options.grant_type !== "authorization_code") {
                this._storeMfaContext(e, scopesToRequest || options.scope, options.audience);
            }
            throw e;
        }
    }
    _buildTokenExchangeParams(options) {
        return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, options), {
            grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
            subject_token: options.subject_token,
            subject_token_type: options.subject_token_type
        }), options.actor_token && {
            actor_token: options.actor_token
        }), options.actor_token_type && {
            actor_token_type: options.actor_token_type
        }), {
            scope: scopesToRequest(this.scope, options.scope, options.audience || this.options.authorizationParams.audience),
            audience: options.audience || this.options.authorizationParams.audience,
            organization: options.organization || this.options.authorizationParams.organization
        });
    }
    async loginWithCustomTokenExchange(options) {
        return this._requestToken(this._buildTokenExchangeParams(options));
    }
    async customTokenExchange(options) {
        const params = this._buildTokenExchangeParams(options);
        try {
            const result = await oauthToken(Object.assign(Object.assign({}, params), {
                baseUrl: this.domainUrl,
                client_id: this.options.clientId,
                auth0Client: this.options.auth0Client,
                useFormData: this.options.useFormData,
                timeout: this.httpTimeoutMs,
                dpop: this.dpop
            }), this.worker, true);
            if (result.id_token) {
                await this._verifyIdToken(result.id_token, undefined, options.organization);
            }
            return result;
        } catch (e) {
            this._storeMfaContext(e, params.scope, params.audience);
            throw e;
        }
    }
    async exchangeToken(options) {
        return this.loginWithCustomTokenExchange(options);
    }
    _assertDpop(dpop) {
        if (!dpop) {
            throw new Error("`useDpop` option must be enabled before using DPoP.");
        }
    }
    getDpopNonce(id) {
        this._assertDpop(this.dpop);
        return this.dpop.getNonce(id);
    }
    setDpopNonce(nonce, id) {
        this._assertDpop(this.dpop);
        return this.dpop.setNonce(nonce, id);
    }
    generateDpopProof(params) {
        this._assertDpop(this.dpop);
        return this.dpop.generateProof(params);
    }
    createFetcher() {
        let config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        return new Fetcher(config, {
            isDpopEnabled: () => !!this.options.useDpop,
            getAccessToken: authParams => {
                var _a;
                return this.getTokenSilently({
                    authorizationParams: {
                        scope: (_a = authParams === null || authParams === void 0 ? void 0 : authParams.scope) === null || _a === void 0 ? void 0 : _a.join(" "),
                        audience: authParams === null || authParams === void 0 ? void 0 : authParams.audience
                    },
                    detailedResponse: true
                });
            },
            getDpopNonce: () => this.getDpopNonce(config.dpopNonceId),
            setDpopNonce: nonce => this.setDpopNonce(nonce, config.dpopNonceId),
            generateDpopProof: params => this.generateDpopProof(params)
        });
    }
    async connectAccountWithRedirect(options) {
        const openUrl = options.openUrl, appState = options.appState, connection = options.connection, scopes = options.scopes, authorization_params = options.authorization_params, _options$redirectUri = options.redirectUri, redirectUri = _options$redirectUri === void 0 ? this.options.authorizationParams.redirect_uri || window.location.origin : _options$redirectUri;
        if (!connection) {
            throw new Error("connection is required");
        }
        const state = encode$3(createRandomString());
        const code_verifier = createRandomString();
        const code_challengeBuffer = await sha256(code_verifier);
        const code_challenge = bufferToBase64UrlEncoded(code_challengeBuffer);
        const _await$this$myAccount = await this.myAccount.connectAccount({
            connection: connection,
            scopes: scopes,
            redirect_uri: redirectUri,
            state: state,
            code_challenge: code_challenge,
            code_challenge_method: "S256",
            authorization_params: authorization_params
        }), connect_uri = _await$this$myAccount.connect_uri, connect_params = _await$this$myAccount.connect_params, auth_session = _await$this$myAccount.auth_session;
        this.transactionManager.create({
            state: state,
            code_verifier: code_verifier,
            auth_session: auth_session,
            redirect_uri: redirectUri,
            appState: appState,
            connection: connection,
            response_type: exports.ResponseType.ConnectCode
        });
        const url = new URL(connect_uri);
        url.searchParams.set("ticket", connect_params.ticket);
        if (openUrl) {
            await openUrl(url.toString());
        } else {
            window.location.assign(url);
        }
    }
    async _requestTokenForPasskey(options) {
        const audience = options.audience || this.options.authorizationParams.audience;
        const organization = options.organization || this.options.authorizationParams.organization;
        return this._requestToken(Object.assign(Object.assign(Object.assign({
            grant_type: "urn:okta:params:oauth:grant-type:webauthn",
            auth_session: options.authSession,
            authn_response: options.credential
        }, options.realm && {
            realm: options.realm
        }), organization && {
            organization: organization
        }), {
            scope: scopesToRequest(this.scope, options.scope, audience),
            audience: audience
        }));
    }
    async _requestTokenForMfa(options, additionalParameters) {
        const mfaToken = options.mfaToken, restOptions = __rest(options, [ "mfaToken" ]);
        const previous = await this.cacheManager.get(new CacheKey({
            scope: restOptions.scope,
            audience: restOptions.audience || DEFAULT_AUDIENCE,
            clientId: this.options.clientId
        }), undefined, this.options.useMrrt);
        const result = await this._requestToken(Object.assign(Object.assign({}, restOptions), {
            mfa_token: mfaToken
        }), additionalParameters);
        await this._propagateRotatedRefreshToken(previous === null || previous === void 0 ? void 0 : previous.refresh_token, result.refresh_token);
        return result;
    }
}

function isFederatedDomain(auth0Domain, emailDomain, options) {
    var _a;
    const bare = auth0Domain.replace(/^https?:\/\//i, "").toLowerCase();
    return isFederatedDomain$1(bare, emailDomain.toLowerCase(), Object.assign(Object.assign({}, options), {
        telemetry: (_a = options === null || options === void 0 ? void 0 : options.telemetry) !== null && _a !== void 0 ? _a : DEFAULT_AUTH0_CLIENT
    }));
}

async function createAuth0Client(options) {
    const auth0 = new Auth0Client(options);
    await auth0.checkSession();
    return auth0;
}

exports.Auth0Client = Auth0Client;

exports.AuthenticationError = AuthenticationError;

exports.CacheKey = CacheKey;

exports.ConnectError = ConnectError;

exports.GenericError = GenericError;

exports.InMemoryCache = InMemoryCache;

exports.InvalidConfigurationError = InvalidConfigurationError;

exports.LocalStorageCache = LocalStorageCache;

exports.MfaApiClient = MfaApiClient;

exports.MfaChallengeError = MfaChallengeError;

exports.MfaEnrollmentError = MfaEnrollmentError;

exports.MfaEnrollmentFactorsError = MfaEnrollmentFactorsError;

exports.MfaError = MfaError;

exports.MfaListAuthenticatorsError = MfaListAuthenticatorsError;

exports.MfaRequiredError = MfaRequiredError;

exports.MfaVerifyError = MfaVerifyError;

exports.MissingRefreshTokenError = MissingRefreshTokenError;

exports.MissingScopesError = MissingScopesError;

exports.MyAccountApiClient = MyAccountApiClient;

exports.MyAccountApiError = MyAccountApiError;

exports.PasskeyApiClient = PasskeyApiClient;

exports.PasskeyChallengeError = PasskeyChallengeError;

exports.PasskeyError = PasskeyError;

exports.PasskeyGetTokenError = PasskeyGetTokenError;

exports.PasskeyRegisterError = PasskeyRegisterError;

exports.PopupCancelledError = PopupCancelledError;

exports.PopupOpenError = PopupOpenError;

exports.PopupTimeoutError = PopupTimeoutError;

exports.RefreshTokenMode = RefreshTokenMode;

exports.TimeoutError = TimeoutError;

exports.UseDpopNonceError = UseDpopNonceError;

exports.User = User;

exports.createAuth0Client = createAuth0Client;

exports.isFederatedDomain = isFederatedDomain;
//# sourceMappingURL=auth0-spa-js.cjs.js.map