// node_modules/@authsignal/browser/dist/index.js
var getRandomValues;
var rnds8 = new Uint8Array(16);
function rng() {
  if (!getRandomValues) {
    getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
    if (!getRandomValues) {
      throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
    }
  }
  return getRandomValues(rnds8);
}
var byteToHex = [];
for (let i = 0; i < 256; ++i) {
  byteToHex.push((i + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 0) {
  return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
}
var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
var native = {
  randomUUID
};
function v4(options, buf, offset) {
  if (native.randomUUID && !buf && !options) {
    return native.randomUUID();
  }
  options = options || {};
  const rnds = options.random || (options.rng || rng)();
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  if (buf) {
    offset = offset || 0;
    for (let i = 0; i < 16; ++i) {
      buf[offset + i] = rnds[i];
    }
    return buf;
  }
  return unsafeStringify(rnds);
}
var setCookie = function(_a) {
  var name = _a.name, value = _a.value, expire = _a.expire, domain = _a.domain, secure = _a.secure;
  var expireString = expire === Infinity ? " expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + expire;
  document.cookie = encodeURIComponent(name) + "=" + value + "; path=/;" + expireString + (domain ? "; domain=" + domain : "") + (secure ? "; secure" : "");
};
var getCookieDomain = function() {
  return document.location.hostname.replace("www.", "");
};
var getCookie = function(name) {
  if (!name) {
    return null;
  }
  return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(name).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
};
var AuthsignalWindowMessage;
(function(AuthsignalWindowMessage2) {
  AuthsignalWindowMessage2["AUTHSIGNAL_CLOSE_POPUP"] = "AUTHSIGNAL_CLOSE_POPUP";
})(AuthsignalWindowMessage || (AuthsignalWindowMessage = {}));
var focusableSelectors = [
  'a[href]:not([tabindex^="-"])',
  'area[href]:not([tabindex^="-"])',
  'input:not([type="hidden"]):not([type="radio"]):not([disabled]):not([tabindex^="-"])',
  'input[type="radio"]:not([disabled]):not([tabindex^="-"])',
  'select:not([disabled]):not([tabindex^="-"])',
  'textarea:not([disabled]):not([tabindex^="-"])',
  'button:not([disabled]):not([tabindex^="-"])',
  'iframe:not([tabindex^="-"])',
  'audio[controls]:not([tabindex^="-"])',
  'video[controls]:not([tabindex^="-"])',
  '[contenteditable]:not([tabindex^="-"])',
  '[tabindex]:not([tabindex^="-"])'
];
var TAB_KEY = "Tab";
var ESCAPE_KEY = "Escape";
function A11yDialog(element) {
  this._show = this.show.bind(this);
  this._hide = this.hide.bind(this);
  this._maintainFocus = this._maintainFocus.bind(this);
  this._bindKeypress = this._bindKeypress.bind(this);
  this.$el = element;
  this.shown = false;
  this._id = this.$el.getAttribute("data-a11y-dialog") || this.$el.id;
  this._previouslyFocused = null;
  this._listeners = {};
  this.create();
}
A11yDialog.prototype.create = function() {
  this.$el.setAttribute("aria-hidden", true);
  this.$el.setAttribute("aria-modal", true);
  this.$el.setAttribute("tabindex", -1);
  if (!this.$el.hasAttribute("role")) {
    this.$el.setAttribute("role", "dialog");
  }
  this._openers = $$('[data-a11y-dialog-show="' + this._id + '"]');
  this._openers.forEach(
    function(opener) {
      opener.addEventListener("click", this._show);
    }.bind(this)
  );
  const $el = this.$el;
  this._closers = $$("[data-a11y-dialog-hide]", this.$el).filter(function(closer) {
    return closer.closest('[aria-modal="true"], [data-a11y-dialog]') === $el;
  }).concat($$('[data-a11y-dialog-hide="' + this._id + '"]'));
  this._closers.forEach(
    function(closer) {
      closer.addEventListener("click", this._hide);
    }.bind(this)
  );
  this._fire("create");
  return this;
};
A11yDialog.prototype.show = function(event) {
  if (this.shown) {
    return this;
  }
  this._previouslyFocused = document.activeElement;
  this.$el.removeAttribute("aria-hidden");
  this.shown = true;
  moveFocusToDialog(this.$el);
  document.body.addEventListener("focus", this._maintainFocus, true);
  document.addEventListener("keydown", this._bindKeypress);
  this._fire("show", event);
  return this;
};
A11yDialog.prototype.hide = function(event) {
  if (!this.shown) {
    return this;
  }
  this.shown = false;
  this.$el.setAttribute("aria-hidden", "true");
  if (this._previouslyFocused && this._previouslyFocused.focus) {
    this._previouslyFocused.focus();
  }
  document.body.removeEventListener("focus", this._maintainFocus, true);
  document.removeEventListener("keydown", this._bindKeypress);
  this._fire("hide", event);
  return this;
};
A11yDialog.prototype.destroy = function() {
  this.hide();
  this._openers.forEach(
    function(opener) {
      opener.removeEventListener("click", this._show);
    }.bind(this)
  );
  this._closers.forEach(
    function(closer) {
      closer.removeEventListener("click", this._hide);
    }.bind(this)
  );
  this._fire("destroy");
  this._listeners = {};
  return this;
};
A11yDialog.prototype.on = function(type, handler) {
  if (typeof this._listeners[type] === "undefined") {
    this._listeners[type] = [];
  }
  this._listeners[type].push(handler);
  return this;
};
A11yDialog.prototype.off = function(type, handler) {
  var index = (this._listeners[type] || []).indexOf(handler);
  if (index > -1) {
    this._listeners[type].splice(index, 1);
  }
  return this;
};
A11yDialog.prototype._fire = function(type, event) {
  var listeners = this._listeners[type] || [];
  var domEvent = new CustomEvent(type, { detail: event });
  this.$el.dispatchEvent(domEvent);
  listeners.forEach(
    function(listener) {
      listener(this.$el, event);
    }.bind(this)
  );
};
A11yDialog.prototype._bindKeypress = function(event) {
  const focused = document.activeElement;
  if (focused && focused.closest('[aria-modal="true"]') !== this.$el)
    return;
  if (this.shown && event.key === ESCAPE_KEY && this.$el.getAttribute("role") !== "alertdialog") {
    event.preventDefault();
    this.hide(event);
  }
  if (this.shown && event.key === TAB_KEY) {
    trapTabKey(this.$el, event);
  }
};
A11yDialog.prototype._maintainFocus = function(event) {
  if (this.shown && !event.target.closest('[aria-modal="true"]') && !event.target.closest("[data-a11y-dialog-ignore-focus-trap]")) {
    moveFocusToDialog(this.$el);
  }
};
function toArray(collection) {
  return Array.prototype.slice.call(collection);
}
function $$(selector, context) {
  return toArray((context || document).querySelectorAll(selector));
}
function moveFocusToDialog(node) {
  var focused = node.querySelector("[autofocus]") || node;
  focused.focus();
}
function getFocusableChildren(node) {
  return $$(focusableSelectors.join(","), node).filter(function(child) {
    return !!(child.offsetWidth || child.offsetHeight || child.getClientRects().length);
  });
}
function trapTabKey(node, event) {
  var focusableChildren = getFocusableChildren(node);
  var focusedItemIndex = focusableChildren.indexOf(document.activeElement);
  if (event.shiftKey && focusedItemIndex === 0) {
    focusableChildren[focusableChildren.length - 1].focus();
    event.preventDefault();
  } else if (!event.shiftKey && focusedItemIndex === focusableChildren.length - 1) {
    focusableChildren[0].focus();
    event.preventDefault();
  }
}
function instantiateDialogs() {
  $$("[data-a11y-dialog]").forEach(function(node) {
    new A11yDialog(node);
  });
}
if (typeof document !== "undefined") {
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", instantiateDialogs);
  } else {
    if (window.requestAnimationFrame) {
      window.requestAnimationFrame(instantiateDialogs);
    } else {
      window.setTimeout(instantiateDialogs, 16);
    }
  }
}
var CONTAINER_ID = "__authsignal-popup-container";
var CONTENT_ID = "__authsignal-popup-content";
var OVERLAY_ID = "__authsignal-popup-overlay";
var STYLE_ID = "__authsignal-popup-style";
var IFRAME_ID = "__authsignal-popup-iframe";
var DEFAULT_WIDTH = "385px";
var PopupHandler = (
  /** @class */
  function() {
    function PopupHandler2(_a) {
      var width = _a.width;
      this.popup = null;
      if (document.querySelector("#".concat(CONTAINER_ID))) {
        throw new Error("Multiple instances of Authsignal popup is not supported.");
      }
      this.create({ width });
    }
    PopupHandler2.prototype.create = function(_a) {
      var _this = this;
      var _b = _a.width, width = _b === void 0 ? DEFAULT_WIDTH : _b;
      var isWidthValidCSSValue = CSS.supports("width", width);
      var popupWidth = width;
      if (!isWidthValidCSSValue) {
        console.warn("Invalid CSS value for `popupOptions.width`. Using default value instead.");
        popupWidth = DEFAULT_WIDTH;
      }
      var container = document.createElement("div");
      container.setAttribute("id", CONTAINER_ID);
      container.setAttribute("aria-hidden", "true");
      var overlay = document.createElement("div");
      overlay.setAttribute("id", OVERLAY_ID);
      overlay.setAttribute("data-a11y-dialog-hide", "true");
      var content = document.createElement("div");
      content.setAttribute("id", CONTENT_ID);
      document.body.appendChild(container);
      var style = document.createElement("style");
      style.setAttribute("id", STYLE_ID);
      style.textContent = "\n      #".concat(CONTAINER_ID, ",\n      #").concat(OVERLAY_ID, " {\n        position: fixed;\n        top: 0;\n        right: 0;\n        bottom: 0;\n        left: 0;\n      }\n\n      #").concat(CONTAINER_ID, " {\n        z-index: 2147483647;\n        display: flex;\n      }\n\n      #").concat(CONTAINER_ID, "[aria-hidden='true'] {\n        display: none;\n      }\n\n      #").concat(OVERLAY_ID, " {\n        background-color: rgba(0, 0, 0, 0.18);\n      }\n\n      #").concat(CONTENT_ID, " {\n        margin: auto;\n        z-index: 2147483647;\n        position: relative;\n        background-color: transparent;\n        border-radius: 8px;\n        width: ").concat(popupWidth, ";\n      }\n\n      #").concat(CONTENT_ID, " iframe {\n        width: 1px;\n        min-width: 100%;\n        border-radius: inherit;\n        max-height: 95vh;\n      }\n    ");
      document.head.insertAdjacentElement("beforeend", style);
      container.appendChild(overlay);
      container.appendChild(content);
      this.popup = new A11yDialog(container);
      this.popup.on("hide", function() {
        _this.destroy();
      });
    };
    PopupHandler2.prototype.destroy = function() {
      var dialogEl = document.querySelector("#".concat(CONTAINER_ID));
      var styleEl = document.querySelector("#".concat(STYLE_ID));
      if (dialogEl && styleEl) {
        document.body.removeChild(dialogEl);
        document.head.removeChild(styleEl);
      }
      window.removeEventListener("message", resizeIframe);
    };
    PopupHandler2.prototype.show = function(_a) {
      var _b;
      var url = _a.url;
      if (!this.popup) {
        throw new Error("Popup is not initialized");
      }
      var iframe = document.createElement("iframe");
      iframe.setAttribute("id", IFRAME_ID);
      iframe.setAttribute("name", "authsignal");
      iframe.setAttribute("title", "Authsignal multi-factor authentication");
      iframe.setAttribute("src", url);
      iframe.setAttribute("frameborder", "0");
      iframe.setAttribute("allow", "publickey-credentials-get *; clipboard-write");
      var dialogContent = document.querySelector("#".concat(CONTENT_ID));
      if (dialogContent) {
        dialogContent.appendChild(iframe);
      }
      window.addEventListener("message", resizeIframe);
      (_b = this.popup) === null || _b === void 0 ? void 0 : _b.show();
    };
    PopupHandler2.prototype.close = function() {
      if (!this.popup) {
        throw new Error("Popup is not initialized");
      }
      this.popup.hide();
    };
    PopupHandler2.prototype.on = function(event, handler) {
      if (!this.popup) {
        throw new Error("Popup is not initialized");
      }
      this.popup.on(event, handler);
    };
    return PopupHandler2;
  }()
);
function resizeIframe(event) {
  var iframeEl = document.querySelector("#".concat(IFRAME_ID));
  if (iframeEl && event.data.height) {
    iframeEl.style.height = event.data.height + "px";
  }
}
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 __awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator(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 };
  }
}
function utf8StringToBuffer(value) {
  return new TextEncoder().encode(value);
}
function bufferToBase64URLString(buffer) {
  const bytes = new Uint8Array(buffer);
  let str = "";
  for (const charCode of bytes) {
    str += String.fromCharCode(charCode);
  }
  const base64String = btoa(str);
  return base64String.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
function base64URLStringToBuffer(base64URLString) {
  const base64 = base64URLString.replace(/-/g, "+").replace(/_/g, "/");
  const padLength = (4 - base64.length % 4) % 4;
  const padded = base64.padEnd(base64.length + padLength, "=");
  const binary = atob(padded);
  const buffer = new ArrayBuffer(binary.length);
  const bytes = new Uint8Array(buffer);
  for (let i = 0; i < binary.length; i++) {
    bytes[i] = binary.charCodeAt(i);
  }
  return buffer;
}
function browserSupportsWebAuthn() {
  return window?.PublicKeyCredential !== void 0 && typeof window.PublicKeyCredential === "function";
}
function toPublicKeyCredentialDescriptor(descriptor) {
  const { id } = descriptor;
  return {
    ...descriptor,
    id: base64URLStringToBuffer(id),
    transports: descriptor.transports
  };
}
function isValidDomain(hostname) {
  return hostname === "localhost" || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname);
}
var WebAuthnError = class extends Error {
  constructor({ message, code, cause, name }) {
    super(message, { cause });
    this.name = name ?? cause.name;
    this.code = code;
  }
};
function identifyRegistrationError({ error, options }) {
  const { publicKey } = options;
  if (!publicKey) {
    throw Error("options was missing required publicKey property");
  }
  if (error.name === "AbortError") {
    if (options.signal instanceof AbortSignal) {
      return new WebAuthnError({
        message: "Registration ceremony was sent an abort signal",
        code: "ERROR_CEREMONY_ABORTED",
        cause: error
      });
    }
  } else if (error.name === "ConstraintError") {
    if (publicKey.authenticatorSelection?.requireResidentKey === true) {
      return new WebAuthnError({
        message: "Discoverable credentials were required but no available authenticator supported it",
        code: "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",
        cause: error
      });
    } else if (publicKey.authenticatorSelection?.userVerification === "required") {
      return new WebAuthnError({
        message: "User verification was required but no available authenticator supported it",
        code: "ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",
        cause: error
      });
    }
  } else if (error.name === "InvalidStateError") {
    return new WebAuthnError({
      message: "The authenticator was previously registered",
      code: "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",
      cause: error
    });
  } else if (error.name === "NotAllowedError") {
    return new WebAuthnError({
      message: error.message,
      code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",
      cause: error
    });
  } else if (error.name === "NotSupportedError") {
    const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === "public-key");
    if (validPubKeyCredParams.length === 0) {
      return new WebAuthnError({
        message: 'No entry in pubKeyCredParams was of type "public-key"',
        code: "ERROR_MALFORMED_PUBKEYCREDPARAMS",
        cause: error
      });
    }
    return new WebAuthnError({
      message: "No available authenticator supported any of the specified pubKeyCredParams algorithms",
      code: "ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",
      cause: error
    });
  } else if (error.name === "SecurityError") {
    const effectiveDomain = window.location.hostname;
    if (!isValidDomain(effectiveDomain)) {
      return new WebAuthnError({
        message: `${window.location.hostname} is an invalid domain`,
        code: "ERROR_INVALID_DOMAIN",
        cause: error
      });
    } else if (publicKey.rp.id !== effectiveDomain) {
      return new WebAuthnError({
        message: `The RP ID "${publicKey.rp.id}" is invalid for this domain`,
        code: "ERROR_INVALID_RP_ID",
        cause: error
      });
    }
  } else if (error.name === "TypeError") {
    if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) {
      return new WebAuthnError({
        message: "User ID was not between 1 and 64 characters",
        code: "ERROR_INVALID_USER_ID_LENGTH",
        cause: error
      });
    }
  } else if (error.name === "UnknownError") {
    return new WebAuthnError({
      message: "The authenticator was unable to process the specified options, or could not create a new credential",
      code: "ERROR_AUTHENTICATOR_GENERAL_ERROR",
      cause: error
    });
  }
  return error;
}
var WebAuthnAbortService = class {
  createNewAbortSignal() {
    if (this.controller) {
      const abortError = new Error("Cancelling existing WebAuthn API call for new one");
      abortError.name = "AbortError";
      this.controller.abort(abortError);
    }
    const newController = new AbortController();
    this.controller = newController;
    return newController.signal;
  }
};
var webauthnAbortService = new WebAuthnAbortService();
var attachments = ["cross-platform", "platform"];
function toAuthenticatorAttachment(attachment) {
  if (!attachment) {
    return;
  }
  if (attachments.indexOf(attachment) < 0) {
    return;
  }
  return attachment;
}
async function startRegistration(creationOptionsJSON) {
  if (!browserSupportsWebAuthn()) {
    throw new Error("WebAuthn is not supported in this browser");
  }
  const publicKey = {
    ...creationOptionsJSON,
    challenge: base64URLStringToBuffer(creationOptionsJSON.challenge),
    user: {
      ...creationOptionsJSON.user,
      id: utf8StringToBuffer(creationOptionsJSON.user.id)
    },
    excludeCredentials: creationOptionsJSON.excludeCredentials?.map(toPublicKeyCredentialDescriptor)
  };
  const options = { publicKey };
  options.signal = webauthnAbortService.createNewAbortSignal();
  let credential;
  try {
    credential = await navigator.credentials.create(options);
  } catch (err) {
    throw identifyRegistrationError({ error: err, options });
  }
  if (!credential) {
    throw new Error("Registration was not completed");
  }
  const { id, rawId, response, type } = credential;
  let transports = void 0;
  if (typeof response.getTransports === "function") {
    transports = response.getTransports();
  }
  let responsePublicKeyAlgorithm = void 0;
  if (typeof response.getPublicKeyAlgorithm === "function") {
    try {
      responsePublicKeyAlgorithm = response.getPublicKeyAlgorithm();
    } catch (error) {
      warnOnBrokenImplementation("getPublicKeyAlgorithm()", error);
    }
  }
  let responsePublicKey = void 0;
  if (typeof response.getPublicKey === "function") {
    try {
      const _publicKey = response.getPublicKey();
      if (_publicKey !== null) {
        responsePublicKey = bufferToBase64URLString(_publicKey);
      }
    } catch (error) {
      warnOnBrokenImplementation("getPublicKey()", error);
    }
  }
  let responseAuthenticatorData;
  if (typeof response.getAuthenticatorData === "function") {
    try {
      responseAuthenticatorData = bufferToBase64URLString(response.getAuthenticatorData());
    } catch (error) {
      warnOnBrokenImplementation("getAuthenticatorData()", error);
    }
  }
  return {
    id,
    rawId: bufferToBase64URLString(rawId),
    response: {
      attestationObject: bufferToBase64URLString(response.attestationObject),
      clientDataJSON: bufferToBase64URLString(response.clientDataJSON),
      transports,
      publicKeyAlgorithm: responsePublicKeyAlgorithm,
      publicKey: responsePublicKey,
      authenticatorData: responseAuthenticatorData
    },
    type,
    clientExtensionResults: credential.getClientExtensionResults(),
    authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment)
  };
}
function warnOnBrokenImplementation(methodName, cause) {
  console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${methodName}. You should report this error to them.
`, cause);
}
function bufferToUTF8String(value) {
  return new TextDecoder("utf-8").decode(value);
}
function browserSupportsWebAuthnAutofill() {
  const globalPublicKeyCredential = window.PublicKeyCredential;
  if (globalPublicKeyCredential.isConditionalMediationAvailable === void 0) {
    return new Promise((resolve) => resolve(false));
  }
  return globalPublicKeyCredential.isConditionalMediationAvailable();
}
function identifyAuthenticationError({ error, options }) {
  const { publicKey } = options;
  if (!publicKey) {
    throw Error("options was missing required publicKey property");
  }
  if (error.name === "AbortError") {
    if (options.signal instanceof AbortSignal) {
      return new WebAuthnError({
        message: "Authentication ceremony was sent an abort signal",
        code: "ERROR_CEREMONY_ABORTED",
        cause: error
      });
    }
  } else if (error.name === "NotAllowedError") {
    return new WebAuthnError({
      message: error.message,
      code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",
      cause: error
    });
  } else if (error.name === "SecurityError") {
    const effectiveDomain = window.location.hostname;
    if (!isValidDomain(effectiveDomain)) {
      return new WebAuthnError({
        message: `${window.location.hostname} is an invalid domain`,
        code: "ERROR_INVALID_DOMAIN",
        cause: error
      });
    } else if (publicKey.rpId !== effectiveDomain) {
      return new WebAuthnError({
        message: `The RP ID "${publicKey.rpId}" is invalid for this domain`,
        code: "ERROR_INVALID_RP_ID",
        cause: error
      });
    }
  } else if (error.name === "UnknownError") {
    return new WebAuthnError({
      message: "The authenticator was unable to process the specified options, or could not create a new assertion signature",
      code: "ERROR_AUTHENTICATOR_GENERAL_ERROR",
      cause: error
    });
  }
  return error;
}
async function startAuthentication(requestOptionsJSON, useBrowserAutofill = false) {
  if (!browserSupportsWebAuthn()) {
    throw new Error("WebAuthn is not supported in this browser");
  }
  let allowCredentials;
  if (requestOptionsJSON.allowCredentials?.length !== 0) {
    allowCredentials = requestOptionsJSON.allowCredentials?.map(toPublicKeyCredentialDescriptor);
  }
  const publicKey = {
    ...requestOptionsJSON,
    challenge: base64URLStringToBuffer(requestOptionsJSON.challenge),
    allowCredentials
  };
  const options = {};
  if (useBrowserAutofill) {
    if (!await browserSupportsWebAuthnAutofill()) {
      throw Error("Browser does not support WebAuthn autofill");
    }
    const eligibleInputs = document.querySelectorAll("input[autocomplete*='webauthn']");
    if (eligibleInputs.length < 1) {
      throw Error('No <input> with `"webauthn"` in its `autocomplete` attribute was detected');
    }
    options.mediation = "conditional";
    publicKey.allowCredentials = [];
  }
  options.publicKey = publicKey;
  options.signal = webauthnAbortService.createNewAbortSignal();
  let credential;
  try {
    credential = await navigator.credentials.get(options);
  } catch (err) {
    throw identifyAuthenticationError({ error: err, options });
  }
  if (!credential) {
    throw new Error("Authentication was not completed");
  }
  const { id, rawId, response, type } = credential;
  let userHandle = void 0;
  if (response.userHandle) {
    userHandle = bufferToUTF8String(response.userHandle);
  }
  return {
    id,
    rawId: bufferToBase64URLString(rawId),
    response: {
      authenticatorData: bufferToBase64URLString(response.authenticatorData),
      clientDataJSON: bufferToBase64URLString(response.clientDataJSON),
      signature: bufferToBase64URLString(response.signature),
      userHandle
    },
    type,
    clientExtensionResults: credential.getClientExtensionResults(),
    authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment)
  };
}
var HTTPError = class extends Error {
  constructor(response, request, options) {
    const code = response.status || response.status === 0 ? response.status : "";
    const title = response.statusText || "";
    const status = `${code} ${title}`.trim();
    const reason = status ? `status code ${status}` : "an unknown error";
    super(`Request failed with ${reason}`);
    Object.defineProperty(this, "response", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "request", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "options", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    this.name = "HTTPError";
    this.response = response;
    this.request = request;
    this.options = options;
  }
};
var TimeoutError = class extends Error {
  constructor(request) {
    super("Request timed out");
    Object.defineProperty(this, "request", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    this.name = "TimeoutError";
    this.request = request;
  }
};
var isObject = (value) => value !== null && typeof value === "object";
var validateAndMerge = (...sources) => {
  for (const source of sources) {
    if ((!isObject(source) || Array.isArray(source)) && typeof source !== "undefined") {
      throw new TypeError("The `options` argument must be an object");
    }
  }
  return deepMerge({}, ...sources);
};
var mergeHeaders = (source1 = {}, source2 = {}) => {
  const result = new globalThis.Headers(source1);
  const isHeadersInstance = source2 instanceof globalThis.Headers;
  const source = new globalThis.Headers(source2);
  for (const [key, value] of source.entries()) {
    if (isHeadersInstance && value === "undefined" || value === void 0) {
      result.delete(key);
    } else {
      result.set(key, value);
    }
  }
  return result;
};
var deepMerge = (...sources) => {
  let returnValue = {};
  let headers = {};
  for (const source of sources) {
    if (Array.isArray(source)) {
      if (!Array.isArray(returnValue)) {
        returnValue = [];
      }
      returnValue = [...returnValue, ...source];
    } else if (isObject(source)) {
      for (let [key, value] of Object.entries(source)) {
        if (isObject(value) && key in returnValue) {
          value = deepMerge(returnValue[key], value);
        }
        returnValue = { ...returnValue, [key]: value };
      }
      if (isObject(source.headers)) {
        headers = mergeHeaders(headers, source.headers);
        returnValue.headers = headers;
      }
    }
  }
  return returnValue;
};
var supportsRequestStreams = (() => {
  let duplexAccessed = false;
  let hasContentType = false;
  const supportsReadableStream = typeof globalThis.ReadableStream === "function";
  const supportsRequest = typeof globalThis.Request === "function";
  if (supportsReadableStream && supportsRequest) {
    hasContentType = new globalThis.Request("https://a.com", {
      body: new globalThis.ReadableStream(),
      method: "POST",
      // @ts-expect-error - Types are outdated.
      get duplex() {
        duplexAccessed = true;
        return "half";
      }
    }).headers.has("Content-Type");
  }
  return duplexAccessed && !hasContentType;
})();
var supportsAbortController = typeof globalThis.AbortController === "function";
var supportsResponseStreams = typeof globalThis.ReadableStream === "function";
var supportsFormData = typeof globalThis.FormData === "function";
var requestMethods = ["get", "post", "put", "patch", "head", "delete"];
var responseTypes = {
  json: "application/json",
  text: "text/*",
  formData: "multipart/form-data",
  arrayBuffer: "*/*",
  blob: "*/*"
};
var maxSafeTimeout = 2147483647;
var stop = Symbol("stop");
var normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
var retryMethods = ["get", "put", "head", "delete", "options", "trace"];
var retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
var retryAfterStatusCodes = [413, 429, 503];
var defaultRetryOptions = {
  limit: 2,
  methods: retryMethods,
  statusCodes: retryStatusCodes,
  afterStatusCodes: retryAfterStatusCodes,
  maxRetryAfter: Number.POSITIVE_INFINITY,
  backoffLimit: Number.POSITIVE_INFINITY
};
var normalizeRetryOptions = (retry = {}) => {
  if (typeof retry === "number") {
    return {
      ...defaultRetryOptions,
      limit: retry
    };
  }
  if (retry.methods && !Array.isArray(retry.methods)) {
    throw new Error("retry.methods must be an array");
  }
  if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
    throw new Error("retry.statusCodes must be an array");
  }
  return {
    ...defaultRetryOptions,
    ...retry,
    afterStatusCodes: retryAfterStatusCodes
  };
};
async function timeout(request, abortController, options) {
  return new Promise((resolve, reject) => {
    const timeoutId = setTimeout(() => {
      if (abortController) {
        abortController.abort();
      }
      reject(new TimeoutError(request));
    }, options.timeout);
    void options.fetch(request).then(resolve).catch(reject).then(() => {
      clearTimeout(timeoutId);
    });
  });
}
var isDomExceptionSupported = Boolean(globalThis.DOMException);
function composeAbortError(signal) {
  if (isDomExceptionSupported) {
    return new DOMException(signal?.reason ?? "The operation was aborted.", "AbortError");
  }
  const error = new Error(signal?.reason ?? "The operation was aborted.");
  error.name = "AbortError";
  return error;
}
async function delay(ms, { signal }) {
  return new Promise((resolve, reject) => {
    if (signal) {
      if (signal.aborted) {
        reject(composeAbortError(signal));
        return;
      }
      signal.addEventListener("abort", handleAbort, { once: true });
    }
    function handleAbort() {
      reject(composeAbortError(signal));
      clearTimeout(timeoutId);
    }
    const timeoutId = setTimeout(() => {
      signal?.removeEventListener("abort", handleAbort);
      resolve();
    }, ms);
  });
}
var Ky = class {
  // eslint-disable-next-line @typescript-eslint/promise-function-async
  static create(input, options) {
    const ky2 = new Ky(input, options);
    const fn = async () => {
      if (ky2._options.timeout > maxSafeTimeout) {
        throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
      }
      await Promise.resolve();
      let response = await ky2._fetch();
      for (const hook of ky2._options.hooks.afterResponse) {
        const modifiedResponse = await hook(ky2.request, ky2._options, ky2._decorateResponse(response.clone()));
        if (modifiedResponse instanceof globalThis.Response) {
          response = modifiedResponse;
        }
      }
      ky2._decorateResponse(response);
      if (!response.ok && ky2._options.throwHttpErrors) {
        let error = new HTTPError(response, ky2.request, ky2._options);
        for (const hook of ky2._options.hooks.beforeError) {
          error = await hook(error);
        }
        throw error;
      }
      if (ky2._options.onDownloadProgress) {
        if (typeof ky2._options.onDownloadProgress !== "function") {
          throw new TypeError("The `onDownloadProgress` option must be a function");
        }
        if (!supportsResponseStreams) {
          throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");
        }
        return ky2._stream(response.clone(), ky2._options.onDownloadProgress);
      }
      return response;
    };
    const isRetriableMethod = ky2._options.retry.methods.includes(ky2.request.method.toLowerCase());
    const result = isRetriableMethod ? ky2._retry(fn) : fn();
    for (const [type, mimeType] of Object.entries(responseTypes)) {
      result[type] = async () => {
        ky2.request.headers.set("accept", ky2.request.headers.get("accept") || mimeType);
        const awaitedResult = await result;
        const response = awaitedResult.clone();
        if (type === "json") {
          if (response.status === 204) {
            return "";
          }
          const arrayBuffer = await response.clone().arrayBuffer();
          const responseSize = arrayBuffer.byteLength;
          if (responseSize === 0) {
            return "";
          }
          if (options.parseJson) {
            return options.parseJson(await response.text());
          }
        }
        return response[type]();
      };
    }
    return result;
  }
  // eslint-disable-next-line complexity
  constructor(input, options = {}) {
    Object.defineProperty(this, "request", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "abortController", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "_retryCount", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 0
    });
    Object.defineProperty(this, "_input", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "_options", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    this._input = input;
    this._options = {
      // TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
      credentials: this._input.credentials || "same-origin",
      ...options,
      headers: mergeHeaders(this._input.headers, options.headers),
      hooks: deepMerge({
        beforeRequest: [],
        beforeRetry: [],
        beforeError: [],
        afterResponse: []
      }, options.hooks),
      method: normalizeRequestMethod(options.method ?? this._input.method),
      // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
      prefixUrl: String(options.prefixUrl || ""),
      retry: normalizeRetryOptions(options.retry),
      throwHttpErrors: options.throwHttpErrors !== false,
      timeout: typeof options.timeout === "undefined" ? 1e4 : options.timeout,
      fetch: options.fetch ?? globalThis.fetch.bind(globalThis)
    };
    if (typeof this._input !== "string" && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
      throw new TypeError("`input` must be a string, URL, or Request");
    }
    if (this._options.prefixUrl && typeof this._input === "string") {
      if (this._input.startsWith("/")) {
        throw new Error("`input` must not begin with a slash when using `prefixUrl`");
      }
      if (!this._options.prefixUrl.endsWith("/")) {
        this._options.prefixUrl += "/";
      }
      this._input = this._options.prefixUrl + this._input;
    }
    if (supportsAbortController) {
      this.abortController = new globalThis.AbortController();
      if (this._options.signal) {
        const originalSignal = this._options.signal;
        this._options.signal.addEventListener("abort", () => {
          this.abortController.abort(originalSignal.reason);
        });
      }
      this._options.signal = this.abortController.signal;
    }
    if (supportsRequestStreams) {
      this._options.duplex = "half";
    }
    this.request = new globalThis.Request(this._input, this._options);
    if (this._options.searchParams) {
      const textSearchParams = typeof this._options.searchParams === "string" ? this._options.searchParams.replace(/^\?/, "") : new URLSearchParams(this._options.searchParams).toString();
      const searchParams = "?" + textSearchParams;
      const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
      if ((supportsFormData && this._options.body instanceof globalThis.FormData || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers["content-type"])) {
        this.request.headers.delete("content-type");
      }
      this.request = new globalThis.Request(new globalThis.Request(url, { ...this.request }), this._options);
    }
    if (this._options.json !== void 0) {
      this._options.body = JSON.stringify(this._options.json);
      this.request.headers.set("content-type", this._options.headers.get("content-type") ?? "application/json");
      this.request = new globalThis.Request(this.request, { body: this._options.body });
    }
  }
  _calculateRetryDelay(error) {
    this._retryCount++;
    if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) {
      if (error instanceof HTTPError) {
        if (!this._options.retry.statusCodes.includes(error.response.status)) {
          return 0;
        }
        const retryAfter = error.response.headers.get("Retry-After");
        if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
          let after = Number(retryAfter);
          if (Number.isNaN(after)) {
            after = Date.parse(retryAfter) - Date.now();
          } else {
            after *= 1e3;
          }
          if (typeof this._options.retry.maxRetryAfter !== "undefined" && after > this._options.retry.maxRetryAfter) {
            return 0;
          }
          return after;
        }
        if (error.response.status === 413) {
          return 0;
        }
      }
      const BACKOFF_FACTOR = 0.3;
      return Math.min(this._options.retry.backoffLimit, BACKOFF_FACTOR * 2 ** (this._retryCount - 1) * 1e3);
    }
    return 0;
  }
  _decorateResponse(response) {
    if (this._options.parseJson) {
      response.json = async () => this._options.parseJson(await response.text());
    }
    return response;
  }
  async _retry(fn) {
    try {
      return await fn();
    } catch (error) {
      const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
      if (ms !== 0 && this._retryCount > 0) {
        await delay(ms, { signal: this._options.signal });
        for (const hook of this._options.hooks.beforeRetry) {
          const hookResult = await hook({
            request: this.request,
            options: this._options,
            error,
            retryCount: this._retryCount
          });
          if (hookResult === stop) {
            return;
          }
        }
        return this._retry(fn);
      }
      throw error;
    }
  }
  async _fetch() {
    for (const hook of this._options.hooks.beforeRequest) {
      const result = await hook(this.request, this._options);
      if (result instanceof Request) {
        this.request = result;
        break;
      }
      if (result instanceof Response) {
        return result;
      }
    }
    if (this._options.timeout === false) {
      return this._options.fetch(this.request.clone());
    }
    return timeout(this.request.clone(), this.abortController, this._options);
  }
  /* istanbul ignore next */
  _stream(response, onDownloadProgress) {
    const totalBytes = Number(response.headers.get("content-length")) || 0;
    let transferredBytes = 0;
    if (response.status === 204) {
      if (onDownloadProgress) {
        onDownloadProgress({ percent: 1, totalBytes, transferredBytes }, new Uint8Array());
      }
      return new globalThis.Response(null, {
        status: response.status,
        statusText: response.statusText,
        headers: response.headers
      });
    }
    return new globalThis.Response(new globalThis.ReadableStream({
      async start(controller) {
        const reader = response.body.getReader();
        if (onDownloadProgress) {
          onDownloadProgress({ percent: 0, transferredBytes: 0, totalBytes }, new Uint8Array());
        }
        async function read() {
          const { done, value } = await reader.read();
          if (done) {
            controller.close();
            return;
          }
          if (onDownloadProgress) {
            transferredBytes += value.byteLength;
            const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
            onDownloadProgress({ percent, transferredBytes, totalBytes }, value);
          }
          controller.enqueue(value);
          await read();
        }
        await read();
      }
    }), {
      status: response.status,
      statusText: response.statusText,
      headers: response.headers
    });
  }
};
var createInstance = (defaults) => {
  const ky2 = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
  for (const method of requestMethods) {
    ky2[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
  }
  ky2.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
  ky2.extend = (newDefaults) => createInstance(validateAndMerge(defaults, newDefaults));
  ky2.stop = stop;
  return ky2;
};
var ky = createInstance();
var ky$1 = ky;
var PasskeyApiClient = (
  /** @class */
  function() {
    function PasskeyApiClient2(_a) {
      var baseUrl = _a.baseUrl, tenantId = _a.tenantId;
      this.tenantId = tenantId;
      this.api = ky$1.create({
        prefixUrl: baseUrl
      });
    }
    PasskeyApiClient2.prototype.registrationOptions = function(_a) {
      var token = _a.token, userName = _a.userName;
      return __awaiter(this, void 0, void 0, function() {
        var response;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              return [4, this.api.post("client/user-authenticators/passkey/registration-options", {
                json: { username: userName },
                headers: this.buildHeaders(token)
              })];
            case 1:
              response = _b.sent();
              return [2, response.json()];
          }
        });
      });
    };
    PasskeyApiClient2.prototype.authenticationOptions = function(_a) {
      var token = _a.token;
      return __awaiter(this, void 0, void 0, function() {
        var response;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              return [4, this.api.post("client/user-authenticators/passkey/authentication-options", {
                json: {},
                headers: this.buildHeaders(token)
              })];
            case 1:
              response = _b.sent();
              return [2, response.json()];
          }
        });
      });
    };
    PasskeyApiClient2.prototype.addAuthenticator = function(_a) {
      var token = _a.token, rest = __rest(_a, ["token"]);
      return __awaiter(this, void 0, void 0, function() {
        var response;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              return [4, this.api.post("client/user-authenticators/passkey", {
                json: rest,
                headers: this.buildHeaders(token)
              })];
            case 1:
              response = _b.sent();
              return [2, response.json()];
          }
        });
      });
    };
    PasskeyApiClient2.prototype.verify = function(_a) {
      var token = _a.token, rest = __rest(_a, ["token"]);
      return __awaiter(this, void 0, void 0, function() {
        var response;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              return [4, this.api.post("client/verify/passkey", {
                json: rest,
                headers: this.buildHeaders(token)
              })];
            case 1:
              response = _b.sent();
              return [2, response.json()];
          }
        });
      });
    };
    PasskeyApiClient2.prototype.buildHeaders = function(token) {
      var authorizationHeader = token ? "Bearer ".concat(token) : "Basic ".concat(window.btoa(encodeURIComponent(this.tenantId)));
      return {
        Authorization: authorizationHeader
      };
    };
    return PasskeyApiClient2;
  }()
);
var Passkey = (
  /** @class */
  function() {
    function Passkey2(_a) {
      var baseUrl = _a.baseUrl, tenantId = _a.tenantId;
      this.api = new PasskeyApiClient({ baseUrl, tenantId });
    }
    Passkey2.prototype.signUp = function(_a) {
      var userName = _a.userName, token = _a.token;
      return __awaiter(this, void 0, void 0, function() {
        var optionsResponse, registrationResponse, addAuthenticatorResponse;
        return __generator(this, function(_b) {
          switch (_b.label) {
            case 0:
              return [4, this.api.registrationOptions({ userName, token })];
            case 1:
              optionsResponse = _b.sent();
              return [4, startRegistration(optionsResponse.options)];
            case 2:
              registrationResponse = _b.sent();
              return [4, this.api.addAuthenticator({
                challengeId: optionsResponse.challengeId,
                registrationCredential: registrationResponse,
                token
              })];
            case 3:
              addAuthenticatorResponse = _b.sent();
              return [2, addAuthenticatorResponse === null || addAuthenticatorResponse === void 0 ? void 0 : addAuthenticatorResponse.accessToken];
          }
        });
      });
    };
    Passkey2.prototype.signIn = function(params) {
      return __awaiter(this, void 0, void 0, function() {
        var optionsResponse, authenticationResponse, verifyResponse;
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              if ((params === null || params === void 0 ? void 0 : params.token) && params.autofill) {
                throw new Error("Autofill is not supported when providing a token");
              }
              return [4, this.api.authenticationOptions({ token: params === null || params === void 0 ? void 0 : params.token })];
            case 1:
              optionsResponse = _a.sent();
              return [4, startAuthentication(optionsResponse.options, params === null || params === void 0 ? void 0 : params.autofill)];
            case 2:
              authenticationResponse = _a.sent();
              return [4, this.api.verify({
                challengeId: optionsResponse.challengeId,
                authenticationCredential: authenticationResponse,
                token: params === null || params === void 0 ? void 0 : params.token
              })];
            case 3:
              verifyResponse = _a.sent();
              return [2, verifyResponse === null || verifyResponse === void 0 ? void 0 : verifyResponse.accessToken];
          }
        });
      });
    };
    return Passkey2;
  }()
);
var DEFAULT_COOKIE_NAME = "__as_aid";
var DEFAULT_BASE_URL = "https://api.authsignal.com/v1";
var Authsignal = (
  /** @class */
  function() {
    function Authsignal2(_a) {
      var cookieDomain = _a.cookieDomain, _b = _a.cookieName, cookieName = _b === void 0 ? DEFAULT_COOKIE_NAME : _b, _c = _a.baseUrl, baseUrl = _c === void 0 ? DEFAULT_BASE_URL : _c, tenantId = _a.tenantId;
      this.anonymousId = "";
      this.cookieDomain = "";
      this.anonymousIdCookieName = "";
      this._token = void 0;
      this.cookieDomain = cookieDomain || getCookieDomain();
      this.anonymousIdCookieName = cookieName;
      if (!tenantId) {
        throw new Error("tenantId is required");
      }
      this.passkey = new Passkey({ tenantId, baseUrl });
      var idCookie = getCookie(this.anonymousIdCookieName);
      if (idCookie) {
        this.anonymousId = idCookie;
      } else {
        this.anonymousId = v4();
        setCookie({
          name: this.anonymousIdCookieName,
          value: this.anonymousId,
          expire: Infinity,
          domain: this.cookieDomain,
          secure: document.location.protocol !== "http:"
        });
      }
    }
    Authsignal2.prototype.launch = function(url, options) {
      var _this = this;
      if (!(options === null || options === void 0 ? void 0 : options.mode) || options.mode === "redirect") {
        window.location.href = url;
      } else {
        var popupOptions = options.popupOptions;
        var Popup_1 = new PopupHandler({ width: popupOptions === null || popupOptions === void 0 ? void 0 : popupOptions.width });
        var popupUrl = "".concat(url, "&mode=popup");
        Popup_1.show({ url: popupUrl });
        return new Promise(function(resolve) {
          var onMessage = function(event) {
            var data = null;
            try {
              data = JSON.parse(event.data);
            } catch (_a) {
            }
            if ((data === null || data === void 0 ? void 0 : data.event) === AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP) {
              _this._token = data.token;
              Popup_1.close();
            }
          };
          Popup_1.on("hide", function() {
            resolve({ token: _this._token });
          });
          window.addEventListener("message", onMessage, false);
        });
      }
    };
    return Authsignal2;
  }()
);
export {
  Authsignal,
  AuthsignalWindowMessage
};
/*! Bundled license information:

@authsignal/browser/dist/index.js:
  (*! MIT License © Sindre Sorhus *)
*/
