{ "version": 3, "sources": ["../../../node_modules/sweetalert2/dist/sweetalert2.all.js", "../../../node_modules/rollbar/src/utility.js", "../../../node_modules/rollbar/src/utility/traverse.js", "../../../node_modules/rollbar/src/scrub.js", "../../../node_modules/rollbar/src/telemetry.js", "../../../node_modules/rollbar/src/tracing/context.js", "../../../node_modules/rollbar/src/tracing/contextManager.js", "../../../node_modules/rollbar/src/tracing/hrtime.js", "../../../node_modules/rollbar/src/tracing/exporter.js", "../../../node_modules/rollbar/src/tracing/id.js", "../../../node_modules/rollbar/src/tracing/session.js", "../../../node_modules/rollbar/src/logger.js", "../../../node_modules/rollbar/src/tracing/spanProcessor.js", "../../../node_modules/rollbar/src/tracing/span.js", "../../../node_modules/rollbar/src/tracing/tracer.js", "../../../node_modules/rollbar/src/tracing/tracing.js", "../../../node_modules/rollbar/src/truncation.js", "../../../node_modules/rollbar/src/apiUtility.js", "../../../node_modules/rollbar/src/api.js", "../../../node_modules/rollbar/src/defaults.js", "../../../node_modules/error-stack-parser-es/dist/lite.mjs", "../../../node_modules/error-stack-parser-es/dist/index.mjs", "../../../node_modules/rollbar/src/errorParser.js", "../../../node_modules/rollbar/src/predicates.js", "../../../node_modules/rollbar/src/notifier.js", "../../../node_modules/rollbar/src/queue.js", "../../../node_modules/rollbar/src/rateLimiter.js", "../../../node_modules/rollbar/src/rollbar.js", "../../../node_modules/rollbar/src/tracing/defaults.js", "../../../node_modules/rollbar/src/transforms.js", "../../../node_modules/rollbar/src/browser/defaults.js", "../../../node_modules/rollbar/src/browser/globalSetup.js", "../../../node_modules/rollbar/src/browser/predicates.js", "../../../node_modules/rollbar/src/browser/replay/defaults.js", "../../../node_modules/rollbar/src/browser/transforms.js", "../../../node_modules/rollbar/src/browser/transport/fetch.js", "../../../node_modules/rollbar/src/browser/transport/xhr.js", "../../../node_modules/rollbar/src/browser/transport.js", "../../../node_modules/rollbar/src/browser/url.js", "../../../node_modules/rollbar/src/browser/core.js", "../../../node_modules/rollbar/src/utility/headers.js", "../../../node_modules/rollbar/src/utility/replace.js", "../../../node_modules/rollbar/src/browser/domUtility.js", "../../../node_modules/rollbar/src/browser/telemetry.js", "../../../node_modules/rollbar/src/browser/wrapGlobals.js", "../../../node_modules/rollbar/src/browser/rollbar.js", "../../../node_modules/@hotwired/stimulus/dist/stimulus.js", "../../components/accordion_component/accordion_controller.js", "../../components/tabs_component/tabs_controller.js", "../javascript/controllers/stimulus_application.js", "../javascript/controllers/application/modal_controller.js", "../../../node_modules/@popperjs/core/lib/enums.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getNodeName.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getWindow.js", "../../../node_modules/@popperjs/core/lib/dom-utils/instanceOf.js", "../../../node_modules/@popperjs/core/lib/modifiers/applyStyles.js", "../../../node_modules/@popperjs/core/lib/utils/getBasePlacement.js", "../../../node_modules/@popperjs/core/lib/utils/math.js", "../../../node_modules/@popperjs/core/lib/utils/userAgent.js", "../../../node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js", "../../../node_modules/@popperjs/core/lib/dom-utils/contains.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js", "../../../node_modules/@popperjs/core/lib/dom-utils/isTableElement.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getParentNode.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js", "../../../node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js", "../../../node_modules/@popperjs/core/lib/utils/within.js", "../../../node_modules/@popperjs/core/lib/utils/getFreshSideObject.js", "../../../node_modules/@popperjs/core/lib/utils/mergePaddingObject.js", "../../../node_modules/@popperjs/core/lib/utils/expandToHashMap.js", "../../../node_modules/@popperjs/core/lib/modifiers/arrow.js", "../../../node_modules/@popperjs/core/lib/utils/getVariation.js", "../../../node_modules/@popperjs/core/lib/modifiers/computeStyles.js", "../../../node_modules/@popperjs/core/lib/modifiers/eventListeners.js", "../../../node_modules/@popperjs/core/lib/utils/getOppositePlacement.js", "../../../node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js", "../../../node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js", "../../../node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js", "../../../node_modules/@popperjs/core/lib/utils/rectToClientRect.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js", "../../../node_modules/@popperjs/core/lib/utils/computeOffsets.js", "../../../node_modules/@popperjs/core/lib/utils/detectOverflow.js", "../../../node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js", "../../../node_modules/@popperjs/core/lib/modifiers/flip.js", "../../../node_modules/@popperjs/core/lib/modifiers/hide.js", "../../../node_modules/@popperjs/core/lib/modifiers/offset.js", "../../../node_modules/@popperjs/core/lib/modifiers/popperOffsets.js", "../../../node_modules/@popperjs/core/lib/utils/getAltAxis.js", "../../../node_modules/@popperjs/core/lib/modifiers/preventOverflow.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js", "../../../node_modules/@popperjs/core/lib/utils/orderModifiers.js", "../../../node_modules/@popperjs/core/lib/utils/debounce.js", "../../../node_modules/@popperjs/core/lib/utils/mergeByName.js", "../../../node_modules/@popperjs/core/lib/createPopper.js", "../../../node_modules/@popperjs/core/lib/popper.js", "../../../node_modules/tippy.js/src/constants.ts", "../../../node_modules/tippy.js/src/utils.ts", "../../../node_modules/tippy.js/src/dom-utils.ts", "../../../node_modules/tippy.js/src/bindGlobalEventListeners.ts", "../../../node_modules/tippy.js/src/browser.ts", "../../../node_modules/tippy.js/src/validation.ts", "../../../node_modules/tippy.js/src/props.ts", "../../../node_modules/tippy.js/src/template.ts", "../../../node_modules/tippy.js/src/createTippy.ts", "../../../node_modules/tippy.js/src/index.ts", "../../../node_modules/tippy.js/src/addons/createSingleton.ts", "../../../node_modules/tippy.js/src/addons/delegate.ts", "../../../node_modules/tippy.js/src/plugins/animateFill.ts", "../../../node_modules/tippy.js/src/plugins/followCursor.ts", "../../../node_modules/tippy.js/src/plugins/inlinePositioning.ts", "../../../node_modules/tippy.js/src/plugins/sticky.ts", "../../../node_modules/tippy.js/build/base.js", "../javascript/controllers/application/tooltip_controller.js", "stimulus_ns:/tmp/build_61d68910/app/assets/javascript/controllers/application", "../javascript/controllers/application/index.js", "../javascript/controllers/shared/autosize_controller.js", "../../../node_modules/@rails/activestorage/app/assets/javascripts/activestorage.esm.js", "../javascript/controllers/shared/file_upload_controller.js", "../javascript/controllers/shared/password_peek_controller.js", "../javascript/controllers/shared/swal_confirm_controller.js", "../javascript/controllers/shared/toggle_controller.js", "stimulus_ns:/tmp/build_61d68910/app/assets/javascript/controllers/shared", "../javascript/controllers/shared/index.js", "../javascript/mobile.js", "../../../node_modules/@fortawesome/fontawesome-svg-core/index.mjs", "../../../node_modules/@fortawesome/free-solid-svg-icons/index.mjs", "../../../node_modules/@fortawesome/pro-solid-svg-icons/index.mjs", "../javascript/icons/index.js", "../javascript/mobile/content.js", "../javascript/mobile/router.js", "../javascript/mobile/domHelpers.js", "../javascript/mobile/pages/home.js", "../javascript/mobile/sections/accordionItem.js", "../javascript/mobile/sections/accordion.js", "../javascript/mobile/pages/spotTheSigns.js", "../javascript/mobile/pages/spotTheSignsVideo.js", "../../../node_modules/@glidejs/glide/dist/glide.esm.js", "../javascript/mobile/sections/carouselItem.js", "../javascript/mobile/sections/carouselDot.js", "../javascript/mobile/sections/carousel.js", "../javascript/mobile/pages/whatIsModernSlavery.js", "../javascript/mobile/pages/complyWithUKLaw.js", "../javascript/mobile/pages/aboutApp.js", "../javascript/mobile/pages/fileAReport.js", "../javascript/mobile/pages/donate.js", "../javascript/mobile/pages/submissionSuccessful.js", "../javascript/mobile/sidebar.js"], "sourcesContent": ["/*!\n* sweetalert2 v11.26.25\n* Released under the MIT License.\n*/\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Sweetalert2 = factory());\n})(this, (function () { 'use strict';\n\n function _assertClassBrand(e, t, n) {\n if (\"function\" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;\n throw new TypeError(\"Private element is not present on this object\");\n }\n function _checkPrivateRedeclaration(e, t) {\n if (t.has(e)) throw new TypeError(\"Cannot initialize the same private elements twice on an object\");\n }\n function _classPrivateFieldGet2(s, a) {\n return s.get(_assertClassBrand(s, a));\n }\n function _classPrivateFieldInitSpec(e, t, a) {\n _checkPrivateRedeclaration(e, t), t.set(e, a);\n }\n function _classPrivateFieldSet2(s, a, r) {\n return s.set(_assertClassBrand(s, a), r), r;\n }\n\n const RESTORE_FOCUS_TIMEOUT = 100;\n\n /** @type {GlobalState} */\n const globalState = {};\n const focusPreviousActiveElement = () => {\n if (globalState.previousActiveElement instanceof HTMLElement) {\n globalState.previousActiveElement.focus();\n globalState.previousActiveElement = null;\n } else if (document.body) {\n document.body.focus();\n }\n };\n\n /**\n * Restore previous active (focused) element\n *\n * @param {boolean} returnFocus\n * @returns {Promise}\n */\n const restoreActiveElement = returnFocus => {\n return new Promise(resolve => {\n if (!returnFocus) {\n return resolve();\n }\n const x = window.scrollX;\n const y = window.scrollY;\n globalState.restoreFocusTimeout = setTimeout(() => {\n focusPreviousActiveElement();\n resolve();\n }, RESTORE_FOCUS_TIMEOUT); // issues/900\n\n window.scrollTo(x, y);\n });\n };\n\n const swalPrefix = 'swal2-';\n\n /**\n * @typedef {Record} SwalClasses\n */\n\n /**\n * @typedef {'success' | 'warning' | 'info' | 'question' | 'error'} SwalIcon\n * @typedef {Record} SwalIcons\n */\n\n /** @type {SwalClass[]} */\n const classNames = ['container', 'shown', 'height-auto', 'iosfix', 'popup', 'modal', 'no-backdrop', 'no-transition', 'toast', 'toast-shown', 'show', 'hide', 'close', 'title', 'html-container', 'actions', 'confirm', 'deny', 'cancel', 'footer', 'icon', 'icon-content', 'image', 'input', 'file', 'range', 'select', 'radio', 'checkbox', 'label', 'textarea', 'inputerror', 'input-label', 'validation-message', 'progress-steps', 'active-progress-step', 'progress-step', 'progress-step-line', 'loader', 'loading', 'styled', 'top', 'top-start', 'top-end', 'top-left', 'top-right', 'center', 'center-start', 'center-end', 'center-left', 'center-right', 'bottom', 'bottom-start', 'bottom-end', 'bottom-left', 'bottom-right', 'grow-row', 'grow-column', 'grow-fullscreen', 'rtl', 'timer-progress-bar', 'timer-progress-bar-container', 'scrollbar-measure', 'icon-success', 'icon-warning', 'icon-info', 'icon-question', 'icon-error', 'draggable', 'dragging'];\n const swalClasses = classNames.reduce((acc, className) => {\n acc[className] = swalPrefix + className;\n return acc;\n }, /** @type {SwalClasses} */{});\n\n /** @type {SwalIcon[]} */\n const icons = ['success', 'warning', 'info', 'question', 'error'];\n const iconTypes = icons.reduce((acc, icon) => {\n acc[icon] = swalPrefix + icon;\n return acc;\n }, /** @type {SwalIcons} */{});\n\n const consolePrefix = 'SweetAlert2:';\n\n /**\n * Capitalize the first letter of a string\n *\n * @param {string} str\n * @returns {string}\n */\n const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1);\n\n /**\n * Standardize console warnings\n *\n * @param {string | string[]} message\n */\n const warn = message => {\n console.warn(`${consolePrefix} ${typeof message === 'object' ? message.join(' ') : message}`);\n };\n\n /**\n * Standardize console errors\n *\n * @param {string} message\n */\n const error = message => {\n console.error(`${consolePrefix} ${message}`);\n };\n\n /**\n * Private global state for `warnOnce`\n *\n * @type {string[]}\n * @private\n */\n const previousWarnOnceMessages = [];\n\n /**\n * Show a console warning, but only if it hasn't already been shown\n *\n * @param {string} message\n */\n const warnOnce = message => {\n if (!previousWarnOnceMessages.includes(message)) {\n previousWarnOnceMessages.push(message);\n warn(message);\n }\n };\n\n /**\n * Show a one-time console warning about deprecated params/methods\n *\n * @param {string} deprecatedParam\n * @param {string?} useInstead\n */\n const warnAboutDeprecation = (deprecatedParam, useInstead = null) => {\n warnOnce(`\"${deprecatedParam}\" is deprecated and will be removed in the next major release.${useInstead ? ` Use \"${useInstead}\" instead.` : ''}`);\n };\n\n /**\n * If `arg` is a function, call it (with no arguments or context) and return the result.\n * Otherwise, just pass the value through\n *\n * @param {(() => *) | *} arg\n * @returns {*}\n */\n const callIfFunction = arg => typeof arg === 'function' ? arg() : arg;\n\n /**\n * @param {*} arg\n * @returns {boolean}\n */\n const hasToPromiseFn = arg => arg && typeof arg.toPromise === 'function';\n\n /**\n * @param {*} arg\n * @returns {Promise<*>}\n */\n const asPromise = arg => hasToPromiseFn(arg) ? arg.toPromise() : Promise.resolve(arg);\n\n /**\n * @param {*} arg\n * @returns {boolean}\n */\n const isPromise = arg => arg && Promise.resolve(arg) === arg;\n\n /**\n * @returns {boolean}\n */\n const isFirefox = () => navigator.userAgent.includes('Firefox');\n\n /**\n * Gets the popup container which contains the backdrop and the popup itself.\n *\n * @returns {HTMLElement | null}\n */\n const getContainer = () => document.body.querySelector(`.${swalClasses.container}`);\n\n /**\n * @param {string} selectorString\n * @returns {HTMLElement | null}\n */\n const elementBySelector = selectorString => {\n const container = getContainer();\n return container ? container.querySelector(selectorString) : null;\n };\n\n /**\n * @param {string} className\n * @returns {HTMLElement | null}\n */\n const elementByClass = className => {\n return elementBySelector(`.${className}`);\n };\n\n /**\n * @returns {HTMLElement | null}\n */\n const getPopup = () => elementByClass(swalClasses.popup);\n\n /**\n * @returns {HTMLElement | null}\n */\n const getIcon = () => elementByClass(swalClasses.icon);\n\n /**\n * @returns {HTMLElement | null}\n */\n const getIconContent = () => elementByClass(swalClasses['icon-content']);\n\n /**\n * @returns {HTMLElement | null}\n */\n const getTitle = () => elementByClass(swalClasses.title);\n\n /**\n * @returns {HTMLElement | null}\n */\n const getHtmlContainer = () => elementByClass(swalClasses['html-container']);\n\n /**\n * @returns {HTMLElement | null}\n */\n const getImage = () => elementByClass(swalClasses.image);\n\n /**\n * @returns {HTMLElement | null}\n */\n const getProgressSteps = () => elementByClass(swalClasses['progress-steps']);\n\n /**\n * @returns {HTMLElement | null}\n */\n const getValidationMessage = () => elementByClass(swalClasses['validation-message']);\n\n /**\n * @returns {HTMLButtonElement | null}\n */\n const getConfirmButton = () => (/** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.confirm}`));\n\n /**\n * @returns {HTMLButtonElement | null}\n */\n const getCancelButton = () => (/** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.cancel}`));\n\n /**\n * @returns {HTMLButtonElement | null}\n */\n const getDenyButton = () => (/** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.deny}`));\n\n /**\n * @returns {HTMLElement | null}\n */\n const getInputLabel = () => elementByClass(swalClasses['input-label']);\n\n /**\n * @returns {HTMLElement | null}\n */\n const getLoader = () => elementBySelector(`.${swalClasses.loader}`);\n\n /**\n * @returns {HTMLElement | null}\n */\n const getActions = () => elementByClass(swalClasses.actions);\n\n /**\n * @returns {HTMLElement | null}\n */\n const getFooter = () => elementByClass(swalClasses.footer);\n\n /**\n * @returns {HTMLElement | null}\n */\n const getTimerProgressBar = () => elementByClass(swalClasses['timer-progress-bar']);\n\n /**\n * @returns {HTMLElement | null}\n */\n const getCloseButton = () => elementByClass(swalClasses.close);\n\n // https://github.com/jkup/focusable/blob/master/index.js\n const focusable = `\n a[href],\n area[href],\n input:not([disabled]),\n select:not([disabled]),\n textarea:not([disabled]),\n button:not([disabled]),\n iframe,\n object,\n embed,\n [tabindex=\"0\"],\n [contenteditable],\n audio[controls],\n video[controls],\n summary\n`;\n /**\n * @returns {HTMLElement[]}\n */\n const getFocusableElements = () => {\n const popup = getPopup();\n if (!popup) {\n return [];\n }\n /** @type {NodeListOf} */\n const focusableElementsWithTabindex = popup.querySelectorAll('[tabindex]:not([tabindex=\"-1\"]):not([tabindex=\"0\"])');\n const focusableElementsWithTabindexSorted = Array.from(focusableElementsWithTabindex)\n // sort according to tabindex\n .sort((a, b) => {\n const tabindexA = parseInt(a.getAttribute('tabindex') || '0');\n const tabindexB = parseInt(b.getAttribute('tabindex') || '0');\n if (tabindexA > tabindexB) {\n return 1;\n } else if (tabindexA < tabindexB) {\n return -1;\n }\n return 0;\n });\n\n /** @type {NodeListOf} */\n const otherFocusableElements = popup.querySelectorAll(focusable);\n const otherFocusableElementsFiltered = Array.from(otherFocusableElements).filter(el => el.getAttribute('tabindex') !== '-1');\n return [...new Set(focusableElementsWithTabindexSorted.concat(otherFocusableElementsFiltered))].filter(el => isVisible$1(el));\n };\n\n /**\n * @returns {boolean}\n */\n const isModal = () => {\n return hasClass(document.body, swalClasses.shown) && !hasClass(document.body, swalClasses['toast-shown']) && !hasClass(document.body, swalClasses['no-backdrop']);\n };\n\n /**\n * @returns {boolean}\n */\n const isToast = () => {\n const popup = getPopup();\n if (!popup) {\n return false;\n }\n return hasClass(popup, swalClasses.toast);\n };\n\n /**\n * @returns {boolean}\n */\n const isLoading = () => {\n const popup = getPopup();\n if (!popup) {\n return false;\n }\n return popup.hasAttribute('data-loading');\n };\n\n /**\n * Securely set innerHTML of an element\n * https://github.com/sweetalert2/sweetalert2/issues/1926\n *\n * @param {HTMLElement} elem\n * @param {string} html\n */\n const setInnerHtml = (elem, html) => {\n elem.textContent = '';\n if (html) {\n const parser = new DOMParser();\n const parsed = parser.parseFromString(html, `text/html`);\n const head = parsed.querySelector('head');\n if (head) {\n Array.from(head.childNodes).forEach(child => {\n elem.appendChild(child);\n });\n }\n const body = parsed.querySelector('body');\n if (body) {\n Array.from(body.childNodes).forEach(child => {\n if (child instanceof HTMLVideoElement || child instanceof HTMLAudioElement) {\n elem.appendChild(child.cloneNode(true)); // https://github.com/sweetalert2/sweetalert2/issues/2507\n } else {\n elem.appendChild(child);\n }\n });\n }\n }\n };\n\n /**\n * @param {HTMLElement} elem\n * @param {string} className\n * @returns {boolean}\n */\n const hasClass = (elem, className) => {\n if (!className) {\n return false;\n }\n return className.split(/\\s+/).every(cls => elem.classList.contains(cls));\n };\n\n /**\n * @param {HTMLElement} elem\n * @param {SweetAlertOptions} params\n */\n const removeCustomClasses = (elem, params) => {\n Array.from(elem.classList).forEach(className => {\n if (!Object.values(swalClasses).includes(className) && !Object.values(iconTypes).includes(className) && !Object.values(params.showClass || {}).includes(className)) {\n elem.classList.remove(className);\n }\n });\n };\n\n /**\n * @param {HTMLElement} elem\n * @param {SweetAlertOptions} params\n * @param {string} className\n */\n const applyCustomClass = (elem, params, className) => {\n removeCustomClasses(elem, params);\n if (!params.customClass) {\n return;\n }\n const customClass = params.customClass[(/** @type {keyof SweetAlertCustomClass} */className)];\n if (!customClass) {\n return;\n }\n if (typeof customClass !== 'string' && !customClass.forEach) {\n warn(`Invalid type of customClass.${className}! Expected string or iterable object, got \"${typeof customClass}\"`);\n return;\n }\n addClass(elem, customClass);\n };\n\n /**\n * @param {HTMLElement} popup\n * @param {import('./renderers/renderInput').InputClass | SweetAlertInput} inputClass\n * @returns {HTMLInputElement | null}\n */\n const getInput$1 = (popup, inputClass) => {\n if (!inputClass) {\n return null;\n }\n switch (inputClass) {\n case 'select':\n case 'textarea':\n case 'file':\n return popup.querySelector(`.${swalClasses.popup} > .${swalClasses[inputClass]}`);\n case 'checkbox':\n return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.checkbox} input`);\n case 'radio':\n return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.radio} input:checked`) || popup.querySelector(`.${swalClasses.popup} > .${swalClasses.radio} input:first-child`);\n case 'range':\n return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.range} input`);\n default:\n return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.input}`);\n }\n };\n\n /**\n * @param {HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement} input\n */\n const focusInput = input => {\n input.focus();\n\n // place cursor at end of text in text input\n if (input.type !== 'file') {\n // http://stackoverflow.com/a/2345915\n const val = input.value;\n input.value = '';\n input.value = val;\n }\n };\n\n /**\n * @param {HTMLElement | HTMLElement[] | null} target\n * @param {string | string[] | readonly string[] | undefined} classList\n * @param {boolean} condition\n */\n const toggleClass = (target, classList, condition) => {\n if (!target || !classList) {\n return;\n }\n const classes = typeof classList === 'string' ? classList.split(/\\s+/).filter(Boolean) : classList;\n const targets = Array.isArray(target) ? target : [target];\n targets.forEach(elem => {\n classes.forEach(className => {\n if (condition) {\n elem.classList.add(className);\n } else {\n elem.classList.remove(className);\n }\n });\n });\n };\n\n /**\n * @param {HTMLElement | HTMLElement[] | null} target\n * @param {string | string[] | readonly string[] | undefined} classList\n */\n const addClass = (target, classList) => {\n toggleClass(target, classList, true);\n };\n\n /**\n * @param {HTMLElement | HTMLElement[] | null} target\n * @param {string | string[] | readonly string[] | undefined} classList\n */\n const removeClass = (target, classList) => {\n toggleClass(target, classList, false);\n };\n\n /**\n * Get direct child of an element by class name\n *\n * @param {HTMLElement} elem\n * @param {string} className\n * @returns {HTMLElement | undefined}\n */\n const getDirectChildByClass = (elem, className) => (/** @type {HTMLElement | undefined} */\n Array.from(elem.children).find(child => child instanceof HTMLElement && hasClass(child, className)));\n\n /**\n * @param {HTMLElement} elem\n * @param {string} property\n * @param {string | number | null | undefined} value\n */\n const applyNumericalStyle = (elem, property, value) => {\n if (value === `${parseInt(`${value}`)}`) {\n value = parseInt(value);\n }\n if (value || value === 0) {\n elem.style.setProperty(property, typeof value === 'number' ? `${value}px` : (/** @type {string} */value));\n } else {\n elem.style.removeProperty(property);\n }\n };\n\n /**\n * @param {HTMLElement | null} elem\n * @param {string} display\n */\n const show = (elem, display = 'flex') => {\n if (!elem) {\n return;\n }\n elem.style.display = display;\n };\n\n /**\n * @param {HTMLElement | null} elem\n */\n const hide = elem => {\n if (!elem) {\n return;\n }\n elem.style.display = 'none';\n };\n\n /**\n * @param {HTMLElement | null} elem\n * @param {string} display\n */\n const showWhenInnerHtmlPresent = (elem, display = 'block') => {\n if (!elem) {\n return;\n }\n new MutationObserver(() => {\n toggle(elem, elem.innerHTML, display);\n }).observe(elem, {\n childList: true,\n subtree: true\n });\n };\n\n /**\n * @param {HTMLElement} parent\n * @param {string} selector\n * @param {string} property\n * @param {string} value\n */\n const setStyle = (parent, selector, property, value) => {\n /** @type {HTMLElement | null} */\n const el = parent.querySelector(selector);\n if (el) {\n el.style.setProperty(property, value);\n }\n };\n\n /**\n * @param {HTMLElement} elem\n * @param {boolean | string | null | undefined} condition\n * @param {string} display\n */\n const toggle = (elem, condition, display = 'flex') => {\n if (condition) {\n show(elem, display);\n } else {\n hide(elem);\n }\n };\n\n /**\n * borrowed from jquery $(elem).is(':visible') implementation\n *\n * @param {HTMLElement | null} elem\n * @returns {boolean}\n */\n const isVisible$1 = elem => Boolean(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length));\n\n /**\n * @returns {boolean}\n */\n const allButtonsAreHidden = () => !isVisible$1(getConfirmButton()) && !isVisible$1(getDenyButton()) && !isVisible$1(getCancelButton());\n\n /**\n * @param {HTMLElement} elem\n * @returns {boolean}\n */\n const isScrollable = elem => Boolean(elem.scrollHeight > elem.clientHeight);\n\n /**\n * @param {HTMLElement} element\n * @param {HTMLElement} stopElement\n * @returns {boolean}\n */\n const selfOrParentIsScrollable = (element, stopElement) => {\n let parent = /** @type {HTMLElement | null} */element;\n while (parent && parent !== stopElement) {\n if (isScrollable(parent)) {\n return true;\n }\n parent = parent.parentElement;\n }\n return false;\n };\n\n /**\n * borrowed from https://stackoverflow.com/a/46352119\n *\n * @param {HTMLElement} elem\n * @returns {boolean}\n */\n const hasCssAnimation = elem => {\n const style = window.getComputedStyle(elem);\n const animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0');\n const transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0');\n return animDuration > 0 || transDuration > 0;\n };\n\n /**\n * @param {number} timer\n * @param {boolean} reset\n */\n const animateTimerProgressBar = (timer, reset = false) => {\n const timerProgressBar = getTimerProgressBar();\n if (!timerProgressBar) {\n return;\n }\n if (isVisible$1(timerProgressBar)) {\n if (reset) {\n timerProgressBar.style.transition = 'none';\n timerProgressBar.style.width = '100%';\n }\n setTimeout(() => {\n timerProgressBar.style.transition = `width ${timer / 1000}s linear`;\n timerProgressBar.style.width = '0%';\n }, 10);\n }\n };\n const stopTimerProgressBar = () => {\n const timerProgressBar = getTimerProgressBar();\n if (!timerProgressBar) {\n return;\n }\n const timerProgressBarWidth = parseInt(window.getComputedStyle(timerProgressBar).width);\n timerProgressBar.style.removeProperty('transition');\n timerProgressBar.style.width = '100%';\n const timerProgressBarFullWidth = parseInt(window.getComputedStyle(timerProgressBar).width);\n const timerProgressBarPercent = timerProgressBarWidth / timerProgressBarFullWidth * 100;\n timerProgressBar.style.width = `${timerProgressBarPercent}%`;\n };\n\n /**\n * Detect Node env\n *\n * @returns {boolean}\n */\n const isNodeEnv = () => typeof window === 'undefined' || typeof document === 'undefined';\n\n const sweetHTML = `\n
\n \n
    \n
    \n \n

    \n
    \n \n \n
    \n \n \n
    \n \n
    \n \n \n
    \n
    \n
    \n \n \n \n
    \n
    \n
    \n
    \n
    \n
    \n`.replace(/(^|\\n)\\s*/g, '');\n\n /**\n * @returns {boolean}\n */\n const resetOldContainer = () => {\n const oldContainer = getContainer();\n if (!oldContainer) {\n return false;\n }\n oldContainer.remove();\n removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'],\n // @ts-ignore: 'has-column' is not defined in swalClasses but may be set dynamically\n swalClasses['has-column']]);\n return true;\n };\n const resetValidationMessage$1 = () => {\n if (globalState.currentInstance) {\n globalState.currentInstance.resetValidationMessage();\n }\n };\n const addInputChangeListeners = () => {\n const popup = getPopup();\n if (!popup) {\n return;\n }\n const input = getDirectChildByClass(popup, swalClasses.input);\n const file = getDirectChildByClass(popup, swalClasses.file);\n /** @type {HTMLInputElement | null} */\n const range = popup.querySelector(`.${swalClasses.range} input`);\n /** @type {HTMLOutputElement | null} */\n const rangeOutput = popup.querySelector(`.${swalClasses.range} output`);\n const select = getDirectChildByClass(popup, swalClasses.select);\n /** @type {HTMLInputElement | null} */\n const checkbox = popup.querySelector(`.${swalClasses.checkbox} input`);\n const textarea = getDirectChildByClass(popup, swalClasses.textarea);\n if (input) {\n input.oninput = resetValidationMessage$1;\n }\n if (file) {\n file.onchange = resetValidationMessage$1;\n }\n if (select) {\n select.onchange = resetValidationMessage$1;\n }\n if (checkbox) {\n checkbox.onchange = resetValidationMessage$1;\n }\n if (textarea) {\n textarea.oninput = resetValidationMessage$1;\n }\n if (range && rangeOutput) {\n range.oninput = () => {\n resetValidationMessage$1();\n rangeOutput.value = range.value;\n };\n range.onchange = () => {\n resetValidationMessage$1();\n rangeOutput.value = range.value;\n };\n }\n };\n\n /**\n * @param {string | HTMLElement} target\n * @returns {HTMLElement}\n */\n const getTarget = target => {\n if (typeof target === 'string') {\n const element = document.querySelector(target);\n if (!element) {\n throw new Error(`Target element \"${target}\" not found`);\n }\n return /** @type {HTMLElement} */element;\n }\n return target;\n };\n\n /**\n * @param {SweetAlertOptions} params\n */\n const setupAccessibility = params => {\n const popup = getPopup();\n if (!popup) {\n return;\n }\n popup.setAttribute('role', params.toast ? 'alert' : 'dialog');\n popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive');\n if (!params.toast) {\n popup.setAttribute('aria-modal', 'true');\n }\n };\n\n /**\n * @param {HTMLElement} targetElement\n */\n const setupRTL = targetElement => {\n if (window.getComputedStyle(targetElement).direction === 'rtl') {\n addClass(getContainer(), swalClasses.rtl);\n globalState.isRTL = true;\n }\n };\n\n /**\n * Add modal + backdrop to DOM\n *\n * @param {SweetAlertOptions} params\n */\n const init = params => {\n // Clean up the old popup container if it exists\n const oldContainerExisted = resetOldContainer();\n if (isNodeEnv()) {\n error('SweetAlert2 requires document to initialize');\n return;\n }\n const container = document.createElement('div');\n container.className = swalClasses.container;\n if (oldContainerExisted) {\n addClass(container, swalClasses['no-transition']);\n }\n setInnerHtml(container, sweetHTML);\n container.dataset['swal2Theme'] = params.theme;\n const targetElement = getTarget(params.target || 'body');\n targetElement.appendChild(container);\n if (params.topLayer) {\n container.setAttribute('popover', '');\n container.showPopover();\n }\n setupAccessibility(params);\n setupRTL(targetElement);\n addInputChangeListeners();\n };\n\n /**\n * @param {HTMLElement | object | string} param\n * @param {HTMLElement} target\n */\n const parseHtmlToContainer = (param, target) => {\n // DOM element\n if (param instanceof HTMLElement) {\n target.appendChild(param);\n }\n\n // Object\n else if (typeof param === 'object') {\n handleObject(param, target);\n }\n\n // Plain string\n else if (param) {\n setInnerHtml(target, param);\n }\n };\n\n /**\n * @param {object} param\n * @param {HTMLElement} target\n */\n const handleObject = (param, target) => {\n // JQuery element(s)\n if ('jquery' in param) {\n handleJqueryElem(target, param);\n }\n\n // For other objects use their string representation\n else {\n setInnerHtml(target, param.toString());\n }\n };\n\n /**\n * @param {HTMLElement} target\n * @param {any} elem\n */\n const handleJqueryElem = (target, elem) => {\n target.textContent = '';\n if (0 in elem) {\n for (let i = 0; i in elem; i++) {\n target.appendChild(elem[i].cloneNode(true));\n }\n } else {\n target.appendChild(elem.cloneNode(true));\n }\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {SweetAlertOptions} params\n */\n const renderActions = (instance, params) => {\n const actions = getActions();\n const loader = getLoader();\n if (!actions || !loader) {\n return;\n }\n\n // Actions (buttons) wrapper\n if (!params.showConfirmButton && !params.showDenyButton && !params.showCancelButton) {\n hide(actions);\n } else {\n show(actions);\n }\n\n // Custom class\n applyCustomClass(actions, params, 'actions');\n\n // Render all the buttons\n renderButtons(actions, loader, params);\n\n // Loader\n setInnerHtml(loader, params.loaderHtml || '');\n applyCustomClass(loader, params, 'loader');\n };\n\n /**\n * @param {HTMLElement} actions\n * @param {HTMLElement} loader\n * @param {SweetAlertOptions} params\n */\n function renderButtons(actions, loader, params) {\n const confirmButton = getConfirmButton();\n const denyButton = getDenyButton();\n const cancelButton = getCancelButton();\n if (!confirmButton || !denyButton || !cancelButton) {\n return;\n }\n\n // Render buttons\n renderButton(confirmButton, 'confirm', params);\n renderButton(denyButton, 'deny', params);\n renderButton(cancelButton, 'cancel', params);\n handleButtonsStyling(confirmButton, denyButton, cancelButton, params);\n if (params.reverseButtons) {\n if (params.toast) {\n actions.insertBefore(cancelButton, confirmButton);\n actions.insertBefore(denyButton, confirmButton);\n } else {\n actions.insertBefore(cancelButton, loader);\n actions.insertBefore(denyButton, loader);\n actions.insertBefore(confirmButton, loader);\n }\n }\n }\n\n /**\n * @param {HTMLElement} confirmButton\n * @param {HTMLElement} denyButton\n * @param {HTMLElement} cancelButton\n * @param {SweetAlertOptions} params\n */\n function handleButtonsStyling(confirmButton, denyButton, cancelButton, params) {\n if (!params.buttonsStyling) {\n removeClass([confirmButton, denyButton, cancelButton], swalClasses.styled);\n return;\n }\n addClass([confirmButton, denyButton, cancelButton], swalClasses.styled);\n\n // Apply custom background colors and outline colors to action buttons\n /** @type {[HTMLElement, string, string | undefined][]} */\n const buttons = [[confirmButton, 'confirm', params.confirmButtonColor], [denyButton, 'deny', params.denyButtonColor], [cancelButton, 'cancel', params.cancelButtonColor]];\n buttons.forEach(([button, type, color]) => {\n if (color) {\n button.style.setProperty(`--swal2-${type}-button-background-color`, color);\n }\n applyOutlineColor(button);\n });\n }\n\n /**\n * @param {HTMLElement} button\n */\n function applyOutlineColor(button) {\n const buttonStyle = window.getComputedStyle(button);\n if (buttonStyle.getPropertyValue('--swal2-action-button-focus-box-shadow')) {\n // If the button already has a custom outline color, no need to change it\n return;\n }\n const outlineColor = buttonStyle.backgroundColor.replace(/rgba?\\((\\d+), (\\d+), (\\d+).*/, 'rgba($1, $2, $3, 0.5)');\n button.style.setProperty('--swal2-action-button-focus-box-shadow', buttonStyle.getPropertyValue('--swal2-outline').replace(/ rgba\\(.*/, ` ${outlineColor}`));\n }\n\n /**\n * @param {HTMLElement} button\n * @param {'confirm' | 'deny' | 'cancel'} buttonType\n * @param {SweetAlertOptions} params\n */\n function renderButton(button, buttonType, params) {\n const buttonName = /** @type {'Confirm' | 'Deny' | 'Cancel'} */capitalizeFirstLetter(buttonType);\n toggle(button, params[`show${buttonName}Button`], 'inline-block');\n setInnerHtml(button, params[`${buttonType}ButtonText`] || ''); // Set caption text\n button.setAttribute('aria-label', params[`${buttonType}ButtonAriaLabel`] || ''); // ARIA label\n\n // Add buttons custom classes\n button.className = swalClasses[buttonType];\n applyCustomClass(button, params, `${buttonType}Button`);\n }\n\n /**\n * @param {SweetAlert} instance\n * @param {SweetAlertOptions} params\n */\n const renderCloseButton = (instance, params) => {\n const closeButton = getCloseButton();\n if (!closeButton) {\n return;\n }\n setInnerHtml(closeButton, params.closeButtonHtml || '');\n\n // Custom class\n applyCustomClass(closeButton, params, 'closeButton');\n toggle(closeButton, params.showCloseButton);\n closeButton.setAttribute('aria-label', params.closeButtonAriaLabel || '');\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {SweetAlertOptions} params\n */\n const renderContainer = (instance, params) => {\n const container = getContainer();\n if (!container) {\n return;\n }\n handleBackdropParam(container, params.backdrop);\n handlePositionParam(container, params.position);\n handleGrowParam(container, params.grow);\n\n // Custom class\n applyCustomClass(container, params, 'container');\n };\n\n /**\n * @param {HTMLElement} container\n * @param {SweetAlertOptions['backdrop']} backdrop\n */\n function handleBackdropParam(container, backdrop) {\n if (typeof backdrop === 'string') {\n container.style.background = backdrop;\n } else if (!backdrop) {\n addClass([document.documentElement, document.body], swalClasses['no-backdrop']);\n }\n }\n\n /**\n * @param {HTMLElement} container\n * @param {SweetAlertOptions['position']} position\n */\n function handlePositionParam(container, position) {\n if (!position) {\n return;\n }\n if (position in swalClasses) {\n addClass(container, swalClasses[position]);\n } else {\n warn('The \"position\" parameter is not valid, defaulting to \"center\"');\n addClass(container, swalClasses.center);\n }\n }\n\n /**\n * @param {HTMLElement} container\n * @param {SweetAlertOptions['grow']} grow\n */\n function handleGrowParam(container, grow) {\n if (!grow) {\n return;\n }\n addClass(container, swalClasses[`grow-${grow}`]);\n }\n\n /**\n * This module contains `WeakMap`s for each effectively-\"private property\" that a `Swal` has.\n * For example, to set the private property \"foo\" of `this` to \"bar\", you can `privateProps.foo.set(this, 'bar')`\n * This is the approach that Babel will probably take to implement private methods/fields\n * https://github.com/tc39/proposal-private-methods\n * https://github.com/babel/babel/pull/7555\n * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*\n * then we can use that language feature.\n */\n\n var privateProps = {\n innerParams: new WeakMap(),\n domCache: new WeakMap(),\n focusedElement: new WeakMap()\n };\n\n /// \n\n\n /** @type {InputClass[]} */\n const inputClasses = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea'];\n\n /**\n * @param {SweetAlert} instance\n * @param {SweetAlertOptions} params\n */\n const renderInput = (instance, params) => {\n const popup = getPopup();\n if (!popup) {\n return;\n }\n const innerParams = privateProps.innerParams.get(instance);\n const rerender = !innerParams || params.input !== innerParams.input;\n inputClasses.forEach(inputClass => {\n const inputContainer = getDirectChildByClass(popup, swalClasses[inputClass]);\n if (!inputContainer) {\n return;\n }\n\n // set attributes\n setAttributes(inputClass, params.inputAttributes);\n\n // set class\n inputContainer.className = swalClasses[inputClass];\n if (rerender) {\n hide(inputContainer);\n }\n });\n if (params.input) {\n if (rerender) {\n showInput(params);\n }\n // set custom class\n setCustomClass(params);\n }\n };\n\n /**\n * @param {SweetAlertOptions} params\n */\n const showInput = params => {\n if (!params.input) {\n return;\n }\n if (!renderInputType[params.input]) {\n error(`Unexpected type of input! Expected ${Object.keys(renderInputType).join(' | ')}, got \"${params.input}\"`);\n return;\n }\n const inputContainer = getInputContainer(params.input);\n if (!inputContainer) {\n return;\n }\n const input = renderInputType[params.input](inputContainer, params);\n show(inputContainer);\n\n // input autofocus\n if (params.inputAutoFocus) {\n setTimeout(() => {\n focusInput(input);\n });\n }\n };\n\n /**\n * @param {HTMLInputElement} input\n */\n const removeAttributes = input => {\n for (const {\n name\n } of Array.from(input.attributes)) {\n if (!['id', 'type', 'value', 'style'].includes(name)) {\n input.removeAttribute(name);\n }\n }\n };\n\n /**\n * @param {InputClass} inputClass\n * @param {SweetAlertOptions['inputAttributes']} inputAttributes\n */\n const setAttributes = (inputClass, inputAttributes) => {\n const popup = getPopup();\n if (!popup) {\n return;\n }\n const input = getInput$1(popup, inputClass);\n if (!input) {\n return;\n }\n removeAttributes(input);\n for (const attr in inputAttributes) {\n input.setAttribute(attr, inputAttributes[attr]);\n }\n };\n\n /**\n * @param {SweetAlertOptions} params\n */\n const setCustomClass = params => {\n if (!params.input) {\n return;\n }\n const inputContainer = getInputContainer(params.input);\n if (inputContainer) {\n applyCustomClass(inputContainer, params, 'input');\n }\n };\n\n /**\n * @param {HTMLInputElement | HTMLTextAreaElement} input\n * @param {SweetAlertOptions} params\n */\n const setInputPlaceholder = (input, params) => {\n if (!input.placeholder && params.inputPlaceholder) {\n input.placeholder = params.inputPlaceholder;\n }\n };\n\n /**\n * @param {Input} input\n * @param {Input} prependTo\n * @param {SweetAlertOptions} params\n */\n const setInputLabel = (input, prependTo, params) => {\n if (params.inputLabel) {\n const label = document.createElement('label');\n const labelClass = swalClasses['input-label'];\n label.setAttribute('for', input.id);\n label.className = labelClass;\n if (typeof params.customClass === 'object') {\n addClass(label, params.customClass.inputLabel);\n }\n label.innerText = params.inputLabel;\n prependTo.insertAdjacentElement('beforebegin', label);\n }\n };\n\n /**\n * @param {SweetAlertInput} inputType\n * @returns {HTMLElement | undefined}\n */\n const getInputContainer = inputType => {\n const popup = getPopup();\n if (!popup) {\n return;\n }\n return getDirectChildByClass(popup, swalClasses[(/** @type {SwalClass} */inputType)] || swalClasses.input);\n };\n\n /**\n * @param {HTMLInputElement | HTMLOutputElement | HTMLTextAreaElement} input\n * @param {SweetAlertOptions['inputValue']} inputValue\n */\n const checkAndSetInputValue = (input, inputValue) => {\n if (['string', 'number'].includes(typeof inputValue)) {\n input.value = `${inputValue}`;\n } else if (!isPromise(inputValue)) {\n warn(`Unexpected type of inputValue! Expected \"string\", \"number\" or \"Promise\", got \"${typeof inputValue}\"`);\n }\n };\n\n /** @type {Record Input>} */\n const renderInputType = {};\n\n /**\n * @param {Input | HTMLElement} input\n * @param {SweetAlertOptions} params\n * @returns {Input}\n */\n renderInputType.text = renderInputType.email = renderInputType.password = renderInputType.number = renderInputType.tel = renderInputType.url = renderInputType.search = renderInputType.date = renderInputType['datetime-local'] = renderInputType.time = renderInputType.week = renderInputType.month = /** @type {(input: Input | HTMLElement, params: SweetAlertOptions) => Input} */\n (input, params) => {\n // oxfmt-ignore\n const inputElement = /** @type {HTMLInputElement} */input;\n checkAndSetInputValue(inputElement, params.inputValue);\n setInputLabel(inputElement, inputElement, params);\n setInputPlaceholder(inputElement, params);\n // oxfmt-ignore\n inputElement.type = /** @type {string} */params.input;\n return inputElement;\n };\n\n /**\n * @param {Input | HTMLElement} input\n * @param {SweetAlertOptions} params\n * @returns {Input}\n */\n renderInputType.file = (input, params) => {\n const inputElement = /** @type {HTMLInputElement} */input;\n setInputLabel(inputElement, inputElement, params);\n setInputPlaceholder(inputElement, params);\n return inputElement;\n };\n\n /**\n * @param {Input | HTMLElement} range\n * @param {SweetAlertOptions} params\n * @returns {Input}\n */\n renderInputType.range = (range, params) => {\n const rangeContainer = /** @type {HTMLElement} */range;\n const rangeInput = rangeContainer.querySelector('input');\n const rangeOutput = rangeContainer.querySelector('output');\n if (rangeInput) {\n checkAndSetInputValue(rangeInput, params.inputValue);\n rangeInput.type = /** @type {string} */params.input;\n setInputLabel(rangeInput, /** @type {Input} */range, params);\n }\n if (rangeOutput) {\n checkAndSetInputValue(rangeOutput, params.inputValue);\n }\n return /** @type {Input} */range;\n };\n\n /**\n * @param {Input | HTMLElement} select\n * @param {SweetAlertOptions} params\n * @returns {Input}\n */\n renderInputType.select = (select, params) => {\n const selectElement = /** @type {HTMLSelectElement} */select;\n selectElement.textContent = '';\n if (params.inputPlaceholder) {\n const placeholder = document.createElement('option');\n setInnerHtml(placeholder, params.inputPlaceholder);\n placeholder.value = '';\n placeholder.disabled = true;\n placeholder.selected = true;\n selectElement.appendChild(placeholder);\n }\n setInputLabel(selectElement, selectElement, params);\n return selectElement;\n };\n\n /**\n * @param {Input | HTMLElement} radio\n * @returns {Input}\n */\n renderInputType.radio = radio => {\n const radioElement = /** @type {HTMLElement} */radio;\n radioElement.textContent = '';\n return /** @type {Input} */radio;\n };\n\n /**\n * @param {Input | HTMLElement} checkboxContainer\n * @param {SweetAlertOptions} params\n * @returns {Input}\n */\n renderInputType.checkbox = (checkboxContainer, params) => {\n const popup = getPopup();\n if (!popup) {\n throw new Error('Popup not found');\n }\n const checkbox = getInput$1(popup, 'checkbox');\n if (!checkbox) {\n throw new Error('Checkbox input not found');\n }\n checkbox.value = '1';\n checkbox.checked = Boolean(params.inputValue);\n const containerElement = /** @type {HTMLElement} */checkboxContainer;\n const label = containerElement.querySelector('span');\n if (label) {\n const placeholderOrLabel = params.inputPlaceholder || params.inputLabel;\n if (placeholderOrLabel) {\n setInnerHtml(label, placeholderOrLabel);\n }\n }\n return checkbox;\n };\n\n /**\n * @param {Input | HTMLElement} textarea\n * @param {SweetAlertOptions} params\n * @returns {Input}\n */\n renderInputType.textarea = (textarea, params) => {\n const textareaElement = /** @type {HTMLTextAreaElement} */textarea;\n checkAndSetInputValue(textareaElement, params.inputValue);\n setInputPlaceholder(textareaElement, params);\n setInputLabel(textareaElement, textareaElement, params);\n\n /**\n * @param {HTMLElement} el\n * @returns {number}\n */\n const getMargin = el => parseInt(window.getComputedStyle(el).marginLeft) + parseInt(window.getComputedStyle(el).marginRight);\n\n // https://github.com/sweetalert2/sweetalert2/issues/2291\n setTimeout(() => {\n // https://github.com/sweetalert2/sweetalert2/issues/1699\n if ('MutationObserver' in window) {\n const popup = getPopup();\n if (!popup) {\n return;\n }\n const initialPopupWidth = parseInt(window.getComputedStyle(popup).width);\n const textareaResizeHandler = () => {\n // check if texarea is still in document (i.e. popup wasn't closed in the meantime)\n if (!document.body.contains(textareaElement)) {\n return;\n }\n const textareaWidth = textareaElement.offsetWidth + getMargin(textareaElement);\n const popupElement = getPopup();\n if (popupElement) {\n if (textareaWidth > initialPopupWidth) {\n popupElement.style.width = `${textareaWidth}px`;\n } else {\n applyNumericalStyle(popupElement, 'width', params.width);\n }\n }\n };\n new MutationObserver(textareaResizeHandler).observe(textareaElement, {\n attributes: true,\n attributeFilter: ['style']\n });\n }\n });\n return textareaElement;\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {SweetAlertOptions} params\n */\n const renderContent = (instance, params) => {\n const htmlContainer = getHtmlContainer();\n if (!htmlContainer) {\n return;\n }\n showWhenInnerHtmlPresent(htmlContainer);\n applyCustomClass(htmlContainer, params, 'htmlContainer');\n\n // Content as HTML\n if (params.html) {\n parseHtmlToContainer(params.html, htmlContainer);\n show(htmlContainer, 'block');\n }\n\n // Content as plain text\n else if (params.text) {\n htmlContainer.textContent = params.text;\n show(htmlContainer, 'block');\n }\n\n // No content\n else {\n hide(htmlContainer);\n }\n renderInput(instance, params);\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {SweetAlertOptions} params\n */\n const renderFooter = (instance, params) => {\n const footer = getFooter();\n if (!footer) {\n return;\n }\n showWhenInnerHtmlPresent(footer);\n toggle(footer, Boolean(params.footer), 'block');\n if (params.footer) {\n parseHtmlToContainer(params.footer, footer);\n }\n\n // Custom class\n applyCustomClass(footer, params, 'footer');\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {SweetAlertOptions} params\n */\n const renderIcon = (instance, params) => {\n const innerParams = privateProps.innerParams.get(instance);\n const icon = getIcon();\n if (!icon) {\n return;\n }\n\n // if the given icon already rendered, apply the styling without re-rendering the icon\n if (innerParams && params.icon === innerParams.icon) {\n // Custom or default content\n setContent(icon, params);\n applyStyles(icon, params);\n return;\n }\n if (!params.icon && !params.iconHtml) {\n hide(icon);\n return;\n }\n if (params.icon && Object.keys(iconTypes).indexOf(params.icon) === -1) {\n error(`Unknown icon! Expected \"success\", \"error\", \"warning\", \"info\" or \"question\", got \"${params.icon}\"`);\n hide(icon);\n return;\n }\n show(icon);\n\n // Custom or default content\n setContent(icon, params);\n applyStyles(icon, params);\n\n // Animate icon\n addClass(icon, params.showClass && params.showClass.icon);\n\n // Re-adjust the success icon on system theme change\n const colorSchemeQueryList = window.matchMedia('(prefers-color-scheme: dark)');\n colorSchemeQueryList.addEventListener('change', adjustSuccessIconBackgroundColor);\n };\n\n /**\n * @param {HTMLElement} icon\n * @param {SweetAlertOptions} params\n */\n const applyStyles = (icon, params) => {\n for (const [iconType, iconClassName] of Object.entries(iconTypes)) {\n if (params.icon !== iconType) {\n removeClass(icon, iconClassName);\n }\n }\n addClass(icon, params.icon && iconTypes[params.icon]);\n\n // Icon color\n setColor(icon, params);\n\n // Success icon background color\n adjustSuccessIconBackgroundColor();\n\n // Custom class\n applyCustomClass(icon, params, 'icon');\n };\n\n // Adjust success icon background color to match the popup background color\n const adjustSuccessIconBackgroundColor = () => {\n const popup = getPopup();\n if (!popup) {\n return;\n }\n const popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color');\n /** @type {NodeListOf} */\n const successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix');\n successIconParts.forEach(part => {\n part.style.backgroundColor = popupBackgroundColor;\n });\n };\n\n /**\n *\n * @param {SweetAlertOptions} params\n * @returns {string}\n */\n const successIconHtml = params => `\n ${params.animation ? '
    ' : ''}\n \n
    \n ${params.animation ? '
    ' : ''}\n ${params.animation ? '
    ' : ''}\n`;\n const errorIconHtml = `\n \n \n \n \n`;\n\n /**\n * @param {HTMLElement} icon\n * @param {SweetAlertOptions} params\n */\n const setContent = (icon, params) => {\n if (!params.icon && !params.iconHtml) {\n return;\n }\n let oldContent = icon.innerHTML;\n let newContent = '';\n if (params.iconHtml) {\n newContent = iconContent(params.iconHtml);\n } else if (params.icon === 'success') {\n newContent = successIconHtml(params);\n oldContent = oldContent.replace(/ style=\".*?\"/g, ''); // undo adjustSuccessIconBackgroundColor()\n } else if (params.icon === 'error') {\n newContent = errorIconHtml;\n } else if (params.icon) {\n const defaultIconHtml = {\n question: '?',\n warning: '!',\n info: 'i'\n };\n newContent = iconContent(defaultIconHtml[params.icon]);\n }\n if (oldContent.trim() !== newContent.trim()) {\n setInnerHtml(icon, newContent);\n }\n };\n\n /**\n * @param {HTMLElement} icon\n * @param {SweetAlertOptions} params\n */\n const setColor = (icon, params) => {\n if (!params.iconColor) {\n return;\n }\n icon.style.color = params.iconColor;\n icon.style.borderColor = params.iconColor;\n for (const sel of ['.swal2-success-line-tip', '.swal2-success-line-long', '.swal2-x-mark-line-left', '.swal2-x-mark-line-right']) {\n setStyle(icon, sel, 'background-color', params.iconColor);\n }\n setStyle(icon, '.swal2-success-ring', 'border-color', params.iconColor);\n };\n\n /**\n * @param {string} content\n * @returns {string}\n */\n const iconContent = content => `
    ${content}
    `;\n\n /**\n * @param {SweetAlert} instance\n * @param {SweetAlertOptions} params\n */\n const renderImage = (instance, params) => {\n const image = getImage();\n if (!image) {\n return;\n }\n if (!params.imageUrl) {\n hide(image);\n return;\n }\n show(image, '');\n\n // Src, alt\n image.setAttribute('src', params.imageUrl);\n image.setAttribute('alt', params.imageAlt || '');\n\n // Width, height\n applyNumericalStyle(image, 'width', params.imageWidth);\n applyNumericalStyle(image, 'height', params.imageHeight);\n\n // Class\n image.className = swalClasses.image;\n applyCustomClass(image, params, 'image');\n };\n\n let dragging = false;\n let mousedownX = 0;\n let mousedownY = 0;\n let initialX = 0;\n let initialY = 0;\n\n /**\n * @param {HTMLElement} popup\n */\n const addDraggableListeners = popup => {\n popup.addEventListener('mousedown', down);\n document.body.addEventListener('mousemove', move);\n popup.addEventListener('mouseup', up);\n popup.addEventListener('touchstart', down);\n document.body.addEventListener('touchmove', move);\n popup.addEventListener('touchend', up);\n };\n\n /**\n * @param {HTMLElement} popup\n */\n const removeDraggableListeners = popup => {\n popup.removeEventListener('mousedown', down);\n document.body.removeEventListener('mousemove', move);\n popup.removeEventListener('mouseup', up);\n popup.removeEventListener('touchstart', down);\n document.body.removeEventListener('touchmove', move);\n popup.removeEventListener('touchend', up);\n };\n\n /**\n * @param {MouseEvent | TouchEvent} event\n */\n const down = event => {\n const popup = getPopup();\n if (!popup) {\n return;\n }\n const icon = getIcon();\n if (event.target === popup || icon && icon.contains(/** @type {HTMLElement} */event.target)) {\n dragging = true;\n const clientXY = getClientXY(event);\n mousedownX = clientXY.clientX;\n mousedownY = clientXY.clientY;\n initialX = parseInt(popup.style.insetInlineStart) || 0;\n initialY = parseInt(popup.style.insetBlockStart) || 0;\n addClass(popup, 'swal2-dragging');\n }\n };\n\n /**\n * @param {MouseEvent | TouchEvent} event\n */\n const move = event => {\n const popup = getPopup();\n if (!popup) {\n return;\n }\n if (dragging) {\n let {\n clientX,\n clientY\n } = getClientXY(event);\n const deltaX = clientX - mousedownX;\n // In RTL mode, negate the horizontal delta since insetInlineStart refers to the right edge\n popup.style.insetInlineStart = `${initialX + (globalState.isRTL ? -deltaX : deltaX)}px`;\n popup.style.insetBlockStart = `${initialY + (clientY - mousedownY)}px`;\n }\n };\n const up = () => {\n const popup = getPopup();\n dragging = false;\n removeClass(popup, 'swal2-dragging');\n };\n\n /**\n * @param {MouseEvent | TouchEvent} event\n * @returns {{ clientX: number, clientY: number }}\n */\n const getClientXY = event => {\n const source = event.type.startsWith('touch') ? /** @type {TouchEvent} */event.touches[0] : (/** @type {MouseEvent} */event);\n return {\n clientX: source.clientX,\n clientY: source.clientY\n };\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {SweetAlertOptions} params\n */\n const renderPopup = (instance, params) => {\n const container = getContainer();\n const popup = getPopup();\n if (!container || !popup) {\n return;\n }\n\n // Width\n // https://github.com/sweetalert2/sweetalert2/issues/2170\n if (params.toast) {\n applyNumericalStyle(container, 'width', params.width);\n popup.style.width = '100%';\n const loader = getLoader();\n if (loader) {\n popup.insertBefore(loader, getIcon());\n }\n } else {\n applyNumericalStyle(popup, 'width', params.width);\n }\n\n // Padding\n applyNumericalStyle(popup, 'padding', params.padding);\n\n // Color\n if (params.color) {\n popup.style.color = params.color;\n }\n\n // Background\n if (params.background) {\n popup.style.background = params.background;\n }\n hide(getValidationMessage());\n\n // Classes\n addClasses$1(popup, params);\n if (params.draggable && !params.toast) {\n addClass(popup, swalClasses.draggable);\n addDraggableListeners(popup);\n } else {\n removeClass(popup, swalClasses.draggable);\n removeDraggableListeners(popup);\n }\n };\n\n /**\n * @param {HTMLElement} popup\n * @param {SweetAlertOptions} params\n */\n const addClasses$1 = (popup, params) => {\n const showClass = params.showClass || {};\n // Default Class + showClass when updating Swal.update({})\n popup.className = `${swalClasses.popup} ${isVisible$1(popup) ? showClass.popup : ''}`;\n if (params.toast) {\n addClass([document.documentElement, document.body], swalClasses['toast-shown']);\n addClass(popup, swalClasses.toast);\n } else {\n addClass(popup, swalClasses.modal);\n }\n\n // Custom class\n applyCustomClass(popup, params, 'popup');\n // TODO: remove in the next major\n if (typeof params.customClass === 'string') {\n addClass(popup, params.customClass);\n }\n\n // Icon class (#1842)\n if (params.icon) {\n addClass(popup, swalClasses[`icon-${params.icon}`]);\n }\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {SweetAlertOptions} params\n */\n const renderProgressSteps = (instance, params) => {\n const progressStepsContainer = getProgressSteps();\n if (!progressStepsContainer) {\n return;\n }\n const {\n progressSteps,\n currentProgressStep\n } = params;\n if (!progressSteps || progressSteps.length === 0 || currentProgressStep === undefined) {\n hide(progressStepsContainer);\n return;\n }\n show(progressStepsContainer);\n progressStepsContainer.textContent = '';\n if (currentProgressStep >= progressSteps.length) {\n warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)');\n }\n progressSteps.forEach((step, index) => {\n const stepEl = createStepElement(step);\n progressStepsContainer.appendChild(stepEl);\n if (index === currentProgressStep) {\n addClass(stepEl, swalClasses['active-progress-step']);\n }\n if (index !== progressSteps.length - 1) {\n const lineEl = createLineElement(params);\n progressStepsContainer.appendChild(lineEl);\n }\n });\n };\n\n /**\n * @param {string} step\n * @returns {HTMLLIElement}\n */\n const createStepElement = step => {\n const stepEl = document.createElement('li');\n addClass(stepEl, swalClasses['progress-step']);\n setInnerHtml(stepEl, step);\n return stepEl;\n };\n\n /**\n * @param {SweetAlertOptions} params\n * @returns {HTMLLIElement}\n */\n const createLineElement = params => {\n const lineEl = document.createElement('li');\n addClass(lineEl, swalClasses['progress-step-line']);\n if (params.progressStepsDistance) {\n applyNumericalStyle(lineEl, 'width', params.progressStepsDistance);\n }\n return lineEl;\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {SweetAlertOptions} params\n */\n const renderTitle = (instance, params) => {\n const title = getTitle();\n if (!title) {\n return;\n }\n showWhenInnerHtmlPresent(title);\n toggle(title, Boolean(params.title || params.titleText), 'block');\n if (params.title) {\n parseHtmlToContainer(params.title, title);\n }\n if (params.titleText) {\n title.innerText = params.titleText;\n }\n\n // Custom class\n applyCustomClass(title, params, 'title');\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {SweetAlertOptions} params\n */\n const render = (instance, params) => {\n var _globalState$eventEmi;\n renderPopup(instance, params);\n renderContainer(instance, params);\n renderProgressSteps(instance, params);\n renderIcon(instance, params);\n renderImage(instance, params);\n renderTitle(instance, params);\n renderCloseButton(instance, params);\n renderContent(instance, params);\n renderActions(instance, params);\n renderFooter(instance, params);\n const popup = getPopup();\n if (typeof params.didRender === 'function' && popup) {\n params.didRender(popup);\n }\n (_globalState$eventEmi = globalState.eventEmitter) === null || _globalState$eventEmi === void 0 || _globalState$eventEmi.emit('didRender', popup);\n };\n\n /*\n * Global function to determine if SweetAlert2 popup is shown\n */\n const isVisible = () => {\n return isVisible$1(getPopup());\n };\n\n /*\n * Global function to click 'Confirm' button\n */\n const clickConfirm = () => {\n var _dom$getConfirmButton;\n return (_dom$getConfirmButton = getConfirmButton()) === null || _dom$getConfirmButton === void 0 ? void 0 : _dom$getConfirmButton.click();\n };\n\n /*\n * Global function to click 'Deny' button\n */\n const clickDeny = () => {\n var _dom$getDenyButton;\n return (_dom$getDenyButton = getDenyButton()) === null || _dom$getDenyButton === void 0 ? void 0 : _dom$getDenyButton.click();\n };\n\n /*\n * Global function to click 'Cancel' button\n */\n const clickCancel = () => {\n var _dom$getCancelButton;\n return (_dom$getCancelButton = getCancelButton()) === null || _dom$getCancelButton === void 0 ? void 0 : _dom$getCancelButton.click();\n };\n\n /** @type {Record} */\n const DismissReason = Object.freeze({\n cancel: 'cancel',\n backdrop: 'backdrop',\n close: 'close',\n esc: 'esc',\n timer: 'timer'\n });\n\n /**\n * @param {GlobalState} globalState\n */\n const removeKeydownHandler = globalState => {\n if (globalState.keydownTarget && globalState.keydownHandlerAdded && globalState.keydownHandler) {\n const handler = /** @type {EventListenerOrEventListenerObject} */\n /** @type {unknown} */globalState.keydownHandler;\n globalState.keydownTarget.removeEventListener('keydown', handler, {\n capture: globalState.keydownListenerCapture\n });\n globalState.keydownHandlerAdded = false;\n }\n };\n\n /**\n * @param {GlobalState} globalState\n * @param {SweetAlertOptions} innerParams\n * @param {(dismiss: DismissReason) => void} dismissWith\n */\n const addKeydownHandler = (globalState, innerParams, dismissWith) => {\n removeKeydownHandler(globalState);\n if (!innerParams.toast) {\n /** @type {(this: HTMLElement, event: KeyboardEvent) => void} */\n const handler = e => keydownHandler(innerParams, e, dismissWith);\n globalState.keydownHandler = handler;\n const target = innerParams.keydownListenerCapture ? window : getPopup();\n if (target) {\n globalState.keydownTarget = target;\n globalState.keydownListenerCapture = innerParams.keydownListenerCapture;\n const eventHandler = /** @type {EventListenerOrEventListenerObject} */ /** @type {unknown} */handler;\n globalState.keydownTarget.addEventListener('keydown', eventHandler, {\n capture: globalState.keydownListenerCapture\n });\n globalState.keydownHandlerAdded = true;\n }\n }\n };\n\n /**\n * @param {number} index\n * @param {number} increment\n * @returns {boolean} shouldPreventDefault\n */\n const setFocus = (index, increment) => {\n var _dom$getPopup;\n const focusableElements = getFocusableElements();\n // search for visible elements and select the next possible match\n if (focusableElements.length) {\n index = index + increment;\n\n // shift + tab when .swal2-popup is focused\n if (index === -2) {\n index = focusableElements.length - 1;\n }\n\n // rollover to first item\n if (index === focusableElements.length) {\n index = 0;\n\n // go to last item\n } else if (index === -1) {\n index = focusableElements.length - 1;\n }\n focusableElements[index].focus();\n\n // don't prevent default for iframes (Firefox fix)\n // https://github.com/sweetalert2/sweetalert2/issues/2931\n if (isFirefox() && focusableElements[index] instanceof HTMLIFrameElement) {\n return false;\n }\n return true;\n }\n // no visible focusable elements, focus the popup\n (_dom$getPopup = getPopup()) === null || _dom$getPopup === void 0 || _dom$getPopup.focus();\n return true;\n };\n const arrowKeysNextButton = ['ArrowRight', 'ArrowDown'];\n const arrowKeysPreviousButton = ['ArrowLeft', 'ArrowUp'];\n\n /**\n * @param {SweetAlertOptions} innerParams\n * @param {KeyboardEvent} event\n * @param {(dismiss: DismissReason) => void} dismissWith\n */\n const keydownHandler = (innerParams, event, dismissWith) => {\n if (!innerParams) {\n return; // This instance has already been destroyed\n }\n\n // Ignore keydown during IME composition\n // https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event#ignoring_keydown_during_ime_composition\n // https://github.com/sweetalert2/sweetalert2/issues/720\n // https://github.com/sweetalert2/sweetalert2/issues/2406\n if (event.isComposing || event.keyCode === 229) {\n return;\n }\n if (innerParams.stopKeydownPropagation) {\n event.stopPropagation();\n }\n\n // ENTER\n if (event.key === 'Enter') {\n handleEnter(event, innerParams);\n }\n\n // TAB\n else if (event.key === 'Tab') {\n handleTab(event);\n }\n\n // ARROWS - switch focus between buttons\n else if ([...arrowKeysNextButton, ...arrowKeysPreviousButton].includes(event.key)) {\n handleArrows(event.key);\n }\n\n // ESC\n else if (event.key === 'Escape') {\n handleEsc(event, innerParams, dismissWith);\n }\n };\n\n /**\n * @param {KeyboardEvent} event\n * @param {SweetAlertOptions} innerParams\n */\n const handleEnter = (event, innerParams) => {\n // https://github.com/sweetalert2/sweetalert2/issues/2386\n if (!callIfFunction(innerParams.allowEnterKey)) {\n return;\n }\n const popup = getPopup();\n if (!popup || !innerParams.input) {\n return;\n }\n const input = getInput$1(popup, innerParams.input);\n if (event.target && input && event.target instanceof HTMLElement && event.target.outerHTML === input.outerHTML) {\n if (['textarea', 'file'].includes(innerParams.input)) {\n return; // do not submit\n }\n clickConfirm();\n event.preventDefault();\n }\n };\n\n /**\n * @param {KeyboardEvent} event\n */\n const handleTab = event => {\n const targetElement = event.target;\n const focusableElements = getFocusableElements();\n const btnIndex = focusableElements.findIndex(el => el === targetElement);\n\n // don't prevent default for iframes (Firefox fix)\n // https://github.com/sweetalert2/sweetalert2/issues/2931\n let shouldPreventDefault = true;\n\n // Cycle to the next button\n if (!event.shiftKey) {\n shouldPreventDefault = setFocus(btnIndex, 1);\n }\n\n // Cycle to the prev button\n else {\n shouldPreventDefault = setFocus(btnIndex, -1);\n }\n event.stopPropagation();\n if (shouldPreventDefault) {\n event.preventDefault();\n }\n };\n\n /**\n * @param {string} key\n */\n const handleArrows = key => {\n const actions = getActions();\n const confirmButton = getConfirmButton();\n const denyButton = getDenyButton();\n const cancelButton = getCancelButton();\n if (!actions || !confirmButton || !denyButton || !cancelButton) {\n return;\n }\n /** @type HTMLElement[] */\n const buttons = [confirmButton, denyButton, cancelButton];\n if (document.activeElement instanceof HTMLElement && !buttons.includes(document.activeElement)) {\n return;\n }\n const sibling = arrowKeysNextButton.includes(key) ? 'nextElementSibling' : 'previousElementSibling';\n let buttonToFocus = document.activeElement;\n if (!buttonToFocus) {\n return;\n }\n for (let i = 0; i < actions.children.length; i++) {\n buttonToFocus = buttonToFocus[sibling];\n if (!buttonToFocus) {\n return;\n }\n if (buttonToFocus instanceof HTMLButtonElement && isVisible$1(buttonToFocus)) {\n break;\n }\n }\n if (buttonToFocus instanceof HTMLButtonElement) {\n buttonToFocus.focus();\n }\n };\n\n /**\n * @param {KeyboardEvent} event\n * @param {SweetAlertOptions} innerParams\n * @param {(dismiss: DismissReason) => void} dismissWith\n */\n const handleEsc = (event, innerParams, dismissWith) => {\n event.preventDefault();\n if (callIfFunction(innerParams.allowEscapeKey)) {\n dismissWith(DismissReason.esc);\n }\n };\n\n /**\n * This module contains `WeakMap`s for each effectively-\"private property\" that a `Swal` has.\n * For example, to set the private property \"foo\" of `this` to \"bar\", you can `privateProps.foo.set(this, 'bar')`\n * This is the approach that Babel will probably take to implement private methods/fields\n * https://github.com/tc39/proposal-private-methods\n * https://github.com/babel/babel/pull/7555\n * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*\n * then we can use that language feature.\n */\n\n var privateMethods = {\n swalPromiseResolve: new WeakMap(),\n swalPromiseReject: new WeakMap()\n };\n\n // From https://developer.paciellogroup.com/blog/2018/06/the-current-state-of-modal-dialog-accessibility/\n // Adding aria-hidden=\"true\" to elements outside of the active modal dialog ensures that\n // elements not within the active modal dialog will not be surfaced if a user opens a screen\n // reader\u2019s list of elements (headings, form controls, landmarks, etc.) in the document.\n\n const setAriaHidden = () => {\n const container = getContainer();\n const bodyChildren = Array.from(document.body.children);\n bodyChildren.forEach(el => {\n if (el.contains(container)) {\n return;\n }\n if (el.hasAttribute('aria-hidden')) {\n el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden') || '');\n }\n el.setAttribute('aria-hidden', 'true');\n });\n };\n const unsetAriaHidden = () => {\n const bodyChildren = Array.from(document.body.children);\n bodyChildren.forEach(el => {\n if (el.hasAttribute('data-previous-aria-hidden')) {\n el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden') || '');\n el.removeAttribute('data-previous-aria-hidden');\n } else {\n el.removeAttribute('aria-hidden');\n }\n });\n };\n\n // @ts-ignore\n const isSafariOrIOS = typeof window !== 'undefined' && Boolean(window.GestureEvent); // true for Safari desktop + all iOS browsers https://stackoverflow.com/a/70585394\n\n // @ts-ignore\n const isIOS = isSafariOrIOS && /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;\n\n /**\n * Fix iOS scrolling\n * http://stackoverflow.com/q/39626302\n */\n const iOSfix = () => {\n if (isSafariOrIOS && !hasClass(document.body, swalClasses.iosfix)) {\n const offset = document.body.scrollTop;\n document.body.style.top = `${offset * -1}px`;\n addClass(document.body, swalClasses.iosfix);\n lockBodyScroll();\n }\n };\n\n /**\n * https://github.com/sweetalert2/sweetalert2/issues/1246\n */\n const lockBodyScroll = () => {\n const container = getContainer();\n if (!container) {\n return;\n }\n /** @type {boolean} */\n let preventTouchMove;\n /**\n * @param {TouchEvent} event\n */\n container.ontouchstart = event => {\n preventTouchMove = shouldPreventTouchMove(event);\n };\n /**\n * @param {TouchEvent} event\n */\n container.ontouchmove = event => {\n if (preventTouchMove) {\n event.preventDefault();\n event.stopPropagation();\n }\n };\n };\n\n /**\n * @param {TouchEvent} event\n * @returns {boolean}\n */\n const shouldPreventTouchMove = event => {\n const target = event.target;\n const container = getContainer();\n const htmlContainer = getHtmlContainer();\n if (!container || !htmlContainer) {\n return false;\n }\n if (isStylus(event) || isZoom(event)) {\n return false;\n }\n if (target === container) {\n return true;\n }\n if (!isScrollable(container) && target instanceof HTMLElement && !selfOrParentIsScrollable(target, htmlContainer) &&\n // #2823\n target.tagName !== 'INPUT' &&\n // #1603\n target.tagName !== 'TEXTAREA' &&\n // #2266\n !(isScrollable(htmlContainer) &&\n // #1944\n htmlContainer.contains(target))) {\n return true;\n }\n return false;\n };\n\n /**\n * https://github.com/sweetalert2/sweetalert2/issues/1786\n *\n * @param {TouchEvent} event\n * @returns {boolean}\n */\n const isStylus = event => {\n return Boolean(event.touches && event.touches.length &&\n // @ts-ignore - touchType is not a standard property\n event.touches[0].touchType === 'stylus');\n };\n\n /**\n * https://github.com/sweetalert2/sweetalert2/issues/1891\n *\n * @param {TouchEvent} event\n * @returns {boolean}\n */\n const isZoom = event => {\n return event.touches && event.touches.length > 1;\n };\n const undoIOSfix = () => {\n if (hasClass(document.body, swalClasses.iosfix)) {\n const offset = parseInt(document.body.style.top, 10);\n removeClass(document.body, swalClasses.iosfix);\n document.body.style.top = '';\n document.body.scrollTop = offset * -1;\n }\n };\n\n /**\n * Measure scrollbar width for padding body during modal show/hide\n * https://github.com/twbs/bootstrap/blob/master/js/src/modal.js\n *\n * @returns {number}\n */\n const measureScrollbar = () => {\n const scrollDiv = document.createElement('div');\n scrollDiv.className = swalClasses['scrollbar-measure'];\n document.body.appendChild(scrollDiv);\n const scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;\n document.body.removeChild(scrollDiv);\n return scrollbarWidth;\n };\n\n /**\n * Remember state in cases where opening and handling a modal will fiddle with it.\n * @type {number | null}\n */\n let previousBodyPadding = null;\n\n /**\n * @param {string} initialBodyOverflow\n */\n const replaceScrollbarWithPadding = initialBodyOverflow => {\n // for queues, do not do this more than once\n if (previousBodyPadding !== null) {\n return;\n }\n // if the body has overflow\n if (document.body.scrollHeight > window.innerHeight || initialBodyOverflow === 'scroll' // https://github.com/sweetalert2/sweetalert2/issues/2663\n ) {\n // add padding so the content doesn't shift after removal of scrollbar\n previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right'));\n document.body.style.paddingRight = `${previousBodyPadding + measureScrollbar()}px`;\n }\n };\n const undoReplaceScrollbarWithPadding = () => {\n if (previousBodyPadding !== null) {\n document.body.style.paddingRight = `${previousBodyPadding}px`;\n previousBodyPadding = null;\n }\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {HTMLElement} container\n * @param {boolean} returnFocus\n * @param {(() => void) | undefined} didClose\n */\n function removePopupAndResetState(instance, container, returnFocus, didClose) {\n if (isToast()) {\n triggerDidCloseAndDispose(instance, didClose);\n } else {\n restoreActiveElement(returnFocus).then(() => triggerDidCloseAndDispose(instance, didClose));\n removeKeydownHandler(globalState);\n }\n\n // workaround for https://github.com/sweetalert2/sweetalert2/issues/2088\n // for some reason removing the container in Safari will scroll the document to bottom\n if (isSafariOrIOS) {\n container.setAttribute('style', 'display:none !important');\n container.removeAttribute('class');\n container.innerHTML = '';\n } else {\n container.remove();\n }\n if (isModal()) {\n undoReplaceScrollbarWithPadding();\n undoIOSfix();\n unsetAriaHidden();\n }\n removeBodyClasses();\n }\n\n /**\n * Remove SweetAlert2 classes from body\n */\n function removeBodyClasses() {\n removeClass([document.documentElement, document.body], [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown']]);\n }\n\n /**\n * Instance method to close sweetAlert\n *\n * @param {SweetAlertResult | undefined} resolveValue\n * @this {SweetAlert}\n */\n function close(resolveValue) {\n resolveValue = prepareResolveValue(resolveValue);\n const swalPromiseResolve = privateMethods.swalPromiseResolve.get(this);\n const didClose = triggerClosePopup(this);\n if (this.isAwaitingPromise) {\n // A swal awaiting for a promise (after a click on Confirm or Deny) cannot be dismissed anymore #2335\n if (!resolveValue.isDismissed) {\n handleAwaitingPromise(this);\n swalPromiseResolve(resolveValue);\n }\n } else if (didClose) {\n // Resolve Swal promise\n swalPromiseResolve(resolveValue);\n }\n }\n\n /**\n * @param {SweetAlert} instance\n * @returns {boolean}\n */\n const triggerClosePopup = instance => {\n const popup = getPopup();\n if (!popup) {\n return false;\n }\n const innerParams = privateProps.innerParams.get(instance);\n if (!innerParams || hasClass(popup, innerParams.hideClass.popup)) {\n return false;\n }\n removeClass(popup, innerParams.showClass.popup);\n addClass(popup, innerParams.hideClass.popup);\n const backdrop = getContainer();\n removeClass(backdrop, innerParams.showClass.backdrop);\n addClass(backdrop, innerParams.hideClass.backdrop);\n handlePopupAnimation(instance, popup, innerParams);\n return true;\n };\n\n /**\n * @param {Error | string} error\n * @this {SweetAlert}\n */\n function rejectPromise(error) {\n const rejectPromise = privateMethods.swalPromiseReject.get(this);\n handleAwaitingPromise(this);\n if (rejectPromise) {\n // Reject Swal promise\n rejectPromise(error);\n }\n }\n\n /**\n * @param {SweetAlert} instance\n */\n const handleAwaitingPromise = instance => {\n if (instance.isAwaitingPromise) {\n // @ts-ignore\n delete instance.isAwaitingPromise;\n // The instance might have been previously partly destroyed, we must resume the destroy process in this case #2335\n if (!privateProps.innerParams.get(instance)) {\n instance._destroy();\n }\n }\n };\n\n /**\n * @param {SweetAlertResult | undefined} resolveValue\n * @returns {SweetAlertResult}\n */\n const prepareResolveValue = resolveValue => {\n // When user calls Swal.close()\n if (typeof resolveValue === 'undefined') {\n return {\n isConfirmed: false,\n isDenied: false,\n isDismissed: true\n };\n }\n return Object.assign({\n isConfirmed: false,\n isDenied: false,\n isDismissed: false\n }, resolveValue);\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {HTMLElement} popup\n * @param {SweetAlertOptions} innerParams\n */\n const handlePopupAnimation = (instance, popup, innerParams) => {\n var _globalState$eventEmi;\n const container = getContainer();\n // If animation is supported, animate\n const animationIsSupported = hasCssAnimation(popup);\n if (typeof innerParams.willClose === 'function') {\n innerParams.willClose(popup);\n }\n (_globalState$eventEmi = globalState.eventEmitter) === null || _globalState$eventEmi === void 0 || _globalState$eventEmi.emit('willClose', popup);\n if (animationIsSupported && container) {\n animatePopup(instance, popup, container, Boolean(innerParams.returnFocus), innerParams.didClose);\n } else if (container) {\n // Otherwise, remove immediately\n removePopupAndResetState(instance, container, Boolean(innerParams.returnFocus), innerParams.didClose);\n }\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {HTMLElement} popup\n * @param {HTMLElement} container\n * @param {boolean} returnFocus\n * @param {(() => void) | undefined} didClose\n */\n const animatePopup = (instance, popup, container, returnFocus, didClose) => {\n globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, returnFocus, didClose);\n /**\n * @param {AnimationEvent | TransitionEvent} e\n */\n const swalCloseAnimationFinished = function (e) {\n if (e.target === popup) {\n var _globalState$swalClos;\n (_globalState$swalClos = globalState.swalCloseEventFinishedCallback) === null || _globalState$swalClos === void 0 || _globalState$swalClos.call(globalState);\n delete globalState.swalCloseEventFinishedCallback;\n popup.removeEventListener('animationend', swalCloseAnimationFinished);\n popup.removeEventListener('transitionend', swalCloseAnimationFinished);\n }\n };\n popup.addEventListener('animationend', swalCloseAnimationFinished);\n popup.addEventListener('transitionend', swalCloseAnimationFinished);\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {(() => void) | undefined} didClose\n */\n const triggerDidCloseAndDispose = (instance, didClose) => {\n setTimeout(() => {\n var _globalState$eventEmi2;\n if (typeof didClose === 'function') {\n didClose.bind(instance.params)();\n }\n (_globalState$eventEmi2 = globalState.eventEmitter) === null || _globalState$eventEmi2 === void 0 || _globalState$eventEmi2.emit('didClose');\n // instance might have been destroyed already\n if (instance._destroy) {\n instance._destroy();\n }\n });\n };\n\n /**\n * Shows loader (spinner), this is useful with AJAX requests.\n * By default the loader be shown instead of the \"Confirm\" button.\n *\n * @param {HTMLButtonElement | null} [buttonToReplace]\n */\n const showLoading = buttonToReplace => {\n let popup = getPopup();\n if (!popup) {\n new Swal();\n }\n popup = getPopup();\n if (!popup) {\n return;\n }\n const loader = getLoader();\n if (isToast()) {\n hide(getIcon());\n } else {\n replaceButton(popup, buttonToReplace);\n }\n show(loader);\n popup.setAttribute('data-loading', 'true');\n popup.setAttribute('aria-busy', 'true');\n popup.focus();\n };\n\n /**\n * @param {HTMLElement} popup\n * @param {HTMLButtonElement | null} [buttonToReplace]\n */\n const replaceButton = (popup, buttonToReplace) => {\n const actions = getActions();\n const loader = getLoader();\n if (!actions || !loader) {\n return;\n }\n if (!buttonToReplace && isVisible$1(getConfirmButton())) {\n buttonToReplace = getConfirmButton();\n }\n show(actions);\n if (buttonToReplace) {\n hide(buttonToReplace);\n loader.setAttribute('data-button-to-replace', buttonToReplace.className);\n actions.insertBefore(loader, buttonToReplace);\n }\n addClass([popup, actions], swalClasses.loading);\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {SweetAlertOptions} params\n */\n const handleInputOptionsAndValue = (instance, params) => {\n if (params.input === 'select' || params.input === 'radio') {\n handleInputOptions(instance, params);\n } else if (['text', 'email', 'number', 'tel', 'textarea'].some(i => i === params.input) && (hasToPromiseFn(params.inputValue) || isPromise(params.inputValue))) {\n showLoading(getConfirmButton());\n handleInputValue(instance, params);\n }\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {SweetAlertOptions} innerParams\n * @returns {SweetAlertInputValue}\n */\n const getInputValue = (instance, innerParams) => {\n const input = instance.getInput();\n if (!input) {\n return null;\n }\n switch (innerParams.input) {\n case 'checkbox':\n return getCheckboxValue(input);\n case 'radio':\n return getRadioValue(input);\n case 'file':\n return getFileValue(input);\n default:\n return innerParams.inputAutoTrim ? input.value.trim() : input.value;\n }\n };\n\n /**\n * @param {HTMLInputElement} input\n * @returns {number}\n */\n const getCheckboxValue = input => input.checked ? 1 : 0;\n\n /**\n * @param {HTMLInputElement} input\n * @returns {string | null}\n */\n const getRadioValue = input => input.checked ? input.value : null;\n\n /**\n * @param {HTMLInputElement} input\n * @returns {FileList | File | null}\n */\n const getFileValue = input => input.files && input.files.length ? input.getAttribute('multiple') !== null ? input.files : input.files[0] : null;\n\n /**\n * @param {SweetAlert} instance\n * @param {SweetAlertOptions} params\n */\n const handleInputOptions = (instance, params) => {\n const popup = getPopup();\n if (!popup) {\n return;\n }\n /**\n * @param {*} inputOptions\n */\n const processInputOptions = inputOptions => {\n if (params.input === 'select') {\n populateSelectOptions(popup, formatInputOptions(inputOptions), params);\n } else if (params.input === 'radio') {\n populateRadioOptions(popup, formatInputOptions(inputOptions), params);\n }\n };\n if (hasToPromiseFn(params.inputOptions) || isPromise(params.inputOptions)) {\n showLoading(getConfirmButton());\n asPromise(params.inputOptions).then(inputOptions => {\n instance.hideLoading();\n processInputOptions(inputOptions);\n });\n } else if (typeof params.inputOptions === 'object') {\n processInputOptions(params.inputOptions);\n } else {\n error(`Unexpected type of inputOptions! Expected object, Map or Promise, got ${typeof params.inputOptions}`);\n }\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {SweetAlertOptions} params\n */\n const handleInputValue = (instance, params) => {\n const input = instance.getInput();\n if (!input) {\n return;\n }\n hide(input);\n asPromise(params.inputValue).then(inputValue => {\n input.value = params.input === 'number' ? `${parseFloat(inputValue) || 0}` : `${inputValue}`;\n show(input);\n input.focus();\n instance.hideLoading();\n }).catch(err => {\n error(`Error in inputValue promise: ${err}`);\n input.value = '';\n show(input);\n input.focus();\n instance.hideLoading();\n });\n };\n\n /**\n * @param {HTMLElement} popup\n * @param {InputOptionFlattened[]} inputOptions\n * @param {SweetAlertOptions} params\n */\n function populateSelectOptions(popup, inputOptions, params) {\n const select = getDirectChildByClass(popup, swalClasses.select);\n if (!select) {\n return;\n }\n /**\n * @param {HTMLElement} parent\n * @param {string} optionLabel\n * @param {string} optionValue\n */\n const renderOption = (parent, optionLabel, optionValue) => {\n const option = document.createElement('option');\n option.value = optionValue;\n setInnerHtml(option, optionLabel);\n option.selected = isSelected(optionValue, params.inputValue);\n parent.appendChild(option);\n };\n inputOptions.forEach(inputOption => {\n const optionValue = inputOption[0];\n const optionLabel = inputOption[1];\n // spec:\n // https://www.w3.org/TR/html401/interact/forms.html#h-17.6\n // \"...all OPTGROUP elements must be specified directly within a SELECT element (i.e., groups may not be nested)...\"\n // check whether this is a \n if (Array.isArray(optionLabel)) {\n // if it is an array, then it is an \n const optgroup = document.createElement('optgroup');\n optgroup.label = optionValue;\n optgroup.disabled = false; // not configurable for now\n select.appendChild(optgroup);\n optionLabel.forEach(o => renderOption(optgroup, o[1], o[0]));\n } else {\n // case of \n };\n\n /**\n * @param {string} optionValue\n * @param {SweetAlertInputValue} inputValue\n * @returns {boolean}\n */\n const isSelected = (optionValue, inputValue) => Boolean(inputValue) && inputValue != null && inputValue.toString() === optionValue.toString();\n\n /**\n * @param {SweetAlert} instance\n */\n const handleConfirmButtonClick = instance => {\n const innerParams = privateProps.innerParams.get(instance);\n instance.disableButtons();\n if (innerParams.input) {\n handleConfirmOrDenyWithInput(instance, 'confirm');\n } else {\n confirm(instance, true);\n }\n };\n\n /**\n * @param {SweetAlert} instance\n */\n const handleDenyButtonClick = instance => {\n const innerParams = privateProps.innerParams.get(instance);\n instance.disableButtons();\n if (innerParams.returnInputValueOnDeny) {\n handleConfirmOrDenyWithInput(instance, 'deny');\n } else {\n deny(instance, false);\n }\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {(dismiss: DismissReason) => void} dismissWith\n */\n const handleCancelButtonClick = (instance, dismissWith) => {\n instance.disableButtons();\n dismissWith(DismissReason.cancel);\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {'confirm' | 'deny'} type\n */\n const handleConfirmOrDenyWithInput = (instance, type) => {\n const innerParams = privateProps.innerParams.get(instance);\n if (!innerParams.input) {\n error(`The \"input\" parameter is needed to be set when using returnInputValueOn${capitalizeFirstLetter(type)}`);\n return;\n }\n const input = instance.getInput();\n const inputValue = getInputValue(instance, innerParams);\n if (innerParams.inputValidator) {\n handleInputValidator(instance, inputValue, type);\n } else if (input && !input.checkValidity()) {\n instance.enableButtons();\n instance.showValidationMessage(innerParams.validationMessage || input.validationMessage);\n } else if (type === 'deny') {\n deny(instance, inputValue);\n } else {\n confirm(instance, inputValue);\n }\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {SweetAlertInputValue} inputValue\n * @param {'confirm' | 'deny'} type\n */\n const handleInputValidator = (instance, inputValue, type) => {\n const innerParams = privateProps.innerParams.get(instance);\n instance.disableInput();\n const validationPromise = Promise.resolve().then(() => asPromise(innerParams.inputValidator(inputValue, innerParams.validationMessage)));\n validationPromise.then(validationMessage => {\n instance.enableButtons();\n instance.enableInput();\n if (validationMessage) {\n instance.showValidationMessage(validationMessage);\n } else if (type === 'deny') {\n deny(instance, inputValue);\n } else {\n confirm(instance, inputValue);\n }\n });\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {*} value\n */\n const deny = (instance, value) => {\n const innerParams = privateProps.innerParams.get(instance);\n if (innerParams.showLoaderOnDeny) {\n showLoading(getDenyButton());\n }\n if (innerParams.preDeny) {\n instance.isAwaitingPromise = true; // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preDeny's promise is received\n const preDenyPromise = Promise.resolve().then(() => asPromise(innerParams.preDeny(value, innerParams.validationMessage)));\n preDenyPromise.then(preDenyValue => {\n if (preDenyValue === false) {\n instance.hideLoading();\n handleAwaitingPromise(instance);\n } else {\n instance.close(/** @type SweetAlertResult */{\n isDenied: true,\n value: typeof preDenyValue === 'undefined' ? value : preDenyValue\n });\n }\n }).catch(error => rejectWith(instance, error));\n } else {\n instance.close(/** @type SweetAlertResult */{\n isDenied: true,\n value\n });\n }\n };\n\n /**\n * @param {SweetAlert} instance\n * @param {*} value\n */\n const succeedWith = (instance, value) => {\n instance.close(/** @type SweetAlertResult */{\n isConfirmed: true,\n value\n });\n };\n\n /**\n *\n * @param {SweetAlert} instance\n * @param {string} error\n */\n const rejectWith = (instance, error) => {\n instance.rejectPromise(error);\n };\n\n /**\n *\n * @param {SweetAlert} instance\n * @param {*} value\n */\n const confirm = (instance, value) => {\n const innerParams = privateProps.innerParams.get(instance);\n if (innerParams.showLoaderOnConfirm) {\n showLoading();\n }\n if (innerParams.preConfirm) {\n instance.resetValidationMessage();\n instance.isAwaitingPromise = true; // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preConfirm's promise is received\n const preConfirmPromise = Promise.resolve().then(() => asPromise(innerParams.preConfirm(value, innerParams.validationMessage)));\n preConfirmPromise.then(preConfirmValue => {\n if (isVisible$1(getValidationMessage()) || preConfirmValue === false) {\n instance.hideLoading();\n handleAwaitingPromise(instance);\n } else {\n succeedWith(instance, typeof preConfirmValue === 'undefined' ? value : preConfirmValue);\n }\n }).catch(error => rejectWith(instance, error));\n } else {\n succeedWith(instance, value);\n }\n };\n\n /**\n * Hides loader and shows back the button which was hidden by .showLoading()\n * @this {SweetAlert}\n */\n function hideLoading() {\n // do nothing if popup is closed\n const innerParams = privateProps.innerParams.get(this);\n if (!innerParams) {\n return;\n }\n const domCache = privateProps.domCache.get(this);\n hide(domCache.loader);\n if (isToast()) {\n if (innerParams.icon) {\n show(getIcon());\n }\n } else {\n showRelatedButton(domCache);\n }\n removeClass([domCache.popup, domCache.actions], swalClasses.loading);\n domCache.popup.removeAttribute('aria-busy');\n domCache.popup.removeAttribute('data-loading');\n this.enableButtons();\n }\n\n /**\n * @param {DomCache} domCache\n */\n const showRelatedButton = domCache => {\n const dataButtonToReplace = domCache.loader.getAttribute('data-button-to-replace');\n const buttonToReplace = dataButtonToReplace ? domCache.popup.getElementsByClassName(dataButtonToReplace) : [];\n if (buttonToReplace.length) {\n show(/** @type {HTMLElement} */buttonToReplace[0], 'inline-block');\n } else if (allButtonsAreHidden()) {\n hide(domCache.actions);\n }\n };\n\n /**\n * Gets the input DOM node, this method works with input parameter.\n *\n * @returns {HTMLInputElement | null}\n * @this {SweetAlert}\n */\n function getInput() {\n const innerParams = privateProps.innerParams.get(this);\n const domCache = privateProps.domCache.get(this);\n if (!domCache) {\n return null;\n }\n return getInput$1(domCache.popup, innerParams.input);\n }\n\n /**\n * @param {SweetAlert} instance\n * @param {string[]} buttons\n * @param {boolean} disabled\n */\n function setButtonsDisabled(instance, buttons, disabled) {\n const domCache = privateProps.domCache.get(instance);\n buttons.forEach(button => {\n domCache[button].disabled = disabled;\n });\n }\n\n /**\n * @param {HTMLInputElement | null} input\n * @param {boolean} disabled\n */\n function setInputDisabled(input, disabled) {\n const popup = getPopup();\n if (!popup || !input) {\n return;\n }\n if (input.type === 'radio') {\n /** @type {NodeListOf} */\n const radios = popup.querySelectorAll(`[name=\"${swalClasses.radio}\"]`);\n radios.forEach(radio => {\n radio.disabled = disabled;\n });\n } else {\n input.disabled = disabled;\n }\n }\n\n /**\n * Enable all the buttons\n * @this {SweetAlert}\n */\n function enableButtons() {\n setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], false);\n const focusedElement = privateProps.focusedElement.get(this);\n if (focusedElement instanceof HTMLElement && document.activeElement === document.body) {\n focusedElement.focus();\n }\n privateProps.focusedElement.delete(this);\n }\n\n /**\n * Disable all the buttons\n * @this {SweetAlert}\n */\n function disableButtons() {\n privateProps.focusedElement.set(this, document.activeElement);\n setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], true);\n }\n\n /**\n * Enable the input field\n * @this {SweetAlert}\n */\n function enableInput() {\n setInputDisabled(this.getInput(), false);\n }\n\n /**\n * Disable the input field\n * @this {SweetAlert}\n */\n function disableInput() {\n setInputDisabled(this.getInput(), true);\n }\n\n /**\n * Show block with validation message\n *\n * @param {string} error\n * @this {SweetAlert}\n */\n function showValidationMessage(error) {\n const domCache = privateProps.domCache.get(this);\n const params = privateProps.innerParams.get(this);\n setInnerHtml(domCache.validationMessage, error);\n domCache.validationMessage.className = swalClasses['validation-message'];\n if (params.customClass && params.customClass.validationMessage) {\n addClass(domCache.validationMessage, params.customClass.validationMessage);\n }\n show(domCache.validationMessage);\n const input = this.getInput();\n if (input) {\n input.setAttribute('aria-invalid', 'true');\n input.setAttribute('aria-describedby', swalClasses['validation-message']);\n focusInput(input);\n addClass(input, swalClasses.inputerror);\n }\n }\n\n /**\n * Hide block with validation message\n *\n * @this {SweetAlert}\n */\n function resetValidationMessage() {\n const domCache = privateProps.domCache.get(this);\n if (domCache.validationMessage) {\n hide(domCache.validationMessage);\n }\n const input = this.getInput();\n if (input) {\n input.removeAttribute('aria-invalid');\n input.removeAttribute('aria-describedby');\n removeClass(input, swalClasses.inputerror);\n }\n }\n\n const defaultParams = {\n title: '',\n titleText: '',\n text: '',\n html: '',\n footer: '',\n icon: undefined,\n iconColor: undefined,\n iconHtml: undefined,\n template: undefined,\n toast: false,\n draggable: false,\n animation: true,\n theme: 'light',\n showClass: {\n popup: 'swal2-show',\n backdrop: 'swal2-backdrop-show',\n icon: 'swal2-icon-show'\n },\n hideClass: {\n popup: 'swal2-hide',\n backdrop: 'swal2-backdrop-hide',\n icon: 'swal2-icon-hide'\n },\n customClass: {},\n target: 'body',\n color: undefined,\n backdrop: true,\n heightAuto: true,\n allowOutsideClick: true,\n allowEscapeKey: true,\n allowEnterKey: true,\n stopKeydownPropagation: true,\n keydownListenerCapture: false,\n showConfirmButton: true,\n showDenyButton: false,\n showCancelButton: false,\n preConfirm: undefined,\n preDeny: undefined,\n confirmButtonText: 'OK',\n confirmButtonAriaLabel: '',\n confirmButtonColor: undefined,\n denyButtonText: 'No',\n denyButtonAriaLabel: '',\n denyButtonColor: undefined,\n cancelButtonText: 'Cancel',\n cancelButtonAriaLabel: '',\n cancelButtonColor: undefined,\n buttonsStyling: true,\n reverseButtons: false,\n focusConfirm: true,\n focusDeny: false,\n focusCancel: false,\n returnFocus: true,\n showCloseButton: false,\n closeButtonHtml: '×',\n closeButtonAriaLabel: 'Close this dialog',\n loaderHtml: '',\n showLoaderOnConfirm: false,\n showLoaderOnDeny: false,\n imageUrl: undefined,\n imageWidth: undefined,\n imageHeight: undefined,\n imageAlt: '',\n timer: undefined,\n timerProgressBar: false,\n width: undefined,\n padding: undefined,\n background: undefined,\n input: undefined,\n inputPlaceholder: '',\n inputLabel: '',\n inputValue: '',\n inputOptions: {},\n inputAutoFocus: true,\n inputAutoTrim: true,\n inputAttributes: {},\n inputValidator: undefined,\n returnInputValueOnDeny: false,\n validationMessage: undefined,\n grow: false,\n position: 'center',\n progressSteps: [],\n currentProgressStep: undefined,\n progressStepsDistance: undefined,\n willOpen: undefined,\n didOpen: undefined,\n didRender: undefined,\n willClose: undefined,\n didClose: undefined,\n didDestroy: undefined,\n scrollbarPadding: true,\n topLayer: false\n };\n const updatableParams = ['allowEscapeKey', 'allowOutsideClick', 'background', 'buttonsStyling', 'cancelButtonAriaLabel', 'cancelButtonColor', 'cancelButtonText', 'closeButtonAriaLabel', 'closeButtonHtml', 'color', 'confirmButtonAriaLabel', 'confirmButtonColor', 'confirmButtonText', 'currentProgressStep', 'customClass', 'denyButtonAriaLabel', 'denyButtonColor', 'denyButtonText', 'didClose', 'didDestroy', 'draggable', 'footer', 'hideClass', 'html', 'icon', 'iconColor', 'iconHtml', 'imageAlt', 'imageHeight', 'imageUrl', 'imageWidth', 'preConfirm', 'preDeny', 'progressSteps', 'returnFocus', 'reverseButtons', 'showCancelButton', 'showCloseButton', 'showConfirmButton', 'showDenyButton', 'text', 'title', 'titleText', 'theme', 'willClose'];\n\n /** @type {Record} */\n const deprecatedParams = {\n allowEnterKey: undefined\n };\n const toastIncompatibleParams = ['allowOutsideClick', 'allowEnterKey', 'backdrop', 'draggable', 'focusConfirm', 'focusDeny', 'focusCancel', 'returnFocus', 'heightAuto', 'keydownListenerCapture'];\n\n /**\n * Is valid parameter\n *\n * @param {string} paramName\n * @returns {boolean}\n */\n const isValidParameter = paramName => {\n return Object.prototype.hasOwnProperty.call(defaultParams, paramName);\n };\n\n /**\n * Is valid parameter for Swal.update() method\n *\n * @param {string} paramName\n * @returns {boolean}\n */\n const isUpdatableParameter = paramName => {\n return updatableParams.indexOf(paramName) !== -1;\n };\n\n /**\n * Is deprecated parameter\n *\n * @param {string} paramName\n * @returns {string | undefined}\n */\n const isDeprecatedParameter = paramName => {\n return deprecatedParams[paramName];\n };\n\n /**\n * @param {string} param\n */\n const checkIfParamIsValid = param => {\n if (!isValidParameter(param)) {\n warn(`Unknown parameter \"${param}\"`);\n }\n };\n\n /**\n * @param {string} param\n */\n const checkIfToastParamIsValid = param => {\n if (toastIncompatibleParams.includes(param)) {\n warn(`The parameter \"${param}\" is incompatible with toasts`);\n }\n };\n\n /**\n * @param {string} param\n */\n const checkIfParamIsDeprecated = param => {\n const isDeprecated = isDeprecatedParameter(param);\n if (isDeprecated) {\n warnAboutDeprecation(param, isDeprecated);\n }\n };\n\n /**\n * Show relevant warnings for given params\n *\n * @param {SweetAlertOptions} params\n */\n const showWarningsForParams = params => {\n if (params.backdrop === false && params.allowOutsideClick) {\n warn('\"allowOutsideClick\" parameter requires `backdrop` parameter to be set to `true`');\n }\n if (params.theme && !['light', 'dark', 'auto', 'minimal', 'borderless', 'bootstrap-4', 'bootstrap-4-light', 'bootstrap-4-dark', 'bootstrap-5', 'bootstrap-5-light', 'bootstrap-5-dark', 'material-ui', 'material-ui-light', 'material-ui-dark', 'embed-iframe', 'bulma', 'bulma-light', 'bulma-dark'].includes(params.theme)) {\n warn(`Invalid theme \"${params.theme}\"`);\n }\n for (const param in params) {\n checkIfParamIsValid(param);\n if (params.toast) {\n checkIfToastParamIsValid(param);\n }\n checkIfParamIsDeprecated(param);\n }\n };\n\n /**\n * Updates popup parameters.\n *\n * @this {any}\n * @param {SweetAlertOptions} params\n */\n function update(params) {\n const container = getContainer();\n const popup = getPopup();\n const innerParams = privateProps.innerParams.get(this);\n if (!popup || hasClass(popup, innerParams.hideClass.popup)) {\n warn(`You're trying to update the closed or closing popup, that won't work. Use the update() method in preConfirm parameter or show a new popup.`);\n return;\n }\n const validUpdatableParams = filterValidParams(params);\n const updatedParams = Object.assign({}, innerParams, validUpdatableParams);\n showWarningsForParams(updatedParams);\n if (container) {\n container.dataset['swal2Theme'] = updatedParams.theme;\n }\n render(this, updatedParams);\n privateProps.innerParams.set(this, updatedParams);\n Object.defineProperties(this, {\n params: {\n value: Object.assign({}, this.params, params),\n writable: false,\n enumerable: true\n }\n });\n }\n\n /**\n * @param {SweetAlertOptions} params\n * @returns {SweetAlertOptions}\n */\n const filterValidParams = params => {\n /** @type {Record} */\n const validUpdatableParams = {};\n Object.keys(params).forEach(param => {\n if (isUpdatableParameter(param)) {\n const typedParams = /** @type {Record} */params;\n validUpdatableParams[param] = typedParams[param];\n } else {\n warn(`Invalid parameter to update: ${param}`);\n }\n });\n return validUpdatableParams;\n };\n\n /**\n * Dispose the current SweetAlert2 instance\n * @this {SweetAlert}\n */\n function _destroy() {\n var _globalState$eventEmi;\n const domCache = privateProps.domCache.get(this);\n const innerParams = privateProps.innerParams.get(this);\n if (!innerParams) {\n disposeWeakMaps(this); // The WeakMaps might have been partly destroyed, we must recall it to dispose any remaining WeakMaps #2335\n return; // This instance has already been destroyed\n }\n\n // Check if there is another Swal closing\n if (domCache.popup && globalState.swalCloseEventFinishedCallback) {\n globalState.swalCloseEventFinishedCallback();\n delete globalState.swalCloseEventFinishedCallback;\n }\n if (typeof innerParams.didDestroy === 'function') {\n innerParams.didDestroy();\n }\n (_globalState$eventEmi = globalState.eventEmitter) === null || _globalState$eventEmi === void 0 || _globalState$eventEmi.emit('didDestroy');\n disposeSwal(this);\n }\n\n /**\n * @param {SweetAlert} instance\n */\n const disposeSwal = instance => {\n disposeWeakMaps(instance);\n // Unset this.params so GC will dispose it (#1569)\n // @ts-ignore\n delete instance.params;\n // Unset globalState props so GC will dispose globalState (#1569)\n delete globalState.keydownHandler;\n delete globalState.keydownTarget;\n // Unset currentInstance\n delete globalState.currentInstance;\n };\n\n /**\n * @param {SweetAlert} instance\n */\n const disposeWeakMaps = instance => {\n // If the current instance is awaiting a promise result, we keep the privateMethods to call them once the promise result is retrieved #2335\n if (instance.isAwaitingPromise) {\n unsetWeakMaps(privateProps, instance);\n instance.isAwaitingPromise = true;\n } else {\n unsetWeakMaps(privateMethods, instance);\n unsetWeakMaps(privateProps, instance);\n\n // @ts-ignore\n delete instance.isAwaitingPromise;\n // Unset instance methods\n // @ts-ignore\n delete instance.disableButtons;\n // @ts-ignore\n delete instance.enableButtons;\n // @ts-ignore\n delete instance.getInput;\n // @ts-ignore\n delete instance.disableInput;\n // @ts-ignore\n delete instance.enableInput;\n // @ts-ignore\n delete instance.hideLoading;\n // @ts-ignore\n delete instance.disableLoading;\n // @ts-ignore\n delete instance.showValidationMessage;\n // @ts-ignore\n delete instance.resetValidationMessage;\n // @ts-ignore\n delete instance.close;\n // @ts-ignore\n delete instance.closePopup;\n // @ts-ignore\n delete instance.closeModal;\n // @ts-ignore\n delete instance.closeToast;\n // @ts-ignore\n delete instance.rejectPromise;\n // @ts-ignore\n delete instance.update;\n // @ts-ignore\n delete instance._destroy;\n }\n };\n\n /**\n * @param {Record>} obj\n * @param {SweetAlert} instance\n */\n const unsetWeakMaps = (obj, instance) => {\n for (const i in obj) {\n obj[i].delete(instance);\n }\n };\n\n var instanceMethods = /*#__PURE__*/Object.freeze({\n __proto__: null,\n _destroy: _destroy,\n close: close,\n closeModal: close,\n closePopup: close,\n closeToast: close,\n disableButtons: disableButtons,\n disableInput: disableInput,\n disableLoading: hideLoading,\n enableButtons: enableButtons,\n enableInput: enableInput,\n getInput: getInput,\n handleAwaitingPromise: handleAwaitingPromise,\n hideLoading: hideLoading,\n rejectPromise: rejectPromise,\n resetValidationMessage: resetValidationMessage,\n showValidationMessage: showValidationMessage,\n update: update\n });\n\n /**\n * @param {SweetAlertOptions} innerParams\n * @param {DomCache} domCache\n * @param {(dismiss: DismissReason) => void} dismissWith\n */\n const handlePopupClick = (innerParams, domCache, dismissWith) => {\n if (innerParams.toast) {\n handleToastClick(innerParams, domCache, dismissWith);\n } else {\n // Ignore click events that had mousedown on the popup but mouseup on the container\n // This can happen when the user drags a slider\n handleModalMousedown(domCache);\n\n // Ignore click events that had mousedown on the container but mouseup on the popup\n handleContainerMousedown(domCache);\n handleModalClick(innerParams, domCache, dismissWith);\n }\n };\n\n /**\n * @param {SweetAlertOptions} innerParams\n * @param {DomCache} domCache\n * @param {(dismiss: DismissReason) => void} dismissWith\n */\n const handleToastClick = (innerParams, domCache, dismissWith) => {\n // Closing toast by internal click\n domCache.popup.onclick = () => {\n if (innerParams && (isAnyButtonShown(innerParams) || innerParams.timer || innerParams.input)) {\n return;\n }\n dismissWith(DismissReason.close);\n };\n };\n\n /**\n * @param {SweetAlertOptions} innerParams\n * @returns {boolean}\n */\n const isAnyButtonShown = innerParams => {\n return Boolean(innerParams.showConfirmButton || innerParams.showDenyButton || innerParams.showCancelButton || innerParams.showCloseButton);\n };\n let ignoreOutsideClick = false;\n\n /**\n * @param {DomCache} domCache\n */\n const handleModalMousedown = domCache => {\n domCache.popup.onmousedown = () => {\n domCache.container.onmouseup = function (e) {\n domCache.container.onmouseup = () => {};\n // We only check if the mouseup target is the container because usually it doesn't\n // have any other direct children aside of the popup\n if (e.target === domCache.container) {\n ignoreOutsideClick = true;\n }\n };\n };\n };\n\n /**\n * @param {DomCache} domCache\n */\n const handleContainerMousedown = domCache => {\n domCache.container.onmousedown = e => {\n // prevent the modal text from being selected on double click on the container (allowOutsideClick: false)\n if (e.target === domCache.container) {\n e.preventDefault();\n }\n domCache.popup.onmouseup = function (e) {\n domCache.popup.onmouseup = () => {};\n // We also need to check if the mouseup target is a child of the popup\n if (e.target === domCache.popup || e.target instanceof HTMLElement && domCache.popup.contains(e.target)) {\n ignoreOutsideClick = true;\n }\n };\n };\n };\n\n /**\n * @param {SweetAlertOptions} innerParams\n * @param {DomCache} domCache\n * @param {(dismiss: DismissReason) => void} dismissWith\n */\n const handleModalClick = (innerParams, domCache, dismissWith) => {\n domCache.container.onclick = e => {\n if (ignoreOutsideClick) {\n ignoreOutsideClick = false;\n return;\n }\n if (e.target === domCache.container && callIfFunction(innerParams.allowOutsideClick)) {\n dismissWith(DismissReason.backdrop);\n }\n };\n };\n\n /**\n * @param {unknown} elem\n * @returns {boolean}\n */\n const isJqueryElement = elem => typeof elem === 'object' && elem !== null && 'jquery' in elem;\n\n /**\n * @param {unknown} elem\n * @returns {boolean}\n */\n const isElement = elem => elem instanceof Element || isJqueryElement(elem);\n\n /**\n * @param {ReadonlyArray} args\n * @returns {SweetAlertOptions}\n */\n const argsToParams = args => {\n /** @type {Record} */\n const params = {};\n if (typeof args[0] === 'object' && !isElement(args[0])) {\n Object.assign(params, args[0]);\n } else {\n ['title', 'html', 'icon'].forEach((name, index) => {\n const arg = args[index];\n if (typeof arg === 'string' || isElement(arg)) {\n params[name] = arg;\n } else if (arg !== undefined) {\n error(`Unexpected type of ${name}! Expected \"string\" or \"Element\", got ${typeof arg}`);\n }\n });\n }\n return /** @type {SweetAlertOptions} */params;\n };\n\n /**\n * Main method to create a new SweetAlert2 popup\n *\n * @this {new (...args: any[]) => any}\n * @param {...SweetAlertOptions} args\n * @returns {Promise}\n */\n function fire(...args) {\n return new this(...args);\n }\n\n /**\n * Returns an extended version of `Swal` containing `params` as defaults.\n * Useful for reusing Swal configuration.\n *\n * For example:\n *\n * Before:\n * const textPromptOptions = { input: 'text', showCancelButton: true }\n * const {value: firstName} = await Swal.fire({ ...textPromptOptions, title: 'What is your first name?' })\n * const {value: lastName} = await Swal.fire({ ...textPromptOptions, title: 'What is your last name?' })\n *\n * After:\n * const TextPrompt = Swal.mixin({ input: 'text', showCancelButton: true })\n * const {value: firstName} = await TextPrompt('What is your first name?')\n * const {value: lastName} = await TextPrompt('What is your last name?')\n *\n * @param {SweetAlertOptions} mixinParams\n * @returns {SweetAlert}\n * @this {typeof import('../SweetAlert.js').SweetAlert}\n */\n function mixin(mixinParams) {\n // @ts-ignore: 'this' refers to the SweetAlert constructor\n class MixinSwal extends this {\n /**\n * @param {any} params\n * @param {any} priorityMixinParams\n */\n _main(params, priorityMixinParams) {\n return super._main(params, Object.assign({}, mixinParams, priorityMixinParams));\n }\n }\n // @ts-ignore\n return MixinSwal;\n }\n\n /**\n * If `timer` parameter is set, returns number of milliseconds of timer remained.\n * Otherwise, returns undefined.\n *\n * @returns {number | undefined}\n */\n const getTimerLeft = () => {\n return globalState.timeout && globalState.timeout.getTimerLeft();\n };\n\n /**\n * Stop timer. Returns number of milliseconds of timer remained.\n * If `timer` parameter isn't set, returns undefined.\n *\n * @returns {number | undefined}\n */\n const stopTimer = () => {\n if (globalState.timeout) {\n stopTimerProgressBar();\n return globalState.timeout.stop();\n }\n };\n\n /**\n * Resume timer. Returns number of milliseconds of timer remained.\n * If `timer` parameter isn't set, returns undefined.\n *\n * @returns {number | undefined}\n */\n const resumeTimer = () => {\n if (globalState.timeout) {\n const remaining = globalState.timeout.start();\n animateTimerProgressBar(remaining);\n return remaining;\n }\n };\n\n /**\n * Resume timer. Returns number of milliseconds of timer remained.\n * If `timer` parameter isn't set, returns undefined.\n *\n * @returns {number | undefined}\n */\n const toggleTimer = () => {\n const timer = globalState.timeout;\n return timer && (timer.running ? stopTimer() : resumeTimer());\n };\n\n /**\n * Increase timer. Returns number of milliseconds of an updated timer.\n * If `timer` parameter isn't set, returns undefined.\n *\n * @param {number} ms\n * @returns {number | undefined}\n */\n const increaseTimer = ms => {\n if (globalState.timeout) {\n const remaining = globalState.timeout.increase(ms);\n animateTimerProgressBar(remaining, true);\n return remaining;\n }\n };\n\n /**\n * Check if timer is running. Returns true if timer is running\n * or false if timer is paused or stopped.\n * If `timer` parameter isn't set, returns undefined\n *\n * @returns {boolean}\n */\n const isTimerRunning = () => {\n return Boolean(globalState.timeout && globalState.timeout.isRunning());\n };\n\n let bodyClickListenerAdded = false;\n /** @type {Record} */\n const clickHandlers = {};\n\n /**\n * @this {any}\n * @param {string} attr\n */\n function bindClickHandler(attr = 'data-swal-template') {\n clickHandlers[attr] = this;\n if (!bodyClickListenerAdded) {\n document.body.addEventListener('click', bodyClickListener);\n bodyClickListenerAdded = true;\n }\n }\n\n /**\n * @param {MouseEvent} event\n */\n const bodyClickListener = event => {\n for (let el = /** @type {any} */event.target; el && el !== document; el = el.parentNode) {\n for (const attr in clickHandlers) {\n const template = el.getAttribute && el.getAttribute(attr);\n if (template) {\n clickHandlers[attr].fire({\n template\n });\n return;\n }\n }\n }\n };\n\n // Source: https://gist.github.com/mudge/5830382?permalink_comment_id=2691957#gistcomment-2691957\n\n class EventEmitter {\n constructor() {\n /** @type {Events} */\n this.events = {};\n }\n\n /**\n * @param {string} eventName\n * @returns {EventHandlers}\n */\n _getHandlersByEventName(eventName) {\n if (typeof this.events[eventName] === 'undefined') {\n // not Set because we need to keep the FIFO order\n // https://github.com/sweetalert2/sweetalert2/pull/2763#discussion_r1748990334\n this.events[eventName] = [];\n }\n return this.events[eventName];\n }\n\n /**\n * @param {string} eventName\n * @param {EventHandler} eventHandler\n */\n on(eventName, eventHandler) {\n const currentHandlers = this._getHandlersByEventName(eventName);\n if (!currentHandlers.includes(eventHandler)) {\n currentHandlers.push(eventHandler);\n }\n }\n\n /**\n * @param {string} eventName\n * @param {EventHandler} eventHandler\n */\n once(eventName, eventHandler) {\n /**\n * @param {...any} args\n */\n const onceFn = (...args) => {\n this.removeListener(eventName, onceFn);\n // @ts-ignore\n eventHandler.apply(this, args);\n };\n this.on(eventName, onceFn);\n }\n\n /**\n * @param {string} eventName\n * @param {...any} args\n */\n emit(eventName, ...args) {\n this._getHandlersByEventName(eventName).forEach(\n /**\n * @param {EventHandler} eventHandler\n */\n eventHandler => {\n try {\n // @ts-ignore\n eventHandler.apply(this, args);\n } catch (error) {\n console.error(error);\n }\n });\n }\n\n /**\n * @param {string} eventName\n * @param {EventHandler} eventHandler\n */\n removeListener(eventName, eventHandler) {\n const currentHandlers = this._getHandlersByEventName(eventName);\n const index = currentHandlers.indexOf(eventHandler);\n if (index > -1) {\n currentHandlers.splice(index, 1);\n }\n }\n\n /**\n * @param {string} eventName\n */\n removeAllListeners(eventName) {\n if (this.events[eventName] !== undefined) {\n // https://github.com/sweetalert2/sweetalert2/pull/2763#discussion_r1749239222\n this.events[eventName].length = 0;\n }\n }\n reset() {\n this.events = {};\n }\n }\n\n globalState.eventEmitter = new EventEmitter();\n\n /**\n * @param {string} eventName\n * @param {EventHandler} eventHandler\n */\n const on = (eventName, eventHandler) => {\n if (globalState.eventEmitter) {\n globalState.eventEmitter.on(eventName, eventHandler);\n }\n };\n\n /**\n * @param {string} eventName\n * @param {EventHandler} eventHandler\n */\n const once = (eventName, eventHandler) => {\n if (globalState.eventEmitter) {\n globalState.eventEmitter.once(eventName, eventHandler);\n }\n };\n\n /**\n * @param {string} [eventName]\n * @param {EventHandler} [eventHandler]\n */\n const off = (eventName, eventHandler) => {\n if (!globalState.eventEmitter) {\n return;\n }\n\n // Remove all handlers for all events\n if (!eventName) {\n globalState.eventEmitter.reset();\n return;\n }\n if (eventHandler) {\n // Remove a specific handler\n globalState.eventEmitter.removeListener(eventName, eventHandler);\n } else {\n // Remove all handlers for a specific event\n globalState.eventEmitter.removeAllListeners(eventName);\n }\n };\n\n var staticMethods = /*#__PURE__*/Object.freeze({\n __proto__: null,\n argsToParams: argsToParams,\n bindClickHandler: bindClickHandler,\n clickCancel: clickCancel,\n clickConfirm: clickConfirm,\n clickDeny: clickDeny,\n enableLoading: showLoading,\n fire: fire,\n getActions: getActions,\n getCancelButton: getCancelButton,\n getCloseButton: getCloseButton,\n getConfirmButton: getConfirmButton,\n getContainer: getContainer,\n getDenyButton: getDenyButton,\n getFocusableElements: getFocusableElements,\n getFooter: getFooter,\n getHtmlContainer: getHtmlContainer,\n getIcon: getIcon,\n getIconContent: getIconContent,\n getImage: getImage,\n getInputLabel: getInputLabel,\n getLoader: getLoader,\n getPopup: getPopup,\n getProgressSteps: getProgressSteps,\n getTimerLeft: getTimerLeft,\n getTimerProgressBar: getTimerProgressBar,\n getTitle: getTitle,\n getValidationMessage: getValidationMessage,\n increaseTimer: increaseTimer,\n isDeprecatedParameter: isDeprecatedParameter,\n isLoading: isLoading,\n isTimerRunning: isTimerRunning,\n isUpdatableParameter: isUpdatableParameter,\n isValidParameter: isValidParameter,\n isVisible: isVisible,\n mixin: mixin,\n off: off,\n on: on,\n once: once,\n resumeTimer: resumeTimer,\n showLoading: showLoading,\n stopTimer: stopTimer,\n toggleTimer: toggleTimer\n });\n\n class Timer {\n /**\n * @param {() => void} callback\n * @param {number} delay\n */\n constructor(callback, delay) {\n this.callback = callback;\n this.remaining = delay;\n this.running = false;\n this.start();\n }\n\n /**\n * @returns {number}\n */\n start() {\n if (!this.running) {\n this.running = true;\n this.started = new Date();\n this.id = setTimeout(this.callback, this.remaining);\n }\n return this.remaining;\n }\n\n /**\n * @returns {number}\n */\n stop() {\n if (this.started && this.running) {\n this.running = false;\n clearTimeout(this.id);\n this.remaining -= new Date().getTime() - this.started.getTime();\n }\n return this.remaining;\n }\n\n /**\n * @param {number} n\n * @returns {number}\n */\n increase(n) {\n const running = this.running;\n if (running) {\n this.stop();\n }\n this.remaining += n;\n if (running) {\n this.start();\n }\n return this.remaining;\n }\n\n /**\n * @returns {number}\n */\n getTimerLeft() {\n if (this.running) {\n this.stop();\n this.start();\n }\n return this.remaining;\n }\n\n /**\n * @returns {boolean}\n */\n isRunning() {\n return this.running;\n }\n }\n\n const swalStringParams = ['swal-title', 'swal-html', 'swal-footer'];\n\n /**\n * @param {SweetAlertOptions} params\n * @returns {SweetAlertOptions}\n */\n const getTemplateParams = params => {\n const template = typeof params.template === 'string' ? (/** @type {HTMLTemplateElement} */document.querySelector(params.template)) : params.template;\n if (!template) {\n return {};\n }\n /** @type {DocumentFragment} */\n const templateContent = template.content;\n showWarningsForElements(templateContent);\n const result = Object.assign(getSwalParams(templateContent), getSwalFunctionParams(templateContent), getSwalButtons(templateContent), getSwalImage(templateContent), getSwalIcon(templateContent), getSwalInput(templateContent), getSwalStringParams(templateContent, swalStringParams));\n return result;\n };\n\n /**\n * @param {DocumentFragment} templateContent\n * @returns {Record}\n */\n const getSwalParams = templateContent => {\n /** @type {Record} */\n const result = {};\n /** @type {HTMLElement[]} */\n const swalParams = Array.from(templateContent.querySelectorAll('swal-param'));\n swalParams.forEach(param => {\n showWarningsForAttributes(param, ['name', 'value']);\n const paramName = /** @type {keyof SweetAlertOptions} */param.getAttribute('name');\n const value = param.getAttribute('value');\n if (!paramName || !value) {\n return;\n }\n if (paramName in defaultParams && typeof defaultParams[(/** @type {keyof typeof defaultParams} */paramName)] === 'boolean') {\n result[paramName] = value !== 'false';\n } else if (paramName in defaultParams && typeof defaultParams[(/** @type {keyof typeof defaultParams} */paramName)] === 'object') {\n result[paramName] = JSON.parse(value);\n } else {\n result[paramName] = value;\n }\n });\n return result;\n };\n\n /**\n * @param {DocumentFragment} templateContent\n * @returns {Record void>}\n */\n const getSwalFunctionParams = templateContent => {\n /** @type {Record void>} */\n const result = {};\n /** @type {HTMLElement[]} */\n const swalFunctions = Array.from(templateContent.querySelectorAll('swal-function-param'));\n swalFunctions.forEach(param => {\n const paramName = /** @type {keyof SweetAlertOptions} */param.getAttribute('name');\n const value = param.getAttribute('value');\n if (!paramName || !value) {\n return;\n }\n result[paramName] = new Function(`return ${value}`)();\n });\n return result;\n };\n\n /**\n * @param {DocumentFragment} templateContent\n * @returns {Record}\n */\n const getSwalButtons = templateContent => {\n /** @type {Record} */\n const result = {};\n /** @type {HTMLElement[]} */\n const swalButtons = Array.from(templateContent.querySelectorAll('swal-button'));\n swalButtons.forEach(button => {\n showWarningsForAttributes(button, ['type', 'color', 'aria-label']);\n const type = button.getAttribute('type');\n if (!type || !['confirm', 'cancel', 'deny'].includes(type)) {\n return;\n }\n result[`${type}ButtonText`] = button.innerHTML;\n result[`show${capitalizeFirstLetter(type)}Button`] = true;\n const color = button.getAttribute('color');\n if (color !== null) {\n result[`${type}ButtonColor`] = color;\n }\n const ariaLabel = button.getAttribute('aria-label');\n if (ariaLabel !== null) {\n result[`${type}ButtonAriaLabel`] = ariaLabel;\n }\n });\n return result;\n };\n\n /**\n * @param {DocumentFragment} templateContent\n * @returns {Pick}\n */\n const getSwalImage = templateContent => {\n const result = {};\n /** @type {HTMLElement | null} */\n const image = templateContent.querySelector('swal-image');\n if (image) {\n showWarningsForAttributes(image, ['src', 'width', 'height', 'alt']);\n // getAttribute returns null if attribute is absent; `|| undefined` converts empty string to undefined\n const src = image.getAttribute('src');\n if (src !== null) result.imageUrl = src || undefined;\n const width = image.getAttribute('width');\n if (width !== null) result.imageWidth = width || undefined;\n const height = image.getAttribute('height');\n if (height !== null) result.imageHeight = height || undefined;\n const alt = image.getAttribute('alt');\n if (alt !== null) result.imageAlt = alt || undefined;\n }\n return result;\n };\n\n /**\n * @param {DocumentFragment} templateContent\n * @returns {object}\n */\n const getSwalIcon = templateContent => {\n const result = {};\n /** @type {HTMLElement | null} */\n const icon = templateContent.querySelector('swal-icon');\n if (icon) {\n showWarningsForAttributes(icon, ['type', 'color']);\n if (icon.hasAttribute('type')) {\n result.icon = icon.getAttribute('type');\n }\n if (icon.hasAttribute('color')) {\n result.iconColor = icon.getAttribute('color');\n }\n result.iconHtml = icon.innerHTML;\n }\n return result;\n };\n\n /**\n * @param {DocumentFragment} templateContent\n * @returns {object}\n */\n const getSwalInput = templateContent => {\n /** @type {Record} */\n const result = {};\n /** @type {HTMLElement | null} */\n const input = templateContent.querySelector('swal-input');\n if (input) {\n showWarningsForAttributes(input, ['type', 'label', 'placeholder', 'value']);\n result.input = input.getAttribute('type') || 'text';\n if (input.hasAttribute('label')) {\n result.inputLabel = input.getAttribute('label');\n }\n if (input.hasAttribute('placeholder')) {\n result.inputPlaceholder = input.getAttribute('placeholder');\n }\n if (input.hasAttribute('value')) {\n result.inputValue = input.getAttribute('value');\n }\n }\n /** @type {HTMLElement[]} */\n const inputOptions = Array.from(templateContent.querySelectorAll('swal-input-option'));\n if (inputOptions.length) {\n result.inputOptions = {};\n inputOptions.forEach(option => {\n showWarningsForAttributes(option, ['value']);\n const optionValue = option.getAttribute('value');\n if (!optionValue) {\n return;\n }\n const optionName = option.innerHTML;\n result.inputOptions[optionValue] = optionName;\n });\n }\n return result;\n };\n\n /**\n * @param {DocumentFragment} templateContent\n * @param {string[]} paramNames\n * @returns {Record}\n */\n const getSwalStringParams = (templateContent, paramNames) => {\n /** @type {Record} */\n const result = {};\n for (const i in paramNames) {\n const paramName = paramNames[i];\n /** @type {HTMLElement | null} */\n const tag = templateContent.querySelector(paramName);\n if (tag) {\n showWarningsForAttributes(tag, []);\n result[paramName.replace(/^swal-/, '')] = tag.innerHTML.trim();\n }\n }\n return result;\n };\n\n /**\n * @param {DocumentFragment} templateContent\n */\n const showWarningsForElements = templateContent => {\n const allowedElements = swalStringParams.concat(['swal-param', 'swal-function-param', 'swal-button', 'swal-image', 'swal-icon', 'swal-input', 'swal-input-option']);\n Array.from(templateContent.children).forEach(el => {\n const tagName = el.tagName.toLowerCase();\n if (!allowedElements.includes(tagName)) {\n warn(`Unrecognized element <${tagName}>`);\n }\n });\n };\n\n /**\n * @param {HTMLElement} el\n * @param {string[]} allowedAttributes\n */\n const showWarningsForAttributes = (el, allowedAttributes) => {\n Array.from(el.attributes).forEach(attribute => {\n if (allowedAttributes.indexOf(attribute.name) === -1) {\n warn([`Unrecognized attribute \"${attribute.name}\" on <${el.tagName.toLowerCase()}>.`, `${allowedAttributes.length ? `Allowed attributes are: ${allowedAttributes.join(', ')}` : 'To set the value, use HTML within the element.'}`]);\n }\n });\n };\n\n const SHOW_CLASS_TIMEOUT = 10;\n\n /**\n * Open popup, add necessary classes and styles, fix scrollbar\n *\n * @param {SweetAlertOptions} params\n */\n const openPopup = params => {\n var _globalState$eventEmi, _globalState$eventEmi2;\n const container = getContainer();\n const popup = getPopup();\n if (!container || !popup) {\n return;\n }\n if (typeof params.willOpen === 'function') {\n params.willOpen(popup);\n }\n (_globalState$eventEmi = globalState.eventEmitter) === null || _globalState$eventEmi === void 0 || _globalState$eventEmi.emit('willOpen', popup);\n const bodyStyles = window.getComputedStyle(document.body);\n const initialBodyOverflow = bodyStyles.overflowY;\n addClasses(container, popup, params);\n\n // scrolling is 'hidden' until animation is done, after that 'auto'\n setTimeout(() => {\n setScrollingVisibility(container, popup);\n }, SHOW_CLASS_TIMEOUT);\n if (isModal()) {\n fixScrollContainer(container, params.scrollbarPadding !== undefined ? params.scrollbarPadding : false, initialBodyOverflow);\n setAriaHidden();\n }\n\n // https://github.com/sweetalert2/sweetalert2/issues/2923\n if (isIOS && params.backdrop === false && popup.scrollHeight > container.clientHeight) {\n // remove pointer-events: none from container, it breaks scrolling tall popups in iOS\n container.style.pointerEvents = 'auto';\n }\n if (!isToast() && !globalState.previousActiveElement) {\n globalState.previousActiveElement = document.activeElement;\n }\n if (typeof params.didOpen === 'function') {\n const didOpen = params.didOpen;\n setTimeout(() => didOpen(popup));\n }\n (_globalState$eventEmi2 = globalState.eventEmitter) === null || _globalState$eventEmi2 === void 0 || _globalState$eventEmi2.emit('didOpen', popup);\n };\n\n /**\n * @param {Event} event\n */\n const swalOpenAnimationFinished = event => {\n const popup = getPopup();\n if (!popup || event.target !== popup) {\n return;\n }\n const container = getContainer();\n if (!container) {\n return;\n }\n popup.removeEventListener('animationend', swalOpenAnimationFinished);\n popup.removeEventListener('transitionend', swalOpenAnimationFinished);\n container.style.overflowY = 'auto';\n\n // no-transition is added in init() in case one swal is opened right after another\n removeClass(container, swalClasses['no-transition']);\n };\n\n /**\n * @param {HTMLElement} container\n * @param {HTMLElement} popup\n */\n const setScrollingVisibility = (container, popup) => {\n if (hasCssAnimation(popup)) {\n container.style.overflowY = 'hidden';\n popup.addEventListener('animationend', swalOpenAnimationFinished);\n popup.addEventListener('transitionend', swalOpenAnimationFinished);\n } else {\n container.style.overflowY = 'auto';\n }\n };\n\n /**\n * @param {HTMLElement} container\n * @param {boolean} scrollbarPadding\n * @param {string} initialBodyOverflow\n */\n const fixScrollContainer = (container, scrollbarPadding, initialBodyOverflow) => {\n iOSfix();\n if (scrollbarPadding && initialBodyOverflow !== 'hidden') {\n replaceScrollbarWithPadding(initialBodyOverflow);\n }\n\n // sweetalert2/issues/1247\n setTimeout(() => {\n container.scrollTop = 0;\n });\n };\n\n /**\n * @param {HTMLElement} container\n * @param {HTMLElement} popup\n * @param {SweetAlertOptions} params\n */\n const addClasses = (container, popup, params) => {\n var _params$showClass;\n if ((_params$showClass = params.showClass) !== null && _params$showClass !== void 0 && _params$showClass.backdrop) {\n addClass(container, params.showClass.backdrop);\n }\n if (params.animation) {\n // this workaround with opacity is needed for https://github.com/sweetalert2/sweetalert2/issues/2059\n popup.style.setProperty('opacity', '0', 'important');\n show(popup, 'grid');\n setTimeout(() => {\n var _params$showClass2;\n // Animate popup right after showing it\n if ((_params$showClass2 = params.showClass) !== null && _params$showClass2 !== void 0 && _params$showClass2.popup) {\n addClass(popup, params.showClass.popup);\n }\n // and remove the opacity workaround\n popup.style.removeProperty('opacity');\n }, SHOW_CLASS_TIMEOUT); // 10ms in order to fix #2062\n } else {\n show(popup, 'grid');\n }\n addClass([document.documentElement, document.body], swalClasses.shown);\n if (params.heightAuto && params.backdrop && !params.toast) {\n addClass([document.documentElement, document.body], swalClasses['height-auto']);\n }\n };\n\n var defaultInputValidators = {\n /**\n * @param {string} string\n * @param {string} [validationMessage]\n * @returns {Promise}\n */\n email: (string, validationMessage) => {\n return /^[a-zA-Z0-9.+_'-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z0-9-]+$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid email address');\n },\n /**\n * @param {string} string\n * @param {string} [validationMessage]\n * @returns {Promise}\n */\n url: (string, validationMessage) => {\n // taken from https://stackoverflow.com/a/3809435 with a small change from #1306 and #2013\n return /^https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-z]{2,63}\\b([-a-zA-Z0-9@:%_+.~#?&/=]*)$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid URL');\n }\n };\n\n /**\n * @param {SweetAlertOptions} params\n */\n function setDefaultInputValidators(params) {\n // Use default `inputValidator` for supported input types if not provided\n if (params.inputValidator) {\n return;\n }\n if (params.input === 'email') {\n params.inputValidator = defaultInputValidators['email'];\n }\n if (params.input === 'url') {\n params.inputValidator = defaultInputValidators['url'];\n }\n }\n\n /**\n * @param {SweetAlertOptions} params\n */\n function validateCustomTargetElement(params) {\n // Determine if the custom target element is valid\n if (!params.target || typeof params.target === 'string' && !document.querySelector(params.target) || typeof params.target !== 'string' && !params.target.appendChild) {\n warn('Target parameter is not valid, defaulting to \"body\"');\n params.target = 'body';\n }\n }\n\n /**\n * Set type, text and actions on popup\n *\n * @param {SweetAlertOptions} params\n */\n function setParameters(params) {\n setDefaultInputValidators(params);\n\n // showLoaderOnConfirm && preConfirm\n if (params.showLoaderOnConfirm && !params.preConfirm) {\n warn('showLoaderOnConfirm is set to true, but preConfirm is not defined.\\n' + 'showLoaderOnConfirm should be used together with preConfirm, see usage example:\\n' + 'https://sweetalert2.github.io/#ajax-request');\n }\n validateCustomTargetElement(params);\n\n // Replace newlines with
    in title\n if (typeof params.title === 'string') {\n params.title = params.title.split('\\n').join('
    ');\n }\n init(params);\n }\n\n /** @type {SweetAlert} */\n let currentInstance;\n var _promise = /*#__PURE__*/new WeakMap();\n class SweetAlert {\n /**\n * @param {...(SweetAlertOptions | string)} args\n * @this {SweetAlert}\n */\n constructor(...args) {\n /**\n * @type {Promise}\n */\n _classPrivateFieldInitSpec(this, _promise, /** @type {Promise} */\n Promise.resolve({\n isConfirmed: false,\n isDenied: false,\n isDismissed: true\n }));\n // Prevent run in Node env\n if (typeof window === 'undefined') {\n return;\n }\n currentInstance = this;\n\n // @ts-ignore\n const outerParams = Object.freeze(this.constructor.argsToParams(args));\n\n /** @type {Readonly} */\n this.params = outerParams;\n\n /** @type {boolean} */\n this.isAwaitingPromise = false;\n _classPrivateFieldSet2(_promise, this, this._main(currentInstance.params));\n }\n\n /**\n * @param {any} userParams\n * @param {any} mixinParams\n */\n _main(userParams, mixinParams = {}) {\n showWarningsForParams(Object.assign({}, mixinParams, userParams));\n if (globalState.currentInstance) {\n const swalPromiseResolve = privateMethods.swalPromiseResolve.get(globalState.currentInstance);\n const {\n isAwaitingPromise\n } = globalState.currentInstance;\n globalState.currentInstance._destroy();\n if (!isAwaitingPromise) {\n swalPromiseResolve({\n isDismissed: true\n });\n }\n if (isModal()) {\n unsetAriaHidden();\n }\n }\n globalState.currentInstance = currentInstance;\n const innerParams = prepareParams(userParams, mixinParams);\n setParameters(innerParams);\n Object.freeze(innerParams);\n\n // clear the previous timer\n if (globalState.timeout) {\n globalState.timeout.stop();\n delete globalState.timeout;\n }\n\n // clear the restore focus timeout\n clearTimeout(globalState.restoreFocusTimeout);\n const domCache = populateDomCache(currentInstance);\n render(currentInstance, innerParams);\n privateProps.innerParams.set(currentInstance, innerParams);\n return swalPromise(currentInstance, domCache, innerParams);\n }\n\n // `catch` cannot be the name of a module export, so we define our thenable methods here instead\n /**\n * @param {any} onFulfilled\n */\n // oxlint-disable-next-line unicorn/no-thenable\n then(onFulfilled) {\n return _classPrivateFieldGet2(_promise, this).then(onFulfilled);\n }\n\n /**\n * @param {any} onFinally\n */\n finally(onFinally) {\n return _classPrivateFieldGet2(_promise, this).finally(onFinally);\n }\n }\n\n /**\n * @param {SweetAlert} instance\n * @param {DomCache} domCache\n * @param {SweetAlertOptions} innerParams\n * @returns {Promise}\n */\n const swalPromise = (instance, domCache, innerParams) => {\n return new Promise((resolve, reject) => {\n // functions to handle all closings/dismissals\n /**\n * @param {DismissReason} dismiss\n */\n const dismissWith = dismiss => {\n instance.close({\n isDismissed: true,\n dismiss,\n isConfirmed: false,\n isDenied: false\n });\n };\n privateMethods.swalPromiseResolve.set(instance, resolve);\n privateMethods.swalPromiseReject.set(instance, reject);\n domCache.confirmButton.onclick = () => {\n handleConfirmButtonClick(instance);\n };\n domCache.denyButton.onclick = () => {\n handleDenyButtonClick(instance);\n };\n domCache.cancelButton.onclick = () => {\n handleCancelButtonClick(instance, dismissWith);\n };\n domCache.closeButton.onclick = () => {\n dismissWith(DismissReason.close);\n };\n handlePopupClick(innerParams, domCache, dismissWith);\n addKeydownHandler(globalState, innerParams, dismissWith);\n handleInputOptionsAndValue(instance, innerParams);\n openPopup(innerParams);\n setupTimer(globalState, innerParams, dismissWith);\n initFocus(domCache, innerParams);\n\n // Scroll container to top on open (#1247, #1946)\n setTimeout(() => {\n domCache.container.scrollTop = 0;\n });\n });\n };\n\n /**\n * @param {SweetAlertOptions} userParams\n * @param {SweetAlertOptions} mixinParams\n * @returns {SweetAlertOptions}\n */\n const prepareParams = (userParams, mixinParams) => {\n const templateParams = getTemplateParams(userParams);\n const params = Object.assign({}, defaultParams, mixinParams, templateParams, userParams); // precedence is described in #2131\n params.showClass = Object.assign({}, defaultParams.showClass, params.showClass);\n params.hideClass = Object.assign({}, defaultParams.hideClass, params.hideClass);\n if (params.animation === false) {\n params.showClass = {\n backdrop: 'swal2-noanimation'\n };\n params.hideClass = {};\n }\n return params;\n };\n\n /**\n * @param {SweetAlert} instance\n * @returns {DomCache}\n */\n const populateDomCache = instance => {\n const domCache = /** @type {DomCache} */{\n popup: (/** @type {HTMLElement} */getPopup()),\n container: (/** @type {HTMLElement} */getContainer()),\n actions: (/** @type {HTMLElement} */getActions()),\n confirmButton: (/** @type {HTMLElement} */getConfirmButton()),\n denyButton: (/** @type {HTMLElement} */getDenyButton()),\n cancelButton: (/** @type {HTMLElement} */getCancelButton()),\n loader: (/** @type {HTMLElement} */getLoader()),\n closeButton: (/** @type {HTMLElement} */getCloseButton()),\n validationMessage: (/** @type {HTMLElement} */getValidationMessage()),\n progressSteps: (/** @type {HTMLElement} */getProgressSteps())\n };\n privateProps.domCache.set(instance, domCache);\n return domCache;\n };\n\n /**\n * @param {GlobalState} globalState\n * @param {SweetAlertOptions} innerParams\n * @param {(dismiss: DismissReason) => void} dismissWith\n */\n const setupTimer = (globalState, innerParams, dismissWith) => {\n const timerProgressBar = getTimerProgressBar();\n hide(timerProgressBar);\n if (innerParams.timer) {\n globalState.timeout = new Timer(() => {\n dismissWith('timer');\n delete globalState.timeout;\n }, innerParams.timer);\n if (innerParams.timerProgressBar && timerProgressBar) {\n show(timerProgressBar);\n applyCustomClass(timerProgressBar, innerParams, 'timerProgressBar');\n setTimeout(() => {\n if (globalState.timeout && globalState.timeout.running) {\n // timer can be already stopped or unset at this point\n animateTimerProgressBar(/** @type {number} */innerParams.timer);\n }\n });\n }\n }\n };\n\n /**\n * Initialize focus in the popup:\n *\n * 1. If `toast` is `true`, don't steal focus from the document.\n * 2. Else if there is an [autofocus] element, focus it.\n * 3. Else if `focusConfirm` is `true` and confirm button is visible, focus it.\n * 4. Else if `focusDeny` is `true` and deny button is visible, focus it.\n * 5. Else if `focusCancel` is `true` and cancel button is visible, focus it.\n * 6. Else focus the first focusable element in a popup (if any).\n *\n * @param {DomCache} domCache\n * @param {SweetAlertOptions} innerParams\n */\n const initFocus = (domCache, innerParams) => {\n if (innerParams.toast) {\n return;\n }\n // TODO: this is dumb, remove `allowEnterKey` param in the next major version\n if (!callIfFunction(innerParams.allowEnterKey)) {\n warnAboutDeprecation('allowEnterKey', 'preConfirm: () => false');\n domCache.popup.focus();\n return;\n }\n if (focusAutofocus(domCache)) {\n return;\n }\n if (focusButton(domCache, innerParams)) {\n return;\n }\n setFocus(-1, 1);\n };\n\n /**\n * @param {DomCache} domCache\n * @returns {boolean}\n */\n const focusAutofocus = domCache => {\n const autofocusElements = Array.from(domCache.popup.querySelectorAll('[autofocus]'));\n for (const autofocusElement of autofocusElements) {\n if (autofocusElement instanceof HTMLElement && isVisible$1(autofocusElement)) {\n autofocusElement.focus();\n return true;\n }\n }\n return false;\n };\n\n /**\n * @param {DomCache} domCache\n * @param {SweetAlertOptions} innerParams\n * @returns {boolean}\n */\n const focusButton = (domCache, innerParams) => {\n if (innerParams.focusDeny && isVisible$1(domCache.denyButton)) {\n domCache.denyButton.focus();\n return true;\n }\n if (innerParams.focusCancel && isVisible$1(domCache.cancelButton)) {\n domCache.cancelButton.focus();\n return true;\n }\n if (innerParams.focusConfirm && isVisible$1(domCache.confirmButton)) {\n domCache.confirmButton.focus();\n return true;\n }\n return false;\n };\n\n // Assign instance methods from src/instanceMethods/*.js to prototype\n SweetAlert.prototype.disableButtons = disableButtons;\n SweetAlert.prototype.enableButtons = enableButtons;\n SweetAlert.prototype.getInput = getInput;\n SweetAlert.prototype.disableInput = disableInput;\n SweetAlert.prototype.enableInput = enableInput;\n SweetAlert.prototype.hideLoading = hideLoading;\n SweetAlert.prototype.disableLoading = hideLoading;\n SweetAlert.prototype.showValidationMessage = showValidationMessage;\n SweetAlert.prototype.resetValidationMessage = resetValidationMessage;\n SweetAlert.prototype.close = close;\n SweetAlert.prototype.closePopup = close;\n SweetAlert.prototype.closeModal = close;\n SweetAlert.prototype.closeToast = close;\n SweetAlert.prototype.rejectPromise = rejectPromise;\n SweetAlert.prototype.update = update;\n SweetAlert.prototype._destroy = _destroy;\n\n // Assign static methods from src/staticMethods/*.js to constructor\n Object.assign(SweetAlert, staticMethods);\n\n // Proxy to instance methods to constructor, for now, for backwards compatibility\n Object.keys(instanceMethods).forEach(key => {\n /**\n * @param {...(SweetAlertOptions | string | undefined)} args\n * @returns {SweetAlertResult | Promise | undefined}\n */\n // @ts-ignore: Dynamic property assignment for backwards compatibility\n SweetAlert[key] = function (...args) {\n // @ts-ignore\n if (currentInstance && currentInstance[key]) {\n // @ts-ignore\n return currentInstance[key](...args);\n }\n return undefined;\n };\n });\n SweetAlert.DismissReason = DismissReason;\n SweetAlert.version = '11.26.25';\n\n const Swal = SweetAlert;\n // @ts-ignore\n Swal.default = Swal;\n\n return Swal;\n\n}));\nif (typeof this !== 'undefined' && this.Sweetalert2){this.swal = this.sweetAlert = this.Swal = this.SweetAlert = this.Sweetalert2}\n\"undefined\"!=typeof document&&function(e,t){var n=e.createElement(\"style\");if(e.getElementsByTagName(\"head\")[0].appendChild(n),n.styleSheet)n.styleSheet.disabled||(n.styleSheet.cssText=t);else try{n.innerHTML=t}catch(e){n.innerText=t}}(document,\":root{--swal2-outline: 0 0 0 3px rgba(100, 150, 200, 0.5);--swal2-container-padding: 0.625em;--swal2-backdrop: rgba(0, 0, 0, 0.4);--swal2-backdrop-transition: background-color 0.15s;--swal2-width: 32em;--swal2-padding: 0 0 1.25em;--swal2-border: none;--swal2-border-radius: 0.3125rem;--swal2-background: white;--swal2-color: #545454;--swal2-show-animation: swal2-show 0.3s;--swal2-hide-animation: swal2-hide 0.15s forwards;--swal2-icon-zoom: 1;--swal2-title-padding: 0.8em 1em 0;--swal2-html-container-padding: 1em 1.6em 0.3em;--swal2-input-border: 1px solid #d9d9d9;--swal2-input-border-radius: 0.1875em;--swal2-input-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.06), 0 0 0 3px transparent;--swal2-input-background: transparent;--swal2-input-transition: border-color 0.2s, box-shadow 0.2s;--swal2-input-hover-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.06), 0 0 0 3px transparent;--swal2-input-focus-border: 1px solid #b4dbed;--swal2-input-focus-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.06), 0 0 0 3px rgba(100, 150, 200, 0.5);--swal2-progress-step-background: #add8e6;--swal2-validation-message-background: #f0f0f0;--swal2-validation-message-color: #666;--swal2-footer-border-color: #eee;--swal2-footer-background: transparent;--swal2-footer-color: inherit;--swal2-timer-progress-bar-background: rgba(0, 0, 0, 0.3);--swal2-close-button-position: initial;--swal2-close-button-inset: auto;--swal2-close-button-font-size: 2.5em;--swal2-close-button-color: #ccc;--swal2-close-button-transition: color 0.2s, box-shadow 0.2s;--swal2-close-button-outline: initial;--swal2-close-button-box-shadow: inset 0 0 0 3px transparent;--swal2-close-button-focus-box-shadow: inset var(--swal2-outline);--swal2-close-button-hover-transform: none;--swal2-actions-justify-content: center;--swal2-actions-width: auto;--swal2-actions-margin: 1.25em auto 0;--swal2-actions-padding: 0;--swal2-actions-border-radius: 0;--swal2-actions-background: transparent;--swal2-action-button-transition: background-color 0.2s, box-shadow 0.2s;--swal2-action-button-hover: black 10%;--swal2-action-button-active: black 10%;--swal2-confirm-button-box-shadow: none;--swal2-confirm-button-border-radius: 0.25em;--swal2-confirm-button-background-color: #7066e0;--swal2-confirm-button-color: #fff;--swal2-deny-button-box-shadow: none;--swal2-deny-button-border-radius: 0.25em;--swal2-deny-button-background-color: #dc3741;--swal2-deny-button-color: #fff;--swal2-cancel-button-box-shadow: none;--swal2-cancel-button-border-radius: 0.25em;--swal2-cancel-button-background-color: #6e7881;--swal2-cancel-button-color: #fff;--swal2-toast-show-animation: swal2-toast-show 0.5s;--swal2-toast-hide-animation: swal2-toast-hide 0.1s forwards;--swal2-toast-border: none;--swal2-toast-box-shadow: 0 0 1px hsl(0deg 0% 0% / 0.075), 0 1px 2px hsl(0deg 0% 0% / 0.075), 1px 2px 4px hsl(0deg 0% 0% / 0.075), 1px 3px 8px hsl(0deg 0% 0% / 0.075), 2px 4px 16px hsl(0deg 0% 0% / 0.075)}[data-swal2-theme=dark]{--swal2-dark-theme-black: #19191a;--swal2-dark-theme-white: #e1e1e1;--swal2-background: var(--swal2-dark-theme-black);--swal2-color: var(--swal2-dark-theme-white);--swal2-footer-border-color: #555;--swal2-input-background: color-mix(in srgb, var(--swal2-dark-theme-black), var(--swal2-dark-theme-white) 10%);--swal2-validation-message-background: color-mix( in srgb, var(--swal2-dark-theme-black), var(--swal2-dark-theme-white) 10% );--swal2-validation-message-color: var(--swal2-dark-theme-white);--swal2-timer-progress-bar-background: rgba(255, 255, 255, 0.7)}@media(prefers-color-scheme: dark){[data-swal2-theme=auto]{--swal2-dark-theme-black: #19191a;--swal2-dark-theme-white: #e1e1e1;--swal2-background: var(--swal2-dark-theme-black);--swal2-color: var(--swal2-dark-theme-white);--swal2-footer-border-color: #555;--swal2-input-background: color-mix(in srgb, var(--swal2-dark-theme-black), var(--swal2-dark-theme-white) 10%);--swal2-validation-message-background: color-mix( in srgb, var(--swal2-dark-theme-black), var(--swal2-dark-theme-white) 10% );--swal2-validation-message-color: var(--swal2-dark-theme-white);--swal2-timer-progress-bar-background: rgba(255, 255, 255, 0.7)}}body.swal2-shown:not(.swal2-no-backdrop,.swal2-toast-shown){overflow:hidden}body.swal2-height-auto{height:auto !important}body.swal2-no-backdrop .swal2-container{background-color:rgba(0,0,0,0) !important;pointer-events:none}body.swal2-no-backdrop .swal2-container .swal2-popup{pointer-events:auto}body.swal2-no-backdrop .swal2-container .swal2-modal{box-shadow:0 0 10px var(--swal2-backdrop)}body.swal2-toast-shown .swal2-container{box-sizing:border-box;width:360px;max-width:100%;background-color:rgba(0,0,0,0);pointer-events:none}body.swal2-toast-shown .swal2-container.swal2-top{inset:0 auto auto 50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-top-end,body.swal2-toast-shown .swal2-container.swal2-top-right{inset:0 0 auto auto}body.swal2-toast-shown .swal2-container.swal2-top-start,body.swal2-toast-shown .swal2-container.swal2-top-left{inset:0 auto auto 0}body.swal2-toast-shown .swal2-container.swal2-center-start,body.swal2-toast-shown .swal2-container.swal2-center-left{inset:50% auto auto 0;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-center{inset:50% auto auto 50%;transform:translate(-50%, -50%)}body.swal2-toast-shown .swal2-container.swal2-center-end,body.swal2-toast-shown .swal2-container.swal2-center-right{inset:50% 0 auto auto;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-start,body.swal2-toast-shown .swal2-container.swal2-bottom-left{inset:auto auto 0 0}body.swal2-toast-shown .swal2-container.swal2-bottom{inset:auto auto 0 50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-end,body.swal2-toast-shown .swal2-container.swal2-bottom-right{inset:auto 0 0 auto}@media print{body.swal2-shown:not(.swal2-no-backdrop,.swal2-toast-shown){overflow-y:scroll !important}body.swal2-shown:not(.swal2-no-backdrop,.swal2-toast-shown)>[aria-hidden=true]{display:none}body.swal2-shown:not(.swal2-no-backdrop,.swal2-toast-shown) .swal2-container{position:static !important}}div:where(.swal2-container){display:grid;position:fixed;z-index:1060;inset:0;box-sizing:border-box;grid-template-areas:\\\"top-start top top-end\\\" \\\"center-start center center-end\\\" \\\"bottom-start bottom-center bottom-end\\\";grid-template-rows:minmax(min-content, auto) minmax(min-content, auto) minmax(min-content, auto);height:100%;padding:var(--swal2-container-padding);overflow-x:hidden;transition:var(--swal2-backdrop-transition);-webkit-overflow-scrolling:touch}div:where(.swal2-container).swal2-backdrop-show,div:where(.swal2-container).swal2-noanimation{background:var(--swal2-backdrop)}div:where(.swal2-container).swal2-backdrop-hide{background:rgba(0,0,0,0) !important}div:where(.swal2-container).swal2-top-start,div:where(.swal2-container).swal2-center-start,div:where(.swal2-container).swal2-bottom-start{grid-template-columns:minmax(0, 1fr) auto auto}div:where(.swal2-container).swal2-top,div:where(.swal2-container).swal2-center,div:where(.swal2-container).swal2-bottom{grid-template-columns:auto minmax(0, 1fr) auto}div:where(.swal2-container).swal2-top-end,div:where(.swal2-container).swal2-center-end,div:where(.swal2-container).swal2-bottom-end{grid-template-columns:auto auto minmax(0, 1fr)}div:where(.swal2-container).swal2-top-start>.swal2-popup{align-self:start}div:where(.swal2-container).swal2-top>.swal2-popup{grid-column:2;place-self:start center}div:where(.swal2-container).swal2-top-end>.swal2-popup,div:where(.swal2-container).swal2-top-right>.swal2-popup{grid-column:3;place-self:start end}div:where(.swal2-container).swal2-center-start>.swal2-popup,div:where(.swal2-container).swal2-center-left>.swal2-popup{grid-row:2;align-self:center}div:where(.swal2-container).swal2-center>.swal2-popup{grid-column:2;grid-row:2;place-self:center center}div:where(.swal2-container).swal2-center-end>.swal2-popup,div:where(.swal2-container).swal2-center-right>.swal2-popup{grid-column:3;grid-row:2;place-self:center end}div:where(.swal2-container).swal2-bottom-start>.swal2-popup,div:where(.swal2-container).swal2-bottom-left>.swal2-popup{grid-column:1;grid-row:3;align-self:end}div:where(.swal2-container).swal2-bottom>.swal2-popup{grid-column:2;grid-row:3;place-self:end center}div:where(.swal2-container).swal2-bottom-end>.swal2-popup,div:where(.swal2-container).swal2-bottom-right>.swal2-popup{grid-column:3;grid-row:3;place-self:end end}div:where(.swal2-container).swal2-grow-row>.swal2-popup,div:where(.swal2-container).swal2-grow-fullscreen>.swal2-popup{grid-column:1/4;width:100%}div:where(.swal2-container).swal2-grow-column>.swal2-popup,div:where(.swal2-container).swal2-grow-fullscreen>.swal2-popup{grid-row:1/4;align-self:stretch}div:where(.swal2-container).swal2-no-transition{transition:none !important}div:where(.swal2-container)[popover]{width:auto;border:0}div:where(.swal2-container) div:where(.swal2-popup){display:none;position:relative;box-sizing:border-box;grid-template-columns:minmax(0, 100%);width:var(--swal2-width);max-width:100%;padding:var(--swal2-padding);border:var(--swal2-border);border-radius:var(--swal2-border-radius);background:var(--swal2-background);color:var(--swal2-color);font-family:inherit;font-size:1rem}div:where(.swal2-container) div:where(.swal2-popup):focus{outline:none}div:where(.swal2-container) div:where(.swal2-popup).swal2-loading{overflow-y:hidden}div:where(.swal2-container) div:where(.swal2-popup).swal2-draggable{cursor:grab}div:where(.swal2-container) div:where(.swal2-popup).swal2-draggable div:where(.swal2-icon){cursor:grab}div:where(.swal2-container) div:where(.swal2-popup).swal2-dragging{cursor:grabbing}div:where(.swal2-container) div:where(.swal2-popup).swal2-dragging div:where(.swal2-icon){cursor:grabbing}div:where(.swal2-container) h2:where(.swal2-title){position:relative;max-width:100%;margin:0;padding:var(--swal2-title-padding);color:inherit;font-size:1.875em;font-weight:600;text-align:center;text-transform:none;overflow-wrap:break-word;cursor:initial}div:where(.swal2-container) div:where(.swal2-actions){display:flex;z-index:1;box-sizing:border-box;flex-wrap:wrap;align-items:center;justify-content:var(--swal2-actions-justify-content);width:var(--swal2-actions-width);margin:var(--swal2-actions-margin);padding:var(--swal2-actions-padding);border-radius:var(--swal2-actions-border-radius);background:var(--swal2-actions-background)}div:where(.swal2-container) div:where(.swal2-loader){display:none;align-items:center;justify-content:center;width:2.2em;height:2.2em;margin:0 1.875em;animation:swal2-rotate-loading 1.5s linear 0s infinite normal;border-width:.25em;border-style:solid;border-radius:100%;border-color:#2778c4 rgba(0,0,0,0) #2778c4 rgba(0,0,0,0)}div:where(.swal2-container) button:where(.swal2-styled){margin:.3125em;padding:.625em 1.1em;transition:var(--swal2-action-button-transition);border:none;box-shadow:0 0 0 3px rgba(0,0,0,0);font-weight:500}div:where(.swal2-container) button:where(.swal2-styled):not([disabled]){cursor:pointer}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-confirm){border-radius:var(--swal2-confirm-button-border-radius);background:initial;background-color:var(--swal2-confirm-button-background-color);box-shadow:var(--swal2-confirm-button-box-shadow);color:var(--swal2-confirm-button-color);font-size:1em}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-confirm):hover{background-color:color-mix(in srgb, var(--swal2-confirm-button-background-color), var(--swal2-action-button-hover))}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-confirm):active{background-color:color-mix(in srgb, var(--swal2-confirm-button-background-color), var(--swal2-action-button-active))}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-deny){border-radius:var(--swal2-deny-button-border-radius);background:initial;background-color:var(--swal2-deny-button-background-color);box-shadow:var(--swal2-deny-button-box-shadow);color:var(--swal2-deny-button-color);font-size:1em}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-deny):hover{background-color:color-mix(in srgb, var(--swal2-deny-button-background-color), var(--swal2-action-button-hover))}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-deny):active{background-color:color-mix(in srgb, var(--swal2-deny-button-background-color), var(--swal2-action-button-active))}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-cancel){border-radius:var(--swal2-cancel-button-border-radius);background:initial;background-color:var(--swal2-cancel-button-background-color);box-shadow:var(--swal2-cancel-button-box-shadow);color:var(--swal2-cancel-button-color);font-size:1em}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-cancel):hover{background-color:color-mix(in srgb, var(--swal2-cancel-button-background-color), var(--swal2-action-button-hover))}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-cancel):active{background-color:color-mix(in srgb, var(--swal2-cancel-button-background-color), var(--swal2-action-button-active))}div:where(.swal2-container) button:where(.swal2-styled):focus-visible{outline:none;box-shadow:var(--swal2-action-button-focus-box-shadow)}div:where(.swal2-container) button:where(.swal2-styled)[disabled]:not(.swal2-loading){opacity:.4}div:where(.swal2-container) button:where(.swal2-styled)::-moz-focus-inner{border:0}div:where(.swal2-container) div:where(.swal2-footer){margin:1em 0 0;padding:1em 1em 0;border-top:1px solid var(--swal2-footer-border-color);background:var(--swal2-footer-background);color:var(--swal2-footer-color);font-size:1em;text-align:center;cursor:initial}div:where(.swal2-container) .swal2-timer-progress-bar-container{position:absolute;right:0;bottom:0;left:0;grid-column:auto !important;overflow:hidden;border-bottom-right-radius:var(--swal2-border-radius);border-bottom-left-radius:var(--swal2-border-radius)}div:where(.swal2-container) div:where(.swal2-timer-progress-bar){width:100%;height:.25em;background:var(--swal2-timer-progress-bar-background)}div:where(.swal2-container) img:where(.swal2-image){max-width:100%;margin:2em auto 1em;cursor:initial}div:where(.swal2-container) button:where(.swal2-close){position:var(--swal2-close-button-position);inset:var(--swal2-close-button-inset);z-index:2;align-items:center;justify-content:center;width:1.2em;height:1.2em;margin-top:0;margin-right:0;margin-bottom:-1.2em;padding:0;overflow:hidden;transition:var(--swal2-close-button-transition);border:none;border-radius:var(--swal2-border-radius);outline:var(--swal2-close-button-outline);background:rgba(0,0,0,0);color:var(--swal2-close-button-color);font-family:monospace;font-size:var(--swal2-close-button-font-size);cursor:pointer;justify-self:end}div:where(.swal2-container) button:where(.swal2-close):hover{transform:var(--swal2-close-button-hover-transform);background:rgba(0,0,0,0);color:#f27474}div:where(.swal2-container) button:where(.swal2-close):focus-visible{outline:none;box-shadow:var(--swal2-close-button-focus-box-shadow)}div:where(.swal2-container) button:where(.swal2-close)::-moz-focus-inner{border:0}div:where(.swal2-container) div:where(.swal2-html-container){z-index:1;justify-content:center;margin:0;padding:var(--swal2-html-container-padding);overflow:auto;color:inherit;font-size:1.125em;font-weight:normal;line-height:normal;text-align:center;overflow-wrap:break-word;word-break:break-word;cursor:initial}div:where(.swal2-container) input:where(.swal2-input),div:where(.swal2-container) input:where(.swal2-file),div:where(.swal2-container) textarea:where(.swal2-textarea),div:where(.swal2-container) select:where(.swal2-select),div:where(.swal2-container) div:where(.swal2-radio),div:where(.swal2-container) label:where(.swal2-checkbox){margin:1em 2em 3px}div:where(.swal2-container) input:where(.swal2-input),div:where(.swal2-container) input:where(.swal2-file),div:where(.swal2-container) textarea:where(.swal2-textarea){box-sizing:border-box;width:auto;transition:var(--swal2-input-transition);border:var(--swal2-input-border);border-radius:var(--swal2-input-border-radius);background:var(--swal2-input-background);box-shadow:var(--swal2-input-box-shadow);color:inherit;font-size:1.125em}div:where(.swal2-container) input:where(.swal2-input).swal2-inputerror,div:where(.swal2-container) input:where(.swal2-file).swal2-inputerror,div:where(.swal2-container) textarea:where(.swal2-textarea).swal2-inputerror{border-color:#f27474 !important;box-shadow:0 0 2px #f27474 !important}div:where(.swal2-container) input:where(.swal2-input):hover,div:where(.swal2-container) input:where(.swal2-file):hover,div:where(.swal2-container) textarea:where(.swal2-textarea):hover{box-shadow:var(--swal2-input-hover-box-shadow)}div:where(.swal2-container) input:where(.swal2-input):focus,div:where(.swal2-container) input:where(.swal2-file):focus,div:where(.swal2-container) textarea:where(.swal2-textarea):focus{border:var(--swal2-input-focus-border);outline:none;box-shadow:var(--swal2-input-focus-box-shadow)}div:where(.swal2-container) input:where(.swal2-input)::placeholder,div:where(.swal2-container) input:where(.swal2-file)::placeholder,div:where(.swal2-container) textarea:where(.swal2-textarea)::placeholder{color:#ccc}div:where(.swal2-container) .swal2-range{margin:1em 2em 3px;background:var(--swal2-background)}div:where(.swal2-container) .swal2-range input{width:80%}div:where(.swal2-container) .swal2-range output{width:20%;color:inherit;font-weight:600;text-align:center}div:where(.swal2-container) .swal2-range input,div:where(.swal2-container) .swal2-range output{height:2.625em;padding:0;font-size:1.125em;line-height:2.625em}div:where(.swal2-container) .swal2-input{height:2.625em;padding:0 .75em}div:where(.swal2-container) .swal2-file{width:75%;margin-right:auto;margin-left:auto;background:var(--swal2-input-background);font-size:1.125em}div:where(.swal2-container) .swal2-textarea{height:6.75em;padding:.75em}div:where(.swal2-container) .swal2-select{min-width:50%;max-width:100%;padding:.375em .625em;background:var(--swal2-input-background);color:inherit;font-size:1.125em}div:where(.swal2-container) .swal2-radio,div:where(.swal2-container) .swal2-checkbox{align-items:center;justify-content:center;background:var(--swal2-background);color:inherit}div:where(.swal2-container) .swal2-radio label,div:where(.swal2-container) .swal2-checkbox label{margin:0 .6em;font-size:1.125em}div:where(.swal2-container) .swal2-radio input,div:where(.swal2-container) .swal2-checkbox input{flex-shrink:0;margin:0 .4em}div:where(.swal2-container) label:where(.swal2-input-label){display:flex;justify-content:center;margin:1em auto 0}div:where(.swal2-container) div:where(.swal2-validation-message){align-items:center;justify-content:center;margin:1em 0 0;padding:.625em;overflow:hidden;background:var(--swal2-validation-message-background);color:var(--swal2-validation-message-color);font-size:1em;font-weight:300}div:where(.swal2-container) div:where(.swal2-validation-message)::before{content:\\\"!\\\";display:inline-block;width:1.5em;min-width:1.5em;height:1.5em;margin:0 .625em;border-radius:50%;background-color:#f27474;color:#fff;font-weight:600;line-height:1.5em;text-align:center}div:where(.swal2-container) .swal2-progress-steps{flex-wrap:wrap;align-items:center;max-width:100%;margin:1.25em auto;padding:0;background:rgba(0,0,0,0);font-weight:600}div:where(.swal2-container) .swal2-progress-steps li{display:inline-block;position:relative}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step{z-index:20;flex-shrink:0;width:2em;height:2em;border-radius:2em;background:#2778c4;color:#fff;line-height:2em;text-align:center}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step.swal2-active-progress-step{background:#2778c4}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step{background:var(--swal2-progress-step-background);color:#fff}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step-line{background:var(--swal2-progress-step-background)}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step-line{z-index:10;flex-shrink:0;width:2.5em;height:.4em;margin:0 -1px;background:#2778c4}div:where(.swal2-icon){position:relative;box-sizing:content-box;justify-content:center;width:5em;height:5em;margin:2.5em auto .6em;zoom:var(--swal2-icon-zoom);border:.25em solid rgba(0,0,0,0);border-radius:50%;border-color:#000;font-family:inherit;line-height:5em;cursor:default;user-select:none}div:where(.swal2-icon) .swal2-icon-content{display:flex;align-items:center;font-size:3.75em}div:where(.swal2-icon).swal2-error{border-color:#f27474;color:#f27474}div:where(.swal2-icon).swal2-error .swal2-x-mark{position:relative;flex-grow:1}div:where(.swal2-icon).swal2-error [class^=swal2-x-mark-line]{display:block;position:absolute;top:2.3125em;width:2.9375em;height:.3125em;border-radius:.125em;background-color:#f27474}div:where(.swal2-icon).swal2-error [class^=swal2-x-mark-line][class$=left]{left:1.0625em;transform:rotate(45deg)}div:where(.swal2-icon).swal2-error [class^=swal2-x-mark-line][class$=right]{right:1em;transform:rotate(-45deg)}div:where(.swal2-icon).swal2-error.swal2-icon-show{animation:swal2-animate-error-icon .5s}div:where(.swal2-icon).swal2-error.swal2-icon-show .swal2-x-mark{animation:swal2-animate-error-x-mark .5s}div:where(.swal2-icon).swal2-warning{border-color:#f8bb86;color:#f8bb86}div:where(.swal2-icon).swal2-warning.swal2-icon-show{animation:swal2-animate-error-icon .5s}div:where(.swal2-icon).swal2-warning.swal2-icon-show .swal2-icon-content{animation:swal2-animate-i-mark .5s}div:where(.swal2-icon).swal2-info{border-color:#3fc3ee;color:#3fc3ee}div:where(.swal2-icon).swal2-info.swal2-icon-show{animation:swal2-animate-error-icon .5s}div:where(.swal2-icon).swal2-info.swal2-icon-show .swal2-icon-content{animation:swal2-animate-i-mark .8s}div:where(.swal2-icon).swal2-question{border-color:#87adbd;color:#87adbd}div:where(.swal2-icon).swal2-question.swal2-icon-show{animation:swal2-animate-error-icon .5s}div:where(.swal2-icon).swal2-question.swal2-icon-show .swal2-icon-content{animation:swal2-animate-question-mark .8s}div:where(.swal2-icon).swal2-success{border-color:#a5dc86;color:#a5dc86}div:where(.swal2-icon).swal2-success [class^=swal2-success-circular-line]{position:absolute;width:3.75em;height:7.5em;border-radius:50%}div:where(.swal2-icon).swal2-success [class^=swal2-success-circular-line][class$=left]{top:-0.4375em;left:-2.0635em;transform:rotate(-45deg);transform-origin:3.75em 3.75em;border-radius:7.5em 0 0 7.5em}div:where(.swal2-icon).swal2-success [class^=swal2-success-circular-line][class$=right]{top:-0.6875em;left:1.875em;transform:rotate(-45deg);transform-origin:0 3.75em;border-radius:0 7.5em 7.5em 0}div:where(.swal2-icon).swal2-success .swal2-success-ring{position:absolute;z-index:2;top:-0.25em;left:-0.25em;box-sizing:content-box;width:100%;height:100%;border:.25em solid rgba(165,220,134,.3);border-radius:50%}div:where(.swal2-icon).swal2-success .swal2-success-fix{position:absolute;z-index:1;top:.5em;left:1.625em;width:.4375em;height:5.625em;transform:rotate(-45deg)}div:where(.swal2-icon).swal2-success [class^=swal2-success-line]{display:block;position:absolute;z-index:2;height:.3125em;border-radius:.125em;background-color:#a5dc86}div:where(.swal2-icon).swal2-success [class^=swal2-success-line][class$=tip]{top:2.875em;left:.8125em;width:1.5625em;transform:rotate(45deg)}div:where(.swal2-icon).swal2-success [class^=swal2-success-line][class$=long]{top:2.375em;right:.5em;width:2.9375em;transform:rotate(-45deg)}div:where(.swal2-icon).swal2-success.swal2-icon-show .swal2-success-line-tip{animation:swal2-animate-success-line-tip .75s}div:where(.swal2-icon).swal2-success.swal2-icon-show .swal2-success-line-long{animation:swal2-animate-success-line-long .75s}div:where(.swal2-icon).swal2-success.swal2-icon-show .swal2-success-circular-line-right{animation:swal2-rotate-success-circular-line 4.25s ease-in}[class^=swal2]{-webkit-tap-highlight-color:rgba(0,0,0,0)}.swal2-show{animation:var(--swal2-show-animation)}.swal2-hide{animation:var(--swal2-hide-animation)}.swal2-noanimation{transition:none}.swal2-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}.swal2-rtl .swal2-close{margin-right:initial;margin-left:0}.swal2-rtl .swal2-timer-progress-bar{right:0;left:auto}.swal2-toast{box-sizing:border-box;grid-column:1/4 !important;grid-row:1/4 !important;grid-template-columns:min-content auto min-content;padding:1em;overflow-y:hidden;border:var(--swal2-toast-border);background:var(--swal2-background);box-shadow:var(--swal2-toast-box-shadow);pointer-events:auto}.swal2-toast>*{grid-column:2}.swal2-toast h2:where(.swal2-title){margin:.5em 1em;padding:0;font-size:1em;text-align:initial}.swal2-toast .swal2-loading{justify-content:center}.swal2-toast input:where(.swal2-input){height:2em;margin:.5em;font-size:1em}.swal2-toast .swal2-validation-message{font-size:1em}.swal2-toast div:where(.swal2-footer){margin:.5em 0 0;padding:.5em 0 0;font-size:.8em}.swal2-toast button:where(.swal2-close){grid-column:3/3;grid-row:1/99;align-self:center;width:.8em;height:.8em;margin:0;font-size:2em}.swal2-toast div:where(.swal2-html-container){margin:.5em 1em;padding:0;overflow:initial;font-size:1em;text-align:initial}.swal2-toast div:where(.swal2-html-container):empty{padding:0}.swal2-toast .swal2-loader{grid-column:1;grid-row:1/99;align-self:center;width:2em;height:2em;margin:.25em}.swal2-toast .swal2-icon{grid-column:1;grid-row:1/99;align-self:center;width:2em;min-width:2em;height:2em;margin:0 .5em 0 0}.swal2-toast .swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:1.8em;font-weight:bold}.swal2-toast .swal2-icon.swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line]{top:.875em;width:1.375em}.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:.3125em}.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:.3125em}.swal2-toast div:where(.swal2-actions){justify-content:flex-start;height:auto;margin:0;margin-top:.5em;padding:0 .5em}.swal2-toast button:where(.swal2-styled){margin:.25em .5em;padding:.4em .6em;font-size:1em}.swal2-toast .swal2-success{border-color:#a5dc86}.swal2-toast .swal2-success [class^=swal2-success-circular-line]{position:absolute;width:1.6em;height:3em;border-radius:50%}.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=left]{top:-0.8em;left:-0.5em;transform:rotate(-45deg);transform-origin:2em 2em;border-radius:4em 0 0 4em}.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=right]{top:-0.25em;left:.9375em;transform-origin:0 1.5em;border-radius:0 4em 4em 0}.swal2-toast .swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-toast .swal2-success .swal2-success-fix{top:0;left:.4375em;width:.4375em;height:2.6875em}.swal2-toast .swal2-success [class^=swal2-success-line]{height:.3125em}.swal2-toast .swal2-success [class^=swal2-success-line][class$=tip]{top:1.125em;left:.1875em;width:.75em}.swal2-toast .swal2-success [class^=swal2-success-line][class$=long]{top:.9375em;right:.1875em;width:1.375em}.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-tip{animation:swal2-toast-animate-success-line-tip .75s}.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-long{animation:swal2-toast-animate-success-line-long .75s}.swal2-toast.swal2-show{animation:var(--swal2-toast-show-animation)}.swal2-toast.swal2-hide{animation:var(--swal2-toast-hide-animation)}@keyframes swal2-show{0%{transform:translate3d(0, -50px, 0) scale(0.9);opacity:0}100%{transform:translate3d(0, 0, 0) scale(1);opacity:1}}@keyframes swal2-hide{0%{transform:translate3d(0, 0, 0) scale(1);opacity:1}100%{transform:translate3d(0, -50px, 0) scale(0.9);opacity:0}}@keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-0.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.8125em;width:1.5625em}}@keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@keyframes swal2-rotate-success-circular-line{0%{transform:rotate(-45deg)}5%{transform:rotate(-45deg)}12%{transform:rotate(-405deg)}100%{transform:rotate(-405deg)}}@keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;transform:scale(0.4);opacity:0}50%{margin-top:1.625em;transform:scale(0.4);opacity:0}80%{margin-top:-0.375em;transform:scale(1.15)}100%{margin-top:0;transform:scale(1);opacity:1}}@keyframes swal2-animate-error-icon{0%{transform:rotateX(100deg);opacity:0}100%{transform:rotateX(0deg);opacity:1}}@keyframes swal2-rotate-loading{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@keyframes swal2-animate-question-mark{0%{transform:rotateY(-360deg)}100%{transform:rotateY(0)}}@keyframes swal2-animate-i-mark{0%{transform:rotateZ(45deg);opacity:0}25%{transform:rotateZ(-25deg);opacity:.4}50%{transform:rotateZ(15deg);opacity:.8}75%{transform:rotateZ(-5deg);opacity:1}100%{transform:rotateX(0);opacity:1}}@keyframes swal2-toast-show{0%{transform:translateY(-0.625em) rotateZ(2deg)}33%{transform:translateY(0) rotateZ(-2deg)}66%{transform:translateY(0.3125em) rotateZ(2deg)}100%{transform:translateY(0) rotateZ(0deg)}}@keyframes swal2-toast-hide{100%{transform:rotateZ(1deg);opacity:0}}@keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-0.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}\");", "/*\n * isType - Given a Javascript value and a string, returns true if the type of the value matches the\n * given string.\n *\n * @param x - any value\n * @param t - a lowercase string containing one of the following type names:\n * - undefined\n * - null\n * - error\n * - number\n * - boolean\n * - string\n * - symbol\n * - function\n * - object\n * - array\n * @returns true if x is of type t, otherwise false\n */\nfunction isType(x, t) {\n return t === typeName(x);\n}\n\n/*\n * typeName - Given a Javascript value, returns the type of the object as a string\n */\nfunction typeName(x) {\n var name = typeof x;\n if (name !== 'object') {\n return name;\n }\n if (!x) {\n return 'null';\n }\n if (x instanceof Error) {\n return 'error';\n }\n return {}.toString\n .call(x)\n .match(/\\s([a-zA-Z]+)/)[1]\n .toLowerCase();\n}\n\n/* isFunction - a convenience function for checking if a value is a function\n *\n * @param f - any value\n * @returns true if f is a function, otherwise false\n */\nfunction isFunction(f) {\n return isType(f, 'function');\n}\n\n/* isNativeFunction - a convenience function for checking if a value is a native JS function\n *\n * @param f - any value\n * @returns true if f is a native JS function, otherwise false\n */\nfunction isNativeFunction(f) {\n var reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n var funcMatchString = Function.prototype.toString\n .call(Object.prototype.hasOwnProperty)\n .replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?');\n var reIsNative = RegExp('^' + funcMatchString + '$');\n return isObject(f) && reIsNative.test(f);\n}\n\n/* isObject - Checks if the argument is an object\n *\n * @param value - any value\n * @returns true is value is an object function is an object)\n */\nfunction isObject(value) {\n return (\n value != null && (typeof value == 'object' || typeof value == 'function')\n );\n}\n\n/* hasOwn - safe helper around Object.hasOwnProperty */\nfunction hasOwn(obj, prop) {\n if (obj == null) {\n return false;\n }\n if (Object.hasOwn) {\n return Object.hasOwn(obj, prop);\n }\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\n/* isString - Checks if the argument is a string\n *\n * @param value - any value\n * @returns true if value is a string\n */\nfunction isString(value) {\n return typeof value === 'string' || value instanceof String;\n}\n\n/**\n * isFiniteNumber - determines whether the passed value is a finite number\n *\n * @param {*} n - any value\n * @returns true if value is a finite number\n */\nfunction isFiniteNumber(n) {\n return Number.isFinite(n);\n}\n\n/*\n * isIterable - convenience function for checking if a value can be iterated, essentially\n * whether it is an object or an array.\n *\n * @param i - any value\n * @returns true if i is an object or an array as determined by `typeName`\n */\nfunction isIterable(i) {\n var type = typeName(i);\n return type === 'object' || type === 'array';\n}\n\n/*\n * isError - convenience function for checking if a value is of an error type\n *\n * @param e - any value\n * @returns true if e is an error\n */\nfunction isError(e) {\n // Detect both Error and Firefox Exception type\n return isType(e, 'error') || isType(e, 'exception');\n}\n\n/* isPromise - a convenience function for checking if a value is a promise\n *\n * @param p - any value\n * @returns true if f is a function, otherwise false\n */\nfunction isPromise(p) {\n return isObject(p) && isType(p.then, 'function');\n}\n\n/**\n * isBrowser - a convenience function for checking if the code is running in a browser\n *\n * @returns true if the code is running in a browser environment\n */\nfunction isBrowser() {\n return typeof window !== 'undefined';\n}\n\nfunction isRequestObject(input) {\n return typeof Request !== 'undefined' && input instanceof Request;\n}\n\nfunction redact() {\n return '********';\n}\n\n// from http://stackoverflow.com/a/8809472/1138191\nfunction uuid4() {\n var d = now();\n var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(\n /[xy]/g,\n function (c) {\n var r = ((d + Math.random() * 16) % 16) | 0;\n d = Math.floor(d / 16);\n return (c === 'x' ? r : (r & 0x7) | 0x8).toString(16);\n },\n );\n return uuid;\n}\n\nvar LEVELS = {\n debug: 0,\n info: 1,\n warning: 2,\n error: 3,\n critical: 4,\n};\n\nfunction sanitizeHref(url) {\n try {\n const urlObject = new URL(url);\n if (urlObject.password) {\n urlObject.password = redact();\n }\n if (urlObject.search) {\n urlObject.search = redact();\n }\n return urlObject.toString();\n } catch (_) {\n return url; // Return original URL if parsing fails\n }\n}\n\nfunction sanitizeUrl(url) {\n var baseUrlParts = parseUri(url);\n if (!baseUrlParts) {\n return '(unknown)';\n }\n\n // remove a trailing # if there is no anchor\n if (baseUrlParts.anchor === '') {\n baseUrlParts.source = baseUrlParts.source.replace('#', '');\n }\n\n url = baseUrlParts.source.replace('?' + baseUrlParts.query, '');\n return url;\n}\n\nvar parseUriOptions = {\n strictMode: false,\n key: [\n 'source',\n 'protocol',\n 'authority',\n 'userInfo',\n 'user',\n 'password',\n 'host',\n 'port',\n 'relative',\n 'path',\n 'directory',\n 'file',\n 'query',\n 'anchor',\n ],\n q: {\n name: 'queryKey',\n parser: /(?:^|&)([^&=]*)=?([^&]*)/g,\n },\n parser: {\n strict:\n /^(?:([^:/?#]+):)?(?:\\/\\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:/?#]*)(?::(\\d*))?))?((((?:[^?#/]*\\/)*)([^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/,\n loose:\n /^(?:(?![^:@]+:[^:@/]*@)([^:/?#.]+):)?(?:\\/\\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[?#]|$)))*\\/?)?([^?#/]*))(?:\\?([^#]*))?(?:#(.*))?)/,\n },\n};\n\nfunction parseUri(str) {\n if (!isType(str, 'string')) {\n return undefined;\n }\n\n var o = parseUriOptions;\n var m = o.parser[o.strictMode ? 'strict' : 'loose'].exec(str);\n var uri = {};\n\n for (var i = 0, l = o.key.length; i < l; ++i) {\n uri[o.key[i]] = m[i] || '';\n }\n\n uri[o.q.name] = {};\n uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {\n if ($1) {\n uri[o.q.name][$1] = $2;\n }\n });\n\n return uri;\n}\n\nfunction addParamsAndAccessTokenToPath(accessToken, options, params) {\n params = params || {};\n params.access_token = accessToken;\n var paramsArray = [];\n var k;\n for (k in params) {\n if (Object.prototype.hasOwnProperty.call(params, k)) {\n paramsArray.push([k, params[k]].join('='));\n }\n }\n var query = '?' + paramsArray.sort().join('&');\n\n options = options || {};\n options.path = options.path || '';\n var qs = options.path.indexOf('?');\n var h = options.path.indexOf('#');\n var p;\n if (qs !== -1 && (h === -1 || h > qs)) {\n p = options.path;\n options.path = p.substring(0, qs) + query + '&' + p.substring(qs + 1);\n } else {\n if (h !== -1) {\n p = options.path;\n options.path = p.substring(0, h) + query + p.substring(h);\n } else {\n options.path = options.path + query;\n }\n }\n}\n\nfunction formatUrl(u, protocol) {\n protocol = protocol || u.protocol;\n if (!protocol && u.port) {\n if (u.port === 80) {\n protocol = 'http:';\n } else if (u.port === 443) {\n protocol = 'https:';\n }\n }\n protocol = protocol || 'https:';\n\n if (!u.hostname) {\n return null;\n }\n var result = protocol + '//' + u.hostname;\n if (u.port) {\n result = result + ':' + u.port;\n }\n if (u.path) {\n result = result + u.path;\n }\n return result;\n}\n\nfunction stringify(obj, backup) {\n var value, error;\n try {\n value = JSON.stringify(obj);\n } catch (jsonError) {\n if (backup && isFunction(backup)) {\n try {\n value = backup(obj);\n } catch (backupError) {\n error = backupError;\n }\n } else {\n error = jsonError;\n }\n }\n return { error: error, value: value };\n}\n\nfunction maxByteSize(string) {\n // The transport will use utf-8, so assume utf-8 encoding.\n //\n // This minimal implementation will accurately count bytes for all UCS-2 and\n // single code point UTF-16. If presented with multi code point UTF-16,\n // which should be rare, it will safely overcount, not undercount.\n //\n // While robust utf-8 encoders exist, this is far smaller and far more performant.\n // For quickly counting payload size for truncation, smaller is better.\n\n var count = 0;\n var length = string.length;\n\n for (var i = 0; i < length; i++) {\n var code = string.charCodeAt(i);\n if (code < 128) {\n // up to 7 bits\n count = count + 1;\n } else if (code < 2048) {\n // up to 11 bits\n count = count + 2;\n } else if (code < 65536) {\n // up to 16 bits\n count = count + 3;\n }\n }\n\n return count;\n}\n\nfunction jsonParse(s) {\n var value, error;\n try {\n value = JSON.parse(s);\n } catch (e) {\n error = e;\n }\n return { error, value };\n}\n\nfunction makeUnhandledStackInfo(\n message,\n url,\n lineno,\n colno,\n error,\n mode,\n backupMessage,\n errorParser,\n) {\n var location = {\n url: url || '',\n line: lineno,\n column: colno,\n };\n location.func = errorParser.guessFunctionName(location.url, location.line);\n location.context = errorParser.gatherContext(location.url, location.line);\n var href =\n typeof document !== 'undefined' &&\n document &&\n document.location &&\n document.location.href;\n var useragent =\n typeof window !== 'undefined' &&\n window &&\n window.navigator &&\n window.navigator.userAgent;\n return {\n mode: mode,\n message: error ? String(error) : message || backupMessage,\n url: href,\n stack: [location],\n useragent: useragent,\n };\n}\n\nfunction wrapCallback(logger, f) {\n return function (err, resp) {\n try {\n f(err, resp);\n } catch (e) {\n logger.error(e);\n }\n };\n}\n\nfunction nonCircularClone(obj) {\n var seen = [obj];\n\n function clone(obj, seen) {\n var value,\n name,\n newSeen,\n result = {};\n\n try {\n for (name in obj) {\n value = obj[name];\n\n if (value && (isType(value, 'object') || isType(value, 'array'))) {\n if (seen.includes(value)) {\n result[name] = 'Removed circular reference: ' + typeName(value);\n } else {\n newSeen = seen.slice();\n newSeen.push(value);\n result[name] = clone(value, newSeen);\n }\n continue;\n }\n\n result[name] = value;\n }\n } catch (e) {\n result = 'Failed cloning custom data: ' + e.message;\n }\n return result;\n }\n return clone(obj, seen);\n}\n\nfunction createItem(args, logger, notifier, requestKeys, lambdaContext) {\n var message, err, custom, callback, request;\n var arg;\n var extraArgs = [];\n var diagnostic = {};\n var argTypes = [];\n\n for (var i = 0, l = args.length; i < l; ++i) {\n arg = args[i];\n\n var typ = typeName(arg);\n argTypes.push(typ);\n switch (typ) {\n case 'undefined':\n break;\n case 'string':\n if (message) {\n extraArgs.push(arg);\n } else {\n message = arg;\n }\n break;\n case 'function':\n callback = wrapCallback(logger, arg);\n break;\n case 'date':\n extraArgs.push(arg);\n break;\n case 'error':\n case 'domexception':\n case 'exception': // Firefox Exception type\n if (err) {\n extraArgs.push(arg);\n } else {\n err = arg;\n }\n break;\n case 'object':\n case 'array':\n if (\n arg instanceof Error ||\n (typeof DOMException !== 'undefined' && arg instanceof DOMException)\n ) {\n if (err) {\n extraArgs.push(arg);\n } else {\n err = arg;\n }\n break;\n }\n if (requestKeys && typ === 'object' && !request) {\n for (var j = 0, len = requestKeys.length; j < len; ++j) {\n if (arg[requestKeys[j]] !== undefined) {\n request = arg;\n break;\n }\n }\n if (request) {\n break;\n }\n }\n if (custom) {\n extraArgs.push(arg);\n } else {\n custom = arg;\n }\n break;\n default:\n if (\n arg instanceof Error ||\n (typeof DOMException !== 'undefined' && arg instanceof DOMException)\n ) {\n if (err) {\n extraArgs.push(arg);\n } else {\n err = arg;\n }\n break;\n }\n extraArgs.push(arg);\n }\n }\n\n // if custom is an array this turns it into an object with integer keys\n if (custom) custom = nonCircularClone(custom);\n\n if (extraArgs.length > 0) {\n if (!custom) custom = nonCircularClone({});\n custom.extraArgs = nonCircularClone(extraArgs);\n }\n\n var item = {\n message: message,\n err: err,\n custom: custom,\n timestamp: now(),\n callback: callback,\n notifier: notifier,\n diagnostic: diagnostic,\n uuid: uuid4(),\n };\n\n item.data = item.data || {};\n\n setCustomItemKeys(item, custom);\n\n if (requestKeys && request) {\n item.request = request;\n }\n if (lambdaContext) {\n item.lambdaContext = lambdaContext;\n }\n item._originalArgs = args;\n item.diagnostic.original_arg_types = argTypes;\n return item;\n}\n\nfunction setCustomItemKeys(item, custom) {\n if (custom && custom.level !== undefined) {\n item.level = custom.level;\n delete custom.level;\n }\n if (custom && custom.skipFrames !== undefined) {\n item.skipFrames = custom.skipFrames;\n delete custom.skipFrames;\n }\n}\n\nfunction addErrorContext(item, errors) {\n var custom = item.data.custom || {};\n var contextAdded = false;\n\n try {\n for (const error of errors) {\n if (hasOwn(error, 'rollbarContext')) {\n custom = merge(custom, nonCircularClone(error.rollbarContext));\n contextAdded = true;\n }\n }\n\n // Avoid adding an empty object to the data.\n if (contextAdded) {\n item.data.custom = custom;\n }\n } catch (e) {\n item.diagnostic.error_context = 'Failed: ' + e.message;\n }\n}\n\nvar TELEMETRY_TYPES = [\n 'log',\n 'network',\n 'dom',\n 'navigation',\n 'error',\n 'manual',\n];\nvar TELEMETRY_LEVELS = ['critical', 'error', 'warning', 'info', 'debug'];\n\nfunction arrayIncludes(arr, val) {\n for (const entry of arr) {\n if (entry === val) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction createTelemetryEvent(args) {\n var type, metadata, level;\n var arg;\n\n for (var i = 0, l = args.length; i < l; ++i) {\n arg = args[i];\n\n var typ = typeName(arg);\n switch (typ) {\n case 'string':\n if (!type && arrayIncludes(TELEMETRY_TYPES, arg)) {\n type = arg;\n } else if (!level && arrayIncludes(TELEMETRY_LEVELS, arg)) {\n level = arg;\n }\n break;\n case 'object':\n metadata = arg;\n break;\n default:\n break;\n }\n }\n var event = {\n type: type || 'manual',\n metadata: metadata || {},\n level: level,\n };\n\n return event;\n}\n\nfunction addItemAttributes(itemData, attributes) {\n itemData.attributes = itemData.attributes || [];\n for (const a of attributes) {\n if (a.value === undefined) {\n continue;\n }\n itemData.attributes.push(a);\n }\n}\n\n/*\n * get - given an obj/array and a keypath, return the value at that keypath or\n * undefined if not possible.\n *\n * @param obj - an object or array\n * @param path - a string of keys separated by '.' such as 'plugin.jquery.0.message'\n * which would correspond to 42 in `{plugin: {jquery: [{message: 42}]}}`\n */\nfunction get(obj, path) {\n if (!obj) {\n return undefined;\n }\n var keys = path.split('.');\n var result = obj;\n try {\n for (var i = 0, len = keys.length; i < len; ++i) {\n result = result[keys[i]];\n }\n } catch (_e) {\n result = undefined;\n }\n return result;\n}\n\nfunction set(obj, path, value) {\n if (!obj) {\n return;\n }\n\n // Prevent prototype pollution by setting the prototype to null.\n Object.setPrototypeOf(obj, null);\n\n var keys = path.split('.');\n var len = keys.length;\n if (len < 1) {\n return;\n }\n if (len === 1) {\n obj[keys[0]] = value;\n return;\n }\n try {\n var temp = obj[keys[0]] || {};\n var replacement = temp;\n for (var i = 1; i < len - 1; ++i) {\n temp[keys[i]] = temp[keys[i]] || {};\n temp = temp[keys[i]];\n }\n temp[keys[len - 1]] = value;\n obj[keys[0]] = replacement;\n } catch (_e) {\n return;\n }\n}\n\nfunction formatArgsAsString(args) {\n var i, len, arg;\n var result = [];\n for (i = 0, len = args.length; i < len; ++i) {\n arg = args[i];\n switch (typeName(arg)) {\n case 'object':\n arg = stringify(arg);\n arg = arg.error || arg.value;\n if (arg.length > 500) {\n arg = arg.substr(0, 497) + '...';\n }\n break;\n case 'null':\n arg = 'null';\n break;\n case 'undefined':\n arg = 'undefined';\n break;\n case 'symbol':\n arg = arg.toString();\n break;\n }\n result.push(arg);\n }\n return result.join(' ');\n}\n\nfunction now() {\n if (Date.now) {\n return Date.now();\n }\n return Number(new Date());\n}\n\nfunction filterIp(requestData, captureIp) {\n if (!requestData || !requestData['user_ip'] || captureIp === true) {\n return;\n }\n var newIp = requestData['user_ip'];\n if (!captureIp) {\n newIp = null;\n } else {\n try {\n var parts;\n if (newIp.indexOf('.') !== -1) {\n parts = newIp.split('.');\n parts.pop();\n parts.push('0');\n newIp = parts.join('.');\n } else if (newIp.indexOf(':') !== -1) {\n parts = newIp.split(':');\n if (parts.length > 2) {\n var beginning = parts.slice(0, 3);\n var slashIdx = beginning[2].indexOf('/');\n if (slashIdx !== -1) {\n beginning[2] = beginning[2].substring(0, slashIdx);\n }\n var terminal = '0000:0000:0000:0000:0000';\n newIp = beginning.concat(terminal).join(':');\n }\n } else {\n newIp = null;\n }\n } catch (_e) {\n newIp = null;\n }\n }\n requestData['user_ip'] = newIp;\n}\n\nfunction handleOptions(current, input, payload, logger) {\n var result = merge(current, input, payload);\n result = updateDeprecatedOptions(result, logger);\n if (!input || input.overwriteScrubFields) {\n return result;\n }\n if (input.scrubFields) {\n result.scrubFields = (current.scrubFields || []).concat(input.scrubFields);\n }\n return result;\n}\n\nfunction updateDeprecatedOptions(options, logger) {\n if (options.hostWhiteList && !options.hostSafeList) {\n options.hostSafeList = options.hostWhiteList;\n options.hostWhiteList = undefined;\n logger && logger.log('hostWhiteList is deprecated. Use hostSafeList.');\n }\n if (options.hostBlackList && !options.hostBlockList) {\n options.hostBlockList = options.hostBlackList;\n options.hostBlackList = undefined;\n logger && logger.log('hostBlackList is deprecated. Use hostBlockList.');\n }\n return options;\n}\n\nfunction merge() {\n function isPlainObject(obj) {\n if (!obj || Object.prototype.toString.call(obj) !== '[object Object]') {\n return false;\n }\n\n var hasOwnConstructor = hasOwn(obj, 'constructor');\n var hasIsPrototypeOf =\n obj.constructor &&\n obj.constructor.prototype &&\n hasOwn(obj.constructor.prototype, 'isPrototypeOf');\n // Not own constructor property must be Object\n if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {\n return false;\n }\n\n // Own properties are enumerated firstly, so to speed up,\n // if last one is own, then all properties are own.\n var key;\n for (key in obj) {\n /**/\n }\n\n return typeof key === 'undefined' || hasOwn(obj, key);\n }\n\n var i,\n src,\n copy,\n clone,\n name,\n result = Object.create(null), // no prototype pollution on Object\n current = null,\n length = arguments.length;\n\n for (i = 0; i < length; i++) {\n current = arguments[i];\n if (current === null || current === undefined) {\n continue;\n }\n\n for (name in current) {\n src = result[name];\n copy = current[name];\n if (result !== copy) {\n if (copy && isPlainObject(copy)) {\n clone = src && isPlainObject(src) ? src : {};\n result[name] = merge(clone, copy);\n } else if (typeof copy !== 'undefined') {\n result[name] = copy;\n }\n }\n }\n }\n return result;\n}\n\nfunction shouldAddBaggageHeader(options, tracing, url) {\n if (!tracing?.sessionId || !url) {\n return false;\n }\n const propagation = options?.tracing?.propagation;\n const enabledHeaders = propagation?.enabledHeaders;\n if (!Array.isArray(enabledHeaders) || !enabledHeaders.includes('baggage')) {\n return false;\n }\n const enabledCorsUrls = propagation?.enabledCorsUrls;\n if (!Array.isArray(enabledCorsUrls) || enabledCorsUrls.length === 0) {\n return false;\n }\n return enabledCorsUrls.some((pattern) => {\n if (isType(pattern, 'string')) {\n return url === pattern;\n }\n if (isType(pattern, 'regexp')) {\n return pattern.test(url);\n }\n return false;\n });\n}\n\nfunction addHeadersToFetch(args, newHeaders) {\n // Headers may be in the request object or the init object.\n // If present in both places, the init object must be used.\n //\n let init = args[1];\n const initHeaders = init?.headers;\n const reqHeaders = isRequestObject(args[0]) && args[0].headers;\n let headers = initHeaders || reqHeaders;\n\n // If headers are not present in either place, they are added to the init object.\n // If there is no init object, one must be created and added to args.\n if (!headers) {\n if (!init) {\n args[1] = init = {};\n }\n headers = init.headers = {};\n }\n\n // `headers` may be a Headers object or a plain object.\n if (headers instanceof Headers) {\n for (const key of Object.keys(newHeaders)) {\n headers.append(key, newHeaders[key]);\n }\n } else if (isObject(headers)) {\n for (const key of Object.keys(newHeaders)) {\n headers[key] = newHeaders[key];\n }\n }\n}\n\nfunction getSessionIdFromAsyncLocalStorage(client) {\n const storage = client.asyncLocalStorage;\n if (!storage || typeof storage.getStore !== 'function') {\n return null;\n }\n const store = storage.getStore();\n return store?.sessionId || null;\n}\n\nexport {\n addParamsAndAccessTokenToPath,\n createItem,\n addErrorContext,\n createTelemetryEvent,\n addItemAttributes,\n filterIp,\n formatArgsAsString,\n formatUrl,\n get,\n handleOptions,\n isError,\n isFiniteNumber,\n isFunction,\n hasOwn,\n isIterable,\n isNativeFunction,\n isObject,\n isString,\n isType,\n isPromise,\n isBrowser,\n jsonParse,\n LEVELS,\n makeUnhandledStackInfo,\n merge,\n now,\n redact,\n sanitizeHref,\n sanitizeUrl,\n set,\n stringify,\n maxByteSize,\n typeName,\n uuid4,\n shouldAddBaggageHeader,\n addHeadersToFetch,\n getSessionIdFromAsyncLocalStorage,\n};\n", "import * as _ from '../utility.js';\n\nfunction traverse(obj, func, seen) {\n var k, v, i;\n var isObj = _.isType(obj, 'object');\n var isArray = _.isType(obj, 'array');\n var keys = [];\n var seenIndex;\n\n // Best might be to use Map here with `obj` as the keys, but we want to support IE < 11.\n seen = seen || { obj: [], mapped: [] };\n\n if (isObj) {\n seenIndex = seen.obj.indexOf(obj);\n\n if (isObj && seenIndex !== -1) {\n // Prefer the mapped object if there is one.\n return seen.mapped[seenIndex] || seen.obj[seenIndex];\n }\n\n seen.obj.push(obj);\n seenIndex = seen.obj.length - 1;\n }\n\n if (isObj) {\n for (k in obj) {\n if (_.hasOwn(obj, k)) {\n keys.push(k);\n }\n }\n } else if (isArray) {\n for (i = 0; i < obj.length; ++i) {\n keys.push(i);\n }\n }\n\n var result = isObj ? {} : [];\n var same = true;\n for (i = 0; i < keys.length; ++i) {\n k = keys[i];\n v = obj[k];\n result[k] = func(k, v, seen);\n same = same && result[k] === obj[k];\n }\n\n if (isObj && !same) {\n seen.mapped[seenIndex] = result;\n }\n\n return !same ? result : obj;\n}\n\nexport default traverse;\n", "import traverse from './utility/traverse.js';\nimport * as _ from './utility.js';\n\nfunction scrub(data, scrubFields, scrubPaths) {\n scrubFields = scrubFields || [];\n\n if (scrubPaths) {\n for (const path of scrubPaths) {\n scrubPath(data, path);\n }\n }\n\n var paramRes = _getScrubFieldRegexs(scrubFields);\n var queryRes = _getScrubQueryParamRegexs(scrubFields);\n\n function redactQueryParam(dummy0, paramPart) {\n return paramPart + _.redact();\n }\n\n function paramScrubber(v) {\n if (_.isType(v, 'string')) {\n for (const regex of queryRes) {\n v = v.replace(regex, redactQueryParam);\n }\n }\n return v;\n }\n\n function valScrubber(k, v) {\n for (const regex of paramRes) {\n if (regex.test(k)) {\n v = _.redact();\n break;\n }\n }\n return v;\n }\n\n function scrubber(k, v, seen) {\n var tmpV = valScrubber(k, v);\n if (tmpV === v) {\n if (_.isType(v, 'object') || _.isType(v, 'array')) {\n return traverse(v, scrubber, seen);\n }\n return paramScrubber(tmpV);\n } else {\n return tmpV;\n }\n }\n\n return traverse(data, scrubber);\n}\n\nfunction scrubPath(obj, path) {\n var keys = path.split('.');\n var last = keys.length - 1;\n try {\n for (const [index, key] of keys.entries()) {\n if (index < last) {\n obj = obj[key];\n } else {\n obj[key] = _.redact();\n }\n }\n } catch (_e) {\n // Missing key is OK;\n }\n}\n\nfunction _getScrubFieldRegexs(scrubFields) {\n var ret = [];\n for (const field of scrubFields) {\n var pat = '^\\\\[?(%5[bB])?' + field + '\\\\[?(%5[bB])?\\\\]?(%5[dD])?$';\n ret.push(new RegExp(pat, 'i'));\n }\n return ret;\n}\n\nfunction _getScrubQueryParamRegexs(scrubFields) {\n var ret = [];\n for (const field of scrubFields) {\n var pat = '\\\\[?(%5[bB])?' + field + '\\\\[?(%5[bB])?\\\\]?(%5[dD])?';\n ret.push(new RegExp('(' + pat + '=)([^&\\\\n]+)', 'igm'));\n }\n return ret;\n}\n\nexport default scrub;\n", "import * as _ from './utility.js';\n\nconst MAX_EVENTS = 100;\n\n// Temporary workaround while solving commonjs -> esm issues in Node 18 - 20.\nfunction fromMillis(millis) {\n return [Math.trunc(millis / 1000), Math.round((millis % 1000) * 1e6)];\n}\n\nclass Telemeter {\n constructor(options, tracing) {\n this.queue = [];\n this.options = _.merge(options);\n var maxTelemetryEvents = this.options.maxTelemetryEvents || MAX_EVENTS;\n this.maxQueueSize = Math.max(0, Math.min(maxTelemetryEvents, MAX_EVENTS));\n this.tracing = tracing;\n this.telemetrySpan = this.tracing?.startSpan('rollbar-telemetry', {});\n }\n\n configure(options) {\n var oldOptions = this.options;\n this.options = _.merge(oldOptions, options);\n var maxTelemetryEvents = this.options.maxTelemetryEvents || MAX_EVENTS;\n var newMaxEvents = Math.max(0, Math.min(maxTelemetryEvents, MAX_EVENTS));\n var deleteCount = 0;\n if (this.queue.length > newMaxEvents) {\n deleteCount = this.queue.length - newMaxEvents;\n }\n this.maxQueueSize = newMaxEvents;\n this.queue.splice(0, deleteCount);\n }\n\n copyEvents() {\n var events = Array.prototype.slice.call(this.queue, 0);\n if (_.isFunction(this.options.filterTelemetry)) {\n try {\n var i = events.length;\n while (i--) {\n if (this.options.filterTelemetry(events[i])) {\n events.splice(i, 1);\n }\n }\n } catch (_e) {\n this.options.filterTelemetry = null;\n }\n }\n\n // Filter until supported in legacy telemetry\n events = events.filter((e) => e.type !== 'connectivity');\n\n // Remove internal keys from output\n events = events.map(\n ({ otelAttributes: _otelAttributes, ...event }) => event,\n );\n\n return events;\n }\n\n exportTelemetrySpan(attributes = {}) {\n if (this.telemetrySpan) {\n this.telemetrySpan.end(attributes);\n this.telemetrySpan = this.tracing.startSpan('rollbar-telemetry', {});\n }\n }\n\n capture(\n type,\n metadata,\n level,\n rollbarUUID,\n timestamp = null,\n otelAttributes = null,\n ) {\n var e = {\n level: getLevel(type, level),\n type: type,\n timestamp_ms: timestamp || _.now(),\n body: metadata,\n source: 'client',\n };\n if (rollbarUUID) {\n e.uuid = rollbarUUID;\n }\n if (otelAttributes) {\n e.otelAttributes = otelAttributes;\n }\n\n try {\n if (\n _.isFunction(this.options.filterTelemetry) &&\n this.options.filterTelemetry(e)\n ) {\n return false;\n }\n } catch (_exc) {\n this.options.filterTelemetry = null;\n }\n\n this.push(e);\n return e;\n }\n\n captureEvent(type, metadata, level, rollbarUUID) {\n return this.capture(type, metadata, level, rollbarUUID);\n }\n\n captureError(err, level, rollbarUUID, timestamp) {\n const message = err.message || String(err);\n var metadata = { message };\n if (err.stack) {\n metadata.stack = err.stack;\n }\n const otelAttributes = {\n message,\n level,\n type: 'error',\n uuid: rollbarUUID,\n };\n\n this.telemetrySpan?.addEvent(\n 'rollbar-occurrence-event',\n otelAttributes,\n fromMillis(timestamp),\n );\n\n return this.capture(\n 'error',\n metadata,\n level,\n rollbarUUID,\n timestamp,\n otelAttributes,\n );\n }\n\n captureLog(message, level, rollbarUUID, timestamp) {\n const event = rollbarUUID\n ? 'rollbar-occurrence-event'\n : 'rollbar-log-event';\n const otelAttributes = {\n message,\n level,\n ...(rollbarUUID ? { type: 'message', uuid: rollbarUUID } : {}),\n };\n\n this.telemetrySpan?.addEvent(event, otelAttributes, fromMillis(timestamp));\n\n return this.capture(\n 'log',\n { message },\n level,\n rollbarUUID,\n timestamp,\n otelAttributes,\n );\n }\n\n captureNetwork(metadata, subtype, rollbarUUID, requestData) {\n subtype = subtype || 'xhr';\n metadata.subtype = metadata.subtype || subtype;\n if (requestData) {\n metadata.request = requestData;\n }\n const level = this.levelFromStatus(metadata.status_code);\n const endTimeNano = (metadata.end_time_ms || 0) * 1e6;\n const otelAttributes = {\n type: metadata.subtype,\n method: metadata.method,\n url: metadata.url,\n statusCode: metadata.status_code,\n 'request.headers': JSON.stringify(metadata.request_headers || {}),\n 'response.headers': JSON.stringify(metadata.response?.headers || {}),\n 'response.timeUnixNano': endTimeNano.toString(),\n };\n const requestBody = metadata.request;\n const responseBody = metadata.response?.body;\n if (requestBody) {\n otelAttributes['request.body'] = JSON.stringify(requestBody);\n }\n if (responseBody) {\n otelAttributes['response.body'] = JSON.stringify(responseBody);\n }\n\n this.telemetrySpan?.addEvent(\n 'rollbar-network-event',\n otelAttributes,\n fromMillis(metadata.start_time_ms),\n );\n\n return this.capture(\n 'network',\n metadata,\n level,\n rollbarUUID,\n metadata.start_time_ms,\n otelAttributes,\n );\n }\n\n levelFromStatus(statusCode) {\n if (statusCode >= 200 && statusCode < 400) {\n return 'info';\n }\n if (statusCode === 0 || statusCode >= 400) {\n return 'error';\n }\n return 'info';\n }\n\n captureDom(subtype, element, value, checked, rollbarUUID) {\n var metadata = {\n subtype: subtype,\n element: element,\n };\n if (value !== undefined) {\n metadata.value = value;\n }\n if (checked !== undefined) {\n metadata.checked = checked;\n }\n return this.capture('dom', metadata, 'info', rollbarUUID);\n }\n\n captureInput({ type, isSynthetic, element, value, timestamp }) {\n const name = 'rollbar-input-event';\n const metadata = {\n type: name,\n subtype: type,\n element,\n value,\n };\n const otelAttributes = {\n type,\n isSynthetic,\n element,\n value,\n endTimeUnixNano: fromMillis(timestamp),\n };\n const event = this._getRepeatedEvent(name, otelAttributes);\n if (event) {\n return this._updateRepeatedEvent(event, otelAttributes, timestamp);\n }\n\n this.telemetrySpan?.addEvent(name, otelAttributes, fromMillis(timestamp));\n\n return this.capture(\n 'dom',\n metadata,\n 'info',\n null,\n timestamp,\n otelAttributes,\n );\n }\n\n captureClick({ type, isSynthetic, element, timestamp }) {\n const name = 'rollbar-click-event';\n const metadata = {\n type: name,\n subtype: type,\n element,\n };\n const otelAttributes = {\n type,\n isSynthetic,\n element,\n endTimeUnixNano: fromMillis(timestamp),\n };\n const event = this._getRepeatedEvent(name, otelAttributes);\n if (event) {\n return this._updateRepeatedEvent(event, otelAttributes, timestamp);\n }\n\n this.telemetrySpan?.addEvent(name, otelAttributes, fromMillis(timestamp));\n\n return this.capture(\n 'dom',\n metadata,\n 'info',\n null,\n timestamp,\n otelAttributes,\n );\n }\n\n _getRepeatedEvent(name, attributes) {\n const lastEvent = this._lastEvent(this.queue);\n\n if (\n lastEvent &&\n lastEvent.body.type === name &&\n lastEvent.otelAttributes.target === attributes.target\n ) {\n return lastEvent;\n }\n }\n\n _updateRepeatedEvent(event, attributes, timestamp) {\n const duration = Math.max(timestamp - event.timestamp_ms, 1);\n event.body.value = attributes.value;\n event.otelAttributes.value = attributes.value;\n event.otelAttributes.height = attributes.height;\n event.otelAttributes.width = attributes.width;\n event.otelAttributes.textZoomRatio = attributes.textZoomRatio;\n event.otelAttributes['endTimeUnixNano'] = fromMillis(timestamp);\n event.otelAttributes['durationUnixNano'] = fromMillis(duration);\n event.otelAttributes.count = (event.otelAttributes.count || 1) + 1;\n event.otelAttributes.rate = event.otelAttributes.count / (duration / 1000);\n }\n\n _lastEvent(list) {\n return list.length > 0 ? list[list.length - 1] : null;\n }\n\n captureFocus({ type, isSynthetic, element, timestamp }) {\n const name = 'rollbar-focus-event';\n const metadata = {\n type: name,\n subtype: type,\n element,\n };\n const otelAttributes = {\n type,\n isSynthetic,\n element,\n };\n\n this.telemetrySpan?.addEvent(name, otelAttributes, fromMillis(timestamp));\n\n return this.capture(\n 'dom',\n metadata,\n 'info',\n null,\n timestamp,\n otelAttributes,\n );\n }\n\n captureResize({\n type,\n isSynthetic,\n width,\n height,\n textZoomRatio,\n timestamp,\n }) {\n const name = 'rollbar-resize-event';\n const metadata = {\n type: name,\n subtype: type,\n width,\n height,\n textZoomRatio,\n };\n const otelAttributes = {\n type,\n isSynthetic,\n width,\n height,\n textZoomRatio,\n };\n\n const event = this._getRepeatedEvent(name, otelAttributes);\n if (event) {\n return this._updateRepeatedEvent(event, otelAttributes, timestamp);\n }\n\n this.telemetrySpan?.addEvent(name, otelAttributes, fromMillis(timestamp));\n\n return this.capture(\n 'dom',\n metadata,\n 'info',\n null,\n timestamp,\n otelAttributes,\n );\n }\n\n captureDragDrop({\n type,\n isSynthetic,\n element,\n dropEffect,\n effectAllowed,\n kinds,\n mediaTypes,\n timestamp,\n }) {\n const name = 'rollbar-dragdrop-event';\n let metadata = {\n type: name,\n subtype: type,\n isSynthetic,\n };\n\n let otelAttributes = {\n type,\n isSynthetic,\n };\n\n if (type === 'dragstart') {\n metadata = { ...metadata, element, dropEffect, effectAllowed };\n otelAttributes = {\n ...otelAttributes,\n element,\n dropEffect,\n effectAllowed,\n };\n }\n\n if (type === 'drop') {\n metadata = {\n ...metadata,\n element,\n dropEffect,\n effectAllowed,\n kinds,\n mediaTypes,\n };\n otelAttributes = {\n ...otelAttributes,\n element,\n dropEffect,\n effectAllowed,\n kinds,\n mediaTypes,\n };\n }\n\n this.telemetrySpan?.addEvent(name, otelAttributes, fromMillis(timestamp));\n\n return this.capture(\n 'dom',\n metadata,\n 'info',\n null,\n timestamp,\n otelAttributes,\n );\n }\n\n captureNavigation(from, to, rollbarUUID, timestamp) {\n this.telemetrySpan?.addEvent(\n 'rollbar-navigation-event',\n { 'previous.url.full': from, 'url.full': to },\n fromMillis(timestamp),\n );\n\n return this.capture(\n 'navigation',\n { from, to },\n 'info',\n rollbarUUID,\n timestamp,\n );\n }\n\n captureDomContentLoaded(ts) {\n return this.capture(\n 'navigation',\n { subtype: 'DOMContentLoaded' },\n 'info',\n undefined,\n ts && ts.getTime(),\n );\n /**\n * If we decide to make this a dom event instead, then use the line below:\n return this.capture('dom', {subtype: 'DOMContentLoaded'}, 'info', undefined, ts && ts.getTime());\n */\n }\n\n captureLoad(ts) {\n return this.capture(\n 'navigation',\n { subtype: 'load' },\n 'info',\n undefined,\n ts && ts.getTime(),\n );\n /**\n * If we decide to make this a dom event instead, then use the line below:\n return this.capture('dom', {subtype: 'load'}, 'info', undefined, ts && ts.getTime());\n */\n }\n\n captureConnectivityChange({ type, isSynthetic, timestamp }) {\n const name = 'rollbar-connectivity-event';\n const metadata = {\n type: name,\n subtype: type,\n };\n const otelAttributes = {\n type,\n isSynthetic,\n };\n\n this.telemetrySpan?.addEvent(name, otelAttributes, fromMillis(timestamp));\n\n return this.capture(\n 'connectivity',\n metadata,\n 'info',\n null,\n timestamp,\n otelAttributes,\n );\n }\n\n // Only intended to be used internally by the notifier\n _captureRollbarItem(item) {\n if (!this.options.includeItemsInTelemetry) {\n return;\n }\n if (item.err) {\n return this.captureError(item.err, item.level, item.uuid, item.timestamp);\n }\n if (item.message) {\n return this.captureLog(\n item.message,\n item.level,\n item.uuid,\n item.timestamp,\n );\n }\n if (item.custom) {\n return this.capture(\n 'log',\n item.custom,\n item.level,\n item.uuid,\n item.timestamp,\n );\n }\n }\n\n push(e) {\n this.queue.push(e);\n if (this.queue.length > this.maxQueueSize) {\n this.queue.shift();\n }\n }\n}\n\nfunction getLevel(type, level) {\n if (level) {\n return level;\n }\n var defaultLevel = {\n error: 'error',\n manual: 'info',\n };\n return defaultLevel[type] || 'info';\n}\n\nexport default Telemeter;\n", "export class Context {\n constructor(parentContext) {\n this._currentContext = parentContext ? new Map(parentContext) : new Map();\n }\n\n getValue(key) {\n return this._currentContext.get(key);\n }\n\n setValue(key, value) {\n const context = new Context(this._currentContext);\n context._currentContext.set(key, value);\n return context;\n }\n\n deleteValue(key) {\n const context = new Context(self._currentContext);\n context._currentContext.delete(key);\n return context;\n }\n}\n\nexport const ROOT_CONTEXT = new Context();\n", "import { ROOT_CONTEXT } from './context.js';\n\nexport class ContextManager {\n constructor() {\n this.currentContext = ROOT_CONTEXT;\n }\n\n active() {\n return this.currentContext;\n }\n\n enterContext(context) {\n const previousContext = this.currentContext;\n this.currentContext = context || ROOT_CONTEXT;\n return previousContext;\n }\n\n exitContext(context) {\n this.currentContext = context;\n return this.currentContext;\n }\n\n with(context, fn, thisArg, ...args) {\n const previousContext = this.enterContext(context);\n try {\n return fn.call(thisArg, ...args);\n } finally {\n this.exitContext(previousContext);\n }\n }\n}\n\nexport function createContextKey(key) {\n // Use Symbol for OpenTelemetry compatibility.\n return Symbol.for(key);\n}\n", "/**\n * @module hrtime\n *\n * @description Methods for handling OpenTelemetry hrtime.\n */\n\n/**\n * Convert a duration in milliseconds to an OpenTelemetry hrtime tuple.\n *\n * @param {number} millis - The duration in milliseconds.\n * @returns {[number, number]} An array where the first element is seconds\n * and the second is nanoseconds.\n */\nfunction fromMillis(millis) {\n return [Math.trunc(millis / 1000), Math.round((millis % 1000) * 1e6)];\n}\n\n/**\n * Convert an OpenTelemetry hrtime tuple back to a duration in milliseconds.\n *\n * @param {[number, number]} hrtime - The hrtime tuple [seconds, nanoseconds].\n * @returns {number} The total duration in milliseconds.\n */\nfunction toMillis(hrtime) {\n return hrtime[0] * 1e3 + Math.round(hrtime[1] / 1e6);\n}\n\n/**\n * Convert an OpenTelemetry hrtime tuple back to a duration in nanoseconds.\n *\n * @param {[number, number]} hrtime - The hrtime tuple [seconds, nanoseconds].\n * @returns {number} The total duration in nanoseconds.\n */\nfunction toNanos(hrtime) {\n return hrtime[0] * 1e9 + hrtime[1];\n}\n\n/**\n * Adds two OpenTelemetry hrtime tuples.\n *\n * @param {[number, number]} a - The first hrtime tuple [s, ns].\n * @param {[number, number]} b - The second hrtime tuple [s, ns].\n * @returns {[number, number]} Summed hrtime tuple, normalized.\n *\n */\nfunction add(a, b) {\n return [a[0] + b[0] + Math.trunc((a[1] + b[1]) / 1e9), (a[1] + b[1]) % 1e9];\n}\n\n/**\n * Get the current high-resolution time as an OpenTelemetry hrtime tuple.\n *\n * @param {boolean} usePerformance=false - If true, uses the Performance API (timeOrigin + now()).\n *\n * @returns {[number, number]} The current hrtime tuple [s, ns].\n */\nfunction now(usePerformance = false) {\n if (usePerformance) {\n return add(\n fromMillis(performance.timeOrigin),\n fromMillis(performance.now()),\n );\n }\n return fromMillis(Date.now());\n}\n\n/**\n * Check if a value is a valid OpenTelemetry hrtime tuple.\n *\n * An hrtime tuple is an Array of exactly two numbers:\n * [seconds, nanoseconds]\n *\n * @param {*} value \u2013 anything to test\n * @returns {boolean} true if `value` is a [number, number] array of length 2\n *\n * @example\n * isHrTime([ 1, 500 ]); // true\n * isHrTime([ 0, 1e9 ]); // true\n * isHrTime([ '1', 500 ]); // false\n * isHrTime({ 0: 1, 1: 500 }); // false\n */\nfunction isHrTime(value) {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number'\n );\n}\n\n/**\n * Methods for handling hrtime. OpenTelemetry uses the [seconds, nanoseconds]\n * format for hrtime in the `ReadableSpan` interface.\n *\n * @example\n * import hrtime from '@tracing/hrtime.js';\n *\n * hrtime.fromMillis(1000);\n * hrtime.toMillis([0, 1000]);\n * hrtime.add([0, 0], [0, 1000]);\n * hrtime.now();\n * hrtime.isHrTime([0, 1000]);\n */\nexport default { fromMillis, toMillis, toNanos, add, now, isHrTime };\n", "import hrtime from './hrtime.js';\n\n/**\n * SpanExporter is responsible for exporting ReadableSpan objects\n * and transforming them into the OTLP-compatible format.\n */\nexport class SpanExporter {\n constructor(api, options = {}) {\n this.api = api;\n this.options = options;\n }\n\n /**\n * Export spans to the span export queue\n *\n * @param {Array} spans - Array of ReadableSpan objects to export\n * @param {Function} _resultCallback - Optional callback (not used)\n */\n export(spans, _resultCallback) {\n spanExportQueue.push(...spans);\n }\n\n /**\n * Transforms an array of ReadableSpan objects into the OTLP format payload\n * compatible with the Rollbar API. This follows the OpenTelemetry protocol\n * specification for traces.\n *\n * @returns {Object} OTLP format payload for API transmission\n */\n toPayload() {\n const spans = spanExportQueue.slice();\n spanExportQueue.length = 0;\n\n if (!spans || !spans.length) {\n return { resourceSpans: [] };\n }\n\n const resource = (spans[0] && spans[0].resource) || {};\n\n const scopeMap = new Map();\n\n for (const span of spans) {\n const scopeKey = span.instrumentationScope\n ? `${span.instrumentationScope.name}:${span.instrumentationScope.version}`\n : 'default:1.0.0';\n\n if (!scopeMap.has(scopeKey)) {\n scopeMap.set(scopeKey, {\n scope: span.instrumentationScope || {\n name: 'default',\n version: '1.0.0',\n attributes: [],\n },\n spans: [],\n });\n }\n\n scopeMap.get(scopeKey).spans.push(this._transformSpan(span));\n }\n\n return {\n resourceSpans: [\n {\n resource: this._transformResource(resource),\n scopeSpans: Array.from(scopeMap.values()).map((scopeData) => ({\n scope: this._transformInstrumentationScope(scopeData.scope),\n spans: scopeData.spans,\n })),\n },\n ],\n };\n }\n\n /**\n * Sends the given payload to the Rollbar API.\n *\n * @param {String} payload - Serialized OTLP format payload\n * @param {Object} headers - Optional request headers\n * @returns {Promise} Promise that resolves when the request completes\n */\n post(payload, headers = {}) {\n return this.api.postSpans(payload, headers);\n }\n\n /**\n * Transforms a ReadableSpan into the OTLP Span format\n *\n * @private\n * @param {Object} span - ReadableSpan object to transform\n * @returns {Object} OTLP Span format\n */\n _transformSpan(span) {\n const transformAttributes = (attributes) => {\n return Object.entries(attributes || {}).map(([key, value]) => ({\n key,\n value: this._transformAnyValue(value),\n }));\n };\n\n const transformEvents = (events) => {\n return (events || []).map((event) => ({\n timeUnixNano: hrtime.toNanos(event.time),\n name: event.name,\n attributes: transformAttributes(event.attributes),\n }));\n };\n\n return {\n traceId: span.spanContext.traceId,\n spanId: span.spanContext.spanId,\n parentSpanId: span.parentSpanId || '',\n name: span.name,\n kind: span.kind || 1, // INTERNAL by default\n startTimeUnixNano: hrtime.toNanos(span.startTime),\n endTimeUnixNano: hrtime.toNanos(span.endTime),\n attributes: transformAttributes(span.attributes),\n events: transformEvents(span.events),\n };\n }\n\n /**\n * Transforms a resource object into OTLP Resource format\n *\n * @private\n * @param {Object} resource - Resource information\n * @returns {Object} OTLP Resource format\n */\n _transformResource(resource) {\n const attributes = resource.attributes || {};\n const keyValues = Object.entries(attributes).map(([key, value]) => ({\n key,\n value: this._transformAnyValue(value),\n }));\n\n return {\n attributes: keyValues,\n };\n }\n\n /**\n * Transforms an instrumentation scope into OTLP InstrumentationScope format\n *\n * @private\n * @param {Object} scope - Instrumentation scope information\n * @returns {Object} OTLP InstrumentationScope format\n */\n _transformInstrumentationScope(scope) {\n return {\n name: scope.name || '',\n version: scope.version || '',\n attributes: (scope.attributes || []).map((attr) => ({\n key: attr.key,\n value: this._transformAnyValue(attr.value),\n })),\n };\n }\n\n /**\n * Transforms a JavaScript value into an OTLP AnyValue\n *\n * @private\n * @param {any} value - Value to transform\n * @returns {Object} OTLP AnyValue format\n */\n _transformAnyValue(value) {\n if (value === null || value === undefined) {\n return { stringValue: '' };\n }\n\n const type = typeof value;\n\n if (type === 'string') {\n return { stringValue: value };\n } else if (type === 'number') {\n if (Number.isInteger(value)) {\n return { intValue: value.toString() };\n } else {\n return { doubleValue: value };\n }\n } else if (type === 'boolean') {\n return { boolValue: value };\n } else if (Array.isArray(value)) {\n return {\n arrayValue: {\n values: value.map((v) => this._transformAnyValue(v)),\n },\n };\n } else if (type === 'object') {\n return {\n kvlistValue: {\n values: Object.entries(value).map(([k, v]) => ({\n key: k,\n value: this._transformAnyValue(v),\n })),\n },\n };\n }\n\n return { stringValue: String(value) };\n }\n}\n\nexport const spanExportQueue = [];\n", "/**\n * Generate a random hexadecimal ID of specified byte length\n *\n * @param {number} bytes - Number of bytes for the ID (default: 16)\n * @returns {string} - Hexadecimal string representation\n */\nfunction gen(bytes = 16) {\n let randomBytes = new Uint8Array(bytes);\n crypto.getRandomValues(randomBytes);\n let randHex = Array.from(randomBytes, (byte) =>\n byte.toString(16).padStart(2, '0'),\n ).join('');\n return randHex;\n}\n\n/**\n * Tracing id generation utils\n *\n * @example\n * import id from './id.js';\n *\n * const spanId = id.gen(8); // => \"a1b2c3d4e5f6...\"\n */\nexport default { gen };\n", "import id from './id.js';\n\nconst SESSION_KEY = 'RollbarSession';\n\nexport class Session {\n _attributes;\n\n constructor(tracing, options) {\n this.options = options;\n this.tracing = tracing;\n this.window = tracing.window;\n this.session = null;\n this._attributes = {};\n }\n\n init(attrs = {}) {\n if (this.session) {\n return this;\n }\n this.getSession() || this.createSession();\n\n this.initSessionAttributes(attrs);\n\n return this;\n }\n\n getSession() {\n try {\n const serializedSession = this.window.sessionStorage.getItem(SESSION_KEY);\n\n if (!serializedSession) {\n return null;\n }\n\n this.session = JSON.parse(serializedSession);\n } catch {\n return null;\n }\n return this;\n }\n\n createSession() {\n this.session = {\n id: id.gen(),\n createdAt: Date.now(),\n };\n\n return this.setSession(this.session);\n }\n\n setSession(session) {\n const sessionString = JSON.stringify(session);\n\n try {\n this.window.sessionStorage.setItem(SESSION_KEY, sessionString);\n } catch {\n return null;\n }\n return this;\n }\n\n get attributes() {\n return this._attributes;\n }\n\n setAttributes(attributes) {\n this._attributes = { ...this._attributes, ...attributes };\n return this;\n }\n\n setUser(user) {\n this.setAttributes({\n 'user.id': user?.id,\n 'user.email': user?.email,\n 'user.name': user?.name || user?.username,\n });\n return this;\n }\n\n initSessionAttributes(attrs) {\n this.setAttributes({\n 'session.id': this.session.id,\n 'browser.brands': navigator.userAgentData?.brands,\n 'browser.language': navigator.language,\n 'browser.mobile': navigator.userAgentData?.mobile,\n 'browser.platform': navigator.userAgentData?.platform,\n 'client.address': '$remote_ip', // updated at the API\n 'rollbar.notifier.framework': 'browser-js',\n 'user_agent.original': navigator.userAgent,\n ...attrs,\n });\n return this;\n }\n}\n", "let log = () => {};\n\nconst levels = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n disable: 4,\n};\n\nconst logger = {\n error: (...args) => log('error', args),\n warn: (...args) => log('warn', args),\n info: (...args) => log('info', args),\n debug: (...args) => log('debug', args),\n log: (...args) => log('info', args),\n init: ({ logLevel }) => {\n log = function (level, args) {\n if (levels[level] < levels[logLevel]) return;\n\n args.unshift('Rollbar:');\n\n // eslint-disable-next-line no-console\n console[level].apply(console, args);\n };\n },\n};\n\nexport default logger;\n", "import logger from '../logger.js';\n\nexport class SpanProcessor {\n constructor(exporter, options = {}) {\n this.exporter = exporter;\n this.options = options;\n this.pendingSpans = new Map();\n this.transforms = [this.userTransform.bind(this)];\n }\n\n addTransform(transformFn) {\n this.transforms.unshift(transformFn);\n }\n\n userTransform(span) {\n if (this.options.transformSpan) {\n this.options.transformSpan({ span: span });\n }\n }\n\n applyTransforms(span) {\n for (const transform of this.transforms) {\n try {\n transform(span);\n } catch (e) {\n logger.error('Error running span transform callback', e);\n }\n }\n }\n\n onStart(span, _parentContext) {\n this.pendingSpans.set(span.span.spanContext.spanId, span);\n }\n\n onEnd(span) {\n this.applyTransforms(span.span);\n this.exporter.export([span.export()]);\n this.pendingSpans.delete(span.span.spanContext.spanId);\n }\n}\n", "import hrtime from './hrtime.js';\n\nexport class Span {\n constructor(options) {\n this.usePerformance = options.usePerformance;\n this.initReadableSpan(options);\n\n this.spanProcessor = options.spanProcessor;\n this.spanProcessor.onStart(this, options.context);\n\n if (options.attributes) {\n this.setAttributes(options.attributes);\n }\n return this;\n }\n\n initReadableSpan(options) {\n this.span = {\n name: options.name,\n kind: options.kind,\n spanContext: options.spanContext,\n parentSpanId: options.parentSpanId,\n startTime: options.startTime || hrtime.now(options.usePerformance),\n endTime: [0, 0],\n status: { code: 0, message: '' },\n attributes: { 'session.id': options.session?.id },\n links: [],\n events: [],\n duration: 0,\n ended: false,\n resource: options.resource,\n instrumentationScope: options.scope,\n droppedAttributesCount: 0,\n droppedEventsCount: 0,\n droppedLinksCount: 0,\n };\n }\n\n spanContext() {\n return this.span.spanContext;\n }\n\n get spanId() {\n return this.span.spanContext.spanId;\n }\n\n get traceId() {\n return this.span.spanContext.traceId;\n }\n\n setAttribute(key, value) {\n if (value == null || this.span.ended) return this;\n if (key.length === 0) return this;\n\n this.span.attributes[key] = value;\n return this;\n }\n\n setAttributes(attributes) {\n for (const [k, v] of Object.entries(attributes)) {\n this.setAttribute(k, v);\n }\n return this;\n }\n\n addEvent(name, attributes = {}, time) {\n if (this.span.ended) return this;\n\n this.span.events.push({\n name,\n attributes,\n time: time || hrtime.now(),\n droppedAttributesCount: 0,\n });\n\n return this;\n }\n\n isRecording() {\n return this.span.ended === false;\n }\n\n end(attributes, time) {\n if (attributes) this.setAttributes(attributes);\n this.span.endTime = time || hrtime.now(this.usePerformance);\n this.span.ended = true;\n this.spanProcessor.onEnd(this);\n }\n\n export() {\n return this.span;\n }\n}\n", "import id from './id.js';\nimport { Span } from './span.js';\n\nexport class Tracer {\n constructor(tracing, spanProcessor) {\n this.spanProcessor = spanProcessor;\n this.tracing = tracing;\n }\n\n startSpan(\n name,\n options = {},\n context = this.tracing.contextManager.active(),\n ) {\n const parentSpan = this.tracing.getSpan(context);\n const parentSpanContext = parentSpan?.spanContext();\n const spanId = id.gen(8);\n let traceId;\n let traceFlags = 0;\n let traceState = null;\n let parentSpanId;\n if (parentSpanContext) {\n traceId = parentSpanContext.traceId;\n traceState = parentSpanContext.traceState;\n parentSpanId = parentSpanContext.spanId;\n } else {\n traceId = id.gen(16);\n }\n\n const kind = 0;\n const spanContext = { traceId, spanId, traceFlags, traceState };\n const resource = {\n attributes: {\n ...(this.tracing.resource?.attributes || {}),\n ...(options.resource?.attributes || {}),\n },\n };\n\n const span = new Span({\n resource: resource,\n scope: this.tracing.scope,\n session: this.tracing.session?.session,\n context,\n spanContext,\n name,\n kind,\n parentSpanId,\n spanProcessor: this.spanProcessor,\n startTime: options.startTime,\n usePerformance: options.usePerformance,\n });\n return span;\n }\n}\n", "import { ContextManager, createContextKey } from './contextManager.js';\nimport { SpanExporter } from './exporter.js';\nimport id from './id.js';\nimport { Session } from './session.js';\nimport { SpanProcessor } from './spanProcessor.js';\nimport { Tracer } from './tracer.js';\n\nconst SPAN_KEY = createContextKey('Rollbar Context Key SPAN');\n\nexport default class Tracing {\n constructor(gWindow, api, options) {\n this.api = api;\n this.options = options;\n this.window = gWindow;\n\n if (this.window.sessionStorage) {\n this.session = new Session(this, options);\n }\n this.createTracer();\n }\n\n configure(options) {\n // Options merge happens before configure is called, so we can just replace.\n this.options = options;\n }\n\n initSession() {\n if (this.session) {\n this.session.init();\n }\n }\n\n get sessionId() {\n if (this.session) {\n return this.session.session.id;\n }\n return null;\n }\n\n get resource() {\n return {\n attributes: {\n ...(this.options.resource || {}),\n 'rollbar.environment':\n this.options.payload?.environment ?? this.options.environment,\n },\n };\n }\n\n get scope() {\n return {\n name: 'rollbar-browser-js',\n version: this.options.version,\n };\n }\n\n idGen(bytes = 16) {\n return id.gen(bytes);\n }\n\n createTracer() {\n this.contextManager = new ContextManager();\n this.exporter = new SpanExporter(this.api, this.options);\n this.spanProcessor = new SpanProcessor(this.exporter, this.options.tracing);\n this.tracer = new Tracer(this, this.spanProcessor);\n }\n\n getTracer() {\n return this.tracer;\n }\n\n addSpanTransform(transformFn) {\n this.spanProcessor.addTransform(transformFn);\n }\n\n getSpan(context = this.contextManager.active()) {\n return context.getValue(SPAN_KEY);\n }\n\n setSpan(context = this.contextManager.active(), span) {\n return context.setValue(SPAN_KEY, span);\n }\n\n startSpan(name, options = {}, context = this.contextManager.active()) {\n return this.tracer.startSpan(name, options, context);\n }\n\n with(context, fn, thisArg, ...args) {\n return this.contextManager.with(context, fn, thisArg, ...args);\n }\n\n withSpan(name, options, fn, thisArg) {\n const span = this.startSpan(name, options);\n return this.with(\n this.setSpan(this.contextManager.active(), span),\n fn,\n thisArg,\n span,\n );\n }\n}\n", "import traverse from './utility/traverse.js';\nimport * as _ from './utility.js';\n\nfunction raw(payload, jsonBackup) {\n return [payload, _.stringify(payload, jsonBackup)];\n}\n\nfunction selectFrames(frames, range) {\n var len = frames.length;\n if (len > range * 2) {\n return frames.slice(0, range).concat(frames.slice(len - range));\n }\n return frames;\n}\n\nfunction truncateFrames(payload, jsonBackup, range) {\n range = typeof range === 'undefined' ? 30 : range;\n var body = payload.data.body;\n var frames;\n if (body.trace_chain) {\n var chain = body.trace_chain;\n for (const trace of chain) {\n frames = trace.frames;\n frames = selectFrames(frames, range);\n trace.frames = frames;\n }\n } else if (body.trace) {\n frames = body.trace.frames;\n frames = selectFrames(frames, range);\n body.trace.frames = frames;\n }\n return [payload, _.stringify(payload, jsonBackup)];\n}\n\nfunction maybeTruncateValue(len, val) {\n if (!val) {\n return val;\n }\n if (val.length > len) {\n return val.slice(0, len - 3).concat('...');\n }\n return val;\n}\n\nfunction truncateStrings(len, payload, jsonBackup) {\n function truncator(k, v, seen) {\n switch (_.typeName(v)) {\n case 'string':\n return maybeTruncateValue(len, v);\n case 'object':\n case 'array':\n return traverse(v, truncator, seen);\n default:\n return v;\n }\n }\n payload = traverse(payload, truncator);\n return [payload, _.stringify(payload, jsonBackup)];\n}\n\nfunction truncateTraceData(traceData) {\n if (traceData.exception) {\n delete traceData.exception.description;\n traceData.exception.message = maybeTruncateValue(\n 255,\n traceData.exception.message,\n );\n }\n traceData.frames = selectFrames(traceData.frames, 1);\n return traceData;\n}\n\nfunction minBody(payload, jsonBackup) {\n var body = payload.data.body;\n if (body.trace_chain) {\n var chain = body.trace_chain;\n for (const [index, trace] of chain.entries()) {\n chain[index] = truncateTraceData(trace);\n }\n } else if (body.trace) {\n body.trace = truncateTraceData(body.trace);\n }\n return [payload, _.stringify(payload, jsonBackup)];\n}\n\nfunction needsTruncation(payload, maxSize) {\n return _.maxByteSize(payload) > maxSize;\n}\n\nfunction truncate(payload, jsonBackup, maxSize) {\n maxSize = typeof maxSize === 'undefined' ? 512 * 1024 : maxSize;\n var strategies = [\n raw,\n truncateFrames,\n truncateStrings.bind(null, 1024),\n truncateStrings.bind(null, 512),\n truncateStrings.bind(null, 256),\n minBody,\n ];\n var strategy, results, result;\n\n while ((strategy = strategies.shift())) {\n results = strategy(payload, jsonBackup);\n payload = results[0];\n result = results[1];\n if (result.error || !needsTruncation(result.value, maxSize)) {\n return result;\n }\n }\n return result;\n}\n\nexport default {\n truncate,\n\n /* for testing */\n raw,\n truncateFrames,\n truncateStrings,\n maybeTruncateValue,\n};\n", "import * as _ from './utility.js';\n\nfunction buildPayload(data) {\n if (!_.isType(data.context, 'string')) {\n var contextResult = _.stringify(data.context);\n if (contextResult.error) {\n data.context = \"Error: could not serialize 'context'\";\n } else {\n data.context = contextResult.value || '';\n }\n if (data.context.length > 255) {\n data.context = data.context.substr(0, 255);\n }\n }\n return {\n data: data,\n };\n}\n\nfunction getTransportFromOptions(options, defaults, url) {\n var hostname = defaults.hostname;\n var protocol = defaults.protocol;\n var port = defaults.port;\n var path = defaults.path;\n var search = defaults.search;\n var timeout = options.timeout;\n var transport = detectTransport(options);\n\n var proxy = options.proxy;\n if (options.endpoint) {\n var opts = url.parse(options.endpoint);\n hostname = opts.hostname;\n protocol = opts.protocol;\n port = opts.port;\n path = opts.pathname;\n search = opts.search;\n }\n return {\n timeout: timeout,\n hostname: hostname,\n protocol: protocol,\n port: port,\n path: path,\n search: search,\n proxy: proxy,\n transport: transport,\n };\n}\n\nfunction detectTransport(options) {\n var gWindow =\n (typeof window !== 'undefined' && window) ||\n (typeof self !== 'undefined' && self);\n var transport = options.defaultTransport || 'xhr';\n if (typeof gWindow.fetch === 'undefined') transport = 'xhr';\n if (typeof gWindow.XMLHttpRequest === 'undefined') transport = 'fetch';\n return transport;\n}\n\nfunction transportOptions(transport, method) {\n var protocol = transport.protocol || 'https:';\n var port =\n transport.port ||\n (protocol === 'http:' ? 80 : protocol === 'https:' ? 443 : undefined);\n var hostname = transport.hostname;\n var path = transport.path;\n var timeout = transport.timeout;\n var transportAPI = transport.transport;\n if (transport.search) {\n path = path + transport.search;\n }\n if (transport.proxy) {\n path = protocol + '//' + hostname + path;\n hostname = transport.proxy.host || transport.proxy.hostname;\n port = transport.proxy.port;\n protocol = transport.proxy.protocol || protocol;\n }\n return {\n timeout: timeout,\n protocol: protocol,\n hostname: hostname,\n path: path,\n port: port,\n method: method,\n transport: transportAPI,\n };\n}\n\nfunction appendPathToPath(base, path) {\n var baseTrailingSlash = /\\/$/.test(base);\n var pathBeginningSlash = /^\\//.test(path);\n\n if (baseTrailingSlash && pathBeginningSlash) {\n path = path.substring(1);\n } else if (!baseTrailingSlash && !pathBeginningSlash) {\n path = '/' + path;\n }\n\n return base + path;\n}\n\nexport {\n buildPayload,\n getTransportFromOptions,\n transportOptions,\n appendPathToPath,\n};\n", "import * as helpers from './apiUtility.js';\nimport { stringify, merge } from './utility.js';\n\nconst defaultOptions = {\n hostname: 'api.rollbar.com',\n path: '/api/1/item/',\n search: null,\n version: '1',\n protocol: 'https:',\n port: 443,\n};\n\nconst OTLPDefaultOptions = {\n hostname: 'api.rollbar.com',\n path: '/api/1/session/',\n search: null,\n version: '1',\n protocol: 'https:',\n port: 443,\n};\n\n/**\n * Api encapsulates methods of communicating with the Rollbar API. It is a\n * standard interface with some parts implemented differently for server or\n * browser contexts. It is an object that should be instantiated when used so\n * it can contain non-global options that may be different for another instance\n * of RollbarApi.\n */\nclass Api {\n /**\n * @param {Object} options - Configuration supplied from the parent Rollbar instance.\n * @param {string} options.accessToken - Token used to authenticate API calls.\n * @param {string} [options.endpoint] - Optional fully qualified URL overriding\n * the default `https://api.rollbar.com/api/1/item`.\n * @param {Object} [options.proxy] - Optional proxy descriptor containing:\n * `host`/`hostname` (required), `port`, and `protocol`.\n * @param {Object} transport - Adapter implementing `post` and `postJsonPayload`.\n * @param {Object} urllib - Minimal URL helper used for option normalization.\n * @param {Object} truncation - Optional truncation helper for payload size enforcement.\n */\n constructor(options, transport, urllib, truncation) {\n this.options = options;\n this.transport = transport;\n this.url = urllib;\n this.truncation = truncation;\n this.accessToken = options.accessToken;\n this.transportOptions = _getTransport(options, urllib);\n this.OTLPTransportOptions = _getOTLPTransport(options, urllib);\n }\n\n /**\n * Wraps transport.post in a Promise to support async/await\n *\n * @param {Object} options - Options for the API request\n * @param {string} options.accessToken - The access token for authentication\n * @param {Object} options.transportOptions - Options for the transport\n * @param {Object} options.payload - The data payload to send\n * @returns {Promise} A promise that resolves with the response or rejects with an error\n * @private\n */\n _postPromise({ accessToken, options, payload, headers }) {\n return new Promise((resolve, reject) => {\n this.transport.post({\n accessToken,\n options,\n payload,\n headers,\n callback: (err, resp) => (err ? reject(err) : resolve(resp)),\n });\n });\n }\n\n /**\n *\n * @param data\n * @param callback\n */\n postItem(data, callback) {\n const options = helpers.transportOptions(this.transportOptions, 'POST');\n const payload = helpers.buildPayload(data);\n\n // ensure the network request is scheduled after the current tick.\n setTimeout(() => {\n this.transport.post({\n accessToken: this.accessToken,\n options,\n payload,\n callback,\n });\n }, 0);\n }\n\n /**\n * Posts spans to the Rollbar API using the session endpoint\n *\n * @param {Array} payload - The spans to send\n * @returns {Promise} A promise that resolves with the API response\n */\n async postSpans(payload, headers = {}) {\n const options = helpers.transportOptions(this.OTLPTransportOptions, 'POST');\n\n return this._postPromise({\n accessToken: this.accessToken,\n options,\n payload,\n headers,\n });\n }\n\n /**\n *\n * @param data\n * @param callback\n */\n buildJsonPayload(data, callback) {\n const payload = helpers.buildPayload(data);\n\n let stringifyResult;\n if (this.truncation) {\n stringifyResult = this.truncation.truncate(payload);\n } else {\n stringifyResult = stringify(payload);\n }\n\n if (stringifyResult.error) {\n if (callback) {\n callback(stringifyResult.error);\n }\n return null;\n }\n\n return stringifyResult.value;\n }\n\n /**\n *\n * @param jsonPayload\n * @param callback\n */\n postJsonPayload(jsonPayload, callback) {\n const transportOptions = helpers.transportOptions(\n this.transportOptions,\n 'POST',\n );\n this.transport.postJsonPayload(\n this.accessToken,\n transportOptions,\n jsonPayload,\n callback,\n );\n }\n\n configure(options) {\n const oldOptions = this.options;\n this.options = merge(oldOptions, options);\n this.transportOptions = _getTransport(this.options, this.url);\n this.OTLPTransportOptions = _getOTLPTransport(this.options, this.url);\n if (this.options.accessToken !== undefined) {\n this.accessToken = this.options.accessToken;\n }\n return this;\n }\n}\n\nfunction _getTransport(options, url) {\n return helpers.getTransportFromOptions(options, defaultOptions, url);\n}\n\nfunction _getOTLPTransport(options, url) {\n options = { ...options, endpoint: options.tracing?.endpoint };\n return helpers.getTransportFromOptions(options, OTLPDefaultOptions, url);\n}\n\nexport default Api;\n", "/**\n * Default options shared across platforms\n */\nexport const version = '3.1.0';\nexport const endpoint = 'api.rollbar.com/api/1/item/';\nexport const logLevel = 'debug';\nexport const reportLevel = 'debug';\nexport const uncaughtErrorLevel = 'error';\nexport const maxItems = 0;\nexport const itemsPerMin = 60;\n\nexport const commonScrubFields = [\n 'pw',\n 'pass',\n 'passwd',\n 'password',\n 'secret',\n 'confirm_password',\n 'confirmPassword',\n 'password_confirmation',\n 'passwordConfirmation',\n 'access_token',\n 'accessToken',\n 'X-Rollbar-Access-Token',\n 'secret_key',\n 'secretKey',\n 'secretToken',\n];\n\nexport const apiScrubFields = [\n 'api_key',\n 'authenticity_token',\n 'oauth_token',\n 'token',\n 'user_session_secret',\n];\n\nexport const requestScrubFields = [\n 'request.session.csrf',\n 'request.session._csrf',\n 'request.params._csrf',\n 'request.cookie',\n 'request.cookies',\n];\n\nexport const commonScrubHeaders = [\n 'authorization',\n 'www-authorization',\n 'http_authorization',\n 'omniauth.auth',\n 'cookie',\n 'oauth-access-token',\n 'x-access-token',\n 'x_csrf_token',\n 'http_x_csrf_token',\n 'x-csrf-token',\n];\n\n// For backward compatibility with default export\nexport default {\n version,\n endpoint,\n logLevel,\n reportLevel,\n uncaughtErrorLevel,\n maxItems,\n itemsPerMin,\n};\n", "const FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\\S+:\\d+/;\nconst CHROME_IE_STACK_REGEXP = /^\\s*at .*(\\S+:\\d+|\\(native\\))/m;\nconst SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\\[native code\\])?$/;\nfunction parse(error, options) {\n if (typeof error.stacktrace !== \"undefined\" || typeof error[\"opera#sourceloc\"] !== \"undefined\")\n return parseOpera(error, options);\n else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP))\n return parseV8OrIE(error, options);\n else if (error.stack)\n return parseFFOrSafari(error, options);\n else if (options?.allowEmpty)\n return [];\n else\n throw new Error(\"Cannot parse given Error object\");\n}\nfunction parseStack(stackString, options) {\n if (stackString.match(CHROME_IE_STACK_REGEXP))\n return parseV8OrIeString(stackString, options);\n else\n return parseFFOrSafariString(stackString, options);\n}\nfunction extractLocation(urlLike) {\n if (!urlLike.includes(\":\"))\n return [urlLike, undefined, undefined];\n const regExp = /(.+?)(?::(\\d+))?(?::(\\d+))?$/;\n const parts = regExp.exec(urlLike.replace(/[()]/g, \"\"));\n return [parts[1], parts[2] || undefined, parts[3] || undefined];\n}\nfunction applySlice(lines, options) {\n if (options && options.slice != null) {\n if (Array.isArray(options.slice))\n return lines.slice(options.slice[0], options.slice[1]);\n return lines.slice(0, options.slice);\n }\n return lines;\n}\nfunction parseV8OrIE(error, options) {\n return parseV8OrIeString(error.stack, options);\n}\nfunction parseV8OrIeString(stack, options) {\n const filtered = applySlice(\n stack.split(\"\\n\").filter((line) => {\n return !!line.match(CHROME_IE_STACK_REGEXP);\n }),\n options\n );\n return filtered.map((line) => {\n if (line.includes(\"(eval \")) {\n line = line.replace(/eval code/g, \"eval\").replace(/(\\(eval at [^()]*)|(,.*$)/g, \"\");\n }\n let sanitizedLine = line.replace(/^\\s+/, \"\").replace(/\\(eval code/g, \"(\").replace(/^.*?\\s+/, \"\");\n const location = sanitizedLine.match(/ (\\(.+\\)$)/);\n sanitizedLine = location ? sanitizedLine.replace(location[0], \"\") : sanitizedLine;\n const locationParts = extractLocation(location ? location[1] : sanitizedLine);\n const functionName = location && sanitizedLine || undefined;\n const fileName = [\"eval\", \"\"].includes(locationParts[0]) ? undefined : locationParts[0];\n return {\n function: functionName,\n file: fileName,\n line: locationParts[1] ? +locationParts[1] : undefined,\n col: locationParts[2] ? +locationParts[2] : undefined,\n raw: line\n };\n });\n}\nfunction parseFFOrSafari(error, options) {\n return parseFFOrSafariString(error.stack, options);\n}\nfunction parseFFOrSafariString(stack, options) {\n const filtered = applySlice(\n stack.split(\"\\n\").filter((line) => {\n return !line.match(SAFARI_NATIVE_CODE_REGEXP);\n }),\n options\n );\n return filtered.map((line) => {\n if (line.includes(\" > eval\"))\n line = line.replace(/ line (\\d+)(?: > eval line \\d+)* > eval:\\d+:\\d+/g, \":$1\");\n if (!line.includes(\"@\") && !line.includes(\":\")) {\n return {\n function: line\n };\n } else {\n const functionNameRegex = /(([^\\n\\r\"\\u2028\\u2029]*\".[^\\n\\r\"\\u2028\\u2029]*\"[^\\n\\r@\\u2028\\u2029]*(?:@[^\\n\\r\"\\u2028\\u2029]*\"[^\\n\\r@\\u2028\\u2029]*)*(?:[\\n\\r\\u2028\\u2029][^@]*)?)?[^@]*)@/;\n const matches = line.match(functionNameRegex);\n const functionName = matches && matches[1] ? matches[1] : undefined;\n const locationParts = extractLocation(line.replace(functionNameRegex, \"\"));\n return {\n function: functionName,\n file: locationParts[0],\n line: locationParts[1] ? +locationParts[1] : undefined,\n col: locationParts[2] ? +locationParts[2] : undefined,\n raw: line\n };\n }\n });\n}\nfunction parseOpera(e, options) {\n if (!e.stacktrace || e.message.includes(\"\\n\") && e.message.split(\"\\n\").length > e.stacktrace.split(\"\\n\").length)\n return parseOpera9(e);\n else if (!e.stack)\n return parseOpera10(e);\n else\n return parseOpera11(e, options);\n}\nfunction parseOpera9(e, options) {\n const lineRE = /Line (\\d+).*script (?:in )?(\\S+)/i;\n const lines = e.message.split(\"\\n\");\n const result = [];\n for (let i = 2, len = lines.length; i < len; i += 2) {\n const match = lineRE.exec(lines[i]);\n if (match) {\n result.push({\n file: match[2],\n line: +match[1],\n raw: lines[i]\n });\n }\n }\n return applySlice(result, options);\n}\nfunction parseOpera10(e, options) {\n const lineRE = /Line (\\d+).*script (?:in )?(\\S+)(?:: In function (\\S+))?$/i;\n const lines = e.stacktrace.split(\"\\n\");\n const result = [];\n for (let i = 0, len = lines.length; i < len; i += 2) {\n const match = lineRE.exec(lines[i]);\n if (match) {\n result.push({\n function: match[3] || undefined,\n file: match[2],\n line: match[1] ? +match[1] : undefined,\n raw: lines[i]\n });\n }\n }\n return applySlice(result, options);\n}\nfunction parseOpera11(error, options) {\n const filtered = applySlice(\n // @ts-expect-error missing stack property\n error.stack.split(\"\\n\").filter((line) => {\n return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) && !line.match(/^Error created at/);\n }),\n options\n );\n return filtered.map((line) => {\n const tokens = line.split(\"@\");\n const locationParts = extractLocation(tokens.pop());\n const functionCall = tokens.shift() || \"\";\n const functionName = functionCall.replace(//, \"$2\").replace(/\\([^)]*\\)/g, \"\") || undefined;\n let argsRaw;\n if (functionCall.match(/\\(([^)]*)\\)/))\n argsRaw = functionCall.replace(/^[^(]+\\(([^)]*)\\)$/, \"$1\");\n const args = argsRaw === undefined || argsRaw === \"[arguments not available]\" ? undefined : argsRaw.split(\",\");\n return {\n function: functionName,\n args,\n file: locationParts[0],\n line: locationParts[1] ? +locationParts[1] : undefined,\n col: locationParts[2] ? +locationParts[2] : undefined,\n raw: line\n };\n });\n}\n\nexport { extractLocation, parse, parseFFOrSafari, parseFFOrSafariString, parseOpera, parseOpera10, parseOpera11, parseOpera9, parseStack, parseV8OrIE, parseV8OrIeString };\n", "import { parse as parse$1, parseV8OrIE as parseV8OrIE$1, parseFFOrSafari as parseFFOrSafari$1, parseOpera as parseOpera$1, parseOpera9 as parseOpera9$1, parseOpera10 as parseOpera10$1, parseOpera11 as parseOpera11$1 } from './lite.mjs';\nexport { extractLocation } from './lite.mjs';\n\nfunction stackframesLiteToStackframes(liteStackframes) {\n return liteStackframes.map((liteStackframe) => {\n return {\n functionName: liteStackframe.function,\n args: liteStackframe.args,\n fileName: liteStackframe.file,\n lineNumber: liteStackframe.line,\n columnNumber: liteStackframe.col,\n source: liteStackframe.raw\n };\n });\n}\nfunction parse(error, options) {\n return stackframesLiteToStackframes(parse$1(error, options));\n}\nfunction parseV8OrIE(error) {\n return stackframesLiteToStackframes(parseV8OrIE$1(error));\n}\nfunction parseFFOrSafari(error) {\n return stackframesLiteToStackframes(parseFFOrSafari$1(error));\n}\nfunction parseOpera(e) {\n return stackframesLiteToStackframes(parseOpera$1(e));\n}\nfunction parseOpera9(e) {\n return stackframesLiteToStackframes(parseOpera9$1(e));\n}\nfunction parseOpera10(e) {\n return stackframesLiteToStackframes(parseOpera10$1(e));\n}\nfunction parseOpera11(error) {\n return stackframesLiteToStackframes(parseOpera11$1(error));\n}\n\nexport { parse, parseFFOrSafari, parseOpera, parseOpera10, parseOpera11, parseOpera9, parseV8OrIE };\n", "import { parse as parseErrorStack } from 'error-stack-parser-es';\n\nvar UNKNOWN_FUNCTION = '?';\nvar ERR_CLASS_REGEXP = new RegExp(\n '^(([a-zA-Z0-9-_$ ]*): *)?(Uncaught )?([a-zA-Z0-9-_$ ]*): ',\n);\n\nfunction guessFunctionName() {\n return UNKNOWN_FUNCTION;\n}\n\nfunction gatherContext() {\n return null;\n}\n\nfunction Frame(stackFrame) {\n var data = {};\n\n data._stackFrame = stackFrame;\n\n data.url = stackFrame.fileName;\n data.line = stackFrame.lineNumber;\n data.func = stackFrame.functionName;\n data.column = stackFrame.columnNumber;\n data.args = stackFrame.args;\n\n data.context = gatherContext();\n\n return data;\n}\n\nfunction Stack(exception, skip) {\n function getStack() {\n var parserStack = [];\n\n skip = skip || 0;\n\n try {\n parserStack = parseErrorStack(exception);\n } catch (_e) {\n parserStack = [];\n }\n\n var stack = [];\n\n for (var i = skip; i < parserStack.length; i++) {\n stack.push(new Frame(parserStack[i]));\n }\n\n return stack;\n }\n\n return {\n stack: getStack(),\n message: exception.message,\n name: _mostSpecificErrorName(exception),\n rawStack: exception.stack,\n rawException: exception,\n };\n}\n\nfunction parse(e, skip) {\n var err = e;\n\n if (err.nested || err.cause) {\n var traceChain = [];\n while (err) {\n traceChain.push(new Stack(err, skip));\n err = err.nested || err.cause;\n\n skip = 0; // Only apply skip value to primary error\n }\n\n // Return primary error with full trace chain attached.\n traceChain[0].traceChain = traceChain;\n return traceChain[0];\n } else {\n return new Stack(err, skip);\n }\n}\n\nfunction guessErrorClass(errMsg) {\n if (!errMsg || !errMsg.match) {\n return ['Unknown error. There was no error message to display.', ''];\n }\n var errClassMatch = errMsg.match(ERR_CLASS_REGEXP);\n var errClass = '(unknown)';\n\n if (errClassMatch) {\n errClass = errClassMatch[errClassMatch.length - 1];\n errMsg = errMsg.replace(\n (errClassMatch[errClassMatch.length - 2] || '') + errClass + ':',\n '',\n );\n errMsg = errMsg.replace(/(^[\\s]+|[\\s]+$)/g, '');\n }\n return [errClass, errMsg];\n}\n\n// * Prefers any value over an empty string\n// * Prefers any value over 'Error' where possible\n// * Prefers name over constructor.name when both are more specific than 'Error'\nfunction _mostSpecificErrorName(error) {\n var name = error.name && error.name.length && error.name;\n var constructorName =\n error.constructor.name &&\n error.constructor.name.length &&\n error.constructor.name;\n\n if (!name || !constructorName) {\n return name || constructorName;\n }\n\n if (name === 'Error') {\n return constructorName;\n }\n return name;\n}\n\nexport default {\n guessFunctionName,\n guessErrorClass,\n gatherContext,\n parse,\n Stack,\n Frame,\n};\n", "import * as _ from './utility.js';\n\nfunction checkLevel(item, settings) {\n var level = item.level;\n var levelVal = _.LEVELS[level] || 0;\n var reportLevel = settings.reportLevel;\n var reportLevelVal = _.LEVELS[reportLevel] || 0;\n\n if (levelVal < reportLevelVal) {\n return false;\n }\n return true;\n}\n\nfunction userCheckIgnore(logger) {\n return function (item, settings) {\n var isUncaught = Boolean(item._isUncaught);\n delete item._isUncaught;\n var args = item._originalArgs;\n delete item._originalArgs;\n try {\n if (_.isFunction(settings.onSendCallback)) {\n settings.onSendCallback(isUncaught, args, item);\n }\n } catch (e) {\n settings.onSendCallback = null;\n logger.error('Error while calling onSendCallback, removing', e);\n }\n try {\n if (\n _.isFunction(settings.checkIgnore) &&\n settings.checkIgnore(isUncaught, args, item)\n ) {\n return false;\n }\n } catch (e) {\n settings.checkIgnore = null;\n logger.error('Error while calling custom checkIgnore(), removing', e);\n }\n return true;\n };\n}\n\nfunction urlIsNotBlockListed(logger) {\n return function (item, settings) {\n return !urlIsOnAList(item, settings, 'blocklist', logger);\n };\n}\n\nfunction urlIsSafeListed(logger) {\n return function (item, settings) {\n return urlIsOnAList(item, settings, 'safelist', logger);\n };\n}\n\nfunction matchFrames(trace, list, block) {\n if (!trace) {\n return !block;\n }\n\n var frames = trace.frames;\n\n if (!frames || frames.length === 0) {\n return !block;\n }\n\n var frame, filename, url, urlRegex;\n var listLength = list.length;\n var frameLength = frames.length;\n for (var i = 0; i < frameLength; i++) {\n frame = frames[i];\n filename = frame.filename;\n\n if (!_.isType(filename, 'string')) {\n return !block;\n }\n\n for (var j = 0; j < listLength; j++) {\n url = list[j];\n urlRegex = new RegExp(url);\n\n if (urlRegex.test(filename)) {\n return true;\n }\n }\n }\n return false;\n}\n\nfunction urlIsOnAList(item, settings, safeOrBlock, logger) {\n // safelist is the default\n var block = false;\n if (safeOrBlock === 'blocklist') {\n block = true;\n }\n\n var list, traces;\n try {\n list = block ? settings.hostBlockList : settings.hostSafeList;\n traces = _.get(item, 'body.trace_chain') || [_.get(item, 'body.trace')];\n\n // These two checks are important to come first as they are defaults\n // in case the list is missing or the trace is missing or not well-formed\n if (!list || list.length === 0) {\n return !block;\n }\n if (traces.length === 0 || !traces[0]) {\n return !block;\n }\n\n var tracesLength = traces.length;\n for (var i = 0; i < tracesLength; i++) {\n if (matchFrames(traces[i], list, block)) {\n return true;\n }\n }\n } catch (\n e\n /* istanbul ignore next */\n ) {\n if (block) {\n settings.hostBlockList = null;\n } else {\n settings.hostSafeList = null;\n }\n var listName = block ? 'hostBlockList' : 'hostSafeList';\n logger.error(\n \"Error while reading your configuration's \" +\n listName +\n ' option. Removing custom ' +\n listName +\n '.',\n e,\n );\n return !block;\n }\n return false;\n}\n\nfunction messageIsIgnored(logger) {\n return function (item, settings) {\n var i, j, ignoredMessages, len, messageIsIgnored, rIgnoredMessage, messages;\n\n try {\n messageIsIgnored = false;\n ignoredMessages = settings.ignoredMessages;\n\n if (!ignoredMessages || ignoredMessages.length === 0) {\n return true;\n }\n\n messages = messagesFromItem(item);\n\n if (messages.length === 0) {\n return true;\n }\n\n len = ignoredMessages.length;\n for (i = 0; i < len; i++) {\n rIgnoredMessage = new RegExp(ignoredMessages[i], 'gi');\n\n for (j = 0; j < messages.length; j++) {\n messageIsIgnored = rIgnoredMessage.test(messages[j]);\n\n if (messageIsIgnored) {\n return false;\n }\n }\n }\n } catch (\n _e\n /* istanbul ignore next */\n ) {\n settings.ignoredMessages = null;\n logger.error(\n \"Error while reading your configuration's ignoredMessages option. Removing custom ignoredMessages.\",\n );\n }\n\n return true;\n };\n}\n\nfunction messagesFromItem(item) {\n var body = item.body;\n var messages = [];\n\n // The payload schema only allows one of trace_chain, message, or trace.\n // However, existing test cases are based on having both trace and message present.\n // So here we preserve the ability to collect strings from any combination of these keys.\n if (body.trace_chain) {\n var traceChain = body.trace_chain;\n for (const trace of traceChain) {\n messages.push(_.get(trace, 'exception.message'));\n }\n }\n if (body.trace) {\n messages.push(_.get(body, 'trace.exception.message'));\n }\n if (body.message) {\n messages.push(_.get(body, 'message.body'));\n }\n return messages;\n}\n\nexport {\n checkLevel,\n userCheckIgnore,\n urlIsNotBlockListed,\n urlIsSafeListed,\n messageIsIgnored,\n};\n", "import { merge, isFunction } from './utility.js';\n\n/*\n * Notifier - delegates between the client exposed API, the chain of transforms\n * necessary to turn an item into something that can be sent to Rollbar, and the\n * queue which handles the communcation with the Rollbar API servers.\n */\nexport default class Notifier {\n /**\n *\n * @param {Object} queue - an object that conforms to the interface:\n * `addItem(item, callback)`\n * @param {Object} options - an object representing the options to be set for\n * this notifier, this should have any defaults already set by the caller\n */\n constructor(queue, options) {\n this.queue = queue;\n this.options = options;\n this.transforms = [];\n this.diagnostic = {};\n }\n\n /**\n * configure - updates the options for this notifier with the passed in object\n *\n * @param {Object} options - an object which gets merged with the current\n * options set on this notifier\n * @returns this\n */\n configure(options) {\n this.queue?.configure(options);\n const oldOptions = this.options;\n this.options = merge(oldOptions, options);\n return this;\n }\n\n /**\n * Adds a transform onto the end of the queue of transforms for this notifier\n *\n * @param {Function} transform - a function which takes three arguments:\n * - item: An Object representing the data to eventually be sent to Rollbar\n * - options: The current value of the options for this notifier\n * - callback: `function(err: (Null|Error), item: (Null|Object))` the\n * transform must call this callback with a null value for error if it\n * wants the processing chain to continue, otherwise with an error to\n * terminate the processing. The item should be the updated item after\n * this transform is finished modifying it.\n */\n addTransform(transform) {\n if (isFunction(transform)) {\n this.transforms.push(transform);\n }\n return this;\n }\n\n /**\n * The internal log function which applies the configured transforms and then\n * pushes onto the queue to be sent to the backend.\n *\n * @param {Object} item - An object with the following structure:\n * - message [String] - An optional string to be sent to rollbar\n * - error [Error] - An optional error\n * @param {Function} callback - A function of type `function(err, resp)` which\n * will be called with exactly one null argument and one non-null argument.\n * The callback will be called once, either during the transform stage if\n * an error occurs inside a transform, or in response to the communication\n * with the backend. The second argument will be the response from the\n * backend in case of success.\n */\n log(item, callback) {\n callback = isFunction(callback) ? callback : () => {};\n\n if (!this.options.enabled) {\n return callback(new Error('Rollbar is not enabled'), null);\n }\n\n this.queue.addPendingItem(item);\n const originalError = item.err;\n this._applyTransforms(item, (err, i) => {\n if (err) {\n this.queue.removePendingItem(item);\n return callback(err, null);\n }\n this.queue.addItem(i, callback, originalError, item);\n });\n }\n\n /* Internal */\n\n /**\n * Applies the transforms that have been added to this notifier sequentially.\n * See `addTransform` for more information.\n *\n * @param {Object} item - An item to be transformed\n * @param {Function} callback - A function of type `function(err, item)` which\n * will be called with a non-null error and a null item in the case of a\n * transform failure, or a null error and non-null item after all\n * transforms have been applied.\n */\n _applyTransforms(item, callback) {\n let transformIndex = -1;\n const transformsLength = this.transforms.length;\n const transforms = this.transforms;\n const options = this.options;\n\n const next = (err, i) => {\n if (err) {\n callback(err, null);\n return;\n }\n\n transformIndex++;\n\n if (transformIndex === transformsLength) {\n callback(null, i);\n return;\n }\n\n transforms[transformIndex](i, options, next);\n };\n\n next(null, item);\n }\n}\n", "import * as _ from './utility.js';\n\n/**\n * Queue - an object which handles which handles a queue of items to be sent to Rollbar.\n * This object handles rate limiting via a passed in rate limiter, retries based on connection\n * errors, and filtering of items based on a set of configurable predicates. The communication to\n * the backend is performed via a given API object.\n */\nclass Queue {\n /**\n * @param rateLimiter - An object which conforms to the interface\n * `rateLimiter.shouldSend(item) -> bool`\n * @param api - An object which conforms to the interface\n * `api.postItem(payload, function(err, response))`\n * @param logger - An object used to log verbose messages if desired\n * @param options - see `Queue.prototype.configure`\n * @param replay - Optional `Replay` for coordinating session replay with error occurrences\n */\n constructor(rateLimiter, api, logger, options, replay) {\n this.rateLimiter = rateLimiter;\n this.api = api;\n this.logger = logger;\n this.options = options;\n this.replay = replay;\n this.predicates = [];\n this.pendingItems = [];\n this.pendingRequests = [];\n this.retryQueue = [];\n this.retryHandle = null;\n this.waitCallback = null;\n this.waitIntervalID = null;\n }\n\n /**\n * configure - updates the options this queue uses\n *\n * @param options\n */\n configure(options) {\n this.api?.configure(options);\n const oldOptions = this.options;\n this.options = _.merge(oldOptions, options);\n return this;\n }\n\n /**\n * addPredicate - adds a predicate to the end of the list of predicates for this queue\n *\n * @param predicate - function(item, options) -> (bool|{err: Error})\n * Returning true means that this predicate passes and the item is okay to go on the queue\n * Returning false means do not add the item to the queue, but it is not an error\n * Returning {err: Error} means do not add the item to the queue, and the given error explains why\n * Returning {err: undefined} is equivalent to returning true but don't do that\n */\n addPredicate(predicate) {\n if (_.isFunction(predicate)) {\n this.predicates.push(predicate);\n }\n return this;\n }\n\n addPendingItem(item) {\n this.pendingItems.push(item);\n }\n\n removePendingItem(item) {\n const idx = this.pendingItems.indexOf(item);\n if (idx !== -1) {\n this.pendingItems.splice(idx, 1);\n }\n }\n\n /**\n * addItem - Send an item to the Rollbar API if all of the predicates are satisfied\n *\n * @param item - Item instance with the payload to send to the backend\n * @param callback - function(error, repsonse) which will be called with the response from the API\n * in the case of a success, otherwise response will be null and error will have a value. If both\n * error and response are null then the item was stopped by a predicate which did not consider this\n * to be an error condition, but nonetheless did not send the item to the API.\n * @param originalError - The original error before any transformations that is to be logged if any\n * @param originalItem - The original item before transforms, used in pendingItems queue\n */\n addItem(item, callback, originalError, originalItem) {\n if (!callback || !_.isFunction(callback)) {\n callback = function () {\n return;\n };\n }\n const data = item.data;\n const predicateResult = this._applyPredicates(data);\n if (predicateResult.stop) {\n this.removePendingItem(originalItem);\n callback(predicateResult.err);\n return;\n }\n this._maybeLog(data, originalError);\n this.removePendingItem(originalItem);\n if (!this.options.transmit) {\n callback(new Error('Transmit disabled'));\n return;\n }\n\n if (this.replay && data.body) {\n item.replayId = this.replay.capture(null, data.uuid, {\n type: 'occurrence',\n level: item.level,\n });\n\n if (item.replayId) {\n _.addItemAttributes(item.data, [\n { key: 'replay_id', value: item.replayId },\n ]);\n }\n }\n\n this.pendingRequests.push(data);\n try {\n this._makeApiRequest(data, (err, resp, headers) => {\n this._dequeuePendingRequest(data);\n\n if (item.replayId) {\n this.replay.sendOrDiscardReplay(item.replayId, err, resp, headers);\n }\n\n callback(err, resp);\n });\n } catch (err) {\n this._dequeuePendingRequest(data);\n\n if (item.replayId) {\n this.replay?.discard(item.replayId);\n }\n\n callback(err);\n }\n }\n\n /**\n * wait - Stop any further errors from being added to the queue, and get called back when all items\n * currently processing have finished sending to the backend.\n *\n * @param callback - function() called when all pending items have been sent\n */\n wait(callback) {\n if (!_.isFunction(callback)) {\n return;\n }\n this.waitCallback = callback;\n if (this._maybeCallWait()) {\n return;\n }\n if (this.waitIntervalID) {\n this.waitIntervalID = clearInterval(this.waitIntervalID);\n }\n this.waitIntervalID = setInterval(() => {\n this._maybeCallWait();\n }, 500);\n }\n\n /**\n * Sequentially applies the predicates that have been added to the queue to the\n * given item with the currently configured options.\n *\n * @param item - An item in the queue\n * @returns {stop: bool, err: (Error|null)} - stop being true means do not add item to the queue,\n * the error value should be passed up to a callbak if we are stopping.\n */\n _applyPredicates(item) {\n let p = null;\n for (let i = 0, len = this.predicates.length; i < len; i++) {\n p = this.predicates[i](item, this.options);\n if (!p || p.err !== undefined) {\n return { stop: true, err: p.err };\n }\n }\n return { stop: false, err: null };\n }\n\n /**\n * Send an item to Rollbar, callback when done, if there is an error make an\n * effort to retry if we are configured to do so.\n *\n * @param item - an item ready to send to the backend\n * @param callback - function(err, response)\n */\n _makeApiRequest(item, callback) {\n const rateLimitResponse = this.rateLimiter.shouldSend(item);\n if (rateLimitResponse.shouldSend) {\n this.api.postItem(item, (err, resp, headers) => {\n if (err) {\n this._maybeRetry(err, item, callback);\n } else {\n callback(err, resp, headers);\n }\n });\n } else if (rateLimitResponse.error) {\n callback(rateLimitResponse.error);\n } else {\n this.api.postItem(rateLimitResponse.payload, callback);\n }\n }\n\n // These are errors basically mean there is no internet connection\n static RETRIABLE_ERRORS = [\n 'ECONNRESET',\n 'ENOTFOUND',\n 'ESOCKETTIMEDOUT',\n 'ETIMEDOUT',\n 'ECONNREFUSED',\n 'EHOSTUNREACH',\n 'EPIPE',\n 'EAI_AGAIN',\n ];\n\n /**\n * Given the error returned by the API, decide if we should retry or just callback\n * with the error.\n *\n * @param err - an error returned by the API transport\n * @param item - the item that was trying to be sent when this error occured\n * @param callback - function(err, response)\n */\n _maybeRetry(err, item, callback) {\n let shouldRetry = false;\n if (this.options.retryInterval) {\n for (let i = 0, len = Queue.RETRIABLE_ERRORS.length; i < len; i++) {\n if (err.code === Queue.RETRIABLE_ERRORS[i]) {\n shouldRetry = true;\n break;\n }\n }\n if (shouldRetry && _.isFiniteNumber(this.options.maxRetries)) {\n item.retries = item.retries ? item.retries + 1 : 1;\n if (item.retries > this.options.maxRetries) {\n shouldRetry = false;\n }\n }\n }\n if (shouldRetry) {\n this._retryApiRequest(item, callback);\n } else {\n callback(err);\n }\n }\n\n /**\n * Add an item and a callback to a queue and possibly start a timer to process\n * that queue based on the retryInterval in the options for this queue.\n *\n * @param item - an item that failed to send due to an error we deem retriable\n * @param callback - function(err, response)\n */\n _retryApiRequest(item, callback) {\n this.retryQueue.push({ item, callback });\n\n if (!this.retryHandle) {\n this.retryHandle = setInterval(() => {\n while (this.retryQueue.length) {\n const retryObject = this.retryQueue.shift();\n this._makeApiRequest(retryObject.item, retryObject.callback);\n }\n }, this.options.retryInterval);\n }\n }\n\n /**\n * Removes the item from the pending request queue, this queue is used to\n * enable to functionality of providing a callback that clients can pass to `wait` to be notified\n * when the pending request queue has been emptied. This must be called when the API finishes\n * processing this item. If a `wait` callback is configured, it is called by this function.\n *\n * @param item - the item previously added to the pending request queue\n */\n _dequeuePendingRequest(item) {\n const idx = this.pendingRequests.indexOf(item);\n if (idx !== -1) {\n this.pendingRequests.splice(idx, 1);\n this._maybeCallWait();\n }\n }\n\n _maybeLog(data, originalError) {\n if (this.logger && this.options.verbose) {\n let message =\n originalError ||\n _.get(data, 'body.trace.exception.message') ||\n _.get(data, 'body.trace_chain.0.exception.message');\n if (message) {\n this.logger.error(message);\n return;\n }\n message = _.get(data, 'body.message.body');\n if (message) {\n this.logger.log(message);\n }\n }\n }\n\n _maybeCallWait() {\n if (\n _.isFunction(this.waitCallback) &&\n this.pendingItems.length === 0 &&\n this.pendingRequests.length === 0\n ) {\n if (this.waitIntervalID) {\n this.waitIntervalID = clearInterval(this.waitIntervalID);\n }\n this.waitCallback();\n return true;\n }\n return false;\n }\n}\n\nexport default Queue;\n", "/*\n * RateLimiter - encapsulates the logic for counting items sent to Rollbar.\n *\n * @param options - the same options that are accepted by configureGlobal offered as a convenience\n */\nclass RateLimiter {\n static globalSettings = {\n startTime: Date.now(),\n maxItems: undefined,\n itemsPerMinute: undefined,\n };\n\n constructor(options = {}) {\n this.startTime = Date.now();\n this.counter = 0;\n this.perMinCounter = 0;\n this.platform = null;\n this.platformOptions = {};\n this.configureGlobal(options);\n }\n\n /*\n * configureGlobal - set the global rate limiter options\n *\n * @param options - Only the following values are recognized:\n * startTime: a timestamp of the form returned by (new Date()).getTime()\n * maxItems: the maximum items\n * itemsPerMinute: the max number of items to send in a given minute\n */\n configureGlobal(options = {}) {\n const { startTime, maxItems, itemsPerMinute } = options;\n\n if (startTime !== undefined) {\n RateLimiter.globalSettings.startTime = startTime;\n }\n if (maxItems !== undefined) {\n RateLimiter.globalSettings.maxItems = maxItems;\n }\n if (itemsPerMinute !== undefined) {\n RateLimiter.globalSettings.itemsPerMinute = itemsPerMinute;\n }\n }\n\n /*\n * shouldSend - determine if we should send a given item based on rate limit settings\n *\n * @param item - the item we are about to send\n * @returns An object with the following structure:\n * error: (Error|null)\n * shouldSend: bool\n * payload: (Object|null)\n * If shouldSend is false, the item passed as a parameter should not be sent to Rollbar, and\n * exactly one of error or payload will be non-null. If error is non-null, the returned Error will\n * describe the situation, but it means that we were already over a rate limit (either globally or\n * per minute) when this item was checked. If error is null, and therefore payload is non-null, it\n * means this item put us over the global rate limit and the payload should be sent to Rollbar in\n * place of the passed in item.\n */\n shouldSend(item, now = Date.now()) {\n const elapsedTime = now - this.startTime;\n if (elapsedTime < 0 || elapsedTime >= 60000) {\n this.startTime = now;\n this.perMinCounter = 0;\n }\n\n const globalRateLimit = RateLimiter.globalSettings.maxItems;\n const globalRateLimitPerMin = RateLimiter.globalSettings.itemsPerMinute;\n\n if (checkRate(item, globalRateLimit, this.counter)) {\n return shouldSendValue(\n this.platform,\n this.platformOptions,\n `${globalRateLimit} max items reached`,\n false,\n );\n }\n\n if (checkRate(item, globalRateLimitPerMin, this.perMinCounter)) {\n return shouldSendValue(\n this.platform,\n this.platformOptions,\n `${globalRateLimitPerMin} items per minute reached`,\n false,\n );\n }\n\n this.counter += 1;\n this.perMinCounter += 1;\n\n const underGlobalLimit = !checkRate(item, globalRateLimit, this.counter);\n const perMinute = underGlobalLimit;\n const shouldSend =\n underGlobalLimit &&\n !checkRate(item, globalRateLimitPerMin, this.perMinCounter);\n\n return shouldSendValue(\n this.platform,\n this.platformOptions,\n null,\n shouldSend,\n globalRateLimit,\n globalRateLimitPerMin,\n perMinute,\n );\n }\n\n setPlatformOptions(platform, options) {\n this.platform = platform;\n this.platformOptions = options;\n }\n}\n\n/* Helpers */\n\nfunction checkRate(item, limit, counter) {\n return !item.ignoreRateLimit && limit >= 1 && counter > limit;\n}\n\nfunction shouldSendValue(\n platform,\n options,\n error,\n shouldSend,\n globalRateLimit,\n limitPerMin,\n perMinute,\n) {\n let payload = null;\n const errorResult = error ? new Error(error) : null;\n\n if (!errorResult && !shouldSend) {\n payload = rateLimitPayload(\n platform,\n options,\n globalRateLimit,\n limitPerMin,\n perMinute,\n );\n }\n\n return { error: errorResult, shouldSend, payload };\n}\n\nfunction rateLimitPayload(\n platform,\n options,\n globalRateLimit,\n limitPerMin,\n perMinute,\n) {\n const environment =\n options.environment || (options.payload && options.payload.environment);\n const msg = perMinute\n ? 'item per minute limit reached, ignoring errors until timeout'\n : 'maxItems has been hit, ignoring errors until reset.';\n const item = {\n body: {\n message: {\n body: msg,\n extra: {\n maxItems: globalRateLimit,\n itemsPerMinute: limitPerMin,\n },\n },\n },\n language: 'javascript',\n environment: environment,\n notifier: {\n version:\n (options.notifier && options.notifier.version) || options.version,\n },\n };\n if (platform === 'browser') {\n item.platform = 'browser';\n item.framework = 'browser-js';\n item.notifier.name = 'rollbar-browser-js';\n } else if (platform === 'server') {\n item.framework = options.framework || 'node-js';\n item.notifier.name = options.notifier.name;\n } else if (platform === 'react-native') {\n item.framework = options.framework || 'react-native';\n item.notifier.name = options.notifier.name;\n }\n return item;\n}\n\nexport default RateLimiter;\n", "import Notifier from './notifier.js';\nimport Queue from './queue.js';\nimport RateLimiter from './rateLimiter.js';\nimport * as _ from './utility.js';\n\n/*\n * Rollbar - the interface to Rollbar\n *\n * @param options\n * @param api\n * @param logger\n */\nfunction Rollbar(options, api, logger, telemeter, tracing, replay, platform) {\n this.options = _.merge(options);\n this.logger = logger;\n Rollbar.rateLimiter.configureGlobal(this.options);\n Rollbar.rateLimiter.setPlatformOptions(platform, this.options);\n this.api = api;\n this.queue = new Queue(\n Rollbar.rateLimiter,\n api,\n logger,\n this.options,\n replay,\n );\n\n this.tracing = tracing;\n\n // Legacy OpenTracing support\n // This must happen before the Notifier is created\n var tracer = this.options.tracer || null;\n if (validateTracer(tracer)) {\n this.tracer = tracer;\n // set to a string for api response serialization\n this.options.tracer = 'opentracing-tracer-enabled';\n this.options._configuredOptions.tracer = 'opentracing-tracer-enabled';\n } else {\n this.tracer = null;\n }\n\n this.notifier = new Notifier(this.queue, this.options);\n this.telemeter = telemeter;\n setStackTraceLimit(options);\n this.lastError = null;\n this.lastErrorHash = 'none';\n}\n\nvar defaultOptions = {\n maxItems: 0,\n itemsPerMinute: 60,\n};\n\nRollbar.rateLimiter = new RateLimiter(defaultOptions);\n\nRollbar.prototype.global = function (options) {\n Rollbar.rateLimiter.configureGlobal(options);\n return this;\n};\n\nRollbar.prototype.configure = function (options, payloadData) {\n var oldOptions = this.options;\n var payload = {};\n if (payloadData) {\n payload = { payload: payloadData };\n }\n\n this.options = _.merge(oldOptions, options, payload);\n\n // Legacy OpenTracing support\n // This must happen before the Notifier is configured\n var tracer = this.options.tracer || null;\n if (validateTracer(tracer)) {\n this.tracer = tracer;\n // set to a string for api response serialization\n this.options.tracer = 'opentracing-tracer-enabled';\n this.options._configuredOptions.tracer = 'opentracing-tracer-enabled';\n } else {\n this.tracer = null;\n }\n\n this.notifier && this.notifier.configure(this.options);\n this.telemeter && this.telemeter.configure(this.options);\n setStackTraceLimit(options);\n this.global(this.options);\n\n if (validateTracer(options.tracer)) {\n this.tracer = options.tracer;\n }\n\n return this;\n};\n\nRollbar.prototype.log = function (item) {\n var level = this._defaultLogLevel();\n return this._log(level, item);\n};\n\nRollbar.prototype.debug = function (item) {\n this._log('debug', item);\n};\n\nRollbar.prototype.info = function (item) {\n this._log('info', item);\n};\n\nRollbar.prototype.warn = function (item) {\n this._log('warning', item);\n};\n\nRollbar.prototype.warning = function (item) {\n this._log('warning', item);\n};\n\nRollbar.prototype.error = function (item) {\n this._log('error', item);\n};\n\nRollbar.prototype.critical = function (item) {\n this._log('critical', item);\n};\n\nRollbar.prototype.wait = function (callback) {\n this.queue.wait(callback);\n};\n\nRollbar.prototype.captureEvent = function (type, metadata, level) {\n return this.telemeter && this.telemeter.captureEvent(type, metadata, level);\n};\n\nRollbar.prototype.captureDomContentLoaded = function (ts) {\n return this.telemeter && this.telemeter.captureDomContentLoaded(ts);\n};\n\nRollbar.prototype.captureLoad = function (ts) {\n return this.telemeter && this.telemeter.captureLoad(ts);\n};\n\nRollbar.prototype.buildJsonPayload = function (item) {\n return this.api.buildJsonPayload(item);\n};\n\nRollbar.prototype.sendJsonPayload = function (jsonPayload) {\n this.api.postJsonPayload(jsonPayload);\n};\n\n/* Internal */\n\nRollbar.prototype._log = function (defaultLevel, item) {\n var callback;\n if (item.callback) {\n callback = item.callback;\n delete item.callback;\n }\n if (this.options.ignoreDuplicateErrors && this._sameAsLastError(item)) {\n if (callback) {\n var error = new Error('ignored identical item');\n error.item = item;\n callback(error);\n }\n return;\n }\n try {\n item.level = item.level || defaultLevel;\n\n this._addItemAttributes(item);\n\n // Legacy OpenTracing support\n this._addTracingInfo(item);\n\n const telemeter = this.telemeter;\n if (telemeter) {\n telemeter._captureRollbarItem(item);\n item.telemetryEvents = telemeter.copyEvents() || [];\n }\n\n this.notifier.log(item, callback);\n } catch (e) {\n if (callback) {\n callback(e);\n }\n this.logger.error(e);\n }\n};\n\nRollbar.prototype._addItemAttributes = function (item) {\n const span = this.tracing?.getSpan();\n const asyncLocalSessionId = _.getSessionIdFromAsyncLocalStorage(this);\n const sessionId = asyncLocalSessionId || this.tracing?.sessionId;\n\n const attributes = [\n { key: 'session_id', value: sessionId },\n { key: 'span_id', value: span?.spanId },\n { key: 'trace_id', value: span?.traceId },\n ];\n if (item._isUncaught) {\n attributes.push({ key: 'is_uncaught', value: 'true' });\n }\n _.addItemAttributes(item.data, attributes);\n\n span?.addEvent('rollbar.occurrence', [\n { key: 'rollbar.occurrence.uuid', value: item.uuid },\n ]);\n};\n\nRollbar.prototype._defaultLogLevel = function () {\n return this.options.logLevel || 'debug';\n};\n\nRollbar.prototype._sameAsLastError = function (item) {\n if (!item._isUncaught) {\n return false;\n }\n var itemHash = generateItemHash(item);\n if (this.lastErrorHash === itemHash) {\n return true;\n }\n this.lastError = item.err;\n this.lastErrorHash = itemHash;\n return false;\n};\n\nRollbar.prototype._addTracingInfo = function (item) {\n // Tracer validation occurs in the constructor\n // or in the Rollbar.prototype.configure methods\n if (this.tracer) {\n // add rollbar occurrence uuid to span\n var span = this.tracer.scope().active();\n\n if (validateSpan(span)) {\n span.setTag('rollbar.error_uuid', item.uuid);\n span.setTag('rollbar.has_error', true);\n span.setTag('error', true);\n span.setTag(\n 'rollbar.item_url',\n `https://rollbar.com/item/uuid/?uuid=${item.uuid}`,\n );\n span.setTag(\n 'rollbar.occurrence_url',\n `https://rollbar.com/occurrence/uuid/?uuid=${item.uuid}`,\n );\n\n // add span ID & trace ID to occurrence\n var opentracingSpanId = span.context().toSpanId();\n var opentracingTraceId = span.context().toTraceId();\n\n if (item.custom) {\n item.custom.opentracing_span_id = opentracingSpanId;\n item.custom.opentracing_trace_id = opentracingTraceId;\n } else {\n item.custom = {\n opentracing_span_id: opentracingSpanId,\n opentracing_trace_id: opentracingTraceId,\n };\n }\n }\n }\n};\n\nfunction generateItemHash(item) {\n var message = item.message || '';\n var stack = (item.err || {}).stack || String(item.err);\n return message + '::' + stack;\n}\n\n// Node.js, Chrome, Safari, and some other browsers support this property\n// which globally sets the number of stack frames returned in an Error object.\n// If a browser can't use it, no harm done.\nfunction setStackTraceLimit(options) {\n if (options.stackTraceLimit) {\n Error.stackTraceLimit = options.stackTraceLimit;\n }\n}\n\n/**\n * Validate the Tracer object provided to the Client\n * is valid for our Opentracing use case.\n * @param {opentracer.Tracer} tracer\n */\nfunction validateTracer(tracer) {\n if (!tracer) {\n return false;\n }\n\n if (!tracer.scope || typeof tracer.scope !== 'function') {\n return false;\n }\n\n var scope = tracer.scope();\n\n if (!scope || !scope.active || typeof scope.active !== 'function') {\n return false;\n }\n\n return true;\n}\n\n/**\n * Validate the Span object provided\n * @param {opentracer.Span} span\n */\nfunction validateSpan(span) {\n if (!span || !span.context || typeof span.context !== 'function') {\n return false;\n }\n\n var spanContext = span.context();\n\n if (\n !spanContext ||\n !spanContext.toSpanId ||\n !spanContext.toTraceId ||\n typeof spanContext.toSpanId !== 'function' ||\n typeof spanContext.toTraceId !== 'function'\n ) {\n return false;\n }\n\n return true;\n}\n\nexport default Rollbar;\n", "/**\n * Default tracing options\n */\nexport default {\n enabled: false,\n endpoint: 'api.rollbar.com/api/1/session/',\n};\n", "import * as _ from './utility.js';\n\nfunction itemToPayload(item, options, callback) {\n if (item._isUncaught) {\n item.data._isUncaught = true;\n }\n if (item._originalArgs) {\n item.data._originalArgs = item._originalArgs;\n }\n callback(null, item);\n}\n\nfunction addPayloadOptions(item, options, callback) {\n var payloadOptions = options.payload || {};\n if (payloadOptions.body) {\n delete payloadOptions.body;\n }\n\n item.data = _.merge(item.data, payloadOptions);\n callback(null, item);\n}\n\nfunction addTelemetryData(item, options, callback) {\n if (item.telemetryEvents) {\n _.set(item, 'data.body.telemetry', item.telemetryEvents);\n }\n callback(null, item);\n}\n\nfunction addMessageWithError(item, options, callback) {\n if (!item.message) {\n callback(null, item);\n return;\n }\n var tracePath = 'data.body.trace_chain.0';\n var trace = _.get(item, tracePath);\n if (!trace) {\n tracePath = 'data.body.trace';\n trace = _.get(item, tracePath);\n }\n if (trace) {\n if (!(trace.exception && trace.exception.description)) {\n _.set(item, tracePath + '.exception.description', item.message);\n callback(null, item);\n return;\n }\n var extra = _.get(item, tracePath + '.extra') || {};\n var newExtra = _.merge(extra, { message: item.message });\n _.set(item, tracePath + '.extra', newExtra);\n }\n callback(null, item);\n}\n\nfunction userTransform(logger) {\n return function (item, options, callback) {\n var newItem = _.merge(item);\n var response = null;\n try {\n if (_.isFunction(options.transform)) {\n response = options.transform(newItem.data, item);\n }\n } catch (e) {\n options.transform = null;\n logger.error(\n 'Error while calling custom transform() function. Removing custom transform().',\n e,\n );\n callback(null, item);\n return;\n }\n if (_.isPromise(response)) {\n response.then(\n function (promisedItem) {\n if (promisedItem) {\n newItem.data = promisedItem;\n }\n callback(null, newItem);\n },\n function (error) {\n callback(error, item);\n },\n );\n } else {\n callback(null, newItem);\n }\n };\n}\n\nfunction addConfigToPayload(item, options, callback) {\n if (!options.sendConfig) {\n return callback(null, item);\n }\n var configKey = '_rollbarConfig';\n var custom = _.get(item, 'data.custom') || {};\n custom[configKey] = options;\n item.data.custom = custom;\n callback(null, item);\n}\n\nfunction addFunctionOption(options, name) {\n if (_.isFunction(options[name])) {\n options[name] = options[name].toString();\n }\n}\n\nfunction addConfiguredOptions(item, options, callback) {\n var configuredOptions = options._configuredOptions;\n\n // These must be stringified or they'll get dropped during serialization.\n addFunctionOption(configuredOptions, 'transform');\n addFunctionOption(configuredOptions, 'checkIgnore');\n addFunctionOption(configuredOptions, 'onSendCallback');\n\n delete configuredOptions.accessToken;\n item.data.notifier.configured_options = configuredOptions;\n callback(null, item);\n}\n\nfunction addDiagnosticKeys(item, options, callback) {\n var diagnostic = _.merge(\n item.notifier.client.notifier.diagnostic,\n item.diagnostic,\n );\n\n if (_.get(item, 'err._isAnonymous')) {\n diagnostic.is_anonymous = true;\n }\n\n if (item._isUncaught) {\n diagnostic.is_uncaught = item._isUncaught;\n }\n\n if (item.err) {\n try {\n diagnostic.raw_error = {\n message: item.err.message,\n name: item.err.name,\n constructor_name: item.err.constructor && item.err.constructor.name,\n filename: item.err.fileName,\n line: item.err.lineNumber,\n column: item.err.columnNumber,\n stack: item.err.stack,\n };\n } catch (e) {\n diagnostic.raw_error = { failed: String(e) };\n }\n }\n\n item.data.notifier.diagnostic = _.merge(\n item.data.notifier.diagnostic,\n diagnostic,\n );\n callback(null, item);\n}\n\nexport {\n itemToPayload,\n addPayloadOptions,\n addTelemetryData,\n addMessageWithError,\n userTransform,\n addConfigToPayload,\n addConfiguredOptions,\n addDiagnosticKeys,\n};\n", "/**\n * Default browser options\n */\nimport { commonScrubFields } from '../defaults.js';\n\nexport const scrubFields = [\n ...commonScrubFields,\n 'cc-number',\n 'card number',\n 'cardnumber',\n 'cardnum',\n 'ccnum',\n 'ccnumber',\n 'cc num',\n 'creditcardnumber',\n 'credit card number',\n 'newcreditcardnumber',\n 'new credit card',\n 'creditcardno',\n 'credit card no',\n 'card#',\n 'card #',\n 'cc-csc',\n 'cvc',\n 'cvc2',\n 'cvv2',\n 'ccv2',\n 'security code',\n 'card verification',\n 'name on credit card',\n 'name on card',\n 'nameoncard',\n 'cardholder',\n 'card holder',\n 'name des karteninhabers',\n 'ccname',\n 'card type',\n 'cardtype',\n 'cc type',\n 'cctype',\n 'payment type',\n 'expiration date',\n 'expirationdate',\n 'expdate',\n 'cc-exp',\n 'ccmonth',\n 'ccyear',\n];\n\n// For compatibility with existing code that expects default export with scrubFields property\nexport default { scrubFields };\n", "function captureUncaughtExceptions(window, handler, shim) {\n if (!window) {\n return;\n }\n var oldOnError;\n\n if (typeof handler._rollbarOldOnError === 'function') {\n oldOnError = handler._rollbarOldOnError;\n } else if (window.onerror) {\n oldOnError = window.onerror;\n while (oldOnError._rollbarOldOnError) {\n oldOnError = oldOnError._rollbarOldOnError;\n }\n handler._rollbarOldOnError = oldOnError;\n }\n\n handler.handleAnonymousErrors();\n\n var fn = function () {\n var args = Array.prototype.slice.call(arguments, 0);\n _rollbarWindowOnError(window, handler, oldOnError, args);\n };\n if (shim) {\n fn._rollbarOldOnError = oldOnError;\n }\n window.onerror = fn;\n}\n\nfunction _rollbarWindowOnError(window, r, old, args) {\n if (window._rollbarWrappedError) {\n if (!args[4]) {\n args[4] = window._rollbarWrappedError;\n }\n if (!args[5]) {\n args[5] = window._rollbarWrappedError._rollbarContext;\n }\n window._rollbarWrappedError = null;\n }\n\n var ret = r.handleUncaughtException.apply(r, args);\n\n if (old) {\n old.apply(window, args);\n }\n\n // Let other chained onerror handlers above run before setting this.\n // If an error is thrown and caught within a chained onerror handler,\n // Error.prepareStackTrace() will see that one before the one we want.\n if (ret === 'anonymous') {\n r.anonymousErrorsPending += 1; // See Rollbar.prototype.handleAnonymousErrors()\n }\n}\n\nfunction captureUnhandledRejections(window, handler, shim) {\n if (!window) {\n return;\n }\n\n if (\n typeof window._rollbarURH === 'function' &&\n window._rollbarURH.belongsToShim\n ) {\n window.removeEventListener('unhandledrejection', window._rollbarURH);\n }\n\n var rejectionHandler = function (evt) {\n var reason, promise, detail;\n try {\n reason = evt.reason;\n } catch (_e) {\n reason = undefined;\n }\n try {\n promise = evt.promise;\n } catch (_e) {\n promise = '[unhandledrejection] error getting `promise` from event';\n }\n try {\n detail = evt.detail;\n if (!reason && detail) {\n reason = detail.reason;\n promise = detail.promise;\n }\n } catch (_e) {\n // Ignore\n }\n if (!reason) {\n reason = '[unhandledrejection] error getting `reason` from event';\n }\n\n if (handler && handler.handleUnhandledRejection) {\n handler.handleUnhandledRejection(reason, promise);\n }\n };\n rejectionHandler.belongsToShim = shim;\n window._rollbarURH = rejectionHandler;\n window.addEventListener('unhandledrejection', rejectionHandler);\n}\n\nexport { captureUncaughtExceptions, captureUnhandledRejections };\n", "import * as _ from '../utility.js';\n\nfunction checkIgnore(item, settings) {\n if (_.get(settings, 'plugins.jquery.ignoreAjaxErrors')) {\n return !_.get(item, 'body.message.extra.isAjax');\n }\n return true;\n}\n\nexport { checkIgnore };\n", "/**\n * Default session replay recording options\n * See https://github.com/rrweb-io/rrweb/blob/master/guide.md#options for details\n */\nexport default {\n enabled: false, // Whether recording is enabled\n autoStart: true, // Start recording automatically when Rollbar initializes\n\n // defaults used by triggers that don't specify them\n triggerDefaults: {\n samplingRatio: 1.0,\n preDuration: 300,\n postDuration: 5,\n },\n triggers: [\n {\n type: 'occurrence',\n level: ['error', 'critical'],\n },\n ],\n\n debug: {\n logErrors: true, // Whether to log errors emitted by rrweb.\n logEmits: false, // Whether to log emitted events\n },\n\n // Recording options\n inlineStylesheet: true, // Whether to inline stylesheets to improve replay accuracy\n inlineImages: false, // Whether to record the image content\n collectFonts: true, // Whether to collect fonts in the website\n\n // Privacy options\n // Fine-grained control over which input types to mask\n // By default only password inputs are masked if maskInputs is true\n maskInputOptions: {\n password: true,\n email: false,\n tel: false,\n text: false,\n color: false,\n date: false,\n 'datetime-local': false,\n month: false,\n number: false,\n range: false,\n search: false,\n time: false,\n url: false,\n week: false,\n },\n\n // Mask all input values\n maskAllInputs: false,\n\n // Class names to block, mask, or ignore the content of elements.\n blockClass: 'rb-block',\n maskTextClass: 'rb-mask',\n ignoreClass: 'rb-ignore',\n\n // Remove unnecessary parts of the DOM\n // By default all removable elements are removed\n slimDOMOptions: {\n script: true, // Remove script elements\n comment: true, // Remove comments\n headFavicon: true, // Remove favicons in the head\n headWhitespace: true, // Remove whitespace in head\n headMetaDescKeywords: true, // Remove meta description and keywords\n headMetaSocial: true, // Remove social media meta tags\n headMetaRobots: true, // Remove robots meta directives\n headMetaHttpEquiv: true, // Remove http-equiv meta directives\n headMetaAuthorship: true, // Remove authorship meta directives\n headMetaVerification: true, // Remove verification meta directives\n },\n\n // Custom callbacks for advanced use cases\n // These are undefined by default and can be set programmatically\n // maskInputFn: undefined, // Custom function to mask input values\n // maskTextFn: undefined, // Custom function to mask text content\n // errorHandler: undefined, // Custom error handler for recording errors\n\n // Plugin system\n // plugins: [] // List of plugins to use (must be set programmatically)\n};\n", "import errorParser from '../errorParser.js';\nimport logger from '../logger.js';\nimport * as _ from '../utility.js';\n\nfunction handleDomException(item, options, callback) {\n if (item.err && errorParser.Stack(item.err).name === 'DOMException') {\n var originalError = new Error();\n originalError.name = item.err.name;\n originalError.message = item.err.message;\n originalError.stack = item.err.stack;\n originalError.nested = item.err;\n item.err = originalError;\n }\n callback(null, item);\n}\n\nfunction handleItemWithError(item, options, callback) {\n item.data = item.data || {};\n if (item.err) {\n try {\n item.stackInfo =\n item.err._savedStackTrace ||\n errorParser.parse(item.err, item.skipFrames);\n\n if (options.addErrorContext) {\n addErrorContext(item);\n }\n } catch (e) {\n logger.error('Error while parsing the error object.', e);\n try {\n item.message =\n item.err.message ||\n item.err.description ||\n item.message ||\n String(item.err);\n } catch (e2) {\n item.message = String(item.err) || String(e2);\n }\n delete item.err;\n }\n }\n callback(null, item);\n}\n\nfunction addErrorContext(item) {\n var chain = [];\n var err = item.err;\n\n chain.push(err);\n\n while (err.nested || err.cause) {\n err = err.nested || err.cause;\n chain.push(err);\n }\n\n _.addErrorContext(item, chain);\n}\n\nfunction ensureItemHasSomethingToSay(item, options, callback) {\n if (!item.message && !item.stackInfo && !item.custom) {\n callback(new Error('No message, stack info, or custom data'), null);\n }\n callback(null, item);\n}\n\nfunction addBaseInfo(item, options, callback) {\n var environment =\n (options.payload && options.payload.environment) || options.environment;\n item.data = _.merge(item.data, {\n environment: environment,\n level: item.level,\n endpoint: options.endpoint,\n platform: 'browser',\n framework: 'browser-js',\n language: 'javascript',\n server: {},\n uuid: item.uuid,\n notifier: {\n name: 'rollbar-browser-js',\n version: options.version,\n },\n custom: item.custom,\n });\n callback(null, item);\n}\n\nfunction addRequestInfo(window) {\n return function (item, options, callback) {\n var requestInfo = {};\n\n if (window && window.location) {\n requestInfo.url = window.location.href;\n requestInfo.query_string = window.location.search;\n }\n\n var remoteString = '$remote_ip';\n if (!options.captureIp) {\n remoteString = null;\n } else if (options.captureIp !== true) {\n remoteString += '_anonymize';\n }\n if (remoteString) requestInfo.user_ip = remoteString;\n\n if (Object.keys(requestInfo).length > 0) {\n _.set(item, 'data.request', requestInfo);\n }\n\n callback(null, item);\n };\n}\n\nfunction addClientInfo(window) {\n return function (item, options, callback) {\n if (!window) {\n return callback(null, item);\n }\n var nav = window.navigator || {};\n var scr = window.screen || {};\n _.set(item, 'data.client', {\n runtime_ms: item.timestamp - window._rollbarStartTime,\n timestamp: Math.round(item.timestamp / 1000),\n javascript: {\n browser: nav.userAgent,\n language: nav.language,\n cookie_enabled: nav.cookieEnabled,\n screen: {\n width: scr.width,\n height: scr.height,\n },\n },\n });\n callback(null, item);\n };\n}\n\nfunction addPluginInfo(window) {\n return function (item, options, callback) {\n if (!window || !window.navigator) {\n return callback(null, item);\n }\n var plugins = [];\n var navPlugins = window.navigator.plugins || [];\n var cur;\n for (var i = 0, l = navPlugins.length; i < l; ++i) {\n cur = navPlugins[i];\n plugins.push({ name: cur.name, description: cur.description });\n }\n _.set(item, 'data.client.javascript.plugins', plugins);\n callback(null, item);\n };\n}\n\nfunction addBody(item, options, callback) {\n if (item.stackInfo) {\n if (item.stackInfo.traceChain) {\n addBodyTraceChain(item, options, callback);\n } else {\n addBodyTrace(item, options, callback);\n }\n } else {\n addBodyMessage(item, options, callback);\n }\n}\n\nfunction addBodyMessage(item, options, callback) {\n var message = item.message;\n var custom = item.custom;\n\n if (!message) {\n message = 'Item sent with null or missing arguments.';\n }\n var result = {\n body: message,\n };\n\n if (custom) {\n result.extra = _.merge(custom);\n }\n\n _.set(item, 'data.body', { message: result });\n callback(null, item);\n}\n\nfunction stackFromItem(item, stackInfo = null) {\n // Transform a TraceKit stackInfo object into a Rollbar trace\n let stack = (stackInfo || item.stackInfo).stack;\n if (\n stack &&\n stack.length === 0 &&\n item._unhandledStackInfo &&\n item._unhandledStackInfo.stack\n ) {\n stack = item._unhandledStackInfo.stack;\n }\n return stack;\n}\n\nfunction addBodyTraceChain(item, options, callback) {\n var traceChain = item.stackInfo.traceChain;\n var traces = [];\n\n var traceChainLength = traceChain.length;\n for (var i = 0; i < traceChainLength; i++) {\n var trace = buildTrace(item, traceChain[i], options);\n traces.push(trace);\n }\n\n _.set(item, 'data.body', { trace_chain: traces });\n callback(null, item);\n}\n\nfunction addBodyTrace(item, options, callback) {\n var stack = stackFromItem(item);\n\n if (stack) {\n var trace = buildTrace(item, item.stackInfo, options);\n _.set(item, 'data.body', { trace: trace });\n callback(null, item);\n } else {\n var stackInfo = item.stackInfo;\n var guess = errorParser.guessErrorClass(stackInfo.message);\n var className = errorClass(stackInfo, guess[0], options);\n var message = guess[1];\n\n item.message = className + ': ' + message;\n addBodyMessage(item, options, callback);\n }\n}\n\nfunction buildTrace(item, stackInfo, options) {\n var description = item && item.data.description;\n var custom = item && item.custom;\n var stack = stackFromItem(item, stackInfo);\n\n var guess = errorParser.guessErrorClass(stackInfo.message);\n var className = errorClass(stackInfo, guess[0], options);\n var message = guess[1];\n var trace = {\n exception: {\n class: className,\n message: message,\n },\n };\n\n if (description) {\n trace.exception.description = description;\n }\n\n if (stack) {\n if (stack.length === 0) {\n trace.exception.stack = stackInfo.rawStack;\n trace.exception.raw = String(stackInfo.rawException);\n }\n var stackFrame;\n var frame;\n var code;\n var pre;\n var post;\n var contextLength;\n var i, mid;\n\n trace.frames = [];\n for (i = 0; i < stack.length; ++i) {\n stackFrame = stack[i];\n frame = {\n filename: stackFrame.url ? _.sanitizeUrl(stackFrame.url) : '(unknown)',\n lineno: stackFrame.line || null,\n method:\n !stackFrame.func || stackFrame.func === '?'\n ? '[anonymous]'\n : stackFrame.func,\n colno: stackFrame.column,\n };\n if (options.sendFrameUrl) {\n frame.url = stackFrame.url;\n }\n if (\n frame.method &&\n frame.method.endsWith &&\n frame.method.endsWith('_rollbar_wrapped')\n ) {\n continue;\n }\n\n code = pre = post = null;\n contextLength = stackFrame.context ? stackFrame.context.length : 0;\n if (contextLength) {\n mid = Math.floor(contextLength / 2);\n pre = stackFrame.context.slice(0, mid);\n code = stackFrame.context[mid];\n post = stackFrame.context.slice(mid);\n }\n\n if (code) {\n frame.code = code;\n }\n\n if (pre || post) {\n frame.context = {};\n if (pre && pre.length) {\n frame.context.pre = pre;\n }\n if (post && post.length) {\n frame.context.post = post;\n }\n }\n\n if (stackFrame.args) {\n frame.args = stackFrame.args;\n }\n\n trace.frames.push(frame);\n }\n\n // NOTE(cory): reverse the frames since rollbar.com expects the most recent call last\n trace.frames.reverse();\n\n if (custom) {\n trace.extra = _.merge(custom);\n }\n }\n\n return trace;\n}\n\nfunction errorClass(stackInfo, guess, options) {\n if (stackInfo.name) {\n return stackInfo.name;\n } else if (options.guessErrorClass) {\n return guess;\n } else {\n return '(unknown)';\n }\n}\n\nfunction addScrubber(scrubFn) {\n return function (item, options, callback) {\n if (scrubFn) {\n var scrubFields = options.scrubFields || [];\n var scrubPaths = options.scrubPaths || [];\n item.data = scrubFn(item.data, scrubFields, scrubPaths);\n }\n callback(null, item);\n };\n}\n\nexport {\n handleDomException,\n handleItemWithError,\n ensureItemHasSomethingToSay,\n addBaseInfo,\n addRequestInfo,\n addClientInfo,\n addPluginInfo,\n addBody,\n addScrubber,\n};\n", "import logger from '../../logger.js';\nimport * as _ from '../../utility.js';\n\nfunction makeFetchRequest({\n accessToken,\n url,\n method,\n payload,\n headers,\n callback,\n timeout,\n}) {\n var controller;\n var timeoutId;\n\n if (_.isFiniteNumber(timeout)) {\n controller = new AbortController();\n timeoutId = setTimeout(function () {\n controller.abort();\n }, timeout);\n }\n\n headers = {\n 'Content-Type': 'application/json',\n 'X-Rollbar-Access-Token': accessToken,\n signal: controller && controller.signal,\n ...headers,\n };\n\n fetch(url, {\n method,\n headers,\n body: payload,\n })\n .then(function (response) {\n if (timeoutId) clearTimeout(timeoutId);\n const respHeaders = response.headers;\n\n const isItemRoute = url.endsWith('/api/1/item/');\n const headers = isItemRoute\n ? {\n 'Rollbar-Replay-Enabled': respHeaders.get('Rollbar-Replay-Enabled'),\n 'Rollbar-Replay-RateLimit-Remaining': respHeaders.get(\n 'Rollbar-Replay-RateLimit-Remaining',\n ),\n 'Rollbar-Replay-RateLimit-Reset': respHeaders.get(\n 'Rollbar-Replay-RateLimit-Reset',\n ),\n }\n : {};\n\n const json = response.json();\n callback(null, json, headers);\n })\n .catch(function (error) {\n logger.error(error.message);\n callback(error);\n });\n}\n\nexport default makeFetchRequest;\n", "/*global XDomainRequest*/\n\nimport logger from '../../logger.js';\nimport * as _ from '../../utility.js';\n\nfunction makeXhrRequest({\n accessToken,\n url,\n method,\n payload,\n headers,\n callback,\n requestFactory,\n timeout,\n}) {\n var request;\n if (requestFactory) {\n request = requestFactory();\n } else {\n request = _createXMLHTTPObject();\n }\n if (!request) {\n // Give up, no way to send requests\n return callback(new Error('No way to send a request'));\n }\n try {\n try {\n var onreadystatechange = function () {\n try {\n if (onreadystatechange && request.readyState === 4) {\n onreadystatechange = undefined;\n\n var parseResponse = _.jsonParse(request.responseText);\n if (_isSuccess(request)) {\n const isItemRoute = url.endsWith('/api/1/item/');\n\n const headers = isItemRoute\n ? {\n 'Rollbar-Replay-Enabled': request.getResponseHeader(\n 'Rollbar-Replay-Enabled',\n ),\n 'Rollbar-Replay-RateLimit-Remaining':\n request.getResponseHeader(\n 'Rollbar-Replay-RateLimit-Remaining',\n ),\n 'Rollbar-Replay-RateLimit-Reset': request.getResponseHeader(\n 'Rollbar-Replay-RateLimit-Reset',\n ),\n }\n : {};\n callback(parseResponse.error, parseResponse.value, headers);\n return;\n } else if (_isNormalFailure(request)) {\n if (request.status === 403) {\n // likely caused by using a server access token\n var message =\n parseResponse.value && parseResponse.value.message;\n logger.error(message);\n }\n // return valid http status codes\n callback(new Error(String(request.status)));\n } else {\n // IE will return a status 12000+ on some sort of connection failure,\n // so we return a blank error\n // http://msdn.microsoft.com/en-us/library/aa383770%28VS.85%29.aspx\n var msg =\n 'XHR response had no status code (likely connection failure)';\n callback(_newRetriableError(msg));\n }\n }\n } catch (ex) {\n //jquery source mentions firefox may error out while accessing the\n //request members if there is a network error\n //https://github.com/jquery/jquery/blob/a938d7b1282fc0e5c52502c225ae8f0cef219f0a/src/ajax/xhr.js#L111\n var exc;\n if (ex && ex.stack) {\n exc = ex;\n } else {\n exc = new Error(ex);\n }\n callback(exc);\n }\n };\n\n request.open(method, url, true);\n if (request.setRequestHeader) {\n request.setRequestHeader('Content-Type', 'application/json');\n request.setRequestHeader('X-Rollbar-Access-Token', accessToken);\n for (const [h, v] of Object.entries(headers ?? {})) {\n request.setRequestHeader(h, v);\n }\n }\n\n if (_.isFiniteNumber(timeout)) {\n request.timeout = timeout;\n }\n\n request.onreadystatechange = onreadystatechange;\n request.send(payload);\n } catch (_e1) {\n // Sending using the normal xmlhttprequest object didn't work, try XDomainRequest\n if (typeof XDomainRequest !== 'undefined') {\n // Assume we are in a really old browser which has a bunch of limitations:\n // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx\n\n // Extreme paranoia: if we have XDomainRequest then we have a window, but just in case\n if (!window || !window.location) {\n return callback(\n new Error(\n 'No window available during request, unknown environment',\n ),\n );\n }\n\n // If the current page is http, try and send over http\n if (\n window.location.href.substring(0, 5) === 'http:' &&\n url.substring(0, 5) === 'https'\n ) {\n url = 'http' + url.substring(5);\n }\n\n var xdomainrequest = new XDomainRequest();\n xdomainrequest.onprogress = () => {};\n xdomainrequest.ontimeout = function () {\n var msg = 'Request timed out';\n var code = 'ETIMEDOUT';\n callback(_newRetriableError(msg, code));\n };\n xdomainrequest.onerror = function () {\n callback(new Error('Error during request'));\n };\n xdomainrequest.onload = function () {\n var parseResponse = _.jsonParse(xdomainrequest.responseText);\n callback(parseResponse.error, parseResponse.value);\n };\n xdomainrequest.open(method, url, true);\n xdomainrequest.send(payload);\n } else {\n callback(new Error('Cannot find a method to transport a request'));\n }\n }\n } catch (e2) {\n callback(e2);\n }\n}\n\nfunction _createXMLHTTPObject() {\n /* global ActiveXObject:false */\n\n var factories = [\n function () {\n return new XMLHttpRequest();\n },\n function () {\n return new ActiveXObject('Msxml2.XMLHTTP');\n },\n function () {\n return new ActiveXObject('Msxml3.XMLHTTP');\n },\n function () {\n return new ActiveXObject('Microsoft.XMLHTTP');\n },\n ];\n var xmlhttp;\n var i;\n var numFactories = factories.length;\n for (i = 0; i < numFactories; i++) {\n try {\n xmlhttp = factories[i]();\n break;\n } catch (_e) {\n // pass\n }\n }\n return xmlhttp;\n}\n\nfunction _isSuccess(r) {\n return r && r.status && r.status === 200;\n}\n\nfunction _isNormalFailure(r) {\n return r && _.isType(r.status, 'number') && r.status >= 400 && r.status < 600;\n}\n\nfunction _newRetriableError(message, code) {\n var err = new Error(message);\n err.code = code || 'ENOTFOUND';\n return err;\n}\n\nexport default makeXhrRequest;\n", "import * as _ from '../utility.js';\n\nimport makeFetchRequest from './transport/fetch.js';\nimport makeXhrRequest from './transport/xhr.js';\n\n/*\n * accessToken may be embedded in payload but that should not\n * be assumed\n *\n * options: {\n * hostname\n * protocol\n * path\n * port\n * method\n * transport ('xhr' | 'fetch')\n * }\n *\n * params is an object containing key/value pairs. These\n * will be appended to the path as 'key=value&key=value'\n *\n * payload is an unserialized object\n */\nfunction Transport(truncation) {\n this.truncation = truncation;\n}\n\nTransport.prototype.get = function (\n accessToken,\n options,\n params,\n callback,\n requestFactory,\n) {\n if (!callback || !_.isFunction(callback)) {\n callback = () => {};\n }\n _.addParamsAndAccessTokenToPath(accessToken, options, params);\n\n var method = 'GET';\n var url = _.formatUrl(options);\n this._makeZoneRequest({\n accessToken,\n url,\n method,\n callback,\n requestFactory,\n timeout: options.timeout,\n transport: options.transport,\n });\n};\n\nTransport.prototype.post = function ({\n accessToken,\n options,\n payload,\n headers,\n callback,\n requestFactory,\n}) {\n if (!callback || !_.isFunction(callback)) {\n callback = () => {};\n }\n\n if (!payload) {\n return callback(new Error('Cannot send empty request'));\n }\n\n var stringifyResult;\n // Check payload.body to ensure only items are truncated.\n if (this.truncation && payload.body) {\n stringifyResult = this.truncation.truncate(payload);\n } else {\n stringifyResult = _.stringify(payload);\n }\n if (stringifyResult.error) {\n return callback(stringifyResult.error);\n }\n\n var method = 'POST';\n var url = _.formatUrl(options);\n this._makeZoneRequest({\n accessToken,\n url,\n method,\n payload: stringifyResult.value,\n headers,\n callback,\n requestFactory,\n timeout: options.timeout,\n transport: options.transport,\n });\n};\n\nTransport.prototype.postJsonPayload = function (\n accessToken,\n options,\n payload,\n callback,\n requestFactory,\n) {\n if (!callback || !_.isFunction(callback)) {\n callback = () => {};\n }\n\n var method = 'POST';\n var url = _.formatUrl(options);\n this._makeZoneRequest({\n accessToken,\n url,\n method,\n payload,\n callback,\n requestFactory,\n timeout: options.timeout,\n transport: options.transport,\n });\n};\n\n// Wraps `_makeRequest` if zone.js is being used, ensuring that Rollbar\n// API calls are not intercepted by any child forked zones.\n// This is equivalent to `NgZone.runOutsideAngular` in Angular.\nTransport.prototype._makeZoneRequest = function () {\n var gWindow =\n (typeof window !== 'undefined' && window) ||\n (typeof self !== 'undefined' && self);\n // Whenever zone.js is loaded and `Zone` is exposed globally, access\n // the root zone to ensure that requests are always made within it.\n // This approach is framework-agnostic, regardless of which\n // framework zone.js is used with.\n var rootZone = gWindow && gWindow.Zone && gWindow.Zone.root;\n var args = Array.prototype.slice.call(arguments);\n\n if (rootZone) {\n rootZone.run(() => {\n this._makeRequest.apply(undefined, args);\n });\n } else {\n this._makeRequest.apply(undefined, args);\n }\n};\n\nTransport.prototype._makeRequest = function (params) {\n const { payload, callback, transport } = params;\n if (typeof RollbarProxy !== 'undefined') {\n return _proxyRequest(payload, callback);\n }\n\n if (transport === 'fetch') {\n makeFetchRequest(params);\n } else {\n makeXhrRequest(params);\n }\n};\n\n/* global RollbarProxy */\nfunction _proxyRequest(json, callback) {\n var rollbarProxy = new RollbarProxy();\n rollbarProxy.sendJsonPayload(\n json,\n function (_msg) {\n /* do nothing */\n },\n function (err) {\n callback(new Error(err));\n },\n );\n}\n\nexport default Transport;\n", "// See https://nodejs.org/docs/latest/api/url.html\nfunction parse(url) {\n var result = {\n protocol: null,\n auth: null,\n host: null,\n path: null,\n hash: null,\n href: url,\n hostname: null,\n port: null,\n pathname: null,\n search: null,\n query: null,\n };\n\n var i, last;\n i = url.indexOf('//');\n if (i !== -1) {\n result.protocol = url.substring(0, i);\n last = i + 2;\n } else {\n last = 0;\n }\n\n i = url.indexOf('@', last);\n if (i !== -1) {\n result.auth = url.substring(last, i);\n last = i + 1;\n }\n\n i = url.indexOf('/', last);\n if (i === -1) {\n i = url.indexOf('?', last);\n if (i === -1) {\n i = url.indexOf('#', last);\n if (i === -1) {\n result.host = url.substring(last);\n } else {\n result.host = url.substring(last, i);\n result.hash = url.substring(i);\n }\n result.hostname = result.host.split(':')[0];\n result.port = result.host.split(':')[1];\n if (result.port) {\n result.port = parseInt(result.port, 10);\n }\n return result;\n } else {\n result.host = url.substring(last, i);\n result.hostname = result.host.split(':')[0];\n result.port = result.host.split(':')[1];\n if (result.port) {\n result.port = parseInt(result.port, 10);\n }\n last = i;\n }\n } else {\n result.host = url.substring(last, i);\n result.hostname = result.host.split(':')[0];\n result.port = result.host.split(':')[1];\n if (result.port) {\n result.port = parseInt(result.port, 10);\n }\n last = i;\n }\n\n i = url.indexOf('#', last);\n if (i === -1) {\n result.path = url.substring(last);\n } else {\n result.path = url.substring(last, i);\n result.hash = url.substring(i);\n }\n\n if (result.path) {\n var pathParts = result.path.split('?');\n result.pathname = pathParts[0];\n result.query = pathParts[1];\n result.search = result.query ? '?' + result.query : null;\n }\n return result;\n}\n\nexport { parse };\n", "import API from '../api.js';\nimport defaults from '../defaults.js';\nimport errorParser from '../errorParser.js';\nimport logger from '../logger.js';\nimport * as sharedPredicates from '../predicates.js';\nimport Client from '../rollbar.js';\nimport tracingDefaults from '../tracing/defaults.js';\nimport * as sharedTransforms from '../transforms.js';\nimport * as _ from '../utility.js';\n\nimport browserDefaults from './defaults.js';\nimport * as globals from './globalSetup.js';\nimport * as predicates from './predicates.js';\nimport replayDefaults from './replay/defaults.js';\nimport * as transforms from './transforms.js';\nimport Transport from './transport.js';\nimport * as urllib from './url.js';\n\n// Used to support global `Rollbar` instance.\nlet _instance = null;\n\nclass Rollbar {\n constructor(options, client) {\n logger.init({ logLevel: options.logLevel || 'error' });\n this.options = _.handleOptions(defaultOptions, options, null, logger);\n this.options._configuredOptions = options;\n this.components = this.components || {};\n const Telemeter = this.components.telemeter;\n const Instrumenter = this.components.instrumenter;\n this.wrapGlobals = this.components.wrapGlobals;\n this.scrub = this.components.scrub;\n const truncation = this.components.truncation;\n const Tracing = this.components.tracing;\n const Replay = this.components.replay;\n\n const transport = new Transport(truncation);\n const api = new API(this.options, transport, urllib, truncation);\n if (Tracing) {\n this.tracing = new Tracing(_gWindow(), api, this.options);\n this.tracing.initSession();\n }\n if (Telemeter) {\n this.telemeter = new Telemeter(this.options, this.tracing);\n }\n\n if (Replay && _.isBrowser()) {\n const replayOptions = this.options.replay;\n this.replay = new Replay({\n tracing: this.tracing,\n telemeter: this.telemeter,\n options: replayOptions,\n });\n\n if (replayOptions.enabled && replayOptions.autoStart) {\n this.replay.recorder.start();\n }\n }\n\n this.client =\n client ||\n new Client(\n this.options,\n api,\n logger,\n this.telemeter,\n this.tracing,\n this.replay,\n 'browser',\n );\n var gWindow = _gWindow();\n var gDocument = typeof document !== 'undefined' && document;\n this.isChrome = gWindow.chrome && gWindow.chrome.runtime; // check .runtime to avoid Edge browsers\n this.anonymousErrorsPending = 0;\n addTransformsToNotifier(this.client.notifier, this, gWindow);\n addPredicatesToQueue(this.client.queue);\n this.setupUnhandledCapture();\n if (Instrumenter) {\n this.instrumenter = new Instrumenter(\n this.options,\n this.client.telemeter,\n this,\n gWindow,\n gDocument,\n );\n this.instrumenter.instrument();\n }\n\n this.setSessionAttributesFromOptions(options);\n\n // Used with rollbar-react for rollbar-react-native compatibility.\n this.rollbar = this;\n }\n\n static init(options, client) {\n if (_instance) {\n return _instance.global(options).configure(options);\n }\n _instance = new Rollbar(options, client);\n return _instance;\n }\n\n static setComponents(components) {\n Rollbar.prototype.components = components;\n }\n\n global(options) {\n this.client.global(options);\n return this;\n }\n\n configure(options, payloadData) {\n if (options.logLevel) {\n logger.init({ logLevel: options.logLevel });\n }\n this.setSessionAttributesFromOptions(options);\n var oldOptions = this.options;\n var payload = {};\n if (payloadData) {\n payload = { payload: payloadData };\n }\n\n this.options = _.handleOptions(oldOptions, options, payload, logger);\n this.options._configuredOptions = _.handleOptions(\n oldOptions._configuredOptions,\n options,\n payload,\n );\n\n this.tracing?.configure(this.options);\n this.replay?.configure(this.options.replay);\n this.client.configure(this.options, payloadData);\n this.instrumenter?.configure(this.options);\n this.setupUnhandledCapture();\n return this;\n }\n\n lastError() {\n return this.client.lastError;\n }\n\n log() {\n var item = this._createItem(arguments);\n var uuid = item.uuid;\n this.client.log(item);\n return { uuid: uuid };\n }\n\n debug() {\n var item = this._createItem(arguments);\n var uuid = item.uuid;\n this.client.debug(item);\n return { uuid: uuid };\n }\n\n info() {\n var item = this._createItem(arguments);\n var uuid = item.uuid;\n this.client.info(item);\n return { uuid: uuid };\n }\n\n warn() {\n var item = this._createItem(arguments);\n var uuid = item.uuid;\n this.client.warn(item);\n return { uuid: uuid };\n }\n\n warning() {\n var item = this._createItem(arguments);\n var uuid = item.uuid;\n this.client.warning(item);\n return { uuid: uuid };\n }\n\n error() {\n var item = this._createItem(arguments);\n var uuid = item.uuid;\n this.client.error(item);\n return { uuid: uuid };\n }\n\n critical() {\n var item = this._createItem(arguments);\n var uuid = item.uuid;\n this.client.critical(item);\n return { uuid: uuid };\n }\n\n buildJsonPayload(item) {\n return this.client.buildJsonPayload(item);\n }\n\n sendJsonPayload(jsonPayload) {\n return this.client.sendJsonPayload(jsonPayload);\n }\n\n triggerDirectReplay(context) {\n return this.triggerReplay({ type: 'direct', ...context });\n }\n\n triggerReplay(context) {\n if (!this.replay) return null;\n\n return this.replay.triggerReplay(context);\n }\n\n setupUnhandledCapture() {\n var gWindow = _gWindow();\n\n if (!this.unhandledExceptionsInitialized) {\n if (\n this.options.captureUncaught ||\n this.options.handleUncaughtExceptions\n ) {\n globals.captureUncaughtExceptions(gWindow, this);\n if (this.wrapGlobals && this.options.wrapGlobalEventHandlers) {\n this.wrapGlobals(gWindow, this);\n }\n this.unhandledExceptionsInitialized = true;\n }\n }\n if (!this.unhandledRejectionsInitialized) {\n if (\n this.options.captureUnhandledRejections ||\n this.options.handleUnhandledRejections\n ) {\n globals.captureUnhandledRejections(gWindow, this);\n this.unhandledRejectionsInitialized = true;\n }\n }\n }\n\n handleUncaughtException(message, url, lineno, colno, error, context) {\n if (\n !this.options.captureUncaught &&\n !this.options.handleUncaughtExceptions\n ) {\n return;\n }\n\n // Chrome will always send 5+ arguments and error will be valid or null, not undefined.\n // If error is undefined, we have a different caller.\n // Chrome also sends errors from web workers with null error, but does not invoke\n // prepareStackTrace() for these. Test for empty url to skip them.\n if (\n this.options.inspectAnonymousErrors &&\n this.isChrome &&\n error === null &&\n url === ''\n ) {\n return 'anonymous';\n }\n\n var item;\n var stackInfo = _.makeUnhandledStackInfo(\n message,\n url,\n lineno,\n colno,\n error,\n 'onerror',\n 'uncaught exception',\n errorParser,\n );\n if (_.isError(error)) {\n item = this._createItem([message, error, context]);\n item._unhandledStackInfo = stackInfo;\n } else if (_.isError(url)) {\n item = this._createItem([message, url, context]);\n item._unhandledStackInfo = stackInfo;\n } else {\n item = this._createItem([message, context]);\n item.stackInfo = stackInfo;\n }\n item.level = this.options.uncaughtErrorLevel;\n item._isUncaught = true;\n this.client.log(item);\n }\n\n /**\n * Chrome only. Other browsers will ignore.\n *\n * Use Error.prepareStackTrace to extract information about errors that\n * do not have a valid error object in onerror().\n *\n * In tested version of Chrome, onerror is called first but has no way\n * to communicate with prepareStackTrace. Use a counter to let this\n * handler know which errors to send to Rollbar.\n *\n * In config options, set inspectAnonymousErrors to enable.\n */\n handleAnonymousErrors() {\n if (!this.options.inspectAnonymousErrors || !this.isChrome) {\n return;\n }\n\n const prepareStackTrace = (error, _stack) => {\n if (this.options.inspectAnonymousErrors) {\n if (this.anonymousErrorsPending) {\n // This is the only known way to detect that onerror saw an anonymous error.\n // It depends on onerror reliably being called before Error.prepareStackTrace,\n // which so far holds true on tested versions of Chrome. If versions of Chrome\n // are tested that behave differently, this logic will need to be updated\n // accordingly.\n this.anonymousErrorsPending -= 1;\n\n if (!error) {\n // Not likely to get here, but calling handleUncaughtException from here\n // without an error object would throw off the anonymousErrorsPending counter,\n // so return now.\n return;\n }\n\n // Allow this to be tracked later.\n error._isAnonymous = true;\n\n // url, lineno, colno shouldn't be needed for these errors.\n // If that changes, update this accordingly, using the unused\n // _stack param as needed (rather than parse error.toString()).\n this.handleUncaughtException(error.message, null, null, null, error);\n }\n }\n\n // Workaround to ensure stack is preserved for normal errors.\n return error.stack;\n };\n\n // https://v8.dev/docs/stack-trace-api\n try {\n Error.prepareStackTrace = prepareStackTrace;\n } catch (e) {\n this.options.inspectAnonymousErrors = false;\n this.error('anonymous error handler failed', e);\n }\n }\n\n handleUnhandledRejection(reason, promise) {\n if (\n !this.options.captureUnhandledRejections &&\n !this.options.handleUnhandledRejections\n ) {\n return;\n }\n\n var message = 'unhandled rejection was null or undefined!';\n if (reason) {\n if (reason.message) {\n message = reason.message;\n } else {\n var reasonResult = _.stringify(reason);\n if (reasonResult.value) {\n message = reasonResult.value;\n }\n }\n }\n var context =\n (reason && reason._rollbarContext) ||\n (promise && promise._rollbarContext);\n\n var item;\n if (_.isError(reason)) {\n item = this._createItem([message, reason, context]);\n } else {\n item = this._createItem([message, reason, context]);\n item.stackInfo = _.makeUnhandledStackInfo(\n message,\n '',\n 0,\n 0,\n null,\n 'unhandledrejection',\n '',\n errorParser,\n );\n }\n item.level = this.options.uncaughtErrorLevel;\n item._isUncaught = true;\n item._originalArgs = item._originalArgs || [];\n item._originalArgs.push(promise);\n this.client.log(item);\n }\n\n wrap(f, context, _before) {\n try {\n var ctxFn;\n if (_.isFunction(context)) {\n ctxFn = context;\n } else {\n ctxFn = function () {\n return context || {};\n };\n }\n\n if (!_.isFunction(f)) {\n return f;\n }\n\n if (f._isWrap) {\n return f;\n }\n\n if (!f._rollbar_wrapped) {\n f._rollbar_wrapped = function () {\n if (_before && _.isFunction(_before)) {\n _before.apply(this, arguments);\n }\n try {\n return f.apply(this, arguments);\n } catch (exc) {\n var e = exc;\n if (e && window._rollbarWrappedError !== e) {\n if (_.isType(e, 'string')) {\n e = new String(e);\n }\n e._rollbarContext = ctxFn() || {};\n e._rollbarContext._wrappedSource = f.toString();\n\n window._rollbarWrappedError = e;\n }\n throw e;\n }\n };\n\n f._rollbar_wrapped._isWrap = true;\n\n for (var prop in f) {\n if (_.hasOwn(f, prop) && prop !== '_rollbar_wrapped') {\n f._rollbar_wrapped[prop] = f[prop];\n }\n }\n }\n\n return f._rollbar_wrapped;\n } catch (_e) {\n // Return the original function if the wrap fails.\n return f;\n }\n }\n\n captureEvent() {\n var event = _.createTelemetryEvent(arguments);\n return this.client.captureEvent(event.type, event.metadata, event.level);\n }\n\n setSessionUser(user) {\n if (!this.tracing?.session) return;\n\n this.tracing.session.setUser(user);\n }\n\n setSessionAttributes(attrs) {\n if (!this.tracing?.session) return;\n\n attrs = { ...attrs };\n\n this.tracing.session.setAttributes(attrs);\n }\n\n setSessionAttributesFromOptions(options) {\n const person = options.person || options.payload?.person;\n if (person) {\n this.setSessionUser(person);\n }\n const code_version =\n options.client?.javascript?.code_version ||\n options.codeVersion ||\n options.code_version ||\n options.payload?.client?.javascript?.code_version ||\n options.payload?.code_version ||\n options.payload?.codeVersion;\n this.setSessionAttributes({\n 'rollbar.codeVersion': code_version,\n 'rollbar.notifier.name': 'rollbar-browser-js',\n 'rollbar.notifier.version': options.version,\n });\n }\n\n // The following two methods are used internally and are not meant for public use\n captureDomContentLoaded(e, ts) {\n if (!ts) {\n ts = new Date();\n }\n return this.client.captureDomContentLoaded(ts);\n }\n\n captureLoad(e, ts) {\n if (!ts) {\n ts = new Date();\n }\n return this.client.captureLoad(ts);\n }\n\n loadFull() {\n logger.info(\n 'Unexpected Rollbar.loadFull() called on a Notifier instance. This can happen when Rollbar is loaded multiple times.',\n );\n }\n\n _createItem(args) {\n return _.createItem(args, logger, this);\n }\n\n // Static version of instance methods support the legacy pattern of a\n // global `Rollbar` instance, where after calling `Rollbar.init()`,\n // `Rollbar` can be used as if it were an instance.\n // If support for this pattern is dropped, these static methods can be removed.\n static callInstance(method, args) {\n if (!_instance) {\n const message = 'Rollbar is not initialized';\n logger.error(message);\n const maybeCallback = _getFirstFunction(args);\n if (maybeCallback) {\n maybeCallback(new Error(message));\n }\n return;\n }\n return _instance[method].apply(_instance, args);\n }\n\n static global = (...args) => Rollbar.callInstance('global', args);\n static configure = (...args) => Rollbar.callInstance('configure', args);\n static lastError = (...args) => Rollbar.callInstance('lastError', args);\n static log = (...args) => Rollbar.callInstance('log', args);\n static debug = (...args) => Rollbar.callInstance('debug', args);\n static info = (...args) => Rollbar.callInstance('info', args);\n static warn = (...args) => Rollbar.callInstance('warn', args);\n static warning = (...args) => Rollbar.callInstance('warning', args);\n static error = (...args) => Rollbar.callInstance('error', args);\n static critical = (...args) => Rollbar.callInstance('critical', args);\n static buildJsonPayload = (...args) =>\n Rollbar.callInstance('buildJsonPayload', args);\n static sendJsonPayload = (...args) =>\n Rollbar.callInstance('sendJsonPayload', args);\n static wrap = (...args) => Rollbar.callInstance('wrap', args);\n static captureEvent = (...args) => Rollbar.callInstance('captureEvent', args);\n}\n\n/* Internal */\n\nfunction addTransformsToNotifier(notifier, rollbar, gWindow) {\n notifier\n .addTransform(transforms.handleDomException)\n .addTransform(transforms.handleItemWithError)\n .addTransform(transforms.ensureItemHasSomethingToSay)\n .addTransform(transforms.addBaseInfo)\n .addTransform(transforms.addRequestInfo(gWindow))\n .addTransform(transforms.addClientInfo(gWindow))\n .addTransform(transforms.addPluginInfo(gWindow))\n .addTransform(transforms.addBody)\n .addTransform(sharedTransforms.addMessageWithError)\n .addTransform(sharedTransforms.addTelemetryData)\n .addTransform(sharedTransforms.addConfigToPayload)\n .addTransform(transforms.addScrubber(rollbar.scrub))\n .addTransform(sharedTransforms.addPayloadOptions)\n .addTransform(sharedTransforms.userTransform(logger))\n .addTransform(sharedTransforms.addConfiguredOptions)\n .addTransform(sharedTransforms.addDiagnosticKeys)\n .addTransform(sharedTransforms.itemToPayload);\n}\n\nfunction addPredicatesToQueue(queue) {\n queue\n .addPredicate(sharedPredicates.checkLevel)\n .addPredicate(predicates.checkIgnore)\n .addPredicate(sharedPredicates.userCheckIgnore(logger))\n .addPredicate(sharedPredicates.urlIsNotBlockListed(logger))\n .addPredicate(sharedPredicates.urlIsSafeListed(logger))\n .addPredicate(sharedPredicates.messageIsIgnored(logger));\n}\n\nfunction _getFirstFunction(args) {\n for (var i = 0, len = args.length; i < len; ++i) {\n if (_.isFunction(args[i])) {\n return args[i];\n }\n }\n return undefined;\n}\n\nfunction _gWindow() {\n return (\n (typeof window !== 'undefined' && window) ||\n (typeof self !== 'undefined' && self)\n );\n}\n\nconst defaultOptions = {\n environment: 'unknown',\n version: defaults.version,\n scrubFields: browserDefaults.scrubFields,\n logLevel: defaults.logLevel,\n reportLevel: defaults.reportLevel,\n uncaughtErrorLevel: defaults.uncaughtErrorLevel,\n endpoint: defaults.endpoint,\n verbose: false,\n enabled: true,\n transmit: true,\n sendConfig: false,\n includeItemsInTelemetry: true,\n captureIp: true,\n inspectAnonymousErrors: true,\n ignoreDuplicateErrors: true,\n wrapGlobalEventHandlers: false,\n replay: replayDefaults,\n tracing: tracingDefaults,\n};\n\nexport default Rollbar;\n", "import { hasOwn } from '../utility.js';\n\n/*\n * headers - Detect when fetch Headers are undefined and use a partial polyfill.\n *\n * A full polyfill is not used in order to keep package size as small as possible.\n * Since this is only used internally and is not added to the window object,\n * the full interface doesn't need to be supported.\n *\n * This implementation is modified from whatwg-fetch:\n * https://github.com/github/fetch\n */\nfunction headers(headers) {\n if (typeof Headers === 'undefined') {\n return new FetchHeaders(headers);\n }\n\n return new Headers(headers);\n}\n\nfunction normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name);\n }\n return name.toLowerCase();\n}\n\nfunction normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value);\n }\n return value;\n}\n\nfunction iteratorFor(items) {\n var iterator = {\n next: function () {\n var value = items.shift();\n return { done: value === undefined, value: value };\n },\n };\n\n return iterator;\n}\n\nfunction FetchHeaders(headers) {\n this.map = {};\n\n if (headers instanceof FetchHeaders) {\n headers.forEach(function (value, name) {\n this.append(name, value);\n }, this);\n } else if (Array.isArray(headers)) {\n headers.forEach(function (header) {\n this.append(header[0], header[1]);\n }, this);\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function (name) {\n this.append(name, headers[name]);\n }, this);\n }\n}\n\nFetchHeaders.prototype.append = function (name, value) {\n name = normalizeName(name);\n value = normalizeValue(value);\n var oldValue = this.map[name];\n this.map[name] = oldValue ? oldValue + ', ' + value : value;\n};\n\nFetchHeaders.prototype.get = function (name) {\n name = normalizeName(name);\n return this.has(name) ? this.map[name] : null;\n};\n\nFetchHeaders.prototype.has = function (name) {\n return hasOwn(this.map, normalizeName(name));\n};\n\nFetchHeaders.prototype.forEach = function (callback, thisArg) {\n for (var name in this.map) {\n if (hasOwn(this.map, name)) {\n callback.call(thisArg, this.map[name], name, this);\n }\n }\n};\n\nFetchHeaders.prototype.entries = function () {\n var items = [];\n this.forEach(function (value, name) {\n items.push([name, value]);\n });\n return iteratorFor(items);\n};\n\nexport default headers;\n", "function replace(obj, name, replacement, replacements, type) {\n var orig = obj[name];\n obj[name] = replacement(orig);\n if (replacements) {\n replacements[type].push([obj, name, orig]);\n }\n}\n\nexport default replace;\n", "function getElementType(e) {\n return (e.getAttribute('type') || '').toLowerCase();\n}\n\nfunction isDescribedElement(element, type, subtypes) {\n if (element.tagName.toLowerCase() !== type.toLowerCase()) {\n return false;\n }\n if (!subtypes) {\n return true;\n }\n const elementType = getElementType(element);\n for (const subtype of subtypes) {\n if (subtype === elementType) {\n return true;\n }\n }\n return false;\n}\n\nfunction getElementFromEvent(evt, doc) {\n if (evt.target) {\n return evt.target;\n }\n if (doc && doc.elementFromPoint) {\n return doc.elementFromPoint(evt.clientX, evt.clientY);\n }\n return undefined;\n}\n\nfunction treeToArray(elem) {\n var MAX_HEIGHT = 5;\n var out = [];\n var nextDescription;\n for (var height = 0; elem && height < MAX_HEIGHT; height++) {\n nextDescription = describeElement(elem);\n if (!nextDescription || nextDescription.tagName === 'html') {\n break;\n }\n out.unshift(nextDescription);\n elem = elem.parentNode;\n }\n return out;\n}\n\nfunction elementArrayToString(a) {\n var MAX_LENGTH = 80;\n var separator = ' > ',\n separatorLength = separator.length;\n var out = [],\n len = 0,\n nextStr,\n totalLength;\n\n for (var i = a.length - 1; i >= 0; i--) {\n nextStr = descriptionToString(a[i]);\n totalLength = len + out.length * separatorLength + nextStr.length;\n if (i < a.length - 1 && totalLength >= MAX_LENGTH + 3) {\n out.unshift('...');\n break;\n }\n out.unshift(nextStr);\n len += nextStr.length;\n }\n return out.join(separator);\n}\n\nfunction elementString(elem) {\n return elementArrayToString(treeToArray(elem));\n}\n\nfunction descriptionToString(desc) {\n if (!desc || !desc.tagName) {\n return '';\n }\n var out = [desc.tagName];\n if (desc.id) {\n out.push('#' + desc.id);\n }\n if (desc.classes) {\n out.push('.' + desc.classes.join('.'));\n }\n for (const attribute of desc.attributes) {\n out.push('[' + attribute.key + '=\"' + attribute.value + '\"]');\n }\n\n return out.join('');\n}\n\n/**\n * Input: a dom element\n * Output: null if tagName is falsey or input is falsey, else\n * {\n * tagName: String,\n * id: String | undefined,\n * classes: [String] | undefined,\n * attributes: [\n * {\n * key: OneOf(type, name, title, alt),\n * value: String\n * }\n * ]\n * }\n */\nfunction describeElement(elem) {\n if (!elem || !elem.tagName) {\n return null;\n }\n var out = {},\n className;\n out.tagName = elem.tagName.toLowerCase();\n if (elem.id) {\n out.id = elem.id;\n }\n className = elem.className;\n if (className && typeof className === 'string') {\n out.classes = className.split(/\\s+/);\n }\n var attributes = ['type', 'name', 'title', 'alt'];\n out.attributes = [];\n for (const attribute of attributes) {\n const attr = elem.getAttribute(attribute);\n if (attr) {\n out.attributes.push({ key: attribute, value: attr });\n }\n }\n return out;\n}\n\n/*\n * Detects if the given element matches any of the given class names (string or regex),\n * or CSS selectors.\n * @param {HTMLElement} element - The DOM element to check.\n * @param {Array} classes - An array of class names (string or regex) to match against.\n * @param {Array} selectors - An array of CSS selectors to match against.\n * @return {boolean} - True if the element matches any of the classes or selectors, false otherwise.\n */\nfunction isMatchingElement(element, classes, selectors) {\n try {\n for (const cls of classes) {\n if (typeof cls === 'string') {\n if (element.classList.contains(cls)) {\n return true;\n }\n } else {\n for (const c of element.classList) {\n if (cls.test(c)) {\n return true;\n }\n }\n }\n }\n for (const sel of selectors) {\n if (element.matches(sel)) {\n return true;\n }\n }\n } catch (_e) {\n // ignore errors from invalid arguments\n }\n return false;\n}\n\nexport {\n describeElement,\n descriptionToString,\n elementArrayToString,\n elementString,\n treeToArray,\n getElementFromEvent,\n isDescribedElement,\n getElementType,\n isMatchingElement,\n};\n", "/* eslint-disable @typescript-eslint/no-this-alias */\n// TODO(matux): refactor to remove no-this-alias disable\n\nimport logger from '../logger.js';\nimport scrub from '../scrub.js';\nimport headers from '../utility/headers.js';\nimport replace from '../utility/replace.js';\nimport * as _ from '../utility.js';\n\nimport * as domUtil from './domUtility.js';\nimport * as urlparser from './url.js';\n\nconst defaults = {\n network: true,\n networkResponseHeaders: false,\n networkResponseBody: false,\n networkRequestHeaders: false,\n networkRequestBody: false,\n networkErrorOnHttp5xx: false,\n networkErrorOnHttp4xx: false,\n networkErrorOnHttp0: false,\n log: true,\n dom: true,\n navigation: true,\n connectivity: true,\n contentSecurityPolicy: true,\n errorOnContentSecurityPolicy: false,\n};\n\nfunction restore(replacements, type) {\n let b;\n while (replacements[type].length) {\n b = replacements[type].shift();\n b[0][b[1]] = b[2];\n }\n}\n\nfunction nameFromDescription(description) {\n if (!description || !description.attributes) {\n return null;\n }\n const attrs = description.attributes;\n for (const a of attrs) {\n if (a.key === 'name') {\n return a.value;\n }\n }\n return null;\n}\n\nfunction defaultValueScrubber(scrubFields) {\n const patterns = [];\n for (const field of scrubFields) {\n patterns.push(new RegExp(field, 'i'));\n }\n return function (description) {\n const name = nameFromDescription(description);\n if (!name) {\n return false;\n }\n for (const p of patterns) {\n if (p.test(name)) {\n return true;\n }\n }\n return false;\n };\n}\n\nclass Instrumenter {\n constructor(options, telemeter, rollbar, _window, _document) {\n this.options = options;\n let autoInstrument = options.autoInstrument;\n if (options.enabled === false || autoInstrument === false) {\n this.autoInstrument = {};\n } else {\n if (!_.isType(autoInstrument, 'object')) {\n autoInstrument = defaults;\n }\n this.autoInstrument = _.merge(defaults, autoInstrument);\n }\n this.configureScrubbing();\n this.telemeter = telemeter;\n this.rollbar = rollbar;\n this.diagnostic = rollbar.client.notifier.diagnostic;\n this._window = _window || {};\n this._document = _document || {};\n this.replacements = {\n network: [],\n log: [],\n navigation: [],\n connectivity: [],\n };\n this.eventRemovers = {\n dom: [],\n connectivity: [],\n contentsecuritypolicy: [],\n };\n\n this._location = this._window.location;\n this._lastHref = this._location && this._location.href;\n }\n\n configureScrubbing() {\n const options = this.options;\n this.scrubTelemetryInputs = Boolean(\n options.scrubTelemetryInputs ?? options.replay?.maskAllInputs,\n );\n this.telemetryScrubber = options.telemetryScrubber;\n this.defaultValueScrubber = defaultValueScrubber(options.scrubFields);\n this.maskInputFn = options.replay?.maskInputFn;\n this.maskInputOptions = options.replay?.maskInputOptions || {};\n this.scrubClasses = [\n options.replay?.blockClass,\n options.replay?.ignoreClass,\n options.replay?.maskTextClass,\n ].filter(Boolean);\n this.scrubSelectors = [\n options.replay?.blockSelector,\n options.replay?.ignoreSelector,\n options.replay?.maskTextSelector,\n ].filter(Boolean);\n }\n\n configure(options) {\n this.options = _.merge(this.options, options);\n let autoInstrument = options.autoInstrument;\n const oldSettings = _.merge(this.autoInstrument);\n if (options.enabled === false || autoInstrument === false) {\n this.autoInstrument = {};\n } else {\n if (!_.isType(autoInstrument, 'object')) {\n autoInstrument = defaults;\n }\n this.autoInstrument = _.merge(defaults, autoInstrument);\n }\n this.configureScrubbing();\n this.instrument(oldSettings);\n }\n\n // eslint-disable-next-line complexity\n instrument(oldSettings) {\n if (this.autoInstrument.network && !(oldSettings && oldSettings.network)) {\n this.instrumentNetwork();\n } else if (\n !this.autoInstrument.network &&\n oldSettings &&\n oldSettings.network\n ) {\n this.deinstrumentNetwork();\n }\n\n if (this.autoInstrument.log && !(oldSettings && oldSettings.log)) {\n this.instrumentConsole();\n } else if (!this.autoInstrument.log && oldSettings && oldSettings.log) {\n this.deinstrumentConsole();\n }\n\n if (this.autoInstrument.dom && !(oldSettings && oldSettings.dom)) {\n this.instrumentDom();\n } else if (!this.autoInstrument.dom && oldSettings && oldSettings.dom) {\n this.deinstrumentDom();\n }\n\n if (\n this.autoInstrument.navigation &&\n !(oldSettings && oldSettings.navigation)\n ) {\n this.instrumentNavigation();\n } else if (\n !this.autoInstrument.navigation &&\n oldSettings &&\n oldSettings.navigation\n ) {\n this.deinstrumentNavigation();\n }\n\n if (\n this.autoInstrument.connectivity &&\n !(oldSettings && oldSettings.connectivity)\n ) {\n this.instrumentConnectivity();\n } else if (\n !this.autoInstrument.connectivity &&\n oldSettings &&\n oldSettings.connectivity\n ) {\n this.deinstrumentConnectivity();\n }\n\n if (\n this.autoInstrument.contentSecurityPolicy &&\n !(oldSettings && oldSettings.contentSecurityPolicy)\n ) {\n this.instrumentContentSecurityPolicy();\n } else if (\n !this.autoInstrument.contentSecurityPolicy &&\n oldSettings &&\n oldSettings.contentSecurityPolicy\n ) {\n this.deinstrumentContentSecurityPolicy();\n }\n }\n\n deinstrumentNetwork() {\n restore(this.replacements, 'network');\n }\n\n instrumentNetwork() {\n const self = this;\n\n function wrapProp(prop, xhr) {\n if (prop in xhr && _.isFunction(xhr[prop])) {\n replace(xhr, prop, function (orig) {\n return self.rollbar.wrap(orig);\n });\n }\n }\n\n if ('XMLHttpRequest' in this._window) {\n const xhrp = this._window.XMLHttpRequest.prototype;\n replace(\n xhrp,\n 'open',\n function (orig) {\n return function (method, url) {\n const isUrlObject = _isUrlObject(url);\n if (_.isType(url, 'string') || isUrlObject) {\n url = isUrlObject ? url.toString() : url;\n if (this.__rollbar_xhr) {\n this.__rollbar_xhr.method = method;\n this.__rollbar_xhr.url = url;\n this.__rollbar_xhr.status_code = null;\n this.__rollbar_xhr.start_time_ms = _.now();\n this.__rollbar_xhr.end_time_ms = null;\n } else {\n this.__rollbar_xhr = {\n method: method,\n url: url,\n status_code: null,\n start_time_ms: _.now(),\n end_time_ms: null,\n };\n }\n }\n return orig.apply(this, arguments);\n };\n },\n this.replacements,\n 'network',\n );\n\n replace(\n xhrp,\n 'setRequestHeader',\n function (orig) {\n return function (header, value) {\n // If xhr.open is async, __rollbar_xhr may not be initialized yet.\n if (!this.__rollbar_xhr) {\n this.__rollbar_xhr = {};\n }\n if (_.isType(header, 'string') && _.isType(value, 'string')) {\n if (self.autoInstrument.networkRequestHeaders) {\n if (!this.__rollbar_xhr.request_headers) {\n this.__rollbar_xhr.request_headers = {};\n }\n this.__rollbar_xhr.request_headers[header] = value;\n }\n // We want the content type even if request header telemetry is off.\n if (header.toLowerCase() === 'content-type') {\n this.__rollbar_xhr.request_content_type = value;\n }\n }\n return orig.apply(this, arguments);\n };\n },\n this.replacements,\n 'network',\n );\n\n replace(\n xhrp,\n 'send',\n function (orig) {\n return function (data) {\n const xhr = this;\n const tracing = self.rollbar?.tracing;\n if (\n _.shouldAddBaggageHeader(\n self.options,\n tracing,\n xhr.__rollbar_xhr?.url,\n )\n ) {\n try {\n xhr.setRequestHeader(\n 'baggage',\n `rollbar.session.id=${tracing.sessionId}`,\n );\n } catch (_e) {\n /* ignore errors from adding baggage header */\n }\n }\n\n function onreadystatechangeHandler() {\n if (xhr.__rollbar_xhr) {\n if (xhr.__rollbar_xhr.status_code === null) {\n xhr.__rollbar_xhr.status_code = 0;\n if (self.autoInstrument.networkRequestBody) {\n xhr.__rollbar_xhr.request = data;\n }\n xhr.__rollbar_event = self.captureNetwork(\n xhr.__rollbar_xhr,\n 'xhr',\n undefined,\n );\n }\n if (xhr.readyState < 2) {\n xhr.__rollbar_xhr.start_time_ms = _.now();\n }\n if (xhr.readyState > 3) {\n const end_time_ms = _.now();\n xhr.__rollbar_xhr.end_time_ms = end_time_ms;\n\n let headers = null;\n xhr.__rollbar_xhr.response_content_type =\n xhr.getResponseHeader('Content-Type');\n if (self.autoInstrument.networkResponseHeaders) {\n const headersConfig =\n self.autoInstrument.networkResponseHeaders;\n headers = {};\n try {\n let header;\n if (headersConfig === true) {\n const allHeaders = xhr.getAllResponseHeaders();\n if (allHeaders) {\n const arr = allHeaders.trim().split(/[\\r\\n]+/);\n let parts, value;\n for (const h of arr) {\n parts = h.split(': ');\n header = parts.shift();\n value = parts.join(': ');\n headers[header] = value;\n }\n }\n } else {\n for (const h of headersConfig) {\n headers[h] = xhr.getResponseHeader(h);\n }\n }\n } catch (_e) {\n /* we ignore the errors here that could come from different\n * browser issues with the xhr methods */\n }\n }\n let body = null;\n if (self.autoInstrument.networkResponseBody) {\n try {\n body = xhr.responseText;\n } catch (_e) {\n /* ignore errors from reading responseText */\n }\n }\n let response = null;\n if (body || headers) {\n response = {};\n if (body) {\n if (\n self.isJsonContentType(\n xhr.__rollbar_xhr.response_content_type,\n )\n ) {\n response.body = self.scrubJson(body);\n } else {\n response.body = body;\n }\n }\n if (headers) {\n response.headers = headers;\n }\n }\n if (response) {\n xhr.__rollbar_xhr.response = response;\n }\n try {\n let code = xhr.status;\n code = code === 1223 ? 204 : code;\n xhr.__rollbar_xhr.status_code = code;\n self.addOtelNetworkResponse(\n xhr.__rollbar_event,\n end_time_ms,\n code,\n );\n xhr.__rollbar_event.level =\n self.telemeter.levelFromStatus(code);\n self.errorOnHttpStatus(xhr.__rollbar_xhr);\n } catch (_e) {\n /* ignore possible exception from xhr.status */\n }\n }\n }\n }\n\n wrapProp('onload', xhr);\n wrapProp('onerror', xhr);\n wrapProp('onprogress', xhr);\n\n if (\n 'onreadystatechange' in xhr &&\n _.isFunction(xhr.onreadystatechange)\n ) {\n replace(xhr, 'onreadystatechange', function (orig) {\n return self.rollbar.wrap(\n orig,\n undefined,\n onreadystatechangeHandler,\n );\n });\n } else {\n xhr.onreadystatechange = onreadystatechangeHandler;\n }\n if (xhr.__rollbar_xhr && self.trackHttpErrors()) {\n xhr.__rollbar_xhr.stack = new Error().stack;\n }\n return orig.apply(this, arguments);\n };\n },\n this.replacements,\n 'network',\n );\n }\n\n if ('fetch' in this._window) {\n replace(\n this._window,\n 'fetch',\n function (orig) {\n return function (_fn, _t) {\n const args = [...arguments];\n const input = args[0];\n let method = 'GET';\n let url;\n const isUrlObject = _isUrlObject(input);\n if (_.isType(input, 'string') || isUrlObject) {\n url = isUrlObject ? input.toString() : input;\n } else if (input) {\n url = input.url;\n if (input.method) {\n method = input.method;\n }\n }\n if (args[1] && args[1].method) {\n method = args[1].method;\n }\n const tracing = self.rollbar?.tracing;\n if (_.shouldAddBaggageHeader(self.options, tracing, url)) {\n const headers = {\n baggage: `rollbar.session.id=${tracing.sessionId}`,\n };\n\n _.addHeadersToFetch(args, headers);\n }\n const metadata = {\n method: method,\n url: url,\n status_code: null,\n start_time_ms: _.now(),\n end_time_ms: null,\n };\n if (args[1] && args[1].headers) {\n // Argument may be a Headers object, or plain object. Ensure here that\n // we are working with a Headers object with case-insensitive keys.\n const reqHeaders = headers(args[1].headers);\n\n metadata.request_content_type = reqHeaders.get('Content-Type');\n\n if (self.autoInstrument.networkRequestHeaders) {\n metadata.request_headers = self.fetchHeaders(\n reqHeaders,\n self.autoInstrument.networkRequestHeaders,\n );\n }\n }\n\n if (self.autoInstrument.networkRequestBody) {\n if (args[1] && args[1].body) {\n metadata.request = args[1].body;\n } else if (\n args[0] &&\n !_.isType(args[0], 'string') &&\n args[0].body\n ) {\n metadata.request = args[0].body;\n }\n }\n const telemetryEvent = self.captureNetwork(\n metadata,\n 'fetch',\n undefined,\n );\n if (self.trackHttpErrors()) {\n metadata.stack = new Error().stack;\n }\n\n // Start our handler before returning the promise. This allows resp.clone()\n // to execute before other handlers touch the response.\n return orig.apply(this, args).then(function (resp) {\n const end_time_ms = _.now();\n metadata.end_time_ms = end_time_ms;\n metadata.status_code = resp.status;\n self.addOtelNetworkResponse(\n telemetryEvent,\n end_time_ms,\n resp.status,\n );\n\n metadata.response_content_type = resp.headers.get('Content-Type');\n let headers = null;\n if (self.autoInstrument.networkResponseHeaders) {\n headers = self.fetchHeaders(\n resp.headers,\n self.autoInstrument.networkResponseHeaders,\n );\n }\n let body = null;\n if (self.autoInstrument.networkResponseBody) {\n if (typeof resp.text === 'function') {\n // Response.text() is not implemented on some platforms\n // The response must be cloned to prevent reading (and locking) the original stream.\n // This must be done before other handlers touch the response.\n body = resp.clone().text(); //returns a Promise\n }\n }\n if (headers || body) {\n metadata.response = {};\n if (body) {\n // Test to ensure body is a Promise, which it should always be.\n if (typeof body.then === 'function') {\n body.then(function (text) {\n if (\n text &&\n self.isJsonContentType(metadata.response_content_type)\n ) {\n metadata.response.body = self.scrubJson(text);\n } else {\n metadata.response.body = text;\n }\n });\n } else {\n metadata.response.body = body;\n }\n }\n if (headers) {\n metadata.response.headers = headers;\n }\n }\n self.errorOnHttpStatus(metadata);\n return resp;\n });\n };\n },\n this.replacements,\n 'network',\n );\n }\n }\n\n captureNetwork(metadata, subtype, rollbarUUID) {\n if (\n metadata.request &&\n this.isJsonContentType(metadata.request_content_type)\n ) {\n metadata.request = this.scrubJson(metadata.request);\n }\n return this.telemeter.captureNetwork(metadata, subtype, rollbarUUID);\n }\n\n isJsonContentType(contentType) {\n return contentType &&\n _.isType(contentType, 'string') &&\n contentType.toLowerCase().includes('json')\n ? true\n : false;\n }\n\n addOtelNetworkResponse(event, endTimeMs, statusCode) {\n if (event.otelAttributes) {\n event.otelAttributes['response.timeUnixNano'] = (\n endTimeMs * 1e6\n ).toString();\n event.otelAttributes.statusCode = statusCode;\n }\n }\n\n scrubJson(json) {\n return JSON.stringify(scrub(JSON.parse(json), this.options.scrubFields));\n }\n\n fetchHeaders(inHeaders, headersConfig) {\n const outHeaders = {};\n try {\n if (headersConfig === true) {\n if (typeof inHeaders.entries === 'function') {\n // Headers.entries() is not implemented in IE\n const allHeaders = inHeaders.entries();\n let currentHeader = allHeaders.next();\n while (!currentHeader.done) {\n outHeaders[currentHeader.value[0]] = currentHeader.value[1];\n currentHeader = allHeaders.next();\n }\n }\n } else {\n for (const h of headersConfig) {\n outHeaders[h] = inHeaders.get(h);\n }\n }\n } catch (_e) {\n /* ignore probable IE errors */\n }\n return outHeaders;\n }\n\n trackHttpErrors() {\n return (\n this.autoInstrument.networkErrorOnHttp5xx ||\n this.autoInstrument.networkErrorOnHttp4xx ||\n this.autoInstrument.networkErrorOnHttp0\n );\n }\n\n errorOnHttpStatus(metadata) {\n const status = metadata.status_code;\n\n if (\n (status >= 500 && this.autoInstrument.networkErrorOnHttp5xx) ||\n (status >= 400 && this.autoInstrument.networkErrorOnHttp4xx) ||\n (status === 0 && this.autoInstrument.networkErrorOnHttp0)\n ) {\n const error = new Error('HTTP request failed with Status ' + status);\n error.stack = metadata.stack;\n this.rollbar.error(error, { skipFrames: 1 });\n }\n }\n\n deinstrumentConsole() {\n let b;\n while (this.replacements['log'].length) {\n b = this.replacements['log'].shift();\n this._window.console[b[0]] = b[1];\n }\n }\n\n instrumentConsole() {\n if (!this._window?.console?.log) {\n return;\n }\n\n const self = this;\n const c = this._window.console;\n\n function wrapConsole(method) {\n // eslint-disable-next-line strict\n 'use strict'; // See https://github.com/rollbar/rollbar.js/pull/778\n\n const orig = c[method];\n const origConsole = c;\n const level = method === 'warn' ? 'warning' : method;\n c[method] = function () {\n const args = Array.prototype.slice.call(arguments);\n const message = _.formatArgsAsString(args);\n self.telemeter.captureLog(message, level, null, _.now());\n if (orig) {\n Function.prototype.apply.call(orig, origConsole, args);\n }\n };\n self.replacements['log'].push([method, orig]);\n }\n const methods = ['debug', 'info', 'warn', 'error', 'log'];\n try {\n for (const m of methods) {\n wrapConsole(m);\n }\n } catch (e) {\n this.diagnostic.instrumentConsole = { error: e.message };\n }\n }\n\n deinstrumentDom() {\n this.removeListeners('dom');\n }\n\n instrumentDom() {\n this.addListener(\n 'dom',\n this._window,\n ['click', 'dblclick', 'contextmenu'],\n (e) => this.handleEvent('click', e),\n );\n this.addListener(\n 'dom',\n this._window,\n ['dragstart', 'dragend', 'dragenter', 'dragleave', 'drop'],\n (e) => this.handleEvent('dragdrop', e),\n );\n this.addListener('dom', this._window, ['blur', 'focus'], (e) =>\n this.handleEvent('focus', e),\n );\n this.addListener('dom', this._window, ['submit', 'invalid'], (e) =>\n this.handleEvent('form', e),\n );\n this.addListener('dom', this._window, ['input', 'change'], (e) =>\n this.handleEvent('input', e),\n );\n this.addListener('dom', this._window, ['resize'], (e) =>\n this.handleEvent('resize', e),\n );\n this.addListener('dom', this._document, ['DOMContentLoaded'], (e) =>\n this.handleEvent('contentLoaded', e),\n );\n }\n\n handleEvent(name, evt) {\n try {\n return {\n click: this.handleClick,\n dragdrop: this.handleDrag,\n focus: this.handleFocus,\n form: this.handleForm,\n input: this.handleInput,\n resize: this.handleResize,\n contentLoaded: this.handleContentLoaded,\n }[name].call(this, evt);\n } catch (exc) {\n logger.log(`${name} handler error`, evt, exc, exc.stack);\n }\n }\n\n handleContentLoaded(_evt) {\n this.rollbar.triggerReplay({\n type: 'navigation',\n path: new URL(this._location.href).pathname,\n });\n }\n\n handleClick(evt) {\n const tagName = evt.target?.tagName.toLowerCase();\n if (['input', 'select', 'textarea'].includes(tagName)) return;\n\n this.telemeter.captureClick({\n type: evt.type,\n isSynthetic: !evt.isTrusted,\n element: domUtil.elementString(evt.target),\n timestamp: _.now(),\n });\n }\n\n handleFocus(evt) {\n const type = evt.type;\n const element = evt.target?.window\n ? 'window'\n : domUtil.elementString(evt.target);\n\n this.telemeter.captureFocus({\n type: type,\n isSynthetic: !evt.isTrusted,\n element,\n timestamp: _.now(),\n });\n }\n\n handleForm(_evt) {\n // TODO: implement form event handling\n //const type = evt.type;\n //const elementString = evt.target?.window\n // ? 'window'\n // : domUtil.elementString(evt.target);\n }\n\n handleResize(evt) {\n const textZoomRatio = window.screen.width / window.innerWidth;\n\n this.telemeter.captureResize({\n type: evt.type,\n isSynthetic: !evt.isTrusted,\n width: window.innerWidth,\n height: window.innerHeight,\n textZoomRatio: textZoomRatio,\n timestamp: _.now(),\n });\n }\n\n handleDrag(evt) {\n const type = evt.type;\n let kinds, mediaTypes, dropEffect, effectAllowed;\n\n if (type === 'drop') {\n kinds = [];\n mediaTypes = [];\n const objs = [...evt.dataTransfer.files, ...evt.dataTransfer.items];\n for (const o of objs) {\n if (o.kind && o.type) {\n kinds.push(o.kind);\n mediaTypes.push(o.type);\n }\n }\n }\n if (['drop', 'dragstart'].includes(type)) {\n dropEffect = evt.dataTransfer?.dropEffect;\n effectAllowed = evt.dataTransfer?.effectAllowed;\n }\n\n this.telemeter.captureDragDrop({\n type,\n isSynthetic: !evt.isTrusted,\n element: domUtil.elementString(evt.target),\n dropEffect: dropEffect,\n effectAllowed: effectAllowed,\n kinds: JSON.stringify(kinds),\n mediaTypes: JSON.stringify(mediaTypes),\n timestamp: _.now(),\n });\n }\n\n /*\n * Applies Rollbar telemetry scrubbing options to the dom input value.\n * When replay options are present, applies those as well.\n */\n scrubInputValue(value, element, tagName, inputType) {\n const mask = '******';\n\n if (inputType === 'password') {\n return mask;\n }\n\n if (this.scrubTelemetryInputs) {\n return mask;\n } else {\n const description = domUtil.describeElement(element);\n if (this.telemetryScrubber) {\n if (this.telemetryScrubber(description)) {\n return mask;\n }\n } else if (this.defaultValueScrubber(description)) {\n return mask;\n }\n }\n\n // Apply replay options regardless of other scrubbing\n if (\n domUtil.isMatchingElement(element, this.scrubClasses, this.scrubSelectors)\n ) {\n return mask;\n }\n\n // This check is last since maskInputFn returns a modified value rather\n // than a boolean, which would cause an early return even if the value\n // was not scrubbed.\n if (\n this.maskInputOptions[tagName.toLowerCase()] ||\n this.maskInputOptions[inputType]\n ) {\n if (this.maskInputFn) {\n return this.maskInputFn(value, element);\n } else {\n return mask;\n }\n }\n\n return value;\n }\n\n /*\n * Uses the `input` event for everything except radio and checkbox inputs.\n * For those, it uses the `change` event.\n */\n handleInput(evt) {\n const type = evt.type;\n const tagName = evt.target?.tagName.toLowerCase();\n let value = evt.target?.value;\n let inputType = evt.target?.attributes?.type?.value || evt.target?.type;\n\n if (value !== undefined) {\n value = this.scrubInputValue(value, evt.target, tagName, inputType);\n }\n\n switch (type) {\n case 'input':\n if (['radio', 'checkbox'].includes(inputType)) return;\n if (['select', 'textarea'].includes(tagName)) {\n inputType = tagName;\n }\n break;\n\n case 'change':\n if (!['radio', 'checkbox'].includes(inputType)) return;\n if (inputType === 'checkbox') {\n value = evt.target?.checked;\n }\n break;\n }\n\n this.telemeter.captureInput({\n type: inputType,\n isSynthetic: !evt.isTrusted,\n element: domUtil.elementString(evt.target),\n value,\n timestamp: _.now(),\n });\n }\n\n deinstrumentNavigation() {\n const chrome = this._window.chrome;\n const chromePackagedApp = chrome && chrome.app && chrome.app.runtime;\n // See https://github.com/angular/angular.js/pull/13945/files\n const hasPushState =\n !chromePackagedApp &&\n this._window.history &&\n this._window.history.pushState;\n if (!hasPushState) {\n return;\n }\n restore(this.replacements, 'navigation');\n }\n\n instrumentNavigation() {\n const chrome = this._window.chrome;\n const chromePackagedApp = chrome && chrome.app && chrome.app.runtime;\n // See https://github.com/angular/angular.js/pull/13945/files\n const hasPushState =\n !chromePackagedApp &&\n this._window.history &&\n this._window.history.pushState;\n if (!hasPushState) {\n return;\n }\n const self = this;\n replace(\n this._window,\n 'onpopstate',\n function (orig) {\n return function () {\n const current = self._location.href;\n self.handleUrlChange(self._lastHref, current);\n if (orig) {\n orig.apply(this, arguments);\n }\n };\n },\n this.replacements,\n 'navigation',\n );\n\n replace(\n this._window.history,\n 'pushState',\n function (orig) {\n return function () {\n const url = arguments.length > 2 ? arguments[2] : undefined;\n if (url) {\n self.handleUrlChange(self._lastHref, String(url));\n }\n return orig.apply(this, arguments);\n };\n },\n this.replacements,\n 'navigation',\n );\n }\n\n handleUrlChange(from, to) {\n const parsedHref = urlparser.parse(this._location.href);\n const parsedTo = urlparser.parse(to);\n const parsedFrom = urlparser.parse(from);\n this._lastHref = to;\n if (\n parsedHref.protocol === parsedTo.protocol &&\n parsedHref.host === parsedTo.host\n ) {\n to = parsedTo.path + (parsedTo.hash || '');\n }\n if (\n parsedHref.protocol === parsedFrom.protocol &&\n parsedHref.host === parsedFrom.host\n ) {\n from = parsedFrom.path + (parsedFrom.hash || '');\n }\n this.telemeter.captureNavigation(from, to, null, _.now());\n this.rollbar.triggerReplay({\n type: 'navigation',\n path: to,\n });\n }\n\n deinstrumentConnectivity = function () {\n this.removeListeners('connectivity');\n };\n\n instrumentConnectivity() {\n const self = this;\n this.addListener(\n 'connectivity',\n this._window,\n ['online', 'offline'],\n (evt) => self.handleConnectivity(evt),\n );\n }\n\n handleConnectivity(evt) {\n const type = evt.type;\n\n this.telemeter.captureConnectivityChange({\n type,\n isSynthetic: !evt.isTrusted,\n timestamp: _.now(),\n });\n }\n\n handleCspEvent(cspEvent) {\n let message =\n 'Security Policy Violation: ' +\n 'blockedURI: ' +\n cspEvent.blockedURI +\n ', ' +\n 'violatedDirective: ' +\n cspEvent.violatedDirective +\n ', ' +\n 'effectiveDirective: ' +\n cspEvent.effectiveDirective +\n ', ';\n\n if (cspEvent.sourceFile) {\n message +=\n 'location: ' +\n cspEvent.sourceFile +\n ', ' +\n 'line: ' +\n cspEvent.lineNumber +\n ', ' +\n 'col: ' +\n cspEvent.columnNumber +\n ', ';\n }\n\n message += 'originalPolicy: ' + cspEvent.originalPolicy;\n\n this.telemeter.captureLog(message, 'error', null, _.now());\n this.handleCspError(message);\n }\n\n handleCspError(message) {\n if (this.autoInstrument.errorOnContentSecurityPolicy) {\n this.rollbar.error(message);\n }\n }\n\n deinstrumentContentSecurityPolicy() {\n this.removeListeners('contentsecuritypolicy');\n }\n\n instrumentContentSecurityPolicy() {\n if (!('addEventListener' in this._document)) {\n return;\n }\n\n const cspHandler = this.handleCspEvent.bind(this);\n this.addListener(\n 'contentsecuritypolicy',\n this._document,\n ['securitypolicyviolation'],\n cspHandler,\n );\n }\n\n addListener(section, obj, types, handler) {\n if (obj.addEventListener) {\n for (const t of types) {\n const options = { capture: true, passive: true };\n obj.addEventListener(t, handler, options, true);\n this.eventRemovers[section].push(function () {\n obj.removeEventListener(t, handler, options);\n });\n }\n }\n }\n\n removeListeners(section) {\n let r;\n while (this.eventRemovers[section].length) {\n r = this.eventRemovers[section].shift();\n r();\n }\n }\n}\n\nfunction _isUrlObject(input) {\n return typeof URL !== 'undefined' && input instanceof URL;\n}\n\nexport default Instrumenter;\n", "import { hasOwn } from '../utility.js';\n\nfunction wrapGlobals(window, handler, shim) {\n if (!window) {\n return;\n }\n // Adapted from https://github.com/bugsnag/bugsnag-js\n var globals =\n 'EventTarget,Window,Node,ApplicationCache,AudioTrackList,ChannelMergerNode,CryptoOperation,EventSource,FileReader,HTMLUnknownElement,IDBDatabase,IDBRequest,IDBTransaction,KeyOperation,MediaController,MessagePort,ModalWindow,Notification,SVGElementInstance,Screen,TextTrack,TextTrackCue,TextTrackList,WebSocket,WebSocketWorker,Worker,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload'.split(\n ',',\n );\n var i, global;\n for (i = 0; i < globals.length; ++i) {\n global = globals[i];\n\n if (window[global] && window[global].prototype) {\n _extendListenerPrototype(handler, window[global].prototype, shim);\n }\n }\n}\n\nfunction _extendListenerPrototype(handler, prototype, shim) {\n if (hasOwn(prototype, 'addEventListener')) {\n var oldAddEventListener = prototype.addEventListener;\n while (\n oldAddEventListener._rollbarOldAdd &&\n oldAddEventListener.belongsToShim\n ) {\n oldAddEventListener = oldAddEventListener._rollbarOldAdd;\n }\n var addFn = function (event, callback, bubble) {\n oldAddEventListener.call(this, event, handler.wrap(callback), bubble);\n };\n addFn._rollbarOldAdd = oldAddEventListener;\n addFn.belongsToShim = shim;\n prototype.addEventListener = addFn;\n\n var oldRemoveEventListener = prototype.removeEventListener;\n while (\n oldRemoveEventListener._rollbarOldRemove &&\n oldRemoveEventListener.belongsToShim\n ) {\n oldRemoveEventListener = oldRemoveEventListener._rollbarOldRemove;\n }\n var removeFn = function (event, callback, bubble) {\n oldRemoveEventListener.call(\n this,\n event,\n (callback && callback._rollbar_wrapped) || callback,\n bubble,\n );\n };\n removeFn._rollbarOldRemove = oldRemoveEventListener;\n removeFn.belongsToShim = shim;\n prototype.removeEventListener = removeFn;\n }\n}\n\nexport default wrapGlobals;\n", "import scrub from '../scrub.js';\nimport Telemeter from '../telemetry.js';\nimport Tracing from '../tracing/tracing.js';\nimport truncation from '../truncation.js';\n\nimport Rollbar from './core.js';\nimport Instrumenter from './telemetry.js';\nimport wrapGlobals from './wrapGlobals.js';\n\nRollbar.setComponents({\n telemeter: Telemeter,\n instrumenter: Instrumenter,\n wrapGlobals: wrapGlobals,\n scrub: scrub,\n truncation: truncation,\n tracing: Tracing,\n});\n\nexport default Rollbar;\n", "/*\nStimulus 3.2.1\nCopyright \u00A9 2023 Basecamp, LLC\n */\nclass EventListener {\n constructor(eventTarget, eventName, eventOptions) {\n this.eventTarget = eventTarget;\n this.eventName = eventName;\n this.eventOptions = eventOptions;\n this.unorderedBindings = new Set();\n }\n connect() {\n this.eventTarget.addEventListener(this.eventName, this, this.eventOptions);\n }\n disconnect() {\n this.eventTarget.removeEventListener(this.eventName, this, this.eventOptions);\n }\n bindingConnected(binding) {\n this.unorderedBindings.add(binding);\n }\n bindingDisconnected(binding) {\n this.unorderedBindings.delete(binding);\n }\n handleEvent(event) {\n const extendedEvent = extendEvent(event);\n for (const binding of this.bindings) {\n if (extendedEvent.immediatePropagationStopped) {\n break;\n }\n else {\n binding.handleEvent(extendedEvent);\n }\n }\n }\n hasBindings() {\n return this.unorderedBindings.size > 0;\n }\n get bindings() {\n return Array.from(this.unorderedBindings).sort((left, right) => {\n const leftIndex = left.index, rightIndex = right.index;\n return leftIndex < rightIndex ? -1 : leftIndex > rightIndex ? 1 : 0;\n });\n }\n}\nfunction extendEvent(event) {\n if (\"immediatePropagationStopped\" in event) {\n return event;\n }\n else {\n const { stopImmediatePropagation } = event;\n return Object.assign(event, {\n immediatePropagationStopped: false,\n stopImmediatePropagation() {\n this.immediatePropagationStopped = true;\n stopImmediatePropagation.call(this);\n },\n });\n }\n}\n\nclass Dispatcher {\n constructor(application) {\n this.application = application;\n this.eventListenerMaps = new Map();\n this.started = false;\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.eventListeners.forEach((eventListener) => eventListener.connect());\n }\n }\n stop() {\n if (this.started) {\n this.started = false;\n this.eventListeners.forEach((eventListener) => eventListener.disconnect());\n }\n }\n get eventListeners() {\n return Array.from(this.eventListenerMaps.values()).reduce((listeners, map) => listeners.concat(Array.from(map.values())), []);\n }\n bindingConnected(binding) {\n this.fetchEventListenerForBinding(binding).bindingConnected(binding);\n }\n bindingDisconnected(binding, clearEventListeners = false) {\n this.fetchEventListenerForBinding(binding).bindingDisconnected(binding);\n if (clearEventListeners)\n this.clearEventListenersForBinding(binding);\n }\n handleError(error, message, detail = {}) {\n this.application.handleError(error, `Error ${message}`, detail);\n }\n clearEventListenersForBinding(binding) {\n const eventListener = this.fetchEventListenerForBinding(binding);\n if (!eventListener.hasBindings()) {\n eventListener.disconnect();\n this.removeMappedEventListenerFor(binding);\n }\n }\n removeMappedEventListenerFor(binding) {\n const { eventTarget, eventName, eventOptions } = binding;\n const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);\n const cacheKey = this.cacheKey(eventName, eventOptions);\n eventListenerMap.delete(cacheKey);\n if (eventListenerMap.size == 0)\n this.eventListenerMaps.delete(eventTarget);\n }\n fetchEventListenerForBinding(binding) {\n const { eventTarget, eventName, eventOptions } = binding;\n return this.fetchEventListener(eventTarget, eventName, eventOptions);\n }\n fetchEventListener(eventTarget, eventName, eventOptions) {\n const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);\n const cacheKey = this.cacheKey(eventName, eventOptions);\n let eventListener = eventListenerMap.get(cacheKey);\n if (!eventListener) {\n eventListener = this.createEventListener(eventTarget, eventName, eventOptions);\n eventListenerMap.set(cacheKey, eventListener);\n }\n return eventListener;\n }\n createEventListener(eventTarget, eventName, eventOptions) {\n const eventListener = new EventListener(eventTarget, eventName, eventOptions);\n if (this.started) {\n eventListener.connect();\n }\n return eventListener;\n }\n fetchEventListenerMapForEventTarget(eventTarget) {\n let eventListenerMap = this.eventListenerMaps.get(eventTarget);\n if (!eventListenerMap) {\n eventListenerMap = new Map();\n this.eventListenerMaps.set(eventTarget, eventListenerMap);\n }\n return eventListenerMap;\n }\n cacheKey(eventName, eventOptions) {\n const parts = [eventName];\n Object.keys(eventOptions)\n .sort()\n .forEach((key) => {\n parts.push(`${eventOptions[key] ? \"\" : \"!\"}${key}`);\n });\n return parts.join(\":\");\n }\n}\n\nconst defaultActionDescriptorFilters = {\n stop({ event, value }) {\n if (value)\n event.stopPropagation();\n return true;\n },\n prevent({ event, value }) {\n if (value)\n event.preventDefault();\n return true;\n },\n self({ event, value, element }) {\n if (value) {\n return element === event.target;\n }\n else {\n return true;\n }\n },\n};\nconst descriptorPattern = /^(?:(?:([^.]+?)\\+)?(.+?)(?:\\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;\nfunction parseActionDescriptorString(descriptorString) {\n const source = descriptorString.trim();\n const matches = source.match(descriptorPattern) || [];\n let eventName = matches[2];\n let keyFilter = matches[3];\n if (keyFilter && ![\"keydown\", \"keyup\", \"keypress\"].includes(eventName)) {\n eventName += `.${keyFilter}`;\n keyFilter = \"\";\n }\n return {\n eventTarget: parseEventTarget(matches[4]),\n eventName,\n eventOptions: matches[7] ? parseEventOptions(matches[7]) : {},\n identifier: matches[5],\n methodName: matches[6],\n keyFilter: matches[1] || keyFilter,\n };\n}\nfunction parseEventTarget(eventTargetName) {\n if (eventTargetName == \"window\") {\n return window;\n }\n else if (eventTargetName == \"document\") {\n return document;\n }\n}\nfunction parseEventOptions(eventOptions) {\n return eventOptions\n .split(\":\")\n .reduce((options, token) => Object.assign(options, { [token.replace(/^!/, \"\")]: !/^!/.test(token) }), {});\n}\nfunction stringifyEventTarget(eventTarget) {\n if (eventTarget == window) {\n return \"window\";\n }\n else if (eventTarget == document) {\n return \"document\";\n }\n}\n\nfunction camelize(value) {\n return value.replace(/(?:[_-])([a-z0-9])/g, (_, char) => char.toUpperCase());\n}\nfunction namespaceCamelize(value) {\n return camelize(value.replace(/--/g, \"-\").replace(/__/g, \"_\"));\n}\nfunction capitalize(value) {\n return value.charAt(0).toUpperCase() + value.slice(1);\n}\nfunction dasherize(value) {\n return value.replace(/([A-Z])/g, (_, char) => `-${char.toLowerCase()}`);\n}\nfunction tokenize(value) {\n return value.match(/[^\\s]+/g) || [];\n}\n\nfunction isSomething(object) {\n return object !== null && object !== undefined;\n}\nfunction hasProperty(object, property) {\n return Object.prototype.hasOwnProperty.call(object, property);\n}\n\nconst allModifiers = [\"meta\", \"ctrl\", \"alt\", \"shift\"];\nclass Action {\n constructor(element, index, descriptor, schema) {\n this.element = element;\n this.index = index;\n this.eventTarget = descriptor.eventTarget || element;\n this.eventName = descriptor.eventName || getDefaultEventNameForElement(element) || error(\"missing event name\");\n this.eventOptions = descriptor.eventOptions || {};\n this.identifier = descriptor.identifier || error(\"missing identifier\");\n this.methodName = descriptor.methodName || error(\"missing method name\");\n this.keyFilter = descriptor.keyFilter || \"\";\n this.schema = schema;\n }\n static forToken(token, schema) {\n return new this(token.element, token.index, parseActionDescriptorString(token.content), schema);\n }\n toString() {\n const eventFilter = this.keyFilter ? `.${this.keyFilter}` : \"\";\n const eventTarget = this.eventTargetName ? `@${this.eventTargetName}` : \"\";\n return `${this.eventName}${eventFilter}${eventTarget}->${this.identifier}#${this.methodName}`;\n }\n shouldIgnoreKeyboardEvent(event) {\n if (!this.keyFilter) {\n return false;\n }\n const filters = this.keyFilter.split(\"+\");\n if (this.keyFilterDissatisfied(event, filters)) {\n return true;\n }\n const standardFilter = filters.filter((key) => !allModifiers.includes(key))[0];\n if (!standardFilter) {\n return false;\n }\n if (!hasProperty(this.keyMappings, standardFilter)) {\n error(`contains unknown key filter: ${this.keyFilter}`);\n }\n return this.keyMappings[standardFilter].toLowerCase() !== event.key.toLowerCase();\n }\n shouldIgnoreMouseEvent(event) {\n if (!this.keyFilter) {\n return false;\n }\n const filters = [this.keyFilter];\n if (this.keyFilterDissatisfied(event, filters)) {\n return true;\n }\n return false;\n }\n get params() {\n const params = {};\n const pattern = new RegExp(`^data-${this.identifier}-(.+)-param$`, \"i\");\n for (const { name, value } of Array.from(this.element.attributes)) {\n const match = name.match(pattern);\n const key = match && match[1];\n if (key) {\n params[camelize(key)] = typecast(value);\n }\n }\n return params;\n }\n get eventTargetName() {\n return stringifyEventTarget(this.eventTarget);\n }\n get keyMappings() {\n return this.schema.keyMappings;\n }\n keyFilterDissatisfied(event, filters) {\n const [meta, ctrl, alt, shift] = allModifiers.map((modifier) => filters.includes(modifier));\n return event.metaKey !== meta || event.ctrlKey !== ctrl || event.altKey !== alt || event.shiftKey !== shift;\n }\n}\nconst defaultEventNames = {\n a: () => \"click\",\n button: () => \"click\",\n form: () => \"submit\",\n details: () => \"toggle\",\n input: (e) => (e.getAttribute(\"type\") == \"submit\" ? \"click\" : \"input\"),\n select: () => \"change\",\n textarea: () => \"input\",\n};\nfunction getDefaultEventNameForElement(element) {\n const tagName = element.tagName.toLowerCase();\n if (tagName in defaultEventNames) {\n return defaultEventNames[tagName](element);\n }\n}\nfunction error(message) {\n throw new Error(message);\n}\nfunction typecast(value) {\n try {\n return JSON.parse(value);\n }\n catch (o_O) {\n return value;\n }\n}\n\nclass Binding {\n constructor(context, action) {\n this.context = context;\n this.action = action;\n }\n get index() {\n return this.action.index;\n }\n get eventTarget() {\n return this.action.eventTarget;\n }\n get eventOptions() {\n return this.action.eventOptions;\n }\n get identifier() {\n return this.context.identifier;\n }\n handleEvent(event) {\n const actionEvent = this.prepareActionEvent(event);\n if (this.willBeInvokedByEvent(event) && this.applyEventModifiers(actionEvent)) {\n this.invokeWithEvent(actionEvent);\n }\n }\n get eventName() {\n return this.action.eventName;\n }\n get method() {\n const method = this.controller[this.methodName];\n if (typeof method == \"function\") {\n return method;\n }\n throw new Error(`Action \"${this.action}\" references undefined method \"${this.methodName}\"`);\n }\n applyEventModifiers(event) {\n const { element } = this.action;\n const { actionDescriptorFilters } = this.context.application;\n const { controller } = this.context;\n let passes = true;\n for (const [name, value] of Object.entries(this.eventOptions)) {\n if (name in actionDescriptorFilters) {\n const filter = actionDescriptorFilters[name];\n passes = passes && filter({ name, value, event, element, controller });\n }\n else {\n continue;\n }\n }\n return passes;\n }\n prepareActionEvent(event) {\n return Object.assign(event, { params: this.action.params });\n }\n invokeWithEvent(event) {\n const { target, currentTarget } = event;\n try {\n this.method.call(this.controller, event);\n this.context.logDebugActivity(this.methodName, { event, target, currentTarget, action: this.methodName });\n }\n catch (error) {\n const { identifier, controller, element, index } = this;\n const detail = { identifier, controller, element, index, event };\n this.context.handleError(error, `invoking action \"${this.action}\"`, detail);\n }\n }\n willBeInvokedByEvent(event) {\n const eventTarget = event.target;\n if (event instanceof KeyboardEvent && this.action.shouldIgnoreKeyboardEvent(event)) {\n return false;\n }\n if (event instanceof MouseEvent && this.action.shouldIgnoreMouseEvent(event)) {\n return false;\n }\n if (this.element === eventTarget) {\n return true;\n }\n else if (eventTarget instanceof Element && this.element.contains(eventTarget)) {\n return this.scope.containsElement(eventTarget);\n }\n else {\n return this.scope.containsElement(this.action.element);\n }\n }\n get controller() {\n return this.context.controller;\n }\n get methodName() {\n return this.action.methodName;\n }\n get element() {\n return this.scope.element;\n }\n get scope() {\n return this.context.scope;\n }\n}\n\nclass ElementObserver {\n constructor(element, delegate) {\n this.mutationObserverInit = { attributes: true, childList: true, subtree: true };\n this.element = element;\n this.started = false;\n this.delegate = delegate;\n this.elements = new Set();\n this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations));\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.mutationObserver.observe(this.element, this.mutationObserverInit);\n this.refresh();\n }\n }\n pause(callback) {\n if (this.started) {\n this.mutationObserver.disconnect();\n this.started = false;\n }\n callback();\n if (!this.started) {\n this.mutationObserver.observe(this.element, this.mutationObserverInit);\n this.started = true;\n }\n }\n stop() {\n if (this.started) {\n this.mutationObserver.takeRecords();\n this.mutationObserver.disconnect();\n this.started = false;\n }\n }\n refresh() {\n if (this.started) {\n const matches = new Set(this.matchElementsInTree());\n for (const element of Array.from(this.elements)) {\n if (!matches.has(element)) {\n this.removeElement(element);\n }\n }\n for (const element of Array.from(matches)) {\n this.addElement(element);\n }\n }\n }\n processMutations(mutations) {\n if (this.started) {\n for (const mutation of mutations) {\n this.processMutation(mutation);\n }\n }\n }\n processMutation(mutation) {\n if (mutation.type == \"attributes\") {\n this.processAttributeChange(mutation.target, mutation.attributeName);\n }\n else if (mutation.type == \"childList\") {\n this.processRemovedNodes(mutation.removedNodes);\n this.processAddedNodes(mutation.addedNodes);\n }\n }\n processAttributeChange(element, attributeName) {\n if (this.elements.has(element)) {\n if (this.delegate.elementAttributeChanged && this.matchElement(element)) {\n this.delegate.elementAttributeChanged(element, attributeName);\n }\n else {\n this.removeElement(element);\n }\n }\n else if (this.matchElement(element)) {\n this.addElement(element);\n }\n }\n processRemovedNodes(nodes) {\n for (const node of Array.from(nodes)) {\n const element = this.elementFromNode(node);\n if (element) {\n this.processTree(element, this.removeElement);\n }\n }\n }\n processAddedNodes(nodes) {\n for (const node of Array.from(nodes)) {\n const element = this.elementFromNode(node);\n if (element && this.elementIsActive(element)) {\n this.processTree(element, this.addElement);\n }\n }\n }\n matchElement(element) {\n return this.delegate.matchElement(element);\n }\n matchElementsInTree(tree = this.element) {\n return this.delegate.matchElementsInTree(tree);\n }\n processTree(tree, processor) {\n for (const element of this.matchElementsInTree(tree)) {\n processor.call(this, element);\n }\n }\n elementFromNode(node) {\n if (node.nodeType == Node.ELEMENT_NODE) {\n return node;\n }\n }\n elementIsActive(element) {\n if (element.isConnected != this.element.isConnected) {\n return false;\n }\n else {\n return this.element.contains(element);\n }\n }\n addElement(element) {\n if (!this.elements.has(element)) {\n if (this.elementIsActive(element)) {\n this.elements.add(element);\n if (this.delegate.elementMatched) {\n this.delegate.elementMatched(element);\n }\n }\n }\n }\n removeElement(element) {\n if (this.elements.has(element)) {\n this.elements.delete(element);\n if (this.delegate.elementUnmatched) {\n this.delegate.elementUnmatched(element);\n }\n }\n }\n}\n\nclass AttributeObserver {\n constructor(element, attributeName, delegate) {\n this.attributeName = attributeName;\n this.delegate = delegate;\n this.elementObserver = new ElementObserver(element, this);\n }\n get element() {\n return this.elementObserver.element;\n }\n get selector() {\n return `[${this.attributeName}]`;\n }\n start() {\n this.elementObserver.start();\n }\n pause(callback) {\n this.elementObserver.pause(callback);\n }\n stop() {\n this.elementObserver.stop();\n }\n refresh() {\n this.elementObserver.refresh();\n }\n get started() {\n return this.elementObserver.started;\n }\n matchElement(element) {\n return element.hasAttribute(this.attributeName);\n }\n matchElementsInTree(tree) {\n const match = this.matchElement(tree) ? [tree] : [];\n const matches = Array.from(tree.querySelectorAll(this.selector));\n return match.concat(matches);\n }\n elementMatched(element) {\n if (this.delegate.elementMatchedAttribute) {\n this.delegate.elementMatchedAttribute(element, this.attributeName);\n }\n }\n elementUnmatched(element) {\n if (this.delegate.elementUnmatchedAttribute) {\n this.delegate.elementUnmatchedAttribute(element, this.attributeName);\n }\n }\n elementAttributeChanged(element, attributeName) {\n if (this.delegate.elementAttributeValueChanged && this.attributeName == attributeName) {\n this.delegate.elementAttributeValueChanged(element, attributeName);\n }\n }\n}\n\nfunction add(map, key, value) {\n fetch(map, key).add(value);\n}\nfunction del(map, key, value) {\n fetch(map, key).delete(value);\n prune(map, key);\n}\nfunction fetch(map, key) {\n let values = map.get(key);\n if (!values) {\n values = new Set();\n map.set(key, values);\n }\n return values;\n}\nfunction prune(map, key) {\n const values = map.get(key);\n if (values != null && values.size == 0) {\n map.delete(key);\n }\n}\n\nclass Multimap {\n constructor() {\n this.valuesByKey = new Map();\n }\n get keys() {\n return Array.from(this.valuesByKey.keys());\n }\n get values() {\n const sets = Array.from(this.valuesByKey.values());\n return sets.reduce((values, set) => values.concat(Array.from(set)), []);\n }\n get size() {\n const sets = Array.from(this.valuesByKey.values());\n return sets.reduce((size, set) => size + set.size, 0);\n }\n add(key, value) {\n add(this.valuesByKey, key, value);\n }\n delete(key, value) {\n del(this.valuesByKey, key, value);\n }\n has(key, value) {\n const values = this.valuesByKey.get(key);\n return values != null && values.has(value);\n }\n hasKey(key) {\n return this.valuesByKey.has(key);\n }\n hasValue(value) {\n const sets = Array.from(this.valuesByKey.values());\n return sets.some((set) => set.has(value));\n }\n getValuesForKey(key) {\n const values = this.valuesByKey.get(key);\n return values ? Array.from(values) : [];\n }\n getKeysForValue(value) {\n return Array.from(this.valuesByKey)\n .filter(([_key, values]) => values.has(value))\n .map(([key, _values]) => key);\n }\n}\n\nclass IndexedMultimap extends Multimap {\n constructor() {\n super();\n this.keysByValue = new Map();\n }\n get values() {\n return Array.from(this.keysByValue.keys());\n }\n add(key, value) {\n super.add(key, value);\n add(this.keysByValue, value, key);\n }\n delete(key, value) {\n super.delete(key, value);\n del(this.keysByValue, value, key);\n }\n hasValue(value) {\n return this.keysByValue.has(value);\n }\n getKeysForValue(value) {\n const set = this.keysByValue.get(value);\n return set ? Array.from(set) : [];\n }\n}\n\nclass SelectorObserver {\n constructor(element, selector, delegate, details) {\n this._selector = selector;\n this.details = details;\n this.elementObserver = new ElementObserver(element, this);\n this.delegate = delegate;\n this.matchesByElement = new Multimap();\n }\n get started() {\n return this.elementObserver.started;\n }\n get selector() {\n return this._selector;\n }\n set selector(selector) {\n this._selector = selector;\n this.refresh();\n }\n start() {\n this.elementObserver.start();\n }\n pause(callback) {\n this.elementObserver.pause(callback);\n }\n stop() {\n this.elementObserver.stop();\n }\n refresh() {\n this.elementObserver.refresh();\n }\n get element() {\n return this.elementObserver.element;\n }\n matchElement(element) {\n const { selector } = this;\n if (selector) {\n const matches = element.matches(selector);\n if (this.delegate.selectorMatchElement) {\n return matches && this.delegate.selectorMatchElement(element, this.details);\n }\n return matches;\n }\n else {\n return false;\n }\n }\n matchElementsInTree(tree) {\n const { selector } = this;\n if (selector) {\n const match = this.matchElement(tree) ? [tree] : [];\n const matches = Array.from(tree.querySelectorAll(selector)).filter((match) => this.matchElement(match));\n return match.concat(matches);\n }\n else {\n return [];\n }\n }\n elementMatched(element) {\n const { selector } = this;\n if (selector) {\n this.selectorMatched(element, selector);\n }\n }\n elementUnmatched(element) {\n const selectors = this.matchesByElement.getKeysForValue(element);\n for (const selector of selectors) {\n this.selectorUnmatched(element, selector);\n }\n }\n elementAttributeChanged(element, _attributeName) {\n const { selector } = this;\n if (selector) {\n const matches = this.matchElement(element);\n const matchedBefore = this.matchesByElement.has(selector, element);\n if (matches && !matchedBefore) {\n this.selectorMatched(element, selector);\n }\n else if (!matches && matchedBefore) {\n this.selectorUnmatched(element, selector);\n }\n }\n }\n selectorMatched(element, selector) {\n this.delegate.selectorMatched(element, selector, this.details);\n this.matchesByElement.add(selector, element);\n }\n selectorUnmatched(element, selector) {\n this.delegate.selectorUnmatched(element, selector, this.details);\n this.matchesByElement.delete(selector, element);\n }\n}\n\nclass StringMapObserver {\n constructor(element, delegate) {\n this.element = element;\n this.delegate = delegate;\n this.started = false;\n this.stringMap = new Map();\n this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations));\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.mutationObserver.observe(this.element, { attributes: true, attributeOldValue: true });\n this.refresh();\n }\n }\n stop() {\n if (this.started) {\n this.mutationObserver.takeRecords();\n this.mutationObserver.disconnect();\n this.started = false;\n }\n }\n refresh() {\n if (this.started) {\n for (const attributeName of this.knownAttributeNames) {\n this.refreshAttribute(attributeName, null);\n }\n }\n }\n processMutations(mutations) {\n if (this.started) {\n for (const mutation of mutations) {\n this.processMutation(mutation);\n }\n }\n }\n processMutation(mutation) {\n const attributeName = mutation.attributeName;\n if (attributeName) {\n this.refreshAttribute(attributeName, mutation.oldValue);\n }\n }\n refreshAttribute(attributeName, oldValue) {\n const key = this.delegate.getStringMapKeyForAttribute(attributeName);\n if (key != null) {\n if (!this.stringMap.has(attributeName)) {\n this.stringMapKeyAdded(key, attributeName);\n }\n const value = this.element.getAttribute(attributeName);\n if (this.stringMap.get(attributeName) != value) {\n this.stringMapValueChanged(value, key, oldValue);\n }\n if (value == null) {\n const oldValue = this.stringMap.get(attributeName);\n this.stringMap.delete(attributeName);\n if (oldValue)\n this.stringMapKeyRemoved(key, attributeName, oldValue);\n }\n else {\n this.stringMap.set(attributeName, value);\n }\n }\n }\n stringMapKeyAdded(key, attributeName) {\n if (this.delegate.stringMapKeyAdded) {\n this.delegate.stringMapKeyAdded(key, attributeName);\n }\n }\n stringMapValueChanged(value, key, oldValue) {\n if (this.delegate.stringMapValueChanged) {\n this.delegate.stringMapValueChanged(value, key, oldValue);\n }\n }\n stringMapKeyRemoved(key, attributeName, oldValue) {\n if (this.delegate.stringMapKeyRemoved) {\n this.delegate.stringMapKeyRemoved(key, attributeName, oldValue);\n }\n }\n get knownAttributeNames() {\n return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)));\n }\n get currentAttributeNames() {\n return Array.from(this.element.attributes).map((attribute) => attribute.name);\n }\n get recordedAttributeNames() {\n return Array.from(this.stringMap.keys());\n }\n}\n\nclass TokenListObserver {\n constructor(element, attributeName, delegate) {\n this.attributeObserver = new AttributeObserver(element, attributeName, this);\n this.delegate = delegate;\n this.tokensByElement = new Multimap();\n }\n get started() {\n return this.attributeObserver.started;\n }\n start() {\n this.attributeObserver.start();\n }\n pause(callback) {\n this.attributeObserver.pause(callback);\n }\n stop() {\n this.attributeObserver.stop();\n }\n refresh() {\n this.attributeObserver.refresh();\n }\n get element() {\n return this.attributeObserver.element;\n }\n get attributeName() {\n return this.attributeObserver.attributeName;\n }\n elementMatchedAttribute(element) {\n this.tokensMatched(this.readTokensForElement(element));\n }\n elementAttributeValueChanged(element) {\n const [unmatchedTokens, matchedTokens] = this.refreshTokensForElement(element);\n this.tokensUnmatched(unmatchedTokens);\n this.tokensMatched(matchedTokens);\n }\n elementUnmatchedAttribute(element) {\n this.tokensUnmatched(this.tokensByElement.getValuesForKey(element));\n }\n tokensMatched(tokens) {\n tokens.forEach((token) => this.tokenMatched(token));\n }\n tokensUnmatched(tokens) {\n tokens.forEach((token) => this.tokenUnmatched(token));\n }\n tokenMatched(token) {\n this.delegate.tokenMatched(token);\n this.tokensByElement.add(token.element, token);\n }\n tokenUnmatched(token) {\n this.delegate.tokenUnmatched(token);\n this.tokensByElement.delete(token.element, token);\n }\n refreshTokensForElement(element) {\n const previousTokens = this.tokensByElement.getValuesForKey(element);\n const currentTokens = this.readTokensForElement(element);\n const firstDifferingIndex = zip(previousTokens, currentTokens).findIndex(([previousToken, currentToken]) => !tokensAreEqual(previousToken, currentToken));\n if (firstDifferingIndex == -1) {\n return [[], []];\n }\n else {\n return [previousTokens.slice(firstDifferingIndex), currentTokens.slice(firstDifferingIndex)];\n }\n }\n readTokensForElement(element) {\n const attributeName = this.attributeName;\n const tokenString = element.getAttribute(attributeName) || \"\";\n return parseTokenString(tokenString, element, attributeName);\n }\n}\nfunction parseTokenString(tokenString, element, attributeName) {\n return tokenString\n .trim()\n .split(/\\s+/)\n .filter((content) => content.length)\n .map((content, index) => ({ element, attributeName, content, index }));\n}\nfunction zip(left, right) {\n const length = Math.max(left.length, right.length);\n return Array.from({ length }, (_, index) => [left[index], right[index]]);\n}\nfunction tokensAreEqual(left, right) {\n return left && right && left.index == right.index && left.content == right.content;\n}\n\nclass ValueListObserver {\n constructor(element, attributeName, delegate) {\n this.tokenListObserver = new TokenListObserver(element, attributeName, this);\n this.delegate = delegate;\n this.parseResultsByToken = new WeakMap();\n this.valuesByTokenByElement = new WeakMap();\n }\n get started() {\n return this.tokenListObserver.started;\n }\n start() {\n this.tokenListObserver.start();\n }\n stop() {\n this.tokenListObserver.stop();\n }\n refresh() {\n this.tokenListObserver.refresh();\n }\n get element() {\n return this.tokenListObserver.element;\n }\n get attributeName() {\n return this.tokenListObserver.attributeName;\n }\n tokenMatched(token) {\n const { element } = token;\n const { value } = this.fetchParseResultForToken(token);\n if (value) {\n this.fetchValuesByTokenForElement(element).set(token, value);\n this.delegate.elementMatchedValue(element, value);\n }\n }\n tokenUnmatched(token) {\n const { element } = token;\n const { value } = this.fetchParseResultForToken(token);\n if (value) {\n this.fetchValuesByTokenForElement(element).delete(token);\n this.delegate.elementUnmatchedValue(element, value);\n }\n }\n fetchParseResultForToken(token) {\n let parseResult = this.parseResultsByToken.get(token);\n if (!parseResult) {\n parseResult = this.parseToken(token);\n this.parseResultsByToken.set(token, parseResult);\n }\n return parseResult;\n }\n fetchValuesByTokenForElement(element) {\n let valuesByToken = this.valuesByTokenByElement.get(element);\n if (!valuesByToken) {\n valuesByToken = new Map();\n this.valuesByTokenByElement.set(element, valuesByToken);\n }\n return valuesByToken;\n }\n parseToken(token) {\n try {\n const value = this.delegate.parseValueForToken(token);\n return { value };\n }\n catch (error) {\n return { error };\n }\n }\n}\n\nclass BindingObserver {\n constructor(context, delegate) {\n this.context = context;\n this.delegate = delegate;\n this.bindingsByAction = new Map();\n }\n start() {\n if (!this.valueListObserver) {\n this.valueListObserver = new ValueListObserver(this.element, this.actionAttribute, this);\n this.valueListObserver.start();\n }\n }\n stop() {\n if (this.valueListObserver) {\n this.valueListObserver.stop();\n delete this.valueListObserver;\n this.disconnectAllActions();\n }\n }\n get element() {\n return this.context.element;\n }\n get identifier() {\n return this.context.identifier;\n }\n get actionAttribute() {\n return this.schema.actionAttribute;\n }\n get schema() {\n return this.context.schema;\n }\n get bindings() {\n return Array.from(this.bindingsByAction.values());\n }\n connectAction(action) {\n const binding = new Binding(this.context, action);\n this.bindingsByAction.set(action, binding);\n this.delegate.bindingConnected(binding);\n }\n disconnectAction(action) {\n const binding = this.bindingsByAction.get(action);\n if (binding) {\n this.bindingsByAction.delete(action);\n this.delegate.bindingDisconnected(binding);\n }\n }\n disconnectAllActions() {\n this.bindings.forEach((binding) => this.delegate.bindingDisconnected(binding, true));\n this.bindingsByAction.clear();\n }\n parseValueForToken(token) {\n const action = Action.forToken(token, this.schema);\n if (action.identifier == this.identifier) {\n return action;\n }\n }\n elementMatchedValue(element, action) {\n this.connectAction(action);\n }\n elementUnmatchedValue(element, action) {\n this.disconnectAction(action);\n }\n}\n\nclass ValueObserver {\n constructor(context, receiver) {\n this.context = context;\n this.receiver = receiver;\n this.stringMapObserver = new StringMapObserver(this.element, this);\n this.valueDescriptorMap = this.controller.valueDescriptorMap;\n }\n start() {\n this.stringMapObserver.start();\n this.invokeChangedCallbacksForDefaultValues();\n }\n stop() {\n this.stringMapObserver.stop();\n }\n get element() {\n return this.context.element;\n }\n get controller() {\n return this.context.controller;\n }\n getStringMapKeyForAttribute(attributeName) {\n if (attributeName in this.valueDescriptorMap) {\n return this.valueDescriptorMap[attributeName].name;\n }\n }\n stringMapKeyAdded(key, attributeName) {\n const descriptor = this.valueDescriptorMap[attributeName];\n if (!this.hasValue(key)) {\n this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), descriptor.writer(descriptor.defaultValue));\n }\n }\n stringMapValueChanged(value, name, oldValue) {\n const descriptor = this.valueDescriptorNameMap[name];\n if (value === null)\n return;\n if (oldValue === null) {\n oldValue = descriptor.writer(descriptor.defaultValue);\n }\n this.invokeChangedCallback(name, value, oldValue);\n }\n stringMapKeyRemoved(key, attributeName, oldValue) {\n const descriptor = this.valueDescriptorNameMap[key];\n if (this.hasValue(key)) {\n this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), oldValue);\n }\n else {\n this.invokeChangedCallback(key, descriptor.writer(descriptor.defaultValue), oldValue);\n }\n }\n invokeChangedCallbacksForDefaultValues() {\n for (const { key, name, defaultValue, writer } of this.valueDescriptors) {\n if (defaultValue != undefined && !this.controller.data.has(key)) {\n this.invokeChangedCallback(name, writer(defaultValue), undefined);\n }\n }\n }\n invokeChangedCallback(name, rawValue, rawOldValue) {\n const changedMethodName = `${name}Changed`;\n const changedMethod = this.receiver[changedMethodName];\n if (typeof changedMethod == \"function\") {\n const descriptor = this.valueDescriptorNameMap[name];\n try {\n const value = descriptor.reader(rawValue);\n let oldValue = rawOldValue;\n if (rawOldValue) {\n oldValue = descriptor.reader(rawOldValue);\n }\n changedMethod.call(this.receiver, value, oldValue);\n }\n catch (error) {\n if (error instanceof TypeError) {\n error.message = `Stimulus Value \"${this.context.identifier}.${descriptor.name}\" - ${error.message}`;\n }\n throw error;\n }\n }\n }\n get valueDescriptors() {\n const { valueDescriptorMap } = this;\n return Object.keys(valueDescriptorMap).map((key) => valueDescriptorMap[key]);\n }\n get valueDescriptorNameMap() {\n const descriptors = {};\n Object.keys(this.valueDescriptorMap).forEach((key) => {\n const descriptor = this.valueDescriptorMap[key];\n descriptors[descriptor.name] = descriptor;\n });\n return descriptors;\n }\n hasValue(attributeName) {\n const descriptor = this.valueDescriptorNameMap[attributeName];\n const hasMethodName = `has${capitalize(descriptor.name)}`;\n return this.receiver[hasMethodName];\n }\n}\n\nclass TargetObserver {\n constructor(context, delegate) {\n this.context = context;\n this.delegate = delegate;\n this.targetsByName = new Multimap();\n }\n start() {\n if (!this.tokenListObserver) {\n this.tokenListObserver = new TokenListObserver(this.element, this.attributeName, this);\n this.tokenListObserver.start();\n }\n }\n stop() {\n if (this.tokenListObserver) {\n this.disconnectAllTargets();\n this.tokenListObserver.stop();\n delete this.tokenListObserver;\n }\n }\n tokenMatched({ element, content: name }) {\n if (this.scope.containsElement(element)) {\n this.connectTarget(element, name);\n }\n }\n tokenUnmatched({ element, content: name }) {\n this.disconnectTarget(element, name);\n }\n connectTarget(element, name) {\n var _a;\n if (!this.targetsByName.has(name, element)) {\n this.targetsByName.add(name, element);\n (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetConnected(element, name));\n }\n }\n disconnectTarget(element, name) {\n var _a;\n if (this.targetsByName.has(name, element)) {\n this.targetsByName.delete(name, element);\n (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetDisconnected(element, name));\n }\n }\n disconnectAllTargets() {\n for (const name of this.targetsByName.keys) {\n for (const element of this.targetsByName.getValuesForKey(name)) {\n this.disconnectTarget(element, name);\n }\n }\n }\n get attributeName() {\n return `data-${this.context.identifier}-target`;\n }\n get element() {\n return this.context.element;\n }\n get scope() {\n return this.context.scope;\n }\n}\n\nfunction readInheritableStaticArrayValues(constructor, propertyName) {\n const ancestors = getAncestorsForConstructor(constructor);\n return Array.from(ancestors.reduce((values, constructor) => {\n getOwnStaticArrayValues(constructor, propertyName).forEach((name) => values.add(name));\n return values;\n }, new Set()));\n}\nfunction readInheritableStaticObjectPairs(constructor, propertyName) {\n const ancestors = getAncestorsForConstructor(constructor);\n return ancestors.reduce((pairs, constructor) => {\n pairs.push(...getOwnStaticObjectPairs(constructor, propertyName));\n return pairs;\n }, []);\n}\nfunction getAncestorsForConstructor(constructor) {\n const ancestors = [];\n while (constructor) {\n ancestors.push(constructor);\n constructor = Object.getPrototypeOf(constructor);\n }\n return ancestors.reverse();\n}\nfunction getOwnStaticArrayValues(constructor, propertyName) {\n const definition = constructor[propertyName];\n return Array.isArray(definition) ? definition : [];\n}\nfunction getOwnStaticObjectPairs(constructor, propertyName) {\n const definition = constructor[propertyName];\n return definition ? Object.keys(definition).map((key) => [key, definition[key]]) : [];\n}\n\nclass OutletObserver {\n constructor(context, delegate) {\n this.started = false;\n this.context = context;\n this.delegate = delegate;\n this.outletsByName = new Multimap();\n this.outletElementsByName = new Multimap();\n this.selectorObserverMap = new Map();\n this.attributeObserverMap = new Map();\n }\n start() {\n if (!this.started) {\n this.outletDefinitions.forEach((outletName) => {\n this.setupSelectorObserverForOutlet(outletName);\n this.setupAttributeObserverForOutlet(outletName);\n });\n this.started = true;\n this.dependentContexts.forEach((context) => context.refresh());\n }\n }\n refresh() {\n this.selectorObserverMap.forEach((observer) => observer.refresh());\n this.attributeObserverMap.forEach((observer) => observer.refresh());\n }\n stop() {\n if (this.started) {\n this.started = false;\n this.disconnectAllOutlets();\n this.stopSelectorObservers();\n this.stopAttributeObservers();\n }\n }\n stopSelectorObservers() {\n if (this.selectorObserverMap.size > 0) {\n this.selectorObserverMap.forEach((observer) => observer.stop());\n this.selectorObserverMap.clear();\n }\n }\n stopAttributeObservers() {\n if (this.attributeObserverMap.size > 0) {\n this.attributeObserverMap.forEach((observer) => observer.stop());\n this.attributeObserverMap.clear();\n }\n }\n selectorMatched(element, _selector, { outletName }) {\n const outlet = this.getOutlet(element, outletName);\n if (outlet) {\n this.connectOutlet(outlet, element, outletName);\n }\n }\n selectorUnmatched(element, _selector, { outletName }) {\n const outlet = this.getOutletFromMap(element, outletName);\n if (outlet) {\n this.disconnectOutlet(outlet, element, outletName);\n }\n }\n selectorMatchElement(element, { outletName }) {\n const selector = this.selector(outletName);\n const hasOutlet = this.hasOutlet(element, outletName);\n const hasOutletController = element.matches(`[${this.schema.controllerAttribute}~=${outletName}]`);\n if (selector) {\n return hasOutlet && hasOutletController && element.matches(selector);\n }\n else {\n return false;\n }\n }\n elementMatchedAttribute(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n elementAttributeValueChanged(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n elementUnmatchedAttribute(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n connectOutlet(outlet, element, outletName) {\n var _a;\n if (!this.outletElementsByName.has(outletName, element)) {\n this.outletsByName.add(outletName, outlet);\n this.outletElementsByName.add(outletName, element);\n (_a = this.selectorObserverMap.get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletConnected(outlet, element, outletName));\n }\n }\n disconnectOutlet(outlet, element, outletName) {\n var _a;\n if (this.outletElementsByName.has(outletName, element)) {\n this.outletsByName.delete(outletName, outlet);\n this.outletElementsByName.delete(outletName, element);\n (_a = this.selectorObserverMap\n .get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletDisconnected(outlet, element, outletName));\n }\n }\n disconnectAllOutlets() {\n for (const outletName of this.outletElementsByName.keys) {\n for (const element of this.outletElementsByName.getValuesForKey(outletName)) {\n for (const outlet of this.outletsByName.getValuesForKey(outletName)) {\n this.disconnectOutlet(outlet, element, outletName);\n }\n }\n }\n }\n updateSelectorObserverForOutlet(outletName) {\n const observer = this.selectorObserverMap.get(outletName);\n if (observer) {\n observer.selector = this.selector(outletName);\n }\n }\n setupSelectorObserverForOutlet(outletName) {\n const selector = this.selector(outletName);\n const selectorObserver = new SelectorObserver(document.body, selector, this, { outletName });\n this.selectorObserverMap.set(outletName, selectorObserver);\n selectorObserver.start();\n }\n setupAttributeObserverForOutlet(outletName) {\n const attributeName = this.attributeNameForOutletName(outletName);\n const attributeObserver = new AttributeObserver(this.scope.element, attributeName, this);\n this.attributeObserverMap.set(outletName, attributeObserver);\n attributeObserver.start();\n }\n selector(outletName) {\n return this.scope.outlets.getSelectorForOutletName(outletName);\n }\n attributeNameForOutletName(outletName) {\n return this.scope.schema.outletAttributeForScope(this.identifier, outletName);\n }\n getOutletNameFromOutletAttributeName(attributeName) {\n return this.outletDefinitions.find((outletName) => this.attributeNameForOutletName(outletName) === attributeName);\n }\n get outletDependencies() {\n const dependencies = new Multimap();\n this.router.modules.forEach((module) => {\n const constructor = module.definition.controllerConstructor;\n const outlets = readInheritableStaticArrayValues(constructor, \"outlets\");\n outlets.forEach((outlet) => dependencies.add(outlet, module.identifier));\n });\n return dependencies;\n }\n get outletDefinitions() {\n return this.outletDependencies.getKeysForValue(this.identifier);\n }\n get dependentControllerIdentifiers() {\n return this.outletDependencies.getValuesForKey(this.identifier);\n }\n get dependentContexts() {\n const identifiers = this.dependentControllerIdentifiers;\n return this.router.contexts.filter((context) => identifiers.includes(context.identifier));\n }\n hasOutlet(element, outletName) {\n return !!this.getOutlet(element, outletName) || !!this.getOutletFromMap(element, outletName);\n }\n getOutlet(element, outletName) {\n return this.application.getControllerForElementAndIdentifier(element, outletName);\n }\n getOutletFromMap(element, outletName) {\n return this.outletsByName.getValuesForKey(outletName).find((outlet) => outlet.element === element);\n }\n get scope() {\n return this.context.scope;\n }\n get schema() {\n return this.context.schema;\n }\n get identifier() {\n return this.context.identifier;\n }\n get application() {\n return this.context.application;\n }\n get router() {\n return this.application.router;\n }\n}\n\nclass Context {\n constructor(module, scope) {\n this.logDebugActivity = (functionName, detail = {}) => {\n const { identifier, controller, element } = this;\n detail = Object.assign({ identifier, controller, element }, detail);\n this.application.logDebugActivity(this.identifier, functionName, detail);\n };\n this.module = module;\n this.scope = scope;\n this.controller = new module.controllerConstructor(this);\n this.bindingObserver = new BindingObserver(this, this.dispatcher);\n this.valueObserver = new ValueObserver(this, this.controller);\n this.targetObserver = new TargetObserver(this, this);\n this.outletObserver = new OutletObserver(this, this);\n try {\n this.controller.initialize();\n this.logDebugActivity(\"initialize\");\n }\n catch (error) {\n this.handleError(error, \"initializing controller\");\n }\n }\n connect() {\n this.bindingObserver.start();\n this.valueObserver.start();\n this.targetObserver.start();\n this.outletObserver.start();\n try {\n this.controller.connect();\n this.logDebugActivity(\"connect\");\n }\n catch (error) {\n this.handleError(error, \"connecting controller\");\n }\n }\n refresh() {\n this.outletObserver.refresh();\n }\n disconnect() {\n try {\n this.controller.disconnect();\n this.logDebugActivity(\"disconnect\");\n }\n catch (error) {\n this.handleError(error, \"disconnecting controller\");\n }\n this.outletObserver.stop();\n this.targetObserver.stop();\n this.valueObserver.stop();\n this.bindingObserver.stop();\n }\n get application() {\n return this.module.application;\n }\n get identifier() {\n return this.module.identifier;\n }\n get schema() {\n return this.application.schema;\n }\n get dispatcher() {\n return this.application.dispatcher;\n }\n get element() {\n return this.scope.element;\n }\n get parentElement() {\n return this.element.parentElement;\n }\n handleError(error, message, detail = {}) {\n const { identifier, controller, element } = this;\n detail = Object.assign({ identifier, controller, element }, detail);\n this.application.handleError(error, `Error ${message}`, detail);\n }\n targetConnected(element, name) {\n this.invokeControllerMethod(`${name}TargetConnected`, element);\n }\n targetDisconnected(element, name) {\n this.invokeControllerMethod(`${name}TargetDisconnected`, element);\n }\n outletConnected(outlet, element, name) {\n this.invokeControllerMethod(`${namespaceCamelize(name)}OutletConnected`, outlet, element);\n }\n outletDisconnected(outlet, element, name) {\n this.invokeControllerMethod(`${namespaceCamelize(name)}OutletDisconnected`, outlet, element);\n }\n invokeControllerMethod(methodName, ...args) {\n const controller = this.controller;\n if (typeof controller[methodName] == \"function\") {\n controller[methodName](...args);\n }\n }\n}\n\nfunction bless(constructor) {\n return shadow(constructor, getBlessedProperties(constructor));\n}\nfunction shadow(constructor, properties) {\n const shadowConstructor = extend(constructor);\n const shadowProperties = getShadowProperties(constructor.prototype, properties);\n Object.defineProperties(shadowConstructor.prototype, shadowProperties);\n return shadowConstructor;\n}\nfunction getBlessedProperties(constructor) {\n const blessings = readInheritableStaticArrayValues(constructor, \"blessings\");\n return blessings.reduce((blessedProperties, blessing) => {\n const properties = blessing(constructor);\n for (const key in properties) {\n const descriptor = blessedProperties[key] || {};\n blessedProperties[key] = Object.assign(descriptor, properties[key]);\n }\n return blessedProperties;\n }, {});\n}\nfunction getShadowProperties(prototype, properties) {\n return getOwnKeys(properties).reduce((shadowProperties, key) => {\n const descriptor = getShadowedDescriptor(prototype, properties, key);\n if (descriptor) {\n Object.assign(shadowProperties, { [key]: descriptor });\n }\n return shadowProperties;\n }, {});\n}\nfunction getShadowedDescriptor(prototype, properties, key) {\n const shadowingDescriptor = Object.getOwnPropertyDescriptor(prototype, key);\n const shadowedByValue = shadowingDescriptor && \"value\" in shadowingDescriptor;\n if (!shadowedByValue) {\n const descriptor = Object.getOwnPropertyDescriptor(properties, key).value;\n if (shadowingDescriptor) {\n descriptor.get = shadowingDescriptor.get || descriptor.get;\n descriptor.set = shadowingDescriptor.set || descriptor.set;\n }\n return descriptor;\n }\n}\nconst getOwnKeys = (() => {\n if (typeof Object.getOwnPropertySymbols == \"function\") {\n return (object) => [...Object.getOwnPropertyNames(object), ...Object.getOwnPropertySymbols(object)];\n }\n else {\n return Object.getOwnPropertyNames;\n }\n})();\nconst extend = (() => {\n function extendWithReflect(constructor) {\n function extended() {\n return Reflect.construct(constructor, arguments, new.target);\n }\n extended.prototype = Object.create(constructor.prototype, {\n constructor: { value: extended },\n });\n Reflect.setPrototypeOf(extended, constructor);\n return extended;\n }\n function testReflectExtension() {\n const a = function () {\n this.a.call(this);\n };\n const b = extendWithReflect(a);\n b.prototype.a = function () { };\n return new b();\n }\n try {\n testReflectExtension();\n return extendWithReflect;\n }\n catch (error) {\n return (constructor) => class extended extends constructor {\n };\n }\n})();\n\nfunction blessDefinition(definition) {\n return {\n identifier: definition.identifier,\n controllerConstructor: bless(definition.controllerConstructor),\n };\n}\n\nclass Module {\n constructor(application, definition) {\n this.application = application;\n this.definition = blessDefinition(definition);\n this.contextsByScope = new WeakMap();\n this.connectedContexts = new Set();\n }\n get identifier() {\n return this.definition.identifier;\n }\n get controllerConstructor() {\n return this.definition.controllerConstructor;\n }\n get contexts() {\n return Array.from(this.connectedContexts);\n }\n connectContextForScope(scope) {\n const context = this.fetchContextForScope(scope);\n this.connectedContexts.add(context);\n context.connect();\n }\n disconnectContextForScope(scope) {\n const context = this.contextsByScope.get(scope);\n if (context) {\n this.connectedContexts.delete(context);\n context.disconnect();\n }\n }\n fetchContextForScope(scope) {\n let context = this.contextsByScope.get(scope);\n if (!context) {\n context = new Context(this, scope);\n this.contextsByScope.set(scope, context);\n }\n return context;\n }\n}\n\nclass ClassMap {\n constructor(scope) {\n this.scope = scope;\n }\n has(name) {\n return this.data.has(this.getDataKey(name));\n }\n get(name) {\n return this.getAll(name)[0];\n }\n getAll(name) {\n const tokenString = this.data.get(this.getDataKey(name)) || \"\";\n return tokenize(tokenString);\n }\n getAttributeName(name) {\n return this.data.getAttributeNameForKey(this.getDataKey(name));\n }\n getDataKey(name) {\n return `${name}-class`;\n }\n get data() {\n return this.scope.data;\n }\n}\n\nclass DataMap {\n constructor(scope) {\n this.scope = scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get(key) {\n const name = this.getAttributeNameForKey(key);\n return this.element.getAttribute(name);\n }\n set(key, value) {\n const name = this.getAttributeNameForKey(key);\n this.element.setAttribute(name, value);\n return this.get(key);\n }\n has(key) {\n const name = this.getAttributeNameForKey(key);\n return this.element.hasAttribute(name);\n }\n delete(key) {\n if (this.has(key)) {\n const name = this.getAttributeNameForKey(key);\n this.element.removeAttribute(name);\n return true;\n }\n else {\n return false;\n }\n }\n getAttributeNameForKey(key) {\n return `data-${this.identifier}-${dasherize(key)}`;\n }\n}\n\nclass Guide {\n constructor(logger) {\n this.warnedKeysByObject = new WeakMap();\n this.logger = logger;\n }\n warn(object, key, message) {\n let warnedKeys = this.warnedKeysByObject.get(object);\n if (!warnedKeys) {\n warnedKeys = new Set();\n this.warnedKeysByObject.set(object, warnedKeys);\n }\n if (!warnedKeys.has(key)) {\n warnedKeys.add(key);\n this.logger.warn(message, object);\n }\n }\n}\n\nfunction attributeValueContainsToken(attributeName, token) {\n return `[${attributeName}~=\"${token}\"]`;\n}\n\nclass TargetSet {\n constructor(scope) {\n this.scope = scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get schema() {\n return this.scope.schema;\n }\n has(targetName) {\n return this.find(targetName) != null;\n }\n find(...targetNames) {\n return targetNames.reduce((target, targetName) => target || this.findTarget(targetName) || this.findLegacyTarget(targetName), undefined);\n }\n findAll(...targetNames) {\n return targetNames.reduce((targets, targetName) => [\n ...targets,\n ...this.findAllTargets(targetName),\n ...this.findAllLegacyTargets(targetName),\n ], []);\n }\n findTarget(targetName) {\n const selector = this.getSelectorForTargetName(targetName);\n return this.scope.findElement(selector);\n }\n findAllTargets(targetName) {\n const selector = this.getSelectorForTargetName(targetName);\n return this.scope.findAllElements(selector);\n }\n getSelectorForTargetName(targetName) {\n const attributeName = this.schema.targetAttributeForScope(this.identifier);\n return attributeValueContainsToken(attributeName, targetName);\n }\n findLegacyTarget(targetName) {\n const selector = this.getLegacySelectorForTargetName(targetName);\n return this.deprecate(this.scope.findElement(selector), targetName);\n }\n findAllLegacyTargets(targetName) {\n const selector = this.getLegacySelectorForTargetName(targetName);\n return this.scope.findAllElements(selector).map((element) => this.deprecate(element, targetName));\n }\n getLegacySelectorForTargetName(targetName) {\n const targetDescriptor = `${this.identifier}.${targetName}`;\n return attributeValueContainsToken(this.schema.targetAttribute, targetDescriptor);\n }\n deprecate(element, targetName) {\n if (element) {\n const { identifier } = this;\n const attributeName = this.schema.targetAttribute;\n const revisedAttributeName = this.schema.targetAttributeForScope(identifier);\n this.guide.warn(element, `target:${targetName}`, `Please replace ${attributeName}=\"${identifier}.${targetName}\" with ${revisedAttributeName}=\"${targetName}\". ` +\n `The ${attributeName} attribute is deprecated and will be removed in a future version of Stimulus.`);\n }\n return element;\n }\n get guide() {\n return this.scope.guide;\n }\n}\n\nclass OutletSet {\n constructor(scope, controllerElement) {\n this.scope = scope;\n this.controllerElement = controllerElement;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get schema() {\n return this.scope.schema;\n }\n has(outletName) {\n return this.find(outletName) != null;\n }\n find(...outletNames) {\n return outletNames.reduce((outlet, outletName) => outlet || this.findOutlet(outletName), undefined);\n }\n findAll(...outletNames) {\n return outletNames.reduce((outlets, outletName) => [...outlets, ...this.findAllOutlets(outletName)], []);\n }\n getSelectorForOutletName(outletName) {\n const attributeName = this.schema.outletAttributeForScope(this.identifier, outletName);\n return this.controllerElement.getAttribute(attributeName);\n }\n findOutlet(outletName) {\n const selector = this.getSelectorForOutletName(outletName);\n if (selector)\n return this.findElement(selector, outletName);\n }\n findAllOutlets(outletName) {\n const selector = this.getSelectorForOutletName(outletName);\n return selector ? this.findAllElements(selector, outletName) : [];\n }\n findElement(selector, outletName) {\n const elements = this.scope.queryElements(selector);\n return elements.filter((element) => this.matchesElement(element, selector, outletName))[0];\n }\n findAllElements(selector, outletName) {\n const elements = this.scope.queryElements(selector);\n return elements.filter((element) => this.matchesElement(element, selector, outletName));\n }\n matchesElement(element, selector, outletName) {\n const controllerAttribute = element.getAttribute(this.scope.schema.controllerAttribute) || \"\";\n return element.matches(selector) && controllerAttribute.split(\" \").includes(outletName);\n }\n}\n\nclass Scope {\n constructor(schema, element, identifier, logger) {\n this.targets = new TargetSet(this);\n this.classes = new ClassMap(this);\n this.data = new DataMap(this);\n this.containsElement = (element) => {\n return element.closest(this.controllerSelector) === this.element;\n };\n this.schema = schema;\n this.element = element;\n this.identifier = identifier;\n this.guide = new Guide(logger);\n this.outlets = new OutletSet(this.documentScope, element);\n }\n findElement(selector) {\n return this.element.matches(selector) ? this.element : this.queryElements(selector).find(this.containsElement);\n }\n findAllElements(selector) {\n return [\n ...(this.element.matches(selector) ? [this.element] : []),\n ...this.queryElements(selector).filter(this.containsElement),\n ];\n }\n queryElements(selector) {\n return Array.from(this.element.querySelectorAll(selector));\n }\n get controllerSelector() {\n return attributeValueContainsToken(this.schema.controllerAttribute, this.identifier);\n }\n get isDocumentScope() {\n return this.element === document.documentElement;\n }\n get documentScope() {\n return this.isDocumentScope\n ? this\n : new Scope(this.schema, document.documentElement, this.identifier, this.guide.logger);\n }\n}\n\nclass ScopeObserver {\n constructor(element, schema, delegate) {\n this.element = element;\n this.schema = schema;\n this.delegate = delegate;\n this.valueListObserver = new ValueListObserver(this.element, this.controllerAttribute, this);\n this.scopesByIdentifierByElement = new WeakMap();\n this.scopeReferenceCounts = new WeakMap();\n }\n start() {\n this.valueListObserver.start();\n }\n stop() {\n this.valueListObserver.stop();\n }\n get controllerAttribute() {\n return this.schema.controllerAttribute;\n }\n parseValueForToken(token) {\n const { element, content: identifier } = token;\n return this.parseValueForElementAndIdentifier(element, identifier);\n }\n parseValueForElementAndIdentifier(element, identifier) {\n const scopesByIdentifier = this.fetchScopesByIdentifierForElement(element);\n let scope = scopesByIdentifier.get(identifier);\n if (!scope) {\n scope = this.delegate.createScopeForElementAndIdentifier(element, identifier);\n scopesByIdentifier.set(identifier, scope);\n }\n return scope;\n }\n elementMatchedValue(element, value) {\n const referenceCount = (this.scopeReferenceCounts.get(value) || 0) + 1;\n this.scopeReferenceCounts.set(value, referenceCount);\n if (referenceCount == 1) {\n this.delegate.scopeConnected(value);\n }\n }\n elementUnmatchedValue(element, value) {\n const referenceCount = this.scopeReferenceCounts.get(value);\n if (referenceCount) {\n this.scopeReferenceCounts.set(value, referenceCount - 1);\n if (referenceCount == 1) {\n this.delegate.scopeDisconnected(value);\n }\n }\n }\n fetchScopesByIdentifierForElement(element) {\n let scopesByIdentifier = this.scopesByIdentifierByElement.get(element);\n if (!scopesByIdentifier) {\n scopesByIdentifier = new Map();\n this.scopesByIdentifierByElement.set(element, scopesByIdentifier);\n }\n return scopesByIdentifier;\n }\n}\n\nclass Router {\n constructor(application) {\n this.application = application;\n this.scopeObserver = new ScopeObserver(this.element, this.schema, this);\n this.scopesByIdentifier = new Multimap();\n this.modulesByIdentifier = new Map();\n }\n get element() {\n return this.application.element;\n }\n get schema() {\n return this.application.schema;\n }\n get logger() {\n return this.application.logger;\n }\n get controllerAttribute() {\n return this.schema.controllerAttribute;\n }\n get modules() {\n return Array.from(this.modulesByIdentifier.values());\n }\n get contexts() {\n return this.modules.reduce((contexts, module) => contexts.concat(module.contexts), []);\n }\n start() {\n this.scopeObserver.start();\n }\n stop() {\n this.scopeObserver.stop();\n }\n loadDefinition(definition) {\n this.unloadIdentifier(definition.identifier);\n const module = new Module(this.application, definition);\n this.connectModule(module);\n const afterLoad = definition.controllerConstructor.afterLoad;\n if (afterLoad) {\n afterLoad.call(definition.controllerConstructor, definition.identifier, this.application);\n }\n }\n unloadIdentifier(identifier) {\n const module = this.modulesByIdentifier.get(identifier);\n if (module) {\n this.disconnectModule(module);\n }\n }\n getContextForElementAndIdentifier(element, identifier) {\n const module = this.modulesByIdentifier.get(identifier);\n if (module) {\n return module.contexts.find((context) => context.element == element);\n }\n }\n proposeToConnectScopeForElementAndIdentifier(element, identifier) {\n const scope = this.scopeObserver.parseValueForElementAndIdentifier(element, identifier);\n if (scope) {\n this.scopeObserver.elementMatchedValue(scope.element, scope);\n }\n else {\n console.error(`Couldn't find or create scope for identifier: \"${identifier}\" and element:`, element);\n }\n }\n handleError(error, message, detail) {\n this.application.handleError(error, message, detail);\n }\n createScopeForElementAndIdentifier(element, identifier) {\n return new Scope(this.schema, element, identifier, this.logger);\n }\n scopeConnected(scope) {\n this.scopesByIdentifier.add(scope.identifier, scope);\n const module = this.modulesByIdentifier.get(scope.identifier);\n if (module) {\n module.connectContextForScope(scope);\n }\n }\n scopeDisconnected(scope) {\n this.scopesByIdentifier.delete(scope.identifier, scope);\n const module = this.modulesByIdentifier.get(scope.identifier);\n if (module) {\n module.disconnectContextForScope(scope);\n }\n }\n connectModule(module) {\n this.modulesByIdentifier.set(module.identifier, module);\n const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);\n scopes.forEach((scope) => module.connectContextForScope(scope));\n }\n disconnectModule(module) {\n this.modulesByIdentifier.delete(module.identifier);\n const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);\n scopes.forEach((scope) => module.disconnectContextForScope(scope));\n }\n}\n\nconst defaultSchema = {\n controllerAttribute: \"data-controller\",\n actionAttribute: \"data-action\",\n targetAttribute: \"data-target\",\n targetAttributeForScope: (identifier) => `data-${identifier}-target`,\n outletAttributeForScope: (identifier, outlet) => `data-${identifier}-${outlet}-outlet`,\n keyMappings: Object.assign(Object.assign({ enter: \"Enter\", tab: \"Tab\", esc: \"Escape\", space: \" \", up: \"ArrowUp\", down: \"ArrowDown\", left: \"ArrowLeft\", right: \"ArrowRight\", home: \"Home\", end: \"End\", page_up: \"PageUp\", page_down: \"PageDown\" }, objectFromEntries(\"abcdefghijklmnopqrstuvwxyz\".split(\"\").map((c) => [c, c]))), objectFromEntries(\"0123456789\".split(\"\").map((n) => [n, n]))),\n};\nfunction objectFromEntries(array) {\n return array.reduce((memo, [k, v]) => (Object.assign(Object.assign({}, memo), { [k]: v })), {});\n}\n\nclass Application {\n constructor(element = document.documentElement, schema = defaultSchema) {\n this.logger = console;\n this.debug = false;\n this.logDebugActivity = (identifier, functionName, detail = {}) => {\n if (this.debug) {\n this.logFormattedMessage(identifier, functionName, detail);\n }\n };\n this.element = element;\n this.schema = schema;\n this.dispatcher = new Dispatcher(this);\n this.router = new Router(this);\n this.actionDescriptorFilters = Object.assign({}, defaultActionDescriptorFilters);\n }\n static start(element, schema) {\n const application = new this(element, schema);\n application.start();\n return application;\n }\n async start() {\n await domReady();\n this.logDebugActivity(\"application\", \"starting\");\n this.dispatcher.start();\n this.router.start();\n this.logDebugActivity(\"application\", \"start\");\n }\n stop() {\n this.logDebugActivity(\"application\", \"stopping\");\n this.dispatcher.stop();\n this.router.stop();\n this.logDebugActivity(\"application\", \"stop\");\n }\n register(identifier, controllerConstructor) {\n this.load({ identifier, controllerConstructor });\n }\n registerActionOption(name, filter) {\n this.actionDescriptorFilters[name] = filter;\n }\n load(head, ...rest) {\n const definitions = Array.isArray(head) ? head : [head, ...rest];\n definitions.forEach((definition) => {\n if (definition.controllerConstructor.shouldLoad) {\n this.router.loadDefinition(definition);\n }\n });\n }\n unload(head, ...rest) {\n const identifiers = Array.isArray(head) ? head : [head, ...rest];\n identifiers.forEach((identifier) => this.router.unloadIdentifier(identifier));\n }\n get controllers() {\n return this.router.contexts.map((context) => context.controller);\n }\n getControllerForElementAndIdentifier(element, identifier) {\n const context = this.router.getContextForElementAndIdentifier(element, identifier);\n return context ? context.controller : null;\n }\n handleError(error, message, detail) {\n var _a;\n this.logger.error(`%s\\n\\n%o\\n\\n%o`, message, error, detail);\n (_a = window.onerror) === null || _a === void 0 ? void 0 : _a.call(window, message, \"\", 0, 0, error);\n }\n logFormattedMessage(identifier, functionName, detail = {}) {\n detail = Object.assign({ application: this }, detail);\n this.logger.groupCollapsed(`${identifier} #${functionName}`);\n this.logger.log(\"details:\", Object.assign({}, detail));\n this.logger.groupEnd();\n }\n}\nfunction domReady() {\n return new Promise((resolve) => {\n if (document.readyState == \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", () => resolve());\n }\n else {\n resolve();\n }\n });\n}\n\nfunction ClassPropertiesBlessing(constructor) {\n const classes = readInheritableStaticArrayValues(constructor, \"classes\");\n return classes.reduce((properties, classDefinition) => {\n return Object.assign(properties, propertiesForClassDefinition(classDefinition));\n }, {});\n}\nfunction propertiesForClassDefinition(key) {\n return {\n [`${key}Class`]: {\n get() {\n const { classes } = this;\n if (classes.has(key)) {\n return classes.get(key);\n }\n else {\n const attribute = classes.getAttributeName(key);\n throw new Error(`Missing attribute \"${attribute}\"`);\n }\n },\n },\n [`${key}Classes`]: {\n get() {\n return this.classes.getAll(key);\n },\n },\n [`has${capitalize(key)}Class`]: {\n get() {\n return this.classes.has(key);\n },\n },\n };\n}\n\nfunction OutletPropertiesBlessing(constructor) {\n const outlets = readInheritableStaticArrayValues(constructor, \"outlets\");\n return outlets.reduce((properties, outletDefinition) => {\n return Object.assign(properties, propertiesForOutletDefinition(outletDefinition));\n }, {});\n}\nfunction getOutletController(controller, element, identifier) {\n return controller.application.getControllerForElementAndIdentifier(element, identifier);\n}\nfunction getControllerAndEnsureConnectedScope(controller, element, outletName) {\n let outletController = getOutletController(controller, element, outletName);\n if (outletController)\n return outletController;\n controller.application.router.proposeToConnectScopeForElementAndIdentifier(element, outletName);\n outletController = getOutletController(controller, element, outletName);\n if (outletController)\n return outletController;\n}\nfunction propertiesForOutletDefinition(name) {\n const camelizedName = namespaceCamelize(name);\n return {\n [`${camelizedName}Outlet`]: {\n get() {\n const outletElement = this.outlets.find(name);\n const selector = this.outlets.getSelectorForOutletName(name);\n if (outletElement) {\n const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name);\n if (outletController)\n return outletController;\n throw new Error(`The provided outlet element is missing an outlet controller \"${name}\" instance for host controller \"${this.identifier}\"`);\n }\n throw new Error(`Missing outlet element \"${name}\" for host controller \"${this.identifier}\". Stimulus couldn't find a matching outlet element using selector \"${selector}\".`);\n },\n },\n [`${camelizedName}Outlets`]: {\n get() {\n const outlets = this.outlets.findAll(name);\n if (outlets.length > 0) {\n return outlets\n .map((outletElement) => {\n const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name);\n if (outletController)\n return outletController;\n console.warn(`The provided outlet element is missing an outlet controller \"${name}\" instance for host controller \"${this.identifier}\"`, outletElement);\n })\n .filter((controller) => controller);\n }\n return [];\n },\n },\n [`${camelizedName}OutletElement`]: {\n get() {\n const outletElement = this.outlets.find(name);\n const selector = this.outlets.getSelectorForOutletName(name);\n if (outletElement) {\n return outletElement;\n }\n else {\n throw new Error(`Missing outlet element \"${name}\" for host controller \"${this.identifier}\". Stimulus couldn't find a matching outlet element using selector \"${selector}\".`);\n }\n },\n },\n [`${camelizedName}OutletElements`]: {\n get() {\n return this.outlets.findAll(name);\n },\n },\n [`has${capitalize(camelizedName)}Outlet`]: {\n get() {\n return this.outlets.has(name);\n },\n },\n };\n}\n\nfunction TargetPropertiesBlessing(constructor) {\n const targets = readInheritableStaticArrayValues(constructor, \"targets\");\n return targets.reduce((properties, targetDefinition) => {\n return Object.assign(properties, propertiesForTargetDefinition(targetDefinition));\n }, {});\n}\nfunction propertiesForTargetDefinition(name) {\n return {\n [`${name}Target`]: {\n get() {\n const target = this.targets.find(name);\n if (target) {\n return target;\n }\n else {\n throw new Error(`Missing target element \"${name}\" for \"${this.identifier}\" controller`);\n }\n },\n },\n [`${name}Targets`]: {\n get() {\n return this.targets.findAll(name);\n },\n },\n [`has${capitalize(name)}Target`]: {\n get() {\n return this.targets.has(name);\n },\n },\n };\n}\n\nfunction ValuePropertiesBlessing(constructor) {\n const valueDefinitionPairs = readInheritableStaticObjectPairs(constructor, \"values\");\n const propertyDescriptorMap = {\n valueDescriptorMap: {\n get() {\n return valueDefinitionPairs.reduce((result, valueDefinitionPair) => {\n const valueDescriptor = parseValueDefinitionPair(valueDefinitionPair, this.identifier);\n const attributeName = this.data.getAttributeNameForKey(valueDescriptor.key);\n return Object.assign(result, { [attributeName]: valueDescriptor });\n }, {});\n },\n },\n };\n return valueDefinitionPairs.reduce((properties, valueDefinitionPair) => {\n return Object.assign(properties, propertiesForValueDefinitionPair(valueDefinitionPair));\n }, propertyDescriptorMap);\n}\nfunction propertiesForValueDefinitionPair(valueDefinitionPair, controller) {\n const definition = parseValueDefinitionPair(valueDefinitionPair, controller);\n const { key, name, reader: read, writer: write } = definition;\n return {\n [name]: {\n get() {\n const value = this.data.get(key);\n if (value !== null) {\n return read(value);\n }\n else {\n return definition.defaultValue;\n }\n },\n set(value) {\n if (value === undefined) {\n this.data.delete(key);\n }\n else {\n this.data.set(key, write(value));\n }\n },\n },\n [`has${capitalize(name)}`]: {\n get() {\n return this.data.has(key) || definition.hasCustomDefaultValue;\n },\n },\n };\n}\nfunction parseValueDefinitionPair([token, typeDefinition], controller) {\n return valueDescriptorForTokenAndTypeDefinition({\n controller,\n token,\n typeDefinition,\n });\n}\nfunction parseValueTypeConstant(constant) {\n switch (constant) {\n case Array:\n return \"array\";\n case Boolean:\n return \"boolean\";\n case Number:\n return \"number\";\n case Object:\n return \"object\";\n case String:\n return \"string\";\n }\n}\nfunction parseValueTypeDefault(defaultValue) {\n switch (typeof defaultValue) {\n case \"boolean\":\n return \"boolean\";\n case \"number\":\n return \"number\";\n case \"string\":\n return \"string\";\n }\n if (Array.isArray(defaultValue))\n return \"array\";\n if (Object.prototype.toString.call(defaultValue) === \"[object Object]\")\n return \"object\";\n}\nfunction parseValueTypeObject(payload) {\n const { controller, token, typeObject } = payload;\n const hasType = isSomething(typeObject.type);\n const hasDefault = isSomething(typeObject.default);\n const fullObject = hasType && hasDefault;\n const onlyType = hasType && !hasDefault;\n const onlyDefault = !hasType && hasDefault;\n const typeFromObject = parseValueTypeConstant(typeObject.type);\n const typeFromDefaultValue = parseValueTypeDefault(payload.typeObject.default);\n if (onlyType)\n return typeFromObject;\n if (onlyDefault)\n return typeFromDefaultValue;\n if (typeFromObject !== typeFromDefaultValue) {\n const propertyPath = controller ? `${controller}.${token}` : token;\n throw new Error(`The specified default value for the Stimulus Value \"${propertyPath}\" must match the defined type \"${typeFromObject}\". The provided default value of \"${typeObject.default}\" is of type \"${typeFromDefaultValue}\".`);\n }\n if (fullObject)\n return typeFromObject;\n}\nfunction parseValueTypeDefinition(payload) {\n const { controller, token, typeDefinition } = payload;\n const typeObject = { controller, token, typeObject: typeDefinition };\n const typeFromObject = parseValueTypeObject(typeObject);\n const typeFromDefaultValue = parseValueTypeDefault(typeDefinition);\n const typeFromConstant = parseValueTypeConstant(typeDefinition);\n const type = typeFromObject || typeFromDefaultValue || typeFromConstant;\n if (type)\n return type;\n const propertyPath = controller ? `${controller}.${typeDefinition}` : token;\n throw new Error(`Unknown value type \"${propertyPath}\" for \"${token}\" value`);\n}\nfunction defaultValueForDefinition(typeDefinition) {\n const constant = parseValueTypeConstant(typeDefinition);\n if (constant)\n return defaultValuesByType[constant];\n const hasDefault = hasProperty(typeDefinition, \"default\");\n const hasType = hasProperty(typeDefinition, \"type\");\n const typeObject = typeDefinition;\n if (hasDefault)\n return typeObject.default;\n if (hasType) {\n const { type } = typeObject;\n const constantFromType = parseValueTypeConstant(type);\n if (constantFromType)\n return defaultValuesByType[constantFromType];\n }\n return typeDefinition;\n}\nfunction valueDescriptorForTokenAndTypeDefinition(payload) {\n const { token, typeDefinition } = payload;\n const key = `${dasherize(token)}-value`;\n const type = parseValueTypeDefinition(payload);\n return {\n type,\n key,\n name: camelize(key),\n get defaultValue() {\n return defaultValueForDefinition(typeDefinition);\n },\n get hasCustomDefaultValue() {\n return parseValueTypeDefault(typeDefinition) !== undefined;\n },\n reader: readers[type],\n writer: writers[type] || writers.default,\n };\n}\nconst defaultValuesByType = {\n get array() {\n return [];\n },\n boolean: false,\n number: 0,\n get object() {\n return {};\n },\n string: \"\",\n};\nconst readers = {\n array(value) {\n const array = JSON.parse(value);\n if (!Array.isArray(array)) {\n throw new TypeError(`expected value of type \"array\" but instead got value \"${value}\" of type \"${parseValueTypeDefault(array)}\"`);\n }\n return array;\n },\n boolean(value) {\n return !(value == \"0\" || String(value).toLowerCase() == \"false\");\n },\n number(value) {\n return Number(value.replace(/_/g, \"\"));\n },\n object(value) {\n const object = JSON.parse(value);\n if (object === null || typeof object != \"object\" || Array.isArray(object)) {\n throw new TypeError(`expected value of type \"object\" but instead got value \"${value}\" of type \"${parseValueTypeDefault(object)}\"`);\n }\n return object;\n },\n string(value) {\n return value;\n },\n};\nconst writers = {\n default: writeString,\n array: writeJSON,\n object: writeJSON,\n};\nfunction writeJSON(value) {\n return JSON.stringify(value);\n}\nfunction writeString(value) {\n return `${value}`;\n}\n\nclass Controller {\n constructor(context) {\n this.context = context;\n }\n static get shouldLoad() {\n return true;\n }\n static afterLoad(_identifier, _application) {\n return;\n }\n get application() {\n return this.context.application;\n }\n get scope() {\n return this.context.scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get targets() {\n return this.scope.targets;\n }\n get outlets() {\n return this.scope.outlets;\n }\n get classes() {\n return this.scope.classes;\n }\n get data() {\n return this.scope.data;\n }\n initialize() {\n }\n connect() {\n }\n disconnect() {\n }\n dispatch(eventName, { target = this.element, detail = {}, prefix = this.identifier, bubbles = true, cancelable = true, } = {}) {\n const type = prefix ? `${prefix}:${eventName}` : eventName;\n const event = new CustomEvent(type, { detail, bubbles, cancelable });\n target.dispatchEvent(event);\n return event;\n }\n}\nController.blessings = [\n ClassPropertiesBlessing,\n TargetPropertiesBlessing,\n ValuePropertiesBlessing,\n OutletPropertiesBlessing,\n];\nController.targets = [];\nController.outlets = [];\nController.values = {};\n\nexport { Application, AttributeObserver, Context, Controller, ElementObserver, IndexedMultimap, Multimap, SelectorObserver, StringMapObserver, TokenListObserver, ValueListObserver, add, defaultSchema, del, fetch, prune };\n", "import { Controller } from '@hotwired/stimulus';\n\nexport default class extends Controller {\n static get targets() {\n return [ \"source\" ]\n }\n\n connect() {\n this.closeAllBefore = this.data.get(\"closeAllBefore\") || \"false\"\n this.classToToggle = this.data.get(\"classToToggle\") || \"hidden\"\n }\n\n toggle(event) {\n event.preventDefault()\n if (this.closeAllBefore === 'true') {\n this.closeOpenElements()\n\n for (var item of document.querySelectorAll('.accordion-title')) {\n item.classList.remove('active');\n }\n\n\n }\n this.toggleClassElement(event.target.closest('div'))\n }\n\n closeOpenElements() {\n var toggleClass = this.classToToggle\n this.sourceTargets.forEach(function(item) {\n item.classList.add(toggleClass)\n });\n }\n\n toggleClassElement(item) {\n item.querySelector('[data-accordion-target=\"source\"]').classList.toggle(this.classToToggle);\n item.querySelector('[data-accordion-target=\"source\"]').previousElementSibling.classList.add('active');\n }\n\n}\n", "import { Controller } from \"@hotwired/stimulus\";\n\nexport default class extends Controller {\n static targets = ['tab', 'content'];\n static classes = ['active', 'hide'];\n\n connect() {\n if (this.data.has(\"equalise\")) {\n this.set_min_height();\n }\n }\n\n switch(e) {\n const tab = e.target.closest('[data-tab]');\n\n // catch clicks that miss a tab (eg. on the UL)\n if (!tab) {\n return;\n }\n\n const tab_id = tab.dataset.tab;\n\n this.tabTargets.forEach(tab => this.update_tab(tab, tab.dataset.tab === tab_id));\n this.contentTargets.forEach(content => this.update_content(content, content.dataset.tab === tab_id));\n }\n\n set_min_height() {\n let min_height = '';\n\n if (!this.hasContentTarget) {\n return;\n }\n\n // determine the minimum height\n this.contentTargets.forEach(content => {\n let hidden = content.classList.contains(this.hideClass);\n if (hidden) {\n content.classList.remove(this.hideClass);\n }\n\n let height = content.offsetHeight;\n if (height > min_height) {\n min_height = height;\n }\n\n if (hidden) {\n content.classList.add(this.hideClass);\n }\n });\n\n // apply to all tabs\n this.contentTargets.forEach(content => content.style.minHeight = min_height + \"px\");\n }\n\n update_tab(tab, active) {\n if (active) {\n tab.classList.add(this.activeClass);\n tab.querySelector('a').setAttribute('aria-selected', true);\n } else {\n tab.classList.remove(this.activeClass);\n tab.querySelector('a').removeAttribute('aria-selected');\n }\n }\n\n update_content(content, active) {\n if (active) {\n content.classList.remove(this.hideClass);\n content.classList.add(this.activeClass);\n } else {\n content.classList.add(this.hideClass);\n content.classList.remove(this.activeClass);\n }\n }\n}\n", "import { Application } from \"@hotwired/stimulus\";\nimport AccordionController from \"./../../../components/accordion_component/accordion_controller\";\nimport TabsController from \"./../../../components/tabs_component/tabs_controller\";\n\nconst application = Application.start();\n\n// Configure Stimulus development experience\napplication.warnings = true;\napplication.debug = false;\nwindow.Stimulus = application;\n\nStimulus.register(\"accordion\", AccordionController);\nStimulus.register(\"tabs\", TabsController);\n\nexport { application };\n", "import { Controller } from '@hotwired/stimulus';\nimport Swal from 'sweetalert2';\n\nexport default class extends Controller {\n\n modal(e) {\n e.preventDefault();\n let content = e.target;\n\n const message = content.dataset.message;\n const text = content.dataset.text;\n\n Swal.fire({\n title: message,\n text: text,\n showCancelButton: false,\n showConfirmButton: false,\n showCloseButton: true,\n buttonsStyling: false,\n padding: 0,\n customClass: {\n container: 'overlay-background',\n popup: 'overlay-content ',\n },\n });\n }\n\n}", "export var top = 'top';\nexport var bottom = 'bottom';\nexport var right = 'right';\nexport var left = 'left';\nexport var auto = 'auto';\nexport var basePlacements = [top, bottom, right, left];\nexport var start = 'start';\nexport var end = 'end';\nexport var clippingParents = 'clippingParents';\nexport var viewport = 'viewport';\nexport var popper = 'popper';\nexport var reference = 'reference';\nexport var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {\n return acc.concat([placement + \"-\" + start, placement + \"-\" + end]);\n}, []);\nexport var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) {\n return acc.concat([placement, placement + \"-\" + start, placement + \"-\" + end]);\n}, []); // modifiers that need to read the DOM\n\nexport var beforeRead = 'beforeRead';\nexport var read = 'read';\nexport var afterRead = 'afterRead'; // pure-logic modifiers\n\nexport var beforeMain = 'beforeMain';\nexport var main = 'main';\nexport var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)\n\nexport var beforeWrite = 'beforeWrite';\nexport var write = 'write';\nexport var afterWrite = 'afterWrite';\nexport var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];", "export default function getNodeName(element) {\n return element ? (element.nodeName || '').toLowerCase() : null;\n}", "export default function getWindow(node) {\n if (node == null) {\n return window;\n }\n\n if (node.toString() !== '[object Window]') {\n var ownerDocument = node.ownerDocument;\n return ownerDocument ? ownerDocument.defaultView || window : window;\n }\n\n return node;\n}", "import getWindow from \"./getWindow.js\";\n\nfunction isElement(node) {\n var OwnElement = getWindow(node).Element;\n return node instanceof OwnElement || node instanceof Element;\n}\n\nfunction isHTMLElement(node) {\n var OwnElement = getWindow(node).HTMLElement;\n return node instanceof OwnElement || node instanceof HTMLElement;\n}\n\nfunction isShadowRoot(node) {\n // IE 11 has no ShadowRoot\n if (typeof ShadowRoot === 'undefined') {\n return false;\n }\n\n var OwnElement = getWindow(node).ShadowRoot;\n return node instanceof OwnElement || node instanceof ShadowRoot;\n}\n\nexport { isElement, isHTMLElement, isShadowRoot };", "import getNodeName from \"../dom-utils/getNodeName.js\";\nimport { isHTMLElement } from \"../dom-utils/instanceOf.js\"; // This modifier takes the styles prepared by the `computeStyles` modifier\n// and applies them to the HTMLElements such as popper and arrow\n\nfunction applyStyles(_ref) {\n var state = _ref.state;\n Object.keys(state.elements).forEach(function (name) {\n var style = state.styles[name] || {};\n var attributes = state.attributes[name] || {};\n var element = state.elements[name]; // arrow is optional + virtual elements\n\n if (!isHTMLElement(element) || !getNodeName(element)) {\n return;\n } // Flow doesn't support to extend this property, but it's the most\n // effective way to apply styles to an HTMLElement\n // $FlowFixMe[cannot-write]\n\n\n Object.assign(element.style, style);\n Object.keys(attributes).forEach(function (name) {\n var value = attributes[name];\n\n if (value === false) {\n element.removeAttribute(name);\n } else {\n element.setAttribute(name, value === true ? '' : value);\n }\n });\n });\n}\n\nfunction effect(_ref2) {\n var state = _ref2.state;\n var initialStyles = {\n popper: {\n position: state.options.strategy,\n left: '0',\n top: '0',\n margin: '0'\n },\n arrow: {\n position: 'absolute'\n },\n reference: {}\n };\n Object.assign(state.elements.popper.style, initialStyles.popper);\n state.styles = initialStyles;\n\n if (state.elements.arrow) {\n Object.assign(state.elements.arrow.style, initialStyles.arrow);\n }\n\n return function () {\n Object.keys(state.elements).forEach(function (name) {\n var element = state.elements[name];\n var attributes = state.attributes[name] || {};\n var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them\n\n var style = styleProperties.reduce(function (style, property) {\n style[property] = '';\n return style;\n }, {}); // arrow is optional + virtual elements\n\n if (!isHTMLElement(element) || !getNodeName(element)) {\n return;\n }\n\n Object.assign(element.style, style);\n Object.keys(attributes).forEach(function (attribute) {\n element.removeAttribute(attribute);\n });\n });\n };\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'applyStyles',\n enabled: true,\n phase: 'write',\n fn: applyStyles,\n effect: effect,\n requires: ['computeStyles']\n};", "import { auto } from \"../enums.js\";\nexport default function getBasePlacement(placement) {\n return placement.split('-')[0];\n}", "export var max = Math.max;\nexport var min = Math.min;\nexport var round = Math.round;", "export default function getUAString() {\n var uaData = navigator.userAgentData;\n\n if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) {\n return uaData.brands.map(function (item) {\n return item.brand + \"/\" + item.version;\n }).join(' ');\n }\n\n return navigator.userAgent;\n}", "import getUAString from \"../utils/userAgent.js\";\nexport default function isLayoutViewport() {\n return !/^((?!chrome|android).)*safari/i.test(getUAString());\n}", "import { isElement, isHTMLElement } from \"./instanceOf.js\";\nimport { round } from \"../utils/math.js\";\nimport getWindow from \"./getWindow.js\";\nimport isLayoutViewport from \"./isLayoutViewport.js\";\nexport default function getBoundingClientRect(element, includeScale, isFixedStrategy) {\n if (includeScale === void 0) {\n includeScale = false;\n }\n\n if (isFixedStrategy === void 0) {\n isFixedStrategy = false;\n }\n\n var clientRect = element.getBoundingClientRect();\n var scaleX = 1;\n var scaleY = 1;\n\n if (includeScale && isHTMLElement(element)) {\n scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1;\n scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1;\n }\n\n var _ref = isElement(element) ? getWindow(element) : window,\n visualViewport = _ref.visualViewport;\n\n var addVisualOffsets = !isLayoutViewport() && isFixedStrategy;\n var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;\n var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;\n var width = clientRect.width / scaleX;\n var height = clientRect.height / scaleY;\n return {\n width: width,\n height: height,\n top: y,\n right: x + width,\n bottom: y + height,\n left: x,\n x: x,\n y: y\n };\n}", "import getBoundingClientRect from \"./getBoundingClientRect.js\"; // Returns the layout rect of an element relative to its offsetParent. Layout\n// means it doesn't take into account transforms.\n\nexport default function getLayoutRect(element) {\n var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed.\n // Fixes https://github.com/popperjs/popper-core/issues/1223\n\n var width = element.offsetWidth;\n var height = element.offsetHeight;\n\n if (Math.abs(clientRect.width - width) <= 1) {\n width = clientRect.width;\n }\n\n if (Math.abs(clientRect.height - height) <= 1) {\n height = clientRect.height;\n }\n\n return {\n x: element.offsetLeft,\n y: element.offsetTop,\n width: width,\n height: height\n };\n}", "import { isShadowRoot } from \"./instanceOf.js\";\nexport default function contains(parent, child) {\n var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method\n\n if (parent.contains(child)) {\n return true;\n } // then fallback to custom implementation with Shadow DOM support\n else if (rootNode && isShadowRoot(rootNode)) {\n var next = child;\n\n do {\n if (next && parent.isSameNode(next)) {\n return true;\n } // $FlowFixMe[prop-missing]: need a better way to handle this...\n\n\n next = next.parentNode || next.host;\n } while (next);\n } // Give up, the result is false\n\n\n return false;\n}", "import getWindow from \"./getWindow.js\";\nexport default function getComputedStyle(element) {\n return getWindow(element).getComputedStyle(element);\n}", "import getNodeName from \"./getNodeName.js\";\nexport default function isTableElement(element) {\n return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;\n}", "import { isElement } from \"./instanceOf.js\";\nexport default function getDocumentElement(element) {\n // $FlowFixMe[incompatible-return]: assume body is always available\n return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing]\n element.document) || window.document).documentElement;\n}", "import getNodeName from \"./getNodeName.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport { isShadowRoot } from \"./instanceOf.js\";\nexport default function getParentNode(element) {\n if (getNodeName(element) === 'html') {\n return element;\n }\n\n return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle\n // $FlowFixMe[incompatible-return]\n // $FlowFixMe[prop-missing]\n element.assignedSlot || // step into the shadow DOM of the parent of a slotted node\n element.parentNode || ( // DOM Element detected\n isShadowRoot(element) ? element.host : null) || // ShadowRoot detected\n // $FlowFixMe[incompatible-call]: HTMLElement is a Node\n getDocumentElement(element) // fallback\n\n );\n}", "import getWindow from \"./getWindow.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport { isHTMLElement, isShadowRoot } from \"./instanceOf.js\";\nimport isTableElement from \"./isTableElement.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport getUAString from \"../utils/userAgent.js\";\n\nfunction getTrueOffsetParent(element) {\n if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837\n getComputedStyle(element).position === 'fixed') {\n return null;\n }\n\n return element.offsetParent;\n} // `.offsetParent` reports `null` for fixed elements, while absolute elements\n// return the containing block\n\n\nfunction getContainingBlock(element) {\n var isFirefox = /firefox/i.test(getUAString());\n var isIE = /Trident/i.test(getUAString());\n\n if (isIE && isHTMLElement(element)) {\n // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport\n var elementCss = getComputedStyle(element);\n\n if (elementCss.position === 'fixed') {\n return null;\n }\n }\n\n var currentNode = getParentNode(element);\n\n if (isShadowRoot(currentNode)) {\n currentNode = currentNode.host;\n }\n\n while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {\n var css = getComputedStyle(currentNode); // This is non-exhaustive but covers the most common CSS properties that\n // create a containing block.\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n\n if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') {\n return currentNode;\n } else {\n currentNode = currentNode.parentNode;\n }\n }\n\n return null;\n} // Gets the closest ancestor positioned element. Handles some edge cases,\n// such as table ancestors and cross browser bugs.\n\n\nexport default function getOffsetParent(element) {\n var window = getWindow(element);\n var offsetParent = getTrueOffsetParent(element);\n\n while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === 'static') {\n offsetParent = getTrueOffsetParent(offsetParent);\n }\n\n if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static')) {\n return window;\n }\n\n return offsetParent || getContainingBlock(element) || window;\n}", "export default function getMainAxisFromPlacement(placement) {\n return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';\n}", "import { max as mathMax, min as mathMin } from \"./math.js\";\nexport function within(min, value, max) {\n return mathMax(min, mathMin(value, max));\n}\nexport function withinMaxClamp(min, value, max) {\n var v = within(min, value, max);\n return v > max ? max : v;\n}", "export default function getFreshSideObject() {\n return {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0\n };\n}", "import getFreshSideObject from \"./getFreshSideObject.js\";\nexport default function mergePaddingObject(paddingObject) {\n return Object.assign({}, getFreshSideObject(), paddingObject);\n}", "export default function expandToHashMap(value, keys) {\n return keys.reduce(function (hashMap, key) {\n hashMap[key] = value;\n return hashMap;\n }, {});\n}", "import getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getLayoutRect from \"../dom-utils/getLayoutRect.js\";\nimport contains from \"../dom-utils/contains.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport getMainAxisFromPlacement from \"../utils/getMainAxisFromPlacement.js\";\nimport { within } from \"../utils/within.js\";\nimport mergePaddingObject from \"../utils/mergePaddingObject.js\";\nimport expandToHashMap from \"../utils/expandToHashMap.js\";\nimport { left, right, basePlacements, top, bottom } from \"../enums.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar toPaddingObject = function toPaddingObject(padding, state) {\n padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, {\n placement: state.placement\n })) : padding;\n return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));\n};\n\nfunction arrow(_ref) {\n var _state$modifiersData$;\n\n var state = _ref.state,\n name = _ref.name,\n options = _ref.options;\n var arrowElement = state.elements.arrow;\n var popperOffsets = state.modifiersData.popperOffsets;\n var basePlacement = getBasePlacement(state.placement);\n var axis = getMainAxisFromPlacement(basePlacement);\n var isVertical = [left, right].indexOf(basePlacement) >= 0;\n var len = isVertical ? 'height' : 'width';\n\n if (!arrowElement || !popperOffsets) {\n return;\n }\n\n var paddingObject = toPaddingObject(options.padding, state);\n var arrowRect = getLayoutRect(arrowElement);\n var minProp = axis === 'y' ? top : left;\n var maxProp = axis === 'y' ? bottom : right;\n var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];\n var startDiff = popperOffsets[axis] - state.rects.reference[axis];\n var arrowOffsetParent = getOffsetParent(arrowElement);\n var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;\n var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is\n // outside of the popper bounds\n\n var min = paddingObject[minProp];\n var max = clientSize - arrowRect[len] - paddingObject[maxProp];\n var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;\n var offset = within(min, center, max); // Prevents breaking syntax highlighting...\n\n var axisProp = axis;\n state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);\n}\n\nfunction effect(_ref2) {\n var state = _ref2.state,\n options = _ref2.options;\n var _options$element = options.element,\n arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element;\n\n if (arrowElement == null) {\n return;\n } // CSS selector\n\n\n if (typeof arrowElement === 'string') {\n arrowElement = state.elements.popper.querySelector(arrowElement);\n\n if (!arrowElement) {\n return;\n }\n }\n\n if (!contains(state.elements.popper, arrowElement)) {\n return;\n }\n\n state.elements.arrow = arrowElement;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'arrow',\n enabled: true,\n phase: 'main',\n fn: arrow,\n effect: effect,\n requires: ['popperOffsets'],\n requiresIfExists: ['preventOverflow']\n};", "export default function getVariation(placement) {\n return placement.split('-')[1];\n}", "import { top, left, right, bottom, end } from \"../enums.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport getWindow from \"../dom-utils/getWindow.js\";\nimport getDocumentElement from \"../dom-utils/getDocumentElement.js\";\nimport getComputedStyle from \"../dom-utils/getComputedStyle.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getVariation from \"../utils/getVariation.js\";\nimport { round } from \"../utils/math.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar unsetSides = {\n top: 'auto',\n right: 'auto',\n bottom: 'auto',\n left: 'auto'\n}; // Round the offsets to the nearest suitable subpixel based on the DPR.\n// Zooming can change the DPR, but it seems to report a value that will\n// cleanly divide the values into the appropriate subpixels.\n\nfunction roundOffsetsByDPR(_ref, win) {\n var x = _ref.x,\n y = _ref.y;\n var dpr = win.devicePixelRatio || 1;\n return {\n x: round(x * dpr) / dpr || 0,\n y: round(y * dpr) / dpr || 0\n };\n}\n\nexport function mapToStyles(_ref2) {\n var _Object$assign2;\n\n var popper = _ref2.popper,\n popperRect = _ref2.popperRect,\n placement = _ref2.placement,\n variation = _ref2.variation,\n offsets = _ref2.offsets,\n position = _ref2.position,\n gpuAcceleration = _ref2.gpuAcceleration,\n adaptive = _ref2.adaptive,\n roundOffsets = _ref2.roundOffsets,\n isFixed = _ref2.isFixed;\n var _offsets$x = offsets.x,\n x = _offsets$x === void 0 ? 0 : _offsets$x,\n _offsets$y = offsets.y,\n y = _offsets$y === void 0 ? 0 : _offsets$y;\n\n var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({\n x: x,\n y: y\n }) : {\n x: x,\n y: y\n };\n\n x = _ref3.x;\n y = _ref3.y;\n var hasX = offsets.hasOwnProperty('x');\n var hasY = offsets.hasOwnProperty('y');\n var sideX = left;\n var sideY = top;\n var win = window;\n\n if (adaptive) {\n var offsetParent = getOffsetParent(popper);\n var heightProp = 'clientHeight';\n var widthProp = 'clientWidth';\n\n if (offsetParent === getWindow(popper)) {\n offsetParent = getDocumentElement(popper);\n\n if (getComputedStyle(offsetParent).position !== 'static' && position === 'absolute') {\n heightProp = 'scrollHeight';\n widthProp = 'scrollWidth';\n }\n } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it\n\n\n offsetParent = offsetParent;\n\n if (placement === top || (placement === left || placement === right) && variation === end) {\n sideY = bottom;\n var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : // $FlowFixMe[prop-missing]\n offsetParent[heightProp];\n y -= offsetY - popperRect.height;\n y *= gpuAcceleration ? 1 : -1;\n }\n\n if (placement === left || (placement === top || placement === bottom) && variation === end) {\n sideX = right;\n var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : // $FlowFixMe[prop-missing]\n offsetParent[widthProp];\n x -= offsetX - popperRect.width;\n x *= gpuAcceleration ? 1 : -1;\n }\n }\n\n var commonStyles = Object.assign({\n position: position\n }, adaptive && unsetSides);\n\n var _ref4 = roundOffsets === true ? roundOffsetsByDPR({\n x: x,\n y: y\n }, getWindow(popper)) : {\n x: x,\n y: y\n };\n\n x = _ref4.x;\n y = _ref4.y;\n\n if (gpuAcceleration) {\n var _Object$assign;\n\n return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? \"translate(\" + x + \"px, \" + y + \"px)\" : \"translate3d(\" + x + \"px, \" + y + \"px, 0)\", _Object$assign));\n }\n\n return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + \"px\" : '', _Object$assign2[sideX] = hasX ? x + \"px\" : '', _Object$assign2.transform = '', _Object$assign2));\n}\n\nfunction computeStyles(_ref5) {\n var state = _ref5.state,\n options = _ref5.options;\n var _options$gpuAccelerat = options.gpuAcceleration,\n gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,\n _options$adaptive = options.adaptive,\n adaptive = _options$adaptive === void 0 ? true : _options$adaptive,\n _options$roundOffsets = options.roundOffsets,\n roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;\n var commonStyles = {\n placement: getBasePlacement(state.placement),\n variation: getVariation(state.placement),\n popper: state.elements.popper,\n popperRect: state.rects.popper,\n gpuAcceleration: gpuAcceleration,\n isFixed: state.options.strategy === 'fixed'\n };\n\n if (state.modifiersData.popperOffsets != null) {\n state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {\n offsets: state.modifiersData.popperOffsets,\n position: state.options.strategy,\n adaptive: adaptive,\n roundOffsets: roundOffsets\n })));\n }\n\n if (state.modifiersData.arrow != null) {\n state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {\n offsets: state.modifiersData.arrow,\n position: 'absolute',\n adaptive: false,\n roundOffsets: roundOffsets\n })));\n }\n\n state.attributes.popper = Object.assign({}, state.attributes.popper, {\n 'data-popper-placement': state.placement\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'computeStyles',\n enabled: true,\n phase: 'beforeWrite',\n fn: computeStyles,\n data: {}\n};", "import getWindow from \"../dom-utils/getWindow.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar passive = {\n passive: true\n};\n\nfunction effect(_ref) {\n var state = _ref.state,\n instance = _ref.instance,\n options = _ref.options;\n var _options$scroll = options.scroll,\n scroll = _options$scroll === void 0 ? true : _options$scroll,\n _options$resize = options.resize,\n resize = _options$resize === void 0 ? true : _options$resize;\n var window = getWindow(state.elements.popper);\n var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);\n\n if (scroll) {\n scrollParents.forEach(function (scrollParent) {\n scrollParent.addEventListener('scroll', instance.update, passive);\n });\n }\n\n if (resize) {\n window.addEventListener('resize', instance.update, passive);\n }\n\n return function () {\n if (scroll) {\n scrollParents.forEach(function (scrollParent) {\n scrollParent.removeEventListener('scroll', instance.update, passive);\n });\n }\n\n if (resize) {\n window.removeEventListener('resize', instance.update, passive);\n }\n };\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'eventListeners',\n enabled: true,\n phase: 'write',\n fn: function fn() {},\n effect: effect,\n data: {}\n};", "var hash = {\n left: 'right',\n right: 'left',\n bottom: 'top',\n top: 'bottom'\n};\nexport default function getOppositePlacement(placement) {\n return placement.replace(/left|right|bottom|top/g, function (matched) {\n return hash[matched];\n });\n}", "var hash = {\n start: 'end',\n end: 'start'\n};\nexport default function getOppositeVariationPlacement(placement) {\n return placement.replace(/start|end/g, function (matched) {\n return hash[matched];\n });\n}", "import getWindow from \"./getWindow.js\";\nexport default function getWindowScroll(node) {\n var win = getWindow(node);\n var scrollLeft = win.pageXOffset;\n var scrollTop = win.pageYOffset;\n return {\n scrollLeft: scrollLeft,\n scrollTop: scrollTop\n };\n}", "import getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getWindowScroll from \"./getWindowScroll.js\";\nexport default function getWindowScrollBarX(element) {\n // If has a CSS width greater than the viewport, then this will be\n // incorrect for RTL.\n // Popper 1 is broken in this case and never had a bug report so let's assume\n // it's not an issue. I don't think anyone ever specifies width on \n // anyway.\n // Browsers where the left scrollbar doesn't cause an issue report `0` for\n // this (e.g. Edge 2019, IE11, Safari)\n return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;\n}", "import getWindow from \"./getWindow.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport isLayoutViewport from \"./isLayoutViewport.js\";\nexport default function getViewportRect(element, strategy) {\n var win = getWindow(element);\n var html = getDocumentElement(element);\n var visualViewport = win.visualViewport;\n var width = html.clientWidth;\n var height = html.clientHeight;\n var x = 0;\n var y = 0;\n\n if (visualViewport) {\n width = visualViewport.width;\n height = visualViewport.height;\n var layoutViewport = isLayoutViewport();\n\n if (layoutViewport || !layoutViewport && strategy === 'fixed') {\n x = visualViewport.offsetLeft;\n y = visualViewport.offsetTop;\n }\n }\n\n return {\n width: width,\n height: height,\n x: x + getWindowScrollBarX(element),\n y: y\n };\n}", "import getDocumentElement from \"./getDocumentElement.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport getWindowScroll from \"./getWindowScroll.js\";\nimport { max } from \"../utils/math.js\"; // Gets the entire size of the scrollable document area, even extending outside\n// of the `` and `` rect bounds if horizontally scrollable\n\nexport default function getDocumentRect(element) {\n var _element$ownerDocumen;\n\n var html = getDocumentElement(element);\n var winScroll = getWindowScroll(element);\n var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;\n var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);\n var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);\n var x = -winScroll.scrollLeft + getWindowScrollBarX(element);\n var y = -winScroll.scrollTop;\n\n if (getComputedStyle(body || html).direction === 'rtl') {\n x += max(html.clientWidth, body ? body.clientWidth : 0) - width;\n }\n\n return {\n width: width,\n height: height,\n x: x,\n y: y\n };\n}", "import getComputedStyle from \"./getComputedStyle.js\";\nexport default function isScrollParent(element) {\n // Firefox wants us to check `-x` and `-y` variations as well\n var _getComputedStyle = getComputedStyle(element),\n overflow = _getComputedStyle.overflow,\n overflowX = _getComputedStyle.overflowX,\n overflowY = _getComputedStyle.overflowY;\n\n return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);\n}", "import getParentNode from \"./getParentNode.js\";\nimport isScrollParent from \"./isScrollParent.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nexport default function getScrollParent(node) {\n if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {\n // $FlowFixMe[incompatible-return]: assume body is always available\n return node.ownerDocument.body;\n }\n\n if (isHTMLElement(node) && isScrollParent(node)) {\n return node;\n }\n\n return getScrollParent(getParentNode(node));\n}", "import getScrollParent from \"./getScrollParent.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport getWindow from \"./getWindow.js\";\nimport isScrollParent from \"./isScrollParent.js\";\n/*\ngiven a DOM element, return the list of all scroll parents, up the list of ancesors\nuntil we get to the top window object. This list is what we attach scroll listeners\nto, because if any of these parent elements scroll, we'll need to re-calculate the\nreference element's position.\n*/\n\nexport default function listScrollParents(element, list) {\n var _element$ownerDocumen;\n\n if (list === void 0) {\n list = [];\n }\n\n var scrollParent = getScrollParent(element);\n var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);\n var win = getWindow(scrollParent);\n var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;\n var updatedList = list.concat(target);\n return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here\n updatedList.concat(listScrollParents(getParentNode(target)));\n}", "export default function rectToClientRect(rect) {\n return Object.assign({}, rect, {\n left: rect.x,\n top: rect.y,\n right: rect.x + rect.width,\n bottom: rect.y + rect.height\n });\n}", "import { viewport } from \"../enums.js\";\nimport getViewportRect from \"./getViewportRect.js\";\nimport getDocumentRect from \"./getDocumentRect.js\";\nimport listScrollParents from \"./listScrollParents.js\";\nimport getOffsetParent from \"./getOffsetParent.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport { isElement, isHTMLElement } from \"./instanceOf.js\";\nimport getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport contains from \"./contains.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport rectToClientRect from \"../utils/rectToClientRect.js\";\nimport { max, min } from \"../utils/math.js\";\n\nfunction getInnerBoundingClientRect(element, strategy) {\n var rect = getBoundingClientRect(element, false, strategy === 'fixed');\n rect.top = rect.top + element.clientTop;\n rect.left = rect.left + element.clientLeft;\n rect.bottom = rect.top + element.clientHeight;\n rect.right = rect.left + element.clientWidth;\n rect.width = element.clientWidth;\n rect.height = element.clientHeight;\n rect.x = rect.left;\n rect.y = rect.top;\n return rect;\n}\n\nfunction getClientRectFromMixedType(element, clippingParent, strategy) {\n return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element)));\n} // A \"clipping parent\" is an overflowable container with the characteristic of\n// clipping (or hiding) overflowing elements with a position different from\n// `initial`\n\n\nfunction getClippingParents(element) {\n var clippingParents = listScrollParents(getParentNode(element));\n var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle(element).position) >= 0;\n var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;\n\n if (!isElement(clipperElement)) {\n return [];\n } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414\n\n\n return clippingParents.filter(function (clippingParent) {\n return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';\n });\n} // Gets the maximum area that the element is visible in due to any number of\n// clipping parents\n\n\nexport default function getClippingRect(element, boundary, rootBoundary, strategy) {\n var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);\n var clippingParents = [].concat(mainClippingParents, [rootBoundary]);\n var firstClippingParent = clippingParents[0];\n var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {\n var rect = getClientRectFromMixedType(element, clippingParent, strategy);\n accRect.top = max(rect.top, accRect.top);\n accRect.right = min(rect.right, accRect.right);\n accRect.bottom = min(rect.bottom, accRect.bottom);\n accRect.left = max(rect.left, accRect.left);\n return accRect;\n }, getClientRectFromMixedType(element, firstClippingParent, strategy));\n clippingRect.width = clippingRect.right - clippingRect.left;\n clippingRect.height = clippingRect.bottom - clippingRect.top;\n clippingRect.x = clippingRect.left;\n clippingRect.y = clippingRect.top;\n return clippingRect;\n}", "import getBasePlacement from \"./getBasePlacement.js\";\nimport getVariation from \"./getVariation.js\";\nimport getMainAxisFromPlacement from \"./getMainAxisFromPlacement.js\";\nimport { top, right, bottom, left, start, end } from \"../enums.js\";\nexport default function computeOffsets(_ref) {\n var reference = _ref.reference,\n element = _ref.element,\n placement = _ref.placement;\n var basePlacement = placement ? getBasePlacement(placement) : null;\n var variation = placement ? getVariation(placement) : null;\n var commonX = reference.x + reference.width / 2 - element.width / 2;\n var commonY = reference.y + reference.height / 2 - element.height / 2;\n var offsets;\n\n switch (basePlacement) {\n case top:\n offsets = {\n x: commonX,\n y: reference.y - element.height\n };\n break;\n\n case bottom:\n offsets = {\n x: commonX,\n y: reference.y + reference.height\n };\n break;\n\n case right:\n offsets = {\n x: reference.x + reference.width,\n y: commonY\n };\n break;\n\n case left:\n offsets = {\n x: reference.x - element.width,\n y: commonY\n };\n break;\n\n default:\n offsets = {\n x: reference.x,\n y: reference.y\n };\n }\n\n var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;\n\n if (mainAxis != null) {\n var len = mainAxis === 'y' ? 'height' : 'width';\n\n switch (variation) {\n case start:\n offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);\n break;\n\n case end:\n offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);\n break;\n\n default:\n }\n }\n\n return offsets;\n}", "import getClippingRect from \"../dom-utils/getClippingRect.js\";\nimport getDocumentElement from \"../dom-utils/getDocumentElement.js\";\nimport getBoundingClientRect from \"../dom-utils/getBoundingClientRect.js\";\nimport computeOffsets from \"./computeOffsets.js\";\nimport rectToClientRect from \"./rectToClientRect.js\";\nimport { clippingParents, reference, popper, bottom, top, right, basePlacements, viewport } from \"../enums.js\";\nimport { isElement } from \"../dom-utils/instanceOf.js\";\nimport mergePaddingObject from \"./mergePaddingObject.js\";\nimport expandToHashMap from \"./expandToHashMap.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport default function detectOverflow(state, options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n _options$placement = _options.placement,\n placement = _options$placement === void 0 ? state.placement : _options$placement,\n _options$strategy = _options.strategy,\n strategy = _options$strategy === void 0 ? state.strategy : _options$strategy,\n _options$boundary = _options.boundary,\n boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,\n _options$rootBoundary = _options.rootBoundary,\n rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,\n _options$elementConte = _options.elementContext,\n elementContext = _options$elementConte === void 0 ? popper : _options$elementConte,\n _options$altBoundary = _options.altBoundary,\n altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,\n _options$padding = _options.padding,\n padding = _options$padding === void 0 ? 0 : _options$padding;\n var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));\n var altContext = elementContext === popper ? reference : popper;\n var popperRect = state.rects.popper;\n var element = state.elements[altBoundary ? altContext : elementContext];\n var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy);\n var referenceClientRect = getBoundingClientRect(state.elements.reference);\n var popperOffsets = computeOffsets({\n reference: referenceClientRect,\n element: popperRect,\n strategy: 'absolute',\n placement: placement\n });\n var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets));\n var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect\n // 0 or negative = within the clipping rect\n\n var overflowOffsets = {\n top: clippingClientRect.top - elementClientRect.top + paddingObject.top,\n bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,\n left: clippingClientRect.left - elementClientRect.left + paddingObject.left,\n right: elementClientRect.right - clippingClientRect.right + paddingObject.right\n };\n var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element\n\n if (elementContext === popper && offsetData) {\n var offset = offsetData[placement];\n Object.keys(overflowOffsets).forEach(function (key) {\n var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;\n var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x';\n overflowOffsets[key] += offset[axis] * multiply;\n });\n }\n\n return overflowOffsets;\n}", "import getVariation from \"./getVariation.js\";\nimport { variationPlacements, basePlacements, placements as allPlacements } from \"../enums.js\";\nimport detectOverflow from \"./detectOverflow.js\";\nimport getBasePlacement from \"./getBasePlacement.js\";\nexport default function computeAutoPlacement(state, options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n placement = _options.placement,\n boundary = _options.boundary,\n rootBoundary = _options.rootBoundary,\n padding = _options.padding,\n flipVariations = _options.flipVariations,\n _options$allowedAutoP = _options.allowedAutoPlacements,\n allowedAutoPlacements = _options$allowedAutoP === void 0 ? allPlacements : _options$allowedAutoP;\n var variation = getVariation(placement);\n var placements = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {\n return getVariation(placement) === variation;\n }) : basePlacements;\n var allowedPlacements = placements.filter(function (placement) {\n return allowedAutoPlacements.indexOf(placement) >= 0;\n });\n\n if (allowedPlacements.length === 0) {\n allowedPlacements = placements;\n } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...\n\n\n var overflows = allowedPlacements.reduce(function (acc, placement) {\n acc[placement] = detectOverflow(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding\n })[getBasePlacement(placement)];\n return acc;\n }, {});\n return Object.keys(overflows).sort(function (a, b) {\n return overflows[a] - overflows[b];\n });\n}", "import getOppositePlacement from \"../utils/getOppositePlacement.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getOppositeVariationPlacement from \"../utils/getOppositeVariationPlacement.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\nimport computeAutoPlacement from \"../utils/computeAutoPlacement.js\";\nimport { bottom, top, start, right, left, auto } from \"../enums.js\";\nimport getVariation from \"../utils/getVariation.js\"; // eslint-disable-next-line import/no-unused-modules\n\nfunction getExpandedFallbackPlacements(placement) {\n if (getBasePlacement(placement) === auto) {\n return [];\n }\n\n var oppositePlacement = getOppositePlacement(placement);\n return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];\n}\n\nfunction flip(_ref) {\n var state = _ref.state,\n options = _ref.options,\n name = _ref.name;\n\n if (state.modifiersData[name]._skip) {\n return;\n }\n\n var _options$mainAxis = options.mainAxis,\n checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,\n _options$altAxis = options.altAxis,\n checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,\n specifiedFallbackPlacements = options.fallbackPlacements,\n padding = options.padding,\n boundary = options.boundary,\n rootBoundary = options.rootBoundary,\n altBoundary = options.altBoundary,\n _options$flipVariatio = options.flipVariations,\n flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,\n allowedAutoPlacements = options.allowedAutoPlacements;\n var preferredPlacement = state.options.placement;\n var basePlacement = getBasePlacement(preferredPlacement);\n var isBasePlacement = basePlacement === preferredPlacement;\n var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));\n var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {\n return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding,\n flipVariations: flipVariations,\n allowedAutoPlacements: allowedAutoPlacements\n }) : placement);\n }, []);\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var checksMap = new Map();\n var makeFallbackChecks = true;\n var firstFittingPlacement = placements[0];\n\n for (var i = 0; i < placements.length; i++) {\n var placement = placements[i];\n\n var _basePlacement = getBasePlacement(placement);\n\n var isStartVariation = getVariation(placement) === start;\n var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;\n var len = isVertical ? 'width' : 'height';\n var overflow = detectOverflow(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n altBoundary: altBoundary,\n padding: padding\n });\n var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;\n\n if (referenceRect[len] > popperRect[len]) {\n mainVariationSide = getOppositePlacement(mainVariationSide);\n }\n\n var altVariationSide = getOppositePlacement(mainVariationSide);\n var checks = [];\n\n if (checkMainAxis) {\n checks.push(overflow[_basePlacement] <= 0);\n }\n\n if (checkAltAxis) {\n checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);\n }\n\n if (checks.every(function (check) {\n return check;\n })) {\n firstFittingPlacement = placement;\n makeFallbackChecks = false;\n break;\n }\n\n checksMap.set(placement, checks);\n }\n\n if (makeFallbackChecks) {\n // `2` may be desired in some cases \u2013 research later\n var numberOfChecks = flipVariations ? 3 : 1;\n\n var _loop = function _loop(_i) {\n var fittingPlacement = placements.find(function (placement) {\n var checks = checksMap.get(placement);\n\n if (checks) {\n return checks.slice(0, _i).every(function (check) {\n return check;\n });\n }\n });\n\n if (fittingPlacement) {\n firstFittingPlacement = fittingPlacement;\n return \"break\";\n }\n };\n\n for (var _i = numberOfChecks; _i > 0; _i--) {\n var _ret = _loop(_i);\n\n if (_ret === \"break\") break;\n }\n }\n\n if (state.placement !== firstFittingPlacement) {\n state.modifiersData[name]._skip = true;\n state.placement = firstFittingPlacement;\n state.reset = true;\n }\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'flip',\n enabled: true,\n phase: 'main',\n fn: flip,\n requiresIfExists: ['offset'],\n data: {\n _skip: false\n }\n};", "import { top, bottom, left, right } from \"../enums.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\n\nfunction getSideOffsets(overflow, rect, preventedOffsets) {\n if (preventedOffsets === void 0) {\n preventedOffsets = {\n x: 0,\n y: 0\n };\n }\n\n return {\n top: overflow.top - rect.height - preventedOffsets.y,\n right: overflow.right - rect.width + preventedOffsets.x,\n bottom: overflow.bottom - rect.height + preventedOffsets.y,\n left: overflow.left - rect.width - preventedOffsets.x\n };\n}\n\nfunction isAnySideFullyClipped(overflow) {\n return [top, right, bottom, left].some(function (side) {\n return overflow[side] >= 0;\n });\n}\n\nfunction hide(_ref) {\n var state = _ref.state,\n name = _ref.name;\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var preventedOffsets = state.modifiersData.preventOverflow;\n var referenceOverflow = detectOverflow(state, {\n elementContext: 'reference'\n });\n var popperAltOverflow = detectOverflow(state, {\n altBoundary: true\n });\n var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);\n var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);\n var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);\n var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);\n state.modifiersData[name] = {\n referenceClippingOffsets: referenceClippingOffsets,\n popperEscapeOffsets: popperEscapeOffsets,\n isReferenceHidden: isReferenceHidden,\n hasPopperEscaped: hasPopperEscaped\n };\n state.attributes.popper = Object.assign({}, state.attributes.popper, {\n 'data-popper-reference-hidden': isReferenceHidden,\n 'data-popper-escaped': hasPopperEscaped\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'hide',\n enabled: true,\n phase: 'main',\n requiresIfExists: ['preventOverflow'],\n fn: hide\n};", "import getBasePlacement from \"../utils/getBasePlacement.js\";\nimport { top, left, right, placements } from \"../enums.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport function distanceAndSkiddingToXY(placement, rects, offset) {\n var basePlacement = getBasePlacement(placement);\n var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;\n\n var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, {\n placement: placement\n })) : offset,\n skidding = _ref[0],\n distance = _ref[1];\n\n skidding = skidding || 0;\n distance = (distance || 0) * invertDistance;\n return [left, right].indexOf(basePlacement) >= 0 ? {\n x: distance,\n y: skidding\n } : {\n x: skidding,\n y: distance\n };\n}\n\nfunction offset(_ref2) {\n var state = _ref2.state,\n options = _ref2.options,\n name = _ref2.name;\n var _options$offset = options.offset,\n offset = _options$offset === void 0 ? [0, 0] : _options$offset;\n var data = placements.reduce(function (acc, placement) {\n acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);\n return acc;\n }, {});\n var _data$state$placement = data[state.placement],\n x = _data$state$placement.x,\n y = _data$state$placement.y;\n\n if (state.modifiersData.popperOffsets != null) {\n state.modifiersData.popperOffsets.x += x;\n state.modifiersData.popperOffsets.y += y;\n }\n\n state.modifiersData[name] = data;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'offset',\n enabled: true,\n phase: 'main',\n requires: ['popperOffsets'],\n fn: offset\n};", "import computeOffsets from \"../utils/computeOffsets.js\";\n\nfunction popperOffsets(_ref) {\n var state = _ref.state,\n name = _ref.name;\n // Offsets are the actual position the popper needs to have to be\n // properly positioned near its reference element\n // This is the most basic placement, and will be adjusted by\n // the modifiers in the next step\n state.modifiersData[name] = computeOffsets({\n reference: state.rects.reference,\n element: state.rects.popper,\n strategy: 'absolute',\n placement: state.placement\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'popperOffsets',\n enabled: true,\n phase: 'read',\n fn: popperOffsets,\n data: {}\n};", "export default function getAltAxis(axis) {\n return axis === 'x' ? 'y' : 'x';\n}", "import { top, left, right, bottom, start } from \"../enums.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getMainAxisFromPlacement from \"../utils/getMainAxisFromPlacement.js\";\nimport getAltAxis from \"../utils/getAltAxis.js\";\nimport { within, withinMaxClamp } from \"../utils/within.js\";\nimport getLayoutRect from \"../dom-utils/getLayoutRect.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\nimport getVariation from \"../utils/getVariation.js\";\nimport getFreshSideObject from \"../utils/getFreshSideObject.js\";\nimport { min as mathMin, max as mathMax } from \"../utils/math.js\";\n\nfunction preventOverflow(_ref) {\n var state = _ref.state,\n options = _ref.options,\n name = _ref.name;\n var _options$mainAxis = options.mainAxis,\n checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,\n _options$altAxis = options.altAxis,\n checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,\n boundary = options.boundary,\n rootBoundary = options.rootBoundary,\n altBoundary = options.altBoundary,\n padding = options.padding,\n _options$tether = options.tether,\n tether = _options$tether === void 0 ? true : _options$tether,\n _options$tetherOffset = options.tetherOffset,\n tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;\n var overflow = detectOverflow(state, {\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding,\n altBoundary: altBoundary\n });\n var basePlacement = getBasePlacement(state.placement);\n var variation = getVariation(state.placement);\n var isBasePlacement = !variation;\n var mainAxis = getMainAxisFromPlacement(basePlacement);\n var altAxis = getAltAxis(mainAxis);\n var popperOffsets = state.modifiersData.popperOffsets;\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, {\n placement: state.placement\n })) : tetherOffset;\n var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? {\n mainAxis: tetherOffsetValue,\n altAxis: tetherOffsetValue\n } : Object.assign({\n mainAxis: 0,\n altAxis: 0\n }, tetherOffsetValue);\n var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;\n var data = {\n x: 0,\n y: 0\n };\n\n if (!popperOffsets) {\n return;\n }\n\n if (checkMainAxis) {\n var _offsetModifierState$;\n\n var mainSide = mainAxis === 'y' ? top : left;\n var altSide = mainAxis === 'y' ? bottom : right;\n var len = mainAxis === 'y' ? 'height' : 'width';\n var offset = popperOffsets[mainAxis];\n var min = offset + overflow[mainSide];\n var max = offset - overflow[altSide];\n var additive = tether ? -popperRect[len] / 2 : 0;\n var minLen = variation === start ? referenceRect[len] : popperRect[len];\n var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go\n // outside the reference bounds\n\n var arrowElement = state.elements.arrow;\n var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {\n width: 0,\n height: 0\n };\n var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();\n var arrowPaddingMin = arrowPaddingObject[mainSide];\n var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want\n // to include its full size in the calculation. If the reference is small\n // and near the edge of a boundary, the popper can overflow even if the\n // reference is not overflowing as well (e.g. virtual elements with no\n // width or height)\n\n var arrowLen = within(0, referenceRect[len], arrowRect[len]);\n var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;\n var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;\n var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);\n var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;\n var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;\n var tetherMin = offset + minOffset - offsetModifierValue - clientOffset;\n var tetherMax = offset + maxOffset - offsetModifierValue;\n var preventedOffset = within(tether ? mathMin(min, tetherMin) : min, offset, tether ? mathMax(max, tetherMax) : max);\n popperOffsets[mainAxis] = preventedOffset;\n data[mainAxis] = preventedOffset - offset;\n }\n\n if (checkAltAxis) {\n var _offsetModifierState$2;\n\n var _mainSide = mainAxis === 'x' ? top : left;\n\n var _altSide = mainAxis === 'x' ? bottom : right;\n\n var _offset = popperOffsets[altAxis];\n\n var _len = altAxis === 'y' ? 'height' : 'width';\n\n var _min = _offset + overflow[_mainSide];\n\n var _max = _offset - overflow[_altSide];\n\n var isOriginSide = [top, left].indexOf(basePlacement) !== -1;\n\n var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;\n\n var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;\n\n var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;\n\n var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);\n\n popperOffsets[altAxis] = _preventedOffset;\n data[altAxis] = _preventedOffset - _offset;\n }\n\n state.modifiersData[name] = data;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'preventOverflow',\n enabled: true,\n phase: 'main',\n fn: preventOverflow,\n requiresIfExists: ['offset']\n};", "export default function getHTMLElementScroll(element) {\n return {\n scrollLeft: element.scrollLeft,\n scrollTop: element.scrollTop\n };\n}", "import getWindowScroll from \"./getWindowScroll.js\";\nimport getWindow from \"./getWindow.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nimport getHTMLElementScroll from \"./getHTMLElementScroll.js\";\nexport default function getNodeScroll(node) {\n if (node === getWindow(node) || !isHTMLElement(node)) {\n return getWindowScroll(node);\n } else {\n return getHTMLElementScroll(node);\n }\n}", "import getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getNodeScroll from \"./getNodeScroll.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport isScrollParent from \"./isScrollParent.js\";\nimport { round } from \"../utils/math.js\";\n\nfunction isElementScaled(element) {\n var rect = element.getBoundingClientRect();\n var scaleX = round(rect.width) / element.offsetWidth || 1;\n var scaleY = round(rect.height) / element.offsetHeight || 1;\n return scaleX !== 1 || scaleY !== 1;\n} // Returns the composite rect of an element relative to its offsetParent.\n// Composite means it takes into account transforms as well as layout.\n\n\nexport default function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {\n if (isFixed === void 0) {\n isFixed = false;\n }\n\n var isOffsetParentAnElement = isHTMLElement(offsetParent);\n var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent);\n var documentElement = getDocumentElement(offsetParent);\n var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed);\n var scroll = {\n scrollLeft: 0,\n scrollTop: 0\n };\n var offsets = {\n x: 0,\n y: 0\n };\n\n if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078\n isScrollParent(documentElement)) {\n scroll = getNodeScroll(offsetParent);\n }\n\n if (isHTMLElement(offsetParent)) {\n offsets = getBoundingClientRect(offsetParent, true);\n offsets.x += offsetParent.clientLeft;\n offsets.y += offsetParent.clientTop;\n } else if (documentElement) {\n offsets.x = getWindowScrollBarX(documentElement);\n }\n }\n\n return {\n x: rect.left + scroll.scrollLeft - offsets.x,\n y: rect.top + scroll.scrollTop - offsets.y,\n width: rect.width,\n height: rect.height\n };\n}", "import { modifierPhases } from \"../enums.js\"; // source: https://stackoverflow.com/questions/49875255\n\nfunction order(modifiers) {\n var map = new Map();\n var visited = new Set();\n var result = [];\n modifiers.forEach(function (modifier) {\n map.set(modifier.name, modifier);\n }); // On visiting object, check for its dependencies and visit them recursively\n\n function sort(modifier) {\n visited.add(modifier.name);\n var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);\n requires.forEach(function (dep) {\n if (!visited.has(dep)) {\n var depModifier = map.get(dep);\n\n if (depModifier) {\n sort(depModifier);\n }\n }\n });\n result.push(modifier);\n }\n\n modifiers.forEach(function (modifier) {\n if (!visited.has(modifier.name)) {\n // check for visited object\n sort(modifier);\n }\n });\n return result;\n}\n\nexport default function orderModifiers(modifiers) {\n // order based on dependencies\n var orderedModifiers = order(modifiers); // order based on phase\n\n return modifierPhases.reduce(function (acc, phase) {\n return acc.concat(orderedModifiers.filter(function (modifier) {\n return modifier.phase === phase;\n }));\n }, []);\n}", "export default function debounce(fn) {\n var pending;\n return function () {\n if (!pending) {\n pending = new Promise(function (resolve) {\n Promise.resolve().then(function () {\n pending = undefined;\n resolve(fn());\n });\n });\n }\n\n return pending;\n };\n}", "export default function mergeByName(modifiers) {\n var merged = modifiers.reduce(function (merged, current) {\n var existing = merged[current.name];\n merged[current.name] = existing ? Object.assign({}, existing, current, {\n options: Object.assign({}, existing.options, current.options),\n data: Object.assign({}, existing.data, current.data)\n }) : current;\n return merged;\n }, {}); // IE11 does not support Object.values\n\n return Object.keys(merged).map(function (key) {\n return merged[key];\n });\n}", "import getCompositeRect from \"./dom-utils/getCompositeRect.js\";\nimport getLayoutRect from \"./dom-utils/getLayoutRect.js\";\nimport listScrollParents from \"./dom-utils/listScrollParents.js\";\nimport getOffsetParent from \"./dom-utils/getOffsetParent.js\";\nimport orderModifiers from \"./utils/orderModifiers.js\";\nimport debounce from \"./utils/debounce.js\";\nimport mergeByName from \"./utils/mergeByName.js\";\nimport detectOverflow from \"./utils/detectOverflow.js\";\nimport { isElement } from \"./dom-utils/instanceOf.js\";\nvar DEFAULT_OPTIONS = {\n placement: 'bottom',\n modifiers: [],\n strategy: 'absolute'\n};\n\nfunction areValidElements() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return !args.some(function (element) {\n return !(element && typeof element.getBoundingClientRect === 'function');\n });\n}\n\nexport function popperGenerator(generatorOptions) {\n if (generatorOptions === void 0) {\n generatorOptions = {};\n }\n\n var _generatorOptions = generatorOptions,\n _generatorOptions$def = _generatorOptions.defaultModifiers,\n defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,\n _generatorOptions$def2 = _generatorOptions.defaultOptions,\n defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;\n return function createPopper(reference, popper, options) {\n if (options === void 0) {\n options = defaultOptions;\n }\n\n var state = {\n placement: 'bottom',\n orderedModifiers: [],\n options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),\n modifiersData: {},\n elements: {\n reference: reference,\n popper: popper\n },\n attributes: {},\n styles: {}\n };\n var effectCleanupFns = [];\n var isDestroyed = false;\n var instance = {\n state: state,\n setOptions: function setOptions(setOptionsAction) {\n var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction;\n cleanupModifierEffects();\n state.options = Object.assign({}, defaultOptions, state.options, options);\n state.scrollParents = {\n reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],\n popper: listScrollParents(popper)\n }; // Orders the modifiers based on their dependencies and `phase`\n // properties\n\n var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers\n\n state.orderedModifiers = orderedModifiers.filter(function (m) {\n return m.enabled;\n });\n runModifierEffects();\n return instance.update();\n },\n // Sync update \u2013 it will always be executed, even if not necessary. This\n // is useful for low frequency updates where sync behavior simplifies the\n // logic.\n // For high frequency updates (e.g. `resize` and `scroll` events), always\n // prefer the async Popper#update method\n forceUpdate: function forceUpdate() {\n if (isDestroyed) {\n return;\n }\n\n var _state$elements = state.elements,\n reference = _state$elements.reference,\n popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements\n // anymore\n\n if (!areValidElements(reference, popper)) {\n return;\n } // Store the reference and popper rects to be read by modifiers\n\n\n state.rects = {\n reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),\n popper: getLayoutRect(popper)\n }; // Modifiers have the ability to reset the current update cycle. The\n // most common use case for this is the `flip` modifier changing the\n // placement, which then needs to re-run all the modifiers, because the\n // logic was previously ran for the previous placement and is therefore\n // stale/incorrect\n\n state.reset = false;\n state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier\n // is filled with the initial data specified by the modifier. This means\n // it doesn't persist and is fresh on each update.\n // To ensure persistent data, use `${name}#persistent`\n\n state.orderedModifiers.forEach(function (modifier) {\n return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);\n });\n\n for (var index = 0; index < state.orderedModifiers.length; index++) {\n if (state.reset === true) {\n state.reset = false;\n index = -1;\n continue;\n }\n\n var _state$orderedModifie = state.orderedModifiers[index],\n fn = _state$orderedModifie.fn,\n _state$orderedModifie2 = _state$orderedModifie.options,\n _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,\n name = _state$orderedModifie.name;\n\n if (typeof fn === 'function') {\n state = fn({\n state: state,\n options: _options,\n name: name,\n instance: instance\n }) || state;\n }\n }\n },\n // Async and optimistically optimized update \u2013 it will not be executed if\n // not necessary (debounced to run at most once-per-tick)\n update: debounce(function () {\n return new Promise(function (resolve) {\n instance.forceUpdate();\n resolve(state);\n });\n }),\n destroy: function destroy() {\n cleanupModifierEffects();\n isDestroyed = true;\n }\n };\n\n if (!areValidElements(reference, popper)) {\n return instance;\n }\n\n instance.setOptions(options).then(function (state) {\n if (!isDestroyed && options.onFirstUpdate) {\n options.onFirstUpdate(state);\n }\n }); // Modifiers have the ability to execute arbitrary code before the first\n // update cycle runs. They will be executed in the same order as the update\n // cycle. This is useful when a modifier adds some persistent data that\n // other modifiers need to use, but the modifier is run after the dependent\n // one.\n\n function runModifierEffects() {\n state.orderedModifiers.forEach(function (_ref) {\n var name = _ref.name,\n _ref$options = _ref.options,\n options = _ref$options === void 0 ? {} : _ref$options,\n effect = _ref.effect;\n\n if (typeof effect === 'function') {\n var cleanupFn = effect({\n state: state,\n name: name,\n instance: instance,\n options: options\n });\n\n var noopFn = function noopFn() {};\n\n effectCleanupFns.push(cleanupFn || noopFn);\n }\n });\n }\n\n function cleanupModifierEffects() {\n effectCleanupFns.forEach(function (fn) {\n return fn();\n });\n effectCleanupFns = [];\n }\n\n return instance;\n };\n}\nexport var createPopper = /*#__PURE__*/popperGenerator(); // eslint-disable-next-line import/no-unused-modules\n\nexport { detectOverflow };", "import { popperGenerator, detectOverflow } from \"./createPopper.js\";\nimport eventListeners from \"./modifiers/eventListeners.js\";\nimport popperOffsets from \"./modifiers/popperOffsets.js\";\nimport computeStyles from \"./modifiers/computeStyles.js\";\nimport applyStyles from \"./modifiers/applyStyles.js\";\nimport offset from \"./modifiers/offset.js\";\nimport flip from \"./modifiers/flip.js\";\nimport preventOverflow from \"./modifiers/preventOverflow.js\";\nimport arrow from \"./modifiers/arrow.js\";\nimport hide from \"./modifiers/hide.js\";\nvar defaultModifiers = [eventListeners, popperOffsets, computeStyles, applyStyles, offset, flip, preventOverflow, arrow, hide];\nvar createPopper = /*#__PURE__*/popperGenerator({\n defaultModifiers: defaultModifiers\n}); // eslint-disable-next-line import/no-unused-modules\n\nexport { createPopper, popperGenerator, defaultModifiers, detectOverflow }; // eslint-disable-next-line import/no-unused-modules\n\nexport { createPopper as createPopperLite } from \"./popper-lite.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport * from \"./modifiers/index.js\";", "export const ROUND_ARROW =\n '';\n\nexport const BOX_CLASS = `__NAMESPACE_PREFIX__-box`;\nexport const CONTENT_CLASS = `__NAMESPACE_PREFIX__-content`;\nexport const BACKDROP_CLASS = `__NAMESPACE_PREFIX__-backdrop`;\nexport const ARROW_CLASS = `__NAMESPACE_PREFIX__-arrow`;\nexport const SVG_ARROW_CLASS = `__NAMESPACE_PREFIX__-svg-arrow`;\n\nexport const TOUCH_OPTIONS = {passive: true, capture: true};\n\nexport const TIPPY_DEFAULT_APPEND_TO = () => document.body;\n", "import {BasePlacement, Placement} from './types';\n\nexport function hasOwnProperty(\n obj: Record,\n key: string\n): boolean {\n return {}.hasOwnProperty.call(obj, key);\n}\n\nexport function getValueAtIndexOrReturn(\n value: T | [T | null, T | null],\n index: number,\n defaultValue: T | [T, T]\n): T {\n if (Array.isArray(value)) {\n const v = value[index];\n return v == null\n ? Array.isArray(defaultValue)\n ? defaultValue[index]\n : defaultValue\n : v;\n }\n\n return value;\n}\n\nexport function isType(value: any, type: string): boolean {\n const str = {}.toString.call(value);\n return str.indexOf('[object') === 0 && str.indexOf(`${type}]`) > -1;\n}\n\nexport function invokeWithArgsOrReturn(value: any, args: any[]): any {\n return typeof value === 'function' ? value(...args) : value;\n}\n\nexport function debounce(\n fn: (arg: T) => void,\n ms: number\n): (arg: T) => void {\n // Avoid wrapping in `setTimeout` if ms is 0 anyway\n if (ms === 0) {\n return fn;\n }\n\n let timeout: any;\n\n return (arg): void => {\n clearTimeout(timeout);\n timeout = setTimeout(() => {\n fn(arg);\n }, ms);\n };\n}\n\nexport function removeProperties(obj: T, keys: string[]): Partial {\n const clone = {...obj};\n keys.forEach((key) => {\n delete (clone as any)[key];\n });\n return clone;\n}\n\nexport function splitBySpaces(value: string): string[] {\n return value.split(/\\s+/).filter(Boolean);\n}\n\nexport function normalizeToArray(value: T | T[]): T[] {\n return ([] as T[]).concat(value);\n}\n\nexport function pushIfUnique(arr: T[], value: T): void {\n if (arr.indexOf(value) === -1) {\n arr.push(value);\n }\n}\n\nexport function appendPxIfNumber(value: string | number): string {\n return typeof value === 'number' ? `${value}px` : value;\n}\n\nexport function unique(arr: T[]): T[] {\n return arr.filter((item, index) => arr.indexOf(item) === index);\n}\n\nexport function getNumber(value: string | number): number {\n return typeof value === 'number' ? value : parseFloat(value);\n}\n\nexport function getBasePlacement(placement: Placement): BasePlacement {\n return placement.split('-')[0] as BasePlacement;\n}\n\nexport function arrayFrom(value: ArrayLike): any[] {\n return [].slice.call(value);\n}\n\nexport function removeUndefinedProps(\n obj: Record\n): Partial> {\n return Object.keys(obj).reduce((acc, key) => {\n if (obj[key] !== undefined) {\n (acc as any)[key] = obj[key];\n }\n\n return acc;\n }, {});\n}\n", "import {ReferenceElement, Targets} from './types';\nimport {PopperTreeData} from './types-internal';\nimport {arrayFrom, isType, normalizeToArray, getBasePlacement} from './utils';\n\nexport function div(): HTMLDivElement {\n return document.createElement('div');\n}\n\nexport function isElement(value: unknown): value is Element | DocumentFragment {\n return ['Element', 'Fragment'].some((type) => isType(value, type));\n}\n\nexport function isNodeList(value: unknown): value is NodeList {\n return isType(value, 'NodeList');\n}\n\nexport function isMouseEvent(value: unknown): value is MouseEvent {\n return isType(value, 'MouseEvent');\n}\n\nexport function isReferenceElement(value: any): value is ReferenceElement {\n return !!(value && value._tippy && value._tippy.reference === value);\n}\n\nexport function getArrayOfElements(value: Targets): Element[] {\n if (isElement(value)) {\n return [value];\n }\n\n if (isNodeList(value)) {\n return arrayFrom(value);\n }\n\n if (Array.isArray(value)) {\n return value;\n }\n\n return arrayFrom(document.querySelectorAll(value));\n}\n\nexport function setTransitionDuration(\n els: (HTMLDivElement | null)[],\n value: number\n): void {\n els.forEach((el) => {\n if (el) {\n el.style.transitionDuration = `${value}ms`;\n }\n });\n}\n\nexport function setVisibilityState(\n els: (HTMLDivElement | null)[],\n state: 'visible' | 'hidden'\n): void {\n els.forEach((el) => {\n if (el) {\n el.setAttribute('data-state', state);\n }\n });\n}\n\nexport function getOwnerDocument(\n elementOrElements: Element | Element[]\n): Document {\n const [element] = normalizeToArray(elementOrElements);\n\n // Elements created via a