{"version":3,"file":"static/js/main.d8a1d176.js","sources":["../node_modules/@sentry/src/env.ts","../node_modules/@sentry/src/node.ts","../node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js","../node_modules/hoist-non-react-statics/node_modules/react-is/cjs/react-is.production.min.js","../node_modules/hoist-non-react-statics/node_modules/react-is/index.js","../node_modules/prop-types/factoryWithThrowingShims.js","../node_modules/prop-types/index.js","../node_modules/prop-types/lib/ReactPropTypesSecret.js","../node_modules/react-dom/cjs/react-dom.production.min.js","../node_modules/react-dom/client.js","../node_modules/react-dom/index.js","../node_modules/react-query/devtools/index.js","../node_modules/react-query/es/core/focusManager.js","../node_modules/react-query/es/core/logger.js","../node_modules/react-query/es/core/mutation.js","../node_modules/react-query/es/core/notifyManager.js","../node_modules/react-query/es/core/onlineManager.js","../node_modules/react-query/es/core/query.js","../node_modules/react-query/es/core/queryCache.js","../node_modules/react-query/es/core/mutationCache.js","../node_modules/react-query/es/core/infiniteQueryBehavior.js","../node_modules/react-query/es/core/queryClient.js","../node_modules/react-query/es/core/retryer.js","../node_modules/react-query/es/core/subscribable.js","../node_modules/react-query/es/core/utils.js","../node_modules/react-query/es/react/reactBatchedUpdates.js","../node_modules/react-query/es/react/setBatchUpdatesFn.js","../node_modules/react-query/es/react/logger.js","../node_modules/react-query/es/react/setLogger.js","../node_modules/react-query/es/react/QueryClientProvider.js","../node_modules/react-query/es/core/mutationObserver.js","../node_modules/react-query/es/react/utils.js","../node_modules/react-query/es/react/useMutation.js","../node_modules/react-query/es/core/queryObserver.js","../node_modules/react-query/es/react/QueryErrorResetBoundary.js","../node_modules/react-query/es/react/useQuery.js","../node_modules/react-query/es/react/useBaseQuery.js","../node_modules/react/cjs/react-jsx-runtime.production.min.js","../node_modules/react/cjs/react.production.min.js","../node_modules/react/index.js","../node_modules/react/jsx-runtime.js","../node_modules/scheduler/cjs/scheduler.production.min.js","../node_modules/scheduler/index.js","../node_modules/@babel/runtime/helpers/esm/extends.js","../node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","../node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","../webpack/bootstrap","../webpack/runtime/compat get default export","../webpack/runtime/create fake namespace object","../webpack/runtime/define property getters","../webpack/runtime/ensure chunk","../webpack/runtime/get javascript chunk filename","../webpack/runtime/get mini-css chunk filename","../webpack/runtime/global","../webpack/runtime/harmony module decorator","../webpack/runtime/hasOwnProperty shorthand","../webpack/runtime/load script","../webpack/runtime/make namespace object","../webpack/runtime/publicPath","../webpack/runtime/jsonp chunk loading","../webpack/runtime/nonce","../node_modules/@babel/runtime/helpers/esm/typeof.js","../node_modules/@babel/runtime/helpers/esm/toPropertyKey.js","../node_modules/@babel/runtime/helpers/esm/toPrimitive.js","../node_modules/@babel/runtime/helpers/esm/defineProperty.js","../node_modules/@babel/runtime/helpers/esm/objectSpread2.js","../node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js","../node_modules/@babel/runtime/helpers/esm/iterableToArray.js","../node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js","../node_modules/@babel/runtime/helpers/esm/toConsumableArray.js","../node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js","../node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js","../node_modules/@sentry/src/debug-build.ts","../node_modules/@sentry/src/worldwide.ts","../node_modules/@sentry/src/logger.ts","../node_modules/@sentry/src/is.ts","../node_modules/@sentry/src/browser.ts","../node_modules/@sentry/src/string.ts","../node_modules/@sentry/src/object.ts","../node_modules/@sentry/src/misc.ts","../node_modules/@sentry/src/syncpromise.ts","../node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js","../node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js","../node_modules/@babel/runtime/helpers/esm/nonIterableRest.js","../node_modules/@babel/runtime/helpers/esm/slicedToArray.js","../node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js","../node_modules/@babel/runtime/helpers/esm/classCallCheck.js","../node_modules/@babel/runtime/helpers/esm/createClass.js","../node_modules/@sentry/src/eventProcessors.ts","../node_modules/@sentry/src/time.ts","../node_modules/@sentry/src/constants.ts","../node_modules/@sentry/src/session.ts","../node_modules/@sentry/src/stacktrace.ts","../node_modules/@sentry/src/normalize.ts","../node_modules/@sentry/src/memo.ts","../node_modules/@sentry/src/baggage.ts","../node_modules/@sentry/src/tracing.ts","../node_modules/@sentry/src/utils/spanUtils.ts","../node_modules/@sentry/src/utils/prepareEvent.ts","../node_modules/@sentry/src/scope.ts","../node_modules/@sentry/src/exports.ts","../node_modules/@sentry/src/utils/getRootSpan.ts","../node_modules/@sentry/src/tracing/dynamicSamplingContext.ts","../node_modules/@sentry/src/utils/applyScopeDataToEvent.ts","../node_modules/@sentry/src/version.ts","../node_modules/@sentry/src/hub.ts","../node_modules/@sentry/src/integration.ts","../node_modules/@sentry/src/integrations/inboundfilters.ts","../node_modules/@sentry/src/integrations/functiontostring.ts","../node_modules/@sentry/src/sdk.ts","../node_modules/@sentry/src/dsn.ts","../node_modules/@sentry/src/api.ts","../node_modules/@sentry/src/supports.ts","../node_modules/@sentry/src/vendor/supportsHistory.ts","../node_modules/@sentry/src/instrument/_handlers.ts","../node_modules/@sentry/src/instrument/history.ts","../node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js","../node_modules/@babel/runtime/helpers/esm/get.js","../node_modules/@babel/runtime/helpers/esm/superPropBase.js","../node_modules/@babel/runtime/helpers/esm/inherits.js","../node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js","../node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js","../node_modules/@babel/runtime/helpers/esm/createSuper.js","../node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js","../node_modules/@sentry/src/utils/sdkMetadata.ts","../node_modules/@sentry/src/envelope.ts","../node_modules/@babel/runtime/helpers/esm/construct.js","../node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js","../node_modules/@babel/runtime/helpers/esm/isNativeFunction.js","../node_modules/@sentry/src/error.ts","../node_modules/@sentry/src/metrics/envelope.ts","../node_modules/@sentry/src/metrics/utils.ts","../node_modules/@sentry/src/baseclient.ts","../node_modules/src/debug-build.ts","../node_modules/src/eventbuilder.ts","../node_modules/src/helpers.ts","../node_modules/src/client.ts","../node_modules/src/userfeedback.ts","../node_modules/@sentry/src/clientreport.ts","../node_modules/@sentry/src/instrument/console.ts","../node_modules/@sentry/src/instrument/dom.ts","../node_modules/@sentry/src/instrument/xhr.ts","../node_modules/@sentry/src/instrument/fetch.ts","../node_modules/@sentry/src/severity.ts","../node_modules/@sentry/src/url.ts","../node_modules/src/integrations/breadcrumbs.ts","../node_modules/src/integrations/dedupe.ts","../node_modules/@sentry/src/instrument/globalError.ts","../node_modules/@sentry/src/instrument/globalUnhandledRejection.ts","../node_modules/src/integrations/globalhandlers.ts","../node_modules/src/integrations/httpcontext.ts","../node_modules/@sentry/src/aggregate-errors.ts","../node_modules/src/integrations/linkederrors.ts","../node_modules/src/integrations/trycatch.ts","../node_modules/src/stack-parsers.ts","../node_modules/@sentry/src/promisebuffer.ts","../node_modules/@sentry/src/ratelimit.ts","../node_modules/@sentry/src/transports/base.ts","../node_modules/src/transports/utils.ts","../node_modules/src/transports/fetch.ts","../node_modules/src/transports/xhr.ts","../node_modules/src/sdk.ts","../node_modules/@sentry/src/metrics/metric-summary.ts","../node_modules/@sentry/src/semanticAttributes.ts","../node_modules/@sentry/src/tracing/spanstatus.ts","../node_modules/@sentry/src/tracing/span.ts","../node_modules/@sentry/src/utils/hasTracingEnabled.ts","../node_modules/@sentry/src/tracing/trace.ts","../node_modules/@sentry/src/tracing/transaction.ts","../node_modules/@sentry/src/tracing/idletransaction.ts","../node_modules/@sentry/src/tracing/utils.ts","../node_modules/@sentry/src/tracing/errors.ts","../node_modules/@sentry/src/tracing/sampling.ts","../node_modules/@sentry/src/tracing/hubextensions.ts","../node_modules/@sentry-internal/src/common/debug-build.ts","../node_modules/@sentry-internal/src/browser/types.ts","../node_modules/@sentry-internal/src/browser/web-vitals/lib/bindReporter.ts","../node_modules/@sentry-internal/src/browser/web-vitals/lib/polyfills/interactionCountPolyfill.ts","../node_modules/@sentry-internal/src/browser/instrument.ts","../node_modules/@sentry-internal/src/browser/web-vitals/lib/getNavigationEntry.ts","../node_modules/@sentry-internal/src/browser/web-vitals/lib/getActivationStart.ts","../node_modules/@sentry-internal/src/browser/web-vitals/lib/initMetric.ts","../node_modules/@sentry-internal/src/browser/web-vitals/lib/generateUniqueID.ts","../node_modules/@sentry-internal/src/browser/web-vitals/lib/observe.ts","../node_modules/@sentry-internal/src/browser/web-vitals/lib/onHidden.ts","../node_modules/@sentry-internal/src/browser/web-vitals/getCLS.ts","../node_modules/@sentry-internal/src/browser/web-vitals/lib/getVisibilityWatcher.ts","../node_modules/@sentry-internal/src/browser/web-vitals/getFID.ts","../node_modules/@sentry-internal/src/browser/web-vitals/getINP.ts","../node_modules/@sentry-internal/src/browser/web-vitals/getLCP.ts","../node_modules/@sentry-internal/src/browser/web-vitals/onTTFB.ts","../node_modules/@sentry/src/span.ts","../node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js","../node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js","../node_modules/@sentry-internal/src/browser/metrics/utils.ts","../node_modules/@sentry-internal/src/browser/metrics/index.ts","../node_modules/@sentry/src/tracing/measurement.ts","../node_modules/@sentry-internal/src/common/fetch.ts","../node_modules/@sentry-internal/src/browser/request.ts","../node_modules/@sentry-internal/src/browser/browserTracingIntegration.ts","../node_modules/@sentry-internal/src/browser/backgroundtab.ts","../node_modules/@sentry/src/reactrouterv6.tsx","../node_modules/@babel/runtime/helpers/esm/regeneratorRuntime.js","../node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js","../node_modules/@sentry/src/buildPolyfills/_optionalChain.ts","../node_modules/@sentry/src/utils/isSentryRequestUrl.ts","../node_modules/@sentry/src/isBrowser.ts","../node_modules/src/constants.ts","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb-snapshot/es/rrweb-snapshot.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/utils.js","../node_modules/@sentry/src/buildPolyfills/_nullishCoalesce.ts","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/types/dist/rrweb-types.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/mutation.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/error-handler.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observer.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/cross-origin-iframe-mirror.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/iframe-manager.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/index.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/shadow-dom-manager.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/canvas-manager.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/stylesheet-manager.js","../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/processed-node-manager.js","../node_modules/src/types/rrweb.ts","../node_modules/src/util/timestamp.ts","../node_modules/src/coreHandlers/util/addBreadcrumbEvent.ts","../node_modules/src/coreHandlers/util/domUtils.ts","../node_modules/src/coreHandlers/util/onWindowOpen.ts","../node_modules/src/coreHandlers/handleClick.ts","../../node_modules/@sentry-internal/rrweb-snapshot/es/rrweb-snapshot.js","../node_modules/src/util/createBreadcrumb.ts","../node_modules/src/coreHandlers/util/getAttributesToRecord.ts","../node_modules/src/coreHandlers/handleDom.ts","../node_modules/src/coreHandlers/handleKeyboardEvent.ts","../node_modules/src/util/createPerformanceEntries.ts","../node_modules/src/coreHandlers/performanceObserver.ts","../replay-worker/build/npm/esm/worker.ts","../node_modules/src/util/log.ts","../node_modules/src/eventBuffer/error.ts","../node_modules/src/eventBuffer/EventBufferArray.ts","../node_modules/src/eventBuffer/WorkerHandler.ts","../node_modules/src/eventBuffer/EventBufferCompressionWorker.ts","../node_modules/src/eventBuffer/EventBufferProxy.ts","../node_modules/src/eventBuffer/index.ts","../replay-worker/build/npm/esm/index.js","../node_modules/src/util/hasSessionStorage.ts","../node_modules/src/session/clearSession.ts","../node_modules/src/util/isSampled.ts","../node_modules/src/session/Session.ts","../node_modules/src/session/saveSession.ts","../node_modules/src/session/createSession.ts","../node_modules/src/util/isExpired.ts","../node_modules/src/util/isSessionExpired.ts","../node_modules/src/session/shouldRefreshSession.ts","../node_modules/src/session/loadOrCreateSession.ts","../node_modules/src/session/fetchSession.ts","../node_modules/src/util/addEvent.ts","../node_modules/src/util/eventUtils.ts","../node_modules/src/coreHandlers/handleAfterSendEvent.ts","../node_modules/src/coreHandlers/handleBeforeSendEvent.ts","../node_modules/src/coreHandlers/handleGlobalEvent.ts","../node_modules/src/coreHandlers/util/addFeedbackBreadcrumb.ts","../node_modules/src/util/isRrwebError.ts","../node_modules/src/coreHandlers/util/shouldSampleForBufferEvent.ts","../node_modules/src/util/createPerformanceSpans.ts","../node_modules/src/coreHandlers/handleHistory.ts","../node_modules/src/coreHandlers/util/addNetworkBreadcrumb.ts","../node_modules/src/util/shouldFilterRequest.ts","../node_modules/src/coreHandlers/handleXhr.ts","../node_modules/src/coreHandlers/util/networkUtils.ts","../node_modules/src/coreHandlers/util/fetchUtils.ts","../node_modules/src/coreHandlers/util/xhrUtils.ts","../node_modules/src/coreHandlers/handleNetworkBreadcrumbs.ts","../node_modules/src/coreHandlers/handleFetch.ts","../node_modules/src/coreHandlers/handleScope.ts","../node_modules/src/util/addGlobalListeners.ts","../node_modules/src/util/addMemoryEntry.ts","../node_modules/src/util/handleRecordingEmit.ts","../node_modules/src/util/createReplayEnvelope.ts","../node_modules/src/util/prepareRecordingData.ts","../node_modules/src/util/prepareReplayEvent.ts","../node_modules/src/util/sendReplayRequest.ts","../node_modules/src/util/sendReplay.ts","../node_modules/src/util/throttle.ts","../node_modules/src/replay.ts","../node_modules/src/util/debounce.ts","../node_modules/src/util/getPrivacyOptions.ts","../node_modules/src/integration.ts","../node_modules/src/util/maskAttribute.ts","../node_modules/src/index.ts","../node_modules/universal-cookie/esm/index.mjs","../node_modules/react-cookie/esm/index.mjs","../node_modules/react-headless-notifier/node_modules/style-inject/dist/style-inject.es.js","../node_modules/react-headless-notifier/src/Timer.ts","../node_modules/react-headless-notifier/src/index.tsx","../node_modules/@remix-run/router/history.ts","../node_modules/@remix-run/router/utils.ts","../node_modules/@babel/runtime/helpers/esm/toArray.js","../node_modules/@remix-run/router/router.ts","../node_modules/react-router/lib/context.ts","../node_modules/react-router/lib/hooks.tsx","../node_modules/react-router/lib/components.tsx","../node_modules/react-router/index.ts","../node_modules/react-router-dom/dom.ts","../node_modules/react-router-dom/index.tsx","../node_modules/jwt-decode/lib/atob.js","../node_modules/jwt-decode/lib/index.js","../node_modules/jwt-decode/lib/base64_url_decode.js","../node_modules/react-hook-form/src/utils/isCheckBoxInput.ts","../node_modules/react-hook-form/src/utils/isDateObject.ts","../node_modules/react-hook-form/src/utils/isNullOrUndefined.ts","../node_modules/react-hook-form/src/utils/isObject.ts","../node_modules/react-hook-form/src/logic/getEventValue.ts","../node_modules/react-hook-form/src/logic/isNameInFieldArray.ts","../node_modules/react-hook-form/src/logic/getNodeParentName.ts","../node_modules/react-hook-form/src/utils/isPlainObject.ts","../node_modules/react-hook-form/src/utils/isWeb.ts","../node_modules/react-hook-form/src/utils/cloneObject.ts","../node_modules/react-hook-form/src/utils/compact.ts","../node_modules/react-hook-form/src/utils/isUndefined.ts","../node_modules/react-hook-form/src/utils/get.ts","../node_modules/react-hook-form/src/constants.ts","../node_modules/react-hook-form/src/useFormContext.tsx","../node_modules/react-hook-form/src/logic/getProxyFormState.ts","../node_modules/react-hook-form/src/utils/isEmptyObject.ts","../node_modules/react-hook-form/src/logic/shouldRenderFormState.ts","../node_modules/react-hook-form/src/utils/convertToArrayPayload.ts","../node_modules/react-hook-form/src/logic/shouldSubscribeByName.ts","../node_modules/react-hook-form/src/useSubscribe.ts","../node_modules/react-hook-form/src/utils/isString.ts","../node_modules/react-hook-form/src/logic/generateWatchOutput.ts","../node_modules/react-hook-form/src/utils/isKey.ts","../node_modules/react-hook-form/src/utils/stringToPath.ts","../node_modules/react-hook-form/src/utils/set.ts","../node_modules/react-hook-form/src/useController.ts","../node_modules/react-hook-form/src/useWatch.ts","../node_modules/react-hook-form/src/useFormState.ts","../node_modules/react-hook-form/src/controller.tsx","../node_modules/react-hook-form/src/logic/appendErrors.ts","../node_modules/react-hook-form/src/logic/focusFieldBy.ts","../node_modules/react-hook-form/src/logic/getValidationModes.ts","../node_modules/react-hook-form/src/logic/isWatched.ts","../node_modules/react-hook-form/src/logic/updateFieldArrayRootError.ts","../node_modules/react-hook-form/src/utils/isBoolean.ts","../node_modules/react-hook-form/src/utils/isFileInput.ts","../node_modules/react-hook-form/src/utils/isFunction.ts","../node_modules/react-hook-form/src/utils/isHTMLElement.ts","../node_modules/react-hook-form/src/utils/isMessage.ts","../node_modules/react-hook-form/src/utils/isRadioInput.ts","../node_modules/react-hook-form/src/utils/isRegex.ts","../node_modules/react-hook-form/src/logic/getCheckboxValue.ts","../node_modules/react-hook-form/src/logic/getRadioValue.ts","../node_modules/react-hook-form/src/logic/getValidateError.ts","../node_modules/react-hook-form/src/logic/getValueAndMessage.ts","../node_modules/react-hook-form/src/logic/validateField.ts","../node_modules/react-hook-form/src/utils/unset.ts","../node_modules/react-hook-form/src/utils/createSubject.ts","../node_modules/react-hook-form/src/utils/isPrimitive.ts","../node_modules/react-hook-form/src/utils/deepEqual.ts","../node_modules/react-hook-form/src/utils/isMultipleSelect.ts","../node_modules/react-hook-form/src/utils/isRadioOrCheckbox.ts","../node_modules/react-hook-form/src/utils/live.ts","../node_modules/react-hook-form/src/utils/objectHasFunction.ts","../node_modules/react-hook-form/src/logic/getDirtyFields.ts","../node_modules/react-hook-form/src/logic/getFieldValueAs.ts","../node_modules/react-hook-form/src/logic/getFieldValue.ts","../node_modules/react-hook-form/src/logic/getResolverOptions.ts","../node_modules/react-hook-form/src/logic/getRuleValue.ts","../node_modules/react-hook-form/src/logic/hasValidation.ts","../node_modules/react-hook-form/src/logic/schemaErrorLookup.ts","../node_modules/react-hook-form/src/logic/skipValidation.ts","../node_modules/react-hook-form/src/logic/unsetEmptyArray.ts","../node_modules/react-hook-form/src/logic/createFormControl.ts","../node_modules/react-hook-form/src/useForm.ts","../node_modules/axios/lib/helpers/bind.js","../node_modules/axios/lib/utils.js","../node_modules/axios/lib/core/AxiosError.js","../node_modules/axios/lib/helpers/null.js","../node_modules/axios/lib/helpers/toFormData.js","../node_modules/axios/lib/helpers/AxiosURLSearchParams.js","../node_modules/axios/lib/helpers/buildURL.js","../node_modules/axios/lib/core/InterceptorManager.js","../node_modules/axios/lib/defaults/transitional.js","../node_modules/axios/lib/platform/browser/index.js","../node_modules/axios/lib/platform/browser/classes/URLSearchParams.js","../node_modules/axios/lib/platform/browser/classes/FormData.js","../node_modules/axios/lib/platform/browser/classes/Blob.js","../node_modules/axios/lib/helpers/formDataToJSON.js","../node_modules/axios/lib/defaults/index.js","../node_modules/axios/lib/helpers/toURLEncodedForm.js","../node_modules/axios/lib/helpers/parseHeaders.js","../node_modules/axios/lib/core/AxiosHeaders.js","../node_modules/axios/lib/core/transformData.js","../node_modules/axios/lib/cancel/isCancel.js","../node_modules/axios/lib/cancel/CanceledError.js","../node_modules/axios/lib/helpers/cookies.js","../node_modules/axios/lib/core/buildFullPath.js","../node_modules/axios/lib/helpers/isAbsoluteURL.js","../node_modules/axios/lib/helpers/combineURLs.js","../node_modules/axios/lib/helpers/isURLSameOrigin.js","../node_modules/axios/lib/helpers/speedometer.js","../node_modules/axios/lib/adapters/xhr.js","../node_modules/axios/lib/core/settle.js","../node_modules/axios/lib/helpers/parseProtocol.js","../node_modules/axios/lib/adapters/adapters.js","../node_modules/axios/lib/core/dispatchRequest.js","../node_modules/axios/lib/core/mergeConfig.js","../node_modules/axios/lib/env/data.js","../node_modules/axios/lib/helpers/validator.js","../node_modules/axios/lib/core/Axios.js","../node_modules/axios/lib/cancel/CancelToken.js","../node_modules/axios/lib/helpers/HttpStatusCode.js","../node_modules/axios/lib/axios.js","../node_modules/axios/lib/helpers/spread.js","../node_modules/axios/lib/helpers/isAxiosError.js","utils/queue.ts","constants/common.ts","constants/ThemeMixins.ts","config.ts","contexts/UserContext.tsx","../node_modules/clsx/dist/clsx.m.js","components/base/LoadingWheel.tsx","components/shared/FullscreenLoading.tsx","contexts/ThemeContext.tsx","hooks/useApiHelper.ts","components/base/Button.tsx","components/base/TextField.tsx","../node_modules/@heroicons/react/24/outline/esm/CheckCircleIcon.js","../node_modules/@heroicons/react/24/outline/esm/XCircleIcon.js","../node_modules/@heroicons/react/24/outline/esm/ExclamationCircleIcon.js","../node_modules/@heroicons/react/24/outline/esm/InformationCircleIcon.js","components/base/Alert.tsx","components/shared/SectionLoading.tsx","pages/public/index.tsx","components/base/Card.tsx","components/base/MiniTable.tsx","types/Alerts/Alerts.ts","components/shared/AlertIcon.tsx","components/Dashboard/Alerts.tsx","data/alerts/useAlert.ts","hooks/useNotifications.ts","components/shared/Notifications.tsx","hooks/useDefaultMutateResponeHandlers.ts","data/job/useJobs.ts","data/customer/useCustomers.ts","data/job/useJobCategories.ts","hooks/useCategoryLookups.ts","components/Dashboard/Jobs.tsx","components/Dashboard/Customers.tsx","data/device/useDevices.ts","data/hardware/useHardware.ts","components/Dashboard/Devices.tsx","contexts/PageTitleContext.tsx","pages/index.tsx","../node_modules/@tanstack/table-core/src/utils.ts","../node_modules/@tanstack/table-core/src/core/headers.ts","../node_modules/@tanstack/table-core/src/features/ColumnSizing.ts","../node_modules/@tanstack/table-core/src/features/Expanding.ts","../node_modules/@tanstack/table-core/src/filterFns.ts","../node_modules/@tanstack/table-core/src/features/Filters.ts","../node_modules/@tanstack/table-core/src/aggregationFns.ts","../node_modules/@tanstack/table-core/src/features/Grouping.ts","../node_modules/@tanstack/table-core/src/features/Ordering.ts","../node_modules/@tanstack/table-core/src/features/Pagination.ts","../node_modules/@tanstack/table-core/src/features/Pinning.ts","../node_modules/@tanstack/table-core/src/features/RowSelection.ts","../node_modules/@tanstack/table-core/src/sortingFns.ts","../node_modules/@tanstack/table-core/src/features/Sorting.ts","../node_modules/@tanstack/table-core/src/features/Visibility.ts","../node_modules/@tanstack/table-core/src/core/table.ts","../node_modules/@tanstack/table-core/src/core/column.ts","../node_modules/@tanstack/table-core/src/core/row.ts","../node_modules/@tanstack/table-core/src/core/cell.ts","../node_modules/@tanstack/table-core/src/columnHelper.ts","../node_modules/date-and-time/esm/date-and-time.mjs","../node_modules/@tanstack/react-table/src/index.tsx","../node_modules/@heroicons/react/24/outline/esm/ChevronDoubleLeftIcon.js","../node_modules/@heroicons/react/24/outline/esm/ChevronLeftIcon.js","../node_modules/@heroicons/react/24/outline/esm/ChevronRightIcon.js","../node_modules/@heroicons/react/24/outline/esm/ChevronDoubleRightIcon.js","components/base/Select.tsx","../node_modules/@headlessui/react/dist/utils/class-names.js","../node_modules/@headlessui/react/dist/utils/match.js","../node_modules/@headlessui/react/dist/utils/render.js","../node_modules/@headlessui/react/dist/utils/env.js","../node_modules/@headlessui/react/dist/hooks/use-id.js","../node_modules/@headlessui/react/dist/hooks/use-iso-morphic-effect.js","../node_modules/@headlessui/react/dist/hooks/use-server-handoff-complete.js","../node_modules/@headlessui/react/dist/components/keyboard.js","../node_modules/@headlessui/react/dist/utils/bugs.js","../node_modules/@headlessui/react/dist/hooks/use-latest-value.js","../node_modules/@headlessui/react/dist/hooks/use-event.js","../node_modules/@headlessui/react/dist/hooks/use-sync-refs.js","../node_modules/@headlessui/react/dist/components/label/label.js","../node_modules/@headlessui/react/dist/components/description/description.js","../node_modules/@headlessui/react/dist/hooks/use-resolve-button-type.js","../node_modules/@headlessui/react/dist/internal/hidden.js","../node_modules/@headlessui/react/dist/utils/micro-task.js","../node_modules/@headlessui/react/dist/utils/disposables.js","../node_modules/@headlessui/react/dist/hooks/use-disposables.js","../node_modules/@headlessui/react/dist/components/switch/switch.js","../node_modules/@headlessui/react/dist/hooks/use-controllable.js","../node_modules/@headlessui/react/dist/utils/form.js","components/base/Toggle.tsx","hooks/useQSBuilder.ts","../node_modules/@heroicons/react/24/outline/esm/XMarkIcon.js","components/base/Table/TableFilterPill.tsx","components/base/Table/TableFilterContext.tsx","components/base/Table/TableFilter.tsx","components/base/Table/Table.tsx","../node_modules/@tanstack/table-core/src/utils/getCoreRowModel.ts","../node_modules/@sentry/src/errorboundary.tsx","../node_modules/@headlessui/react/dist/internal/open-closed.js","../node_modules/@headlessui/react/dist/hooks/use-is-mounted.js","../node_modules/@headlessui/react/dist/components/transitions/utils/transition.js","../node_modules/@headlessui/react/dist/utils/once.js","../node_modules/@headlessui/react/dist/components/transitions/transition.js","../node_modules/@headlessui/react/dist/hooks/use-flags.js","../node_modules/@headlessui/react/dist/hooks/use-transition.js","../node_modules/@headlessui/react/dist/utils/owner.js","../node_modules/@headlessui/react/dist/utils/focus-management.js","../node_modules/@headlessui/react/dist/hooks/use-tab-direction.js","../node_modules/@headlessui/react/dist/hooks/use-window-event.js","../node_modules/@headlessui/react/dist/hooks/use-owner.js","../node_modules/@headlessui/react/dist/hooks/use-event-listener.js","../node_modules/@headlessui/react/dist/hooks/use-watch.js","../node_modules/@headlessui/react/dist/components/focus-trap/focus-trap.js","../node_modules/@headlessui/react/dist/utils/document-ready.js","../node_modules/@headlessui/react/dist/internal/portal-force-root.js","../node_modules/@headlessui/react/dist/components/portal/portal.js","../node_modules/@headlessui/react/dist/internal/stack-context.js","../node_modules/@headlessui/react/dist/hooks/use-document-event.js","../node_modules/@headlessui/react/dist/hooks/use-outside-click.js","../node_modules/@headlessui/react/dist/use-sync-external-store-shim/useSyncExternalStoreShimClient.js","../node_modules/@headlessui/react/dist/use-sync-external-store-shim/index.js","../node_modules/@headlessui/react/dist/hooks/document-overflow/adjust-scrollbar-padding.js","../node_modules/@headlessui/react/dist/utils/platform.js","../node_modules/@headlessui/react/dist/hooks/document-overflow/handle-ios-locking.js","../node_modules/@headlessui/react/dist/hooks/document-overflow/overflow-store.js","../node_modules/@headlessui/react/dist/utils/store.js","../node_modules/@headlessui/react/dist/hooks/document-overflow/prevent-scroll.js","../node_modules/@headlessui/react/dist/hooks/document-overflow/use-document-overflow.js","../node_modules/@headlessui/react/dist/hooks/use-store.js","../node_modules/@headlessui/react/dist/hooks/use-inert.js","../node_modules/@headlessui/react/dist/components/dialog/dialog.js","ErrorFallback.tsx","layouts/Modal.tsx","components/base/TextArea.tsx","components/Job/CreateEditJob.tsx","components/Job/CategoryPill.tsx","../node_modules/@heroicons/react/24/outline/esm/PencilIcon.js","pages/Jobs/index.tsx","pages/System/index.tsx","data/alerts/useAlertMutations.ts","components/Alerts/CreateEditAlert.tsx","../node_modules/@heroicons/react/24/outline/esm/ArrowUturnDownIcon.js","../node_modules/@heroicons/react/24/outline/esm/EnvelopeOpenIcon.js","../node_modules/@heroicons/react/24/outline/esm/EnvelopeIcon.js","../node_modules/@heroicons/react/24/outline/esm/TrashIcon.js","../node_modules/@heroicons/react/24/outline/esm/WrenchScrewdriverIcon.js","components/shared/ConfirmDelete.tsx","pages/Alerts/index.tsx","../node_modules/@heroicons/react/20/solid/esm/ChartBarIcon.js","../node_modules/@heroicons/react/20/solid/esm/AdjustmentsVerticalIcon.js","../node_modules/@heroicons/react/20/solid/esm/ChartPieIcon.js","../node_modules/@heroicons/react/20/solid/esm/XMarkIcon.js","../node_modules/@heroicons/react/20/solid/esm/PlusIcon.js","../node_modules/@heroicons/react/20/solid/esm/CheckIcon.js","../node_modules/@heroicons/react/20/solid/esm/PencilIcon.js","../node_modules/@heroicons/react/20/solid/esm/ChevronUpIcon.js","../node_modules/@heroicons/react/20/solid/esm/ChevronDownIcon.js","../node_modules/@heroicons/react/20/solid/esm/TrashIcon.js","../node_modules/@heroicons/react/20/solid/esm/Cog6ToothIcon.js","../node_modules/luxon/src/errors.js","../node_modules/luxon/src/impl/formats.js","../node_modules/luxon/src/zone.js","../node_modules/luxon/src/zones/systemZone.js","../node_modules/luxon/src/zones/IANAZone.js","../node_modules/luxon/src/impl/locale.js","../node_modules/luxon/src/impl/english.js","../node_modules/luxon/src/zones/fixedOffsetZone.js","../node_modules/luxon/src/zones/invalidZone.js","../node_modules/luxon/src/impl/zoneUtil.js","../node_modules/luxon/src/impl/util.js","../node_modules/luxon/src/settings.js","../node_modules/luxon/src/impl/formatter.js","../node_modules/luxon/src/impl/invalid.js","../node_modules/luxon/src/impl/regexParser.js","../node_modules/luxon/src/duration.js","../node_modules/luxon/src/interval.js","../node_modules/luxon/src/info.js","../node_modules/luxon/src/impl/diff.js","../node_modules/luxon/src/impl/digits.js","../node_modules/luxon/src/impl/tokenParser.js","../node_modules/luxon/src/impl/conversions.js","../node_modules/luxon/src/datetime.js","../node_modules/luxon/src/luxon.js","utils/graphUtils.ts","types/system/GranularityOptions.ts","data/datapoint/useGraphData.ts","contexts/GraphSettingsContext.tsx","types/Statistic/Statistic.ts","constants/datapointLists.ts","data/datapoint/useDataPointsByHardwareModel.ts","components/History/StatCard.tsx","../node_modules/@heroicons/react/20/solid/esm/MinusCircleIcon.js","../node_modules/@heroicons/react/20/solid/esm/PlusCircleIcon.js","../node_modules/src/.internal/core/util/Array.ts","../node_modules/src/.internal/core/util/Disposer.ts","../node_modules/src/.internal/core/util/Type.ts","../node_modules/src/.internal/core/util/EventDispatcher.ts","../node_modules/src/.internal/core/util/List.ts","../node_modules/src/.internal/core/util/Children.ts","../node_modules/src/.internal/core/util/Percent.ts","../node_modules/@amcharts/amcharts5/node_modules/tslib/tslib.es6.mjs","../node_modules/src/.internal/core/util/Utils.ts","../node_modules/src/.internal/core/util/Color.ts","../node_modules/src/.internal/core/util/Object.ts","../node_modules/src/.internal/core/util/Animation.ts","../node_modules/src/.internal/core/util/Ease.ts","../node_modules/src/.internal/core/util/States.ts","../node_modules/src/.internal/core/Registry.ts","../node_modules/src/.internal/core/util/Order.ts","../node_modules/src/.internal/core/util/Entity.ts","../node_modules/src/.internal/core/util/Template.ts","../node_modules/src/.internal/core/util/Math.ts","../node_modules/src/.internal/core/render/Sprite.ts","../node_modules/src/.internal/core/render/patterns/Pattern.ts","../node_modules/src/.internal/core/render/patterns/PicturePattern.ts","../node_modules/src/.internal/core/render/backend/Renderer.ts","../node_modules/src/.internal/core/render/Graphics.ts","../node_modules/src/.internal/core/render/Rectangle.ts","../node_modules/src/.internal/core/render/Layout.ts","../node_modules/src/.internal/core/render/HorizontalLayout.ts","../node_modules/src/.internal/core/render/VerticalLayout.ts","../node_modules/src/.internal/core/render/GridLayout.ts","../node_modules/src/.internal/core/util/TextFormatter.ts","../node_modules/src/.internal/core/util/PopulateString.ts","../node_modules/src/.internal/core/render/Container.ts","../node_modules/src/.internal/core/render/Text.ts","../node_modules/src/.internal/core/util/ResizeSensor.ts","../node_modules/src/.internal/core/util/InterfaceColors.ts","../node_modules/src/.internal/core/render/Label.ts","../node_modules/src/.internal/core/render/PointedRectangle.ts","../node_modules/src/.internal/core/render/Tooltip.ts","../node_modules/src/.internal/core/util/NumberFormatter.ts","../node_modules/src/.internal/core/util/Timezone.ts","../node_modules/src/.internal/core/util/DateFormatter.ts","../node_modules/src/.internal/core/util/DurationFormatter.ts","../node_modules/src/locales/en.ts","../node_modules/src/.internal/core/util/Language.ts","../node_modules/src/.internal/core/Theme.ts","../node_modules/src/.internal/themes/DefaultTheme.ts","../node_modules/src/.internal/core/util/Matrix.ts","../node_modules/svg-arc-to-cubic-bezier/modules/index.js","../node_modules/src/.internal/core/render/backend/CanvasRenderer.ts","../node_modules/src/.internal/core/Root.ts","../node_modules/src/.internal/core/render/Bullet.ts","../node_modules/src/.internal/core/render/Circle.ts","../node_modules/src/.internal/core/util/Data.ts","../node_modules/src/.internal/core/render/Component.ts","../node_modules/src/.internal/core/util/Time.ts","../node_modules/src/.internal/core/render/Series.ts","../node_modules/src/.internal/core/render/RoundedRectangle.ts","../node_modules/src/.internal/core/render/Legend.ts","../node_modules/src/.internal/core/util/ColorSet.ts","../node_modules/src/.internal/charts/xy/XYChartDefaultTheme.ts","../node_modules/src/.internal/core/render/Chart.ts","../node_modules/src/.internal/core/render/SerialChart.ts","../node_modules/src/.internal/core/render/Button.ts","../node_modules/src/.internal/charts/xy/XYChart.ts","../node_modules/src/.internal/charts/xy/axes/Axis.ts","../node_modules/src/.internal/charts/xy/axes/ValueAxis.ts","../node_modules/src/.internal/charts/xy/axes/DateAxis.ts","../node_modules/src/.internal/core/util/Draw.ts","../node_modules/src/.internal/core/render/Line.ts","../node_modules/src/.internal/core/render/Tick.ts","../node_modules/src/.internal/charts/xy/axes/AxisTick.ts","../node_modules/src/.internal/charts/xy/axes/Grid.ts","../node_modules/src/.internal/charts/xy/axes/AxisLabel.ts","../node_modules/src/.internal/charts/xy/axes/AxisRenderer.ts","../node_modules/src/.internal/charts/xy/axes/AxisRendererX.ts","../node_modules/src/.internal/charts/xy/axes/AxisRendererY.ts","../node_modules/src/.internal/charts/xy/series/XYSeries.ts","../node_modules/d3-shape/src/array.js","../node_modules/d3-shape/src/constant.js","../node_modules/d3-shape/src/curve/linear.js","../node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js","../node_modules/d3-path/src/path.js","../node_modules/d3-shape/src/path.js","../node_modules/d3-shape/src/point.js","../node_modules/d3-shape/src/line.js","../node_modules/d3-shape/src/area.js","../node_modules/src/.internal/charts/xy/series/LineSeries.ts","../node_modules/d3-shape/src/curve/cardinal.js","../node_modules/src/.internal/charts/xy/series/SmoothedXYLineSeries.ts","../node_modules/src/.internal/themes/AnimatedTheme.ts","../node_modules/src/themes/Animated.ts","utils/GUIDtoHEX.ts","components/History/LineGraph.tsx","components/History/GraphCard.tsx","utils/random.ts","data/QueryKeys.ts","components/History/Statistics.tsx","data/configuration/useStatisticConfigurationsMutations.ts","components/History/HardwareSelection.tsx","components/History/TimespanGranularity.tsx","components/History/GraphSettings.tsx","types/Configuration/Configuration.ts","pages/History/index.tsx","data/configuration/useStatisticConfigurations.ts","pages/public/invite.tsx","data/hardware/useHardwareTypes.ts","data/hardware/useHardwareModel.ts","data/hardware/useHardwareManufacturers.ts","hooks/useHardwareLookups.ts","data/hardware/useHardwareMutations.ts","components/base/Form/Form.tsx","components/base/Form/getErrorTypeText.ts","components/base/Form/FormSelect.tsx","components/Hardware/FormModelSelect.tsx","components/base/Form/FormToggle.tsx","data/billing/QueryKeys.ts","data/billing/useUsedSeats.ts","components/base/Form/FormTextField.tsx","utils/getByPatth.ts","data/billing/useSubscription.ts","components/Hardware/FormManufacturerSelect.tsx","components/Hardware/CreateEditHardware/PowerSettings.tsx","types/Hardware/Hardware.ts","components/Hardware/CreateEditHardware/SerialSettings.tsx","components/Hardware/CreateEditHardware/ModbusSettings.tsx","components/Hardware/CreateEditHardware/HeatPumpSettings.tsx","hooks/useCalibrationDefaults.ts","data/metadata/useMetadata.ts","components/Hardware/ConfirmDefaultSerialSettings.tsx","components/Hardware/ComponentCalibration.tsx","utils/validationFunctions.ts","components/Hardware/CreateEditHardware/VoltageMeterSettings.tsx","utils/hardwareSettingsFormatters.ts","components/shared/ConfirmSubscriptionChangeModal.tsx","components/Hardware/CreateEditHardware/TemperatureSensorSettings.tsx","components/Hardware/CreateEditHardware/CurrentTransformerSettings.tsx","components/Hardware/CreateEditHardware.tsx","types/Billing/Subscription.ts","pages/Hardware/index.tsx","../node_modules/react-responsive-masonry/es/Masonry/index.js","../node_modules/react-responsive-masonry/es/ResponsiveMasonry/index.js","../node_modules/react-responsive-masonry/es/index.js","data/datapoint/useReading.ts","contexts/LiveReadingContext.tsx","data/datapoint/QueryKey.ts","data/datapoint/useDataPointsByHardwareProfile.ts","data/datapoint/useDataPointFunctions.ts","hooks/useReadingProcessor.tsx","../node_modules/@fortawesome/fontawesome-svg-core/index.mjs","../node_modules/@fortawesome/react-fontawesome/index.es.js","components/LiveView/LiveReadingCard/LiveGraph.tsx","data/datapoint/useReadingsHistory.ts","../node_modules/@fortawesome/free-solid-svg-icons/index.mjs","hooks/useFreeTierNotification.tsx","components/LiveView/LiveReadingCard/ActionSendButton.tsx","components/LiveView/LiveReadingCard/ValueAction.tsx","components/LiveView/LiveReadingCard/ToggleAction.tsx","../node_modules/react-click-away-listener/src/index.tsx","components/LiveView/LiveReadingCard/SelectAction.tsx","utils/addTimeout.ts","data/device/useDevice.ts","data/organisation/useOrganisation.ts","types/Action/ActionProfile.ts","contexts/PendingActionContext.tsx","data/organisationUsers/useOrganisationUsers.ts","components/LiveView/LiveReadingCard/ReadingCard.tsx","components/LiveView/LiveReadingTable/ReadingTableRow.tsx","components/LiveView/ReadingsDisplay.tsx","components/base/Seperator.tsx","components/LiveView/LiveViewSettings/DeviceStatusPopover.tsx","components/LiveView/LiveViewSettings/DeviceStatusBar.tsx","components/LiveView/LiveViewSettings/HardwareSettings.tsx","data/configuration/useCustomerTemplateConfiguration.ts","data/configuration/useInstallerTemplateConfiguration.ts","components/LiveView/LiveViewSettings/ViewTemplateSelect.tsx","../node_modules/@heroicons/react/20/solid/esm/ChevronRightIcon.js","../node_modules/@heroicons/react/20/solid/esm/ChevronLeftIcon.js","types/Tile/Tile.ts","contexts/TemplateEditContext.tsx","components/shared/TemplateViewConfigDataPointSelect.tsx","components/LiveView/LiveViewSettings/EditViewConfigurationModal.tsx","data/configuration/useTileViewConfigurationsMutations.ts","data/configuration/useTileViewConfigurations.ts","components/LiveView/LiveViewSettings/ViewSettings.tsx","pages/LiveView/index.tsx","../node_modules/@heroicons/react/20/solid/esm/PaperClipIcon.js","pages/Alerts/error.tsx","../node_modules/@heroicons/react/24/outline/esm/ArrowRightOnRectangleIcon.js","data/customer/useCustomerMutations.ts","components/Customer/UnlinkCustomer.tsx","components/base/Form/FormErrors.tsx","components/Customer/CreateEditCustomer.tsx","pages/Customers/index.tsx","pages/public/register.tsx","pages/public/NotFound.tsx","pages/Installers/index.tsx","components/shared/AuthGuard.tsx","utils/alphabeticalSort.ts","utils/upsert.ts","components/EngineerView/ReadingsTable.tsx","components/EngineerView/AllReadingsDisplay.tsx","pages/EngineerView/index.tsx","../node_modules/@heroicons/react/24/outline/esm/UserCircleIcon.js","../node_modules/@heroicons/react/24/outline/esm/BanknotesIcon.js","../node_modules/@heroicons/react/24/outline/esm/FingerPrintIcon.js","../node_modules/@heroicons/react/24/outline/esm/UsersIcon.js","../node_modules/@heroicons/react/24/outline/esm/CreditCardIcon.js","../node_modules/@heroicons/react/24/outline/esm/SwatchIcon.js","../node_modules/@heroicons/react/24/outline/esm/ClipboardDocumentIcon.js","layouts/SettingsLayout.tsx","data/organisationUsers/useOrganisationUsersMutations.ts","data/organisationUsers/useOrganisationInvitesMutations copy.ts","components/User/CreateEditUser.tsx","components/base/Pill.tsx","components/shared/Avatar.tsx","components/Settings/UsersTab.tsx","data/organisationUsers/useOrganisationInvites.ts","data/action/useSuperAdminActionMutations.ts","data/action/useSuperAdminActions.ts","components/Action/CreateEditAction.tsx","hooks/useClipboardCopy.tsx","pages/System/action/action.tsx","../node_modules/@headlessui/react/dist/utils/start-transition.js","components/Settings/Tariff/TariffUpdate.tsx","data/organisation/useOrganisationTariffsMutations.ts","components/Settings/TariffTab.tsx","data/organisation/useOrganisationTariffs.ts","pages/public/resetPassword.tsx","data/user/useUser.ts","components/Settings/GeneralTab.tsx","components/Settings/Billing/BillingStat.tsx","components/Settings/BillingTab.tsx","../node_modules/@headlessui/react/dist/components/disclosure/disclosure.js","../node_modules/@headlessui/react/dist/utils/calculate-active-index.js","../node_modules/@headlessui/react/dist/hooks/use-tracked-pointer.js","../node_modules/@headlessui/react/dist/components/menu/menu.js","../node_modules/@headlessui/react/dist/hooks/use-tree-walker.js","../node_modules/@heroicons/react/24/outline/esm/Bars3Icon.js","../node_modules/@heroicons/react/24/outline/esm/SunIcon.js","../node_modules/@heroicons/react/24/outline/esm/MoonIcon.js","layouts/AuthenticatedLayout.tsx","data/user/useUserOrganisations.ts","components/Settings/Security/MFASetup.tsx","components/Settings/Security/MFADisable.tsx","components/shared/ConfirmPassword.tsx","components/Settings/Security/MFARecoveryCodes.tsx","components/Settings/SecurityTab.tsx","../node_modules/react-colorful/src/hooks/useEventCallback.ts","../node_modules/react-colorful/src/utils/clamp.ts","../node_modules/react-colorful/src/components/common/Interactive.tsx","../node_modules/react-colorful/src/utils/format.ts","../node_modules/react-colorful/src/components/common/Pointer.tsx","../node_modules/react-colorful/src/utils/round.ts","../node_modules/react-colorful/src/utils/convert.ts","../node_modules/react-colorful/src/components/common/Hue.tsx","../node_modules/react-colorful/src/components/common/Saturation.tsx","../node_modules/react-colorful/src/utils/compare.ts","../node_modules/react-colorful/src/hooks/useColorManipulation.ts","../node_modules/react-colorful/src/utils/nonce.ts","../node_modules/react-colorful/src/hooks/useIsomorphicLayoutEffect.ts","../node_modules/react-colorful/src/hooks/useStyleSheet.ts","../node_modules/react-colorful/src/components/common/ColorPicker.tsx","../node_modules/react-colorful/src/components/RgbColorPicker.tsx","utils/RGBtoHEX.ts","utils/HEXtoRGB.ts","data/branding/useBrandingMutations.ts","../node_modules/react-image-crop/dist/index.js","components/Settings/Branding/canvasPreview.ts","components/Settings/Branding/LogoCrop.tsx","components/Settings/Branding/useDebounceEffect.ts","components/Settings/BrandingTab.tsx","data/branding/useBranding.ts","../node_modules/@heroicons/react/24/outline/esm/CheckIcon.js","data/hardware/useHardwareTypeMutations.ts","components/Hardware/CreateEditHardwareType.tsx","pages/System/hardware/types.tsx","data/job/useJobCategoriesMutations.ts","components/Job/CreateEditJobCategory.tsx","pages/System/job/categories.tsx","utils/getAddress.ts","components/Settings/Installer/UnlinkInstaller.tsx","data/organisationInstaller/useOrganisationInstallerMutations.ts","components/Settings/InstallerTab.tsx","data/organisationInstaller/useOrganisationInstaller.ts","data/configuration/useInstallerTemplateConfigurationsMutations.ts","components/Settings/Templates/CreateTemplateHardwareInformation.tsx","data/configuration/useCustomerTemplateConfigurationsMutations.ts","components/Settings/Templates/TemplateSelect.tsx","components/Settings/Templates/ImportTemplate.tsx","components/Settings/Templates/AddTemplate.tsx","components/Settings/Templates/TemplateListRow.tsx","components/Settings/Templates/DataPointConfiguration.tsx","components/Settings/Templates/CreateEditTemplateModal.tsx","components/Settings/Templates/CustomerTemplates.tsx","components/Settings/Templates/InstallerTemplates.tsx","components/Settings/TemplatesTab.tsx","../node_modules/@heroicons/react/24/outline/esm/FunnelIcon.js","data/hardware/useHardwareModelMutations.ts","contexts/GlobalHardwareFilterContext.tsx","components/Hardware/ModelSelect.tsx","components/Hardware/ManufacturerSelect.tsx","components/Hardware/CreateEditHardwareModel.tsx","components/shared/GlobalHardwareModelFilterBanner.tsx","hooks/useSuperAdminHardwareLookups.ts","data/hardware/useSuperAdminHardwareTypes.ts","data/hardware/useSuperAdminHardwareManufacturers.ts","data/hardware/useSuperAdminHardwareModels.ts","pages/System/hardware/models.tsx","data/datapoint/superadmin/useSuperAdminDataPointMutation.ts","components/DataPoint/CreateEditDataPoint.tsx","pages/System/datapoint/dataPoints.tsx","pages/public/forgottenPassword.tsx","layouts/UnauthenticatedLayout.tsx","components/Action/ActionSelect.tsx","data/action/useSuperAdminActionProfiles.ts","data/action/useSuperAdminActionProfileMutation.ts","data/datapoint/superadmin/useSuperAdminDataPoints.ts","data/datapoint/superadmin/useSuperAdminDataPointProfiles.ts","components/DataPoint/DataPointSelect.tsx","components/Action/CreateEditActionProfile.tsx","hooks/useActionLookups.ts","pages/System/action/actionProfiles.tsx","data/datapoint/superadmin/useSuperAdminDataPointOptionMutation.ts","components/DataPoint/CreateEditDataPointOption.tsx","hooks/useSuperAdminDataPointLookups.ts","pages/System/datapoint/dataPointOptions.tsx","data/hardware/useHardwareManufacturerMutations.ts","components/Hardware/CreateEditHardwareManufacturer.tsx","pages/System/hardware/manufacturers.tsx","../node_modules/@heroicons/react/24/outline/esm/PencilSquareIcon.js","data/datapoint/superadmin/useSuperAdminDataPointProfileMutation.ts","components/DataPoint/CreateEditDataPointProfile.tsx","pages/System/datapoint/dataPointProfiles.tsx","../node_modules/@heroicons/react/24/outline/esm/CodeBracketIcon.js","data/datapoint/superadmin/useSuperAdminDataPointFunctionMutation.ts","components/DataPoint/CreateEditDataPointFunction.tsx","pages/System/datapoint/dataPointFunctions.tsx","hooks/useDataPointLookups.ts","data/action/useSuperAdminActionTransformationMutation.ts","components/Action/CreateEditActionTransformation.tsx","pages/System/action/actionTransformations.tsx","components/DataPoint/DataPointProfileSelect.tsx","components/DataPoint/DuplicateDataPointProfile.tsx","../node_modules/@heroicons/react/24/outline/esm/ArrowSmallUpIcon.js","../node_modules/@heroicons/react/24/outline/esm/ArrowSmallDownIcon.js","components/DataPoint/EditDataPointProfile.tsx","data/datapoint/superadmin/useSuperAdminDataPointTransformations.ts","data/datapoint/superadmin/useSuperAdminDataPointOptions.ts","pages/System/datapoint/dataPointProfileAddEdit.tsx","data/datapoint/superadmin/useSuperAdminDataPointTransformationMutation.ts","components/DataPoint/CreateEditDataPointTransformation.tsx","pages/System/datapoint/dataPointTransformations.tsx","routes.tsx","App.tsx","reportWebVitals.ts","index.tsx"],"sourceRoot":"","sourcesContent":["/*\n * This module exists for optimizations in the build process through rollup and terser. We define some global\n * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these\n * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will\n * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to\n * `logger` and preventing node-related code from appearing in browser bundles.\n *\n * Attention:\n * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by\n * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack)\n * having issues tree-shaking these constants across package boundaries.\n * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want\n * users to be able to shake away expressions that it guards.\n */\n\ndeclare const __SENTRY_BROWSER_BUNDLE__: boolean | undefined;\n\nexport type SdkSource = 'npm' | 'cdn' | 'loader';\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nexport function isBrowserBundle(): boolean {\n return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Get source of SDK.\n */\nexport function getSDKSource(): SdkSource {\n // @ts-expect-error __SENTRY_SDK_SOURCE__ is injected by rollup during build process\n return __SENTRY_SDK_SOURCE__;\n}\n","/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n */\n\nimport { isBrowserBundle } from './env';\n\n/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */\nexport function isNodeEnv(): boolean {\n // explicitly check for browser bundles as those can be optimized statically\n // by terser/rollup.\n return (\n !isBrowserBundle() &&\n Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'\n );\n}\n\n/**\n * Requires a module which is protected against bundler minification.\n *\n * @param request The module path to resolve\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any\nexport function dynamicRequire(mod: any, request: string): any {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return mod.require(request);\n}\n\n/**\n * Helper for dynamically loading module that should work with linked dependencies.\n * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`\n * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during\n * build time. `require.resolve` is also not available in any other way, so we cannot create,\n * a fake helper like we do with `dynamicRequire`.\n *\n * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.\n * That is to mimic the behavior of `require.resolve` exactly.\n *\n * @param moduleName module name to require\n * @returns possibly required module\n */\nexport function loadModule(moduleName: string): T | undefined {\n let mod: T | undefined;\n\n try {\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n try {\n const { cwd } = dynamicRequire(module, 'process');\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) as T;\n } catch (e) {\n // no-empty\n }\n\n return mod;\n}\n","'use strict';\n\nvar reactIs = require('react-is');\n\n/**\n * Copyright 2015, Yahoo! Inc.\n * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.\n */\nvar REACT_STATICS = {\n childContextTypes: true,\n contextType: true,\n contextTypes: true,\n defaultProps: true,\n displayName: true,\n getDefaultProps: true,\n getDerivedStateFromError: true,\n getDerivedStateFromProps: true,\n mixins: true,\n propTypes: true,\n type: true\n};\nvar KNOWN_STATICS = {\n name: true,\n length: true,\n prototype: true,\n caller: true,\n callee: true,\n arguments: true,\n arity: true\n};\nvar FORWARD_REF_STATICS = {\n '$$typeof': true,\n render: true,\n defaultProps: true,\n displayName: true,\n propTypes: true\n};\nvar MEMO_STATICS = {\n '$$typeof': true,\n compare: true,\n defaultProps: true,\n displayName: true,\n propTypes: true,\n type: true\n};\nvar TYPE_STATICS = {};\nTYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;\nTYPE_STATICS[reactIs.Memo] = MEMO_STATICS;\n\nfunction getStatics(component) {\n // React v16.11 and below\n if (reactIs.isMemo(component)) {\n return MEMO_STATICS;\n } // React v16.12 and above\n\n\n return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;\n}\n\nvar defineProperty = Object.defineProperty;\nvar getOwnPropertyNames = Object.getOwnPropertyNames;\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nvar getPrototypeOf = Object.getPrototypeOf;\nvar objectPrototype = Object.prototype;\nfunction hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {\n if (typeof sourceComponent !== 'string') {\n // don't hoist over string (html) components\n if (objectPrototype) {\n var inheritedComponent = getPrototypeOf(sourceComponent);\n\n if (inheritedComponent && inheritedComponent !== objectPrototype) {\n hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);\n }\n }\n\n var keys = getOwnPropertyNames(sourceComponent);\n\n if (getOwnPropertySymbols) {\n keys = keys.concat(getOwnPropertySymbols(sourceComponent));\n }\n\n var targetStatics = getStatics(targetComponent);\n var sourceStatics = getStatics(sourceComponent);\n\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n\n if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {\n var descriptor = getOwnPropertyDescriptor(sourceComponent, key);\n\n try {\n // Avoid failures from read-only properties\n defineProperty(targetComponent, key, descriptor);\n } catch (e) {}\n }\n }\n }\n\n return targetComponent;\n}\n\nmodule.exports = hoistNonReactStatics;\n","/** @license React v16.13.1\n * react-is.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';var b=\"function\"===typeof Symbol&&Symbol.for,c=b?Symbol.for(\"react.element\"):60103,d=b?Symbol.for(\"react.portal\"):60106,e=b?Symbol.for(\"react.fragment\"):60107,f=b?Symbol.for(\"react.strict_mode\"):60108,g=b?Symbol.for(\"react.profiler\"):60114,h=b?Symbol.for(\"react.provider\"):60109,k=b?Symbol.for(\"react.context\"):60110,l=b?Symbol.for(\"react.async_mode\"):60111,m=b?Symbol.for(\"react.concurrent_mode\"):60111,n=b?Symbol.for(\"react.forward_ref\"):60112,p=b?Symbol.for(\"react.suspense\"):60113,q=b?\nSymbol.for(\"react.suspense_list\"):60120,r=b?Symbol.for(\"react.memo\"):60115,t=b?Symbol.for(\"react.lazy\"):60116,v=b?Symbol.for(\"react.block\"):60121,w=b?Symbol.for(\"react.fundamental\"):60117,x=b?Symbol.for(\"react.responder\"):60118,y=b?Symbol.for(\"react.scope\"):60119;\nfunction z(a){if(\"object\"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;\nexports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t};\nexports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p};\nexports.isValidElementType=function(a){return\"string\"===typeof a||\"function\"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||\"object\"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-is.production.min.js');\n} else {\n module.exports = require('./cjs/react-is.development.js');\n}\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');\n\nfunction emptyFunction() {}\nfunction emptyFunctionWithReset() {}\nemptyFunctionWithReset.resetWarningCache = emptyFunction;\n\nmodule.exports = function() {\n function shim(props, propName, componentName, location, propFullName, secret) {\n if (secret === ReactPropTypesSecret) {\n // It is still safe when called from React.\n return;\n }\n var err = new Error(\n 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n 'Use PropTypes.checkPropTypes() to call them. ' +\n 'Read more at http://fb.me/use-check-prop-types'\n );\n err.name = 'Invariant Violation';\n throw err;\n };\n shim.isRequired = shim;\n function getShim() {\n return shim;\n };\n // Important!\n // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.\n var ReactPropTypes = {\n array: shim,\n bigint: shim,\n bool: shim,\n func: shim,\n number: shim,\n object: shim,\n string: shim,\n symbol: shim,\n\n any: shim,\n arrayOf: getShim,\n element: shim,\n elementType: shim,\n instanceOf: getShim,\n node: shim,\n objectOf: getShim,\n oneOf: getShim,\n oneOfType: getShim,\n shape: getShim,\n exact: getShim,\n\n checkPropTypes: emptyFunctionWithReset,\n resetWarningCache: emptyFunction\n };\n\n ReactPropTypes.PropTypes = ReactPropTypes;\n\n return ReactPropTypes;\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nif (process.env.NODE_ENV !== 'production') {\n var ReactIs = require('react-is');\n\n // By explicitly using `prop-types` you are opting into new development behavior.\n // http://fb.me/prop-types-in-prod\n var throwOnDirectAccess = true;\n module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);\n} else {\n // By explicitly using `prop-types` you are opting into new production behavior.\n // http://fb.me/prop-types-in-prod\n module.exports = require('./factoryWithThrowingShims')();\n}\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\nmodule.exports = ReactPropTypesSecret;\n","/**\n * @license React\n * react-dom.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n'use strict';var aa=require(\"react\"),ca=require(\"scheduler\");function p(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;cb}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});\"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope\".split(\" \").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}\n\"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height\".split(\" \").forEach(function(a){var b=a.replace(ra,\nsa);z[b]=new v(b,1,!1,a,null,!1,!1)});\"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type\".split(\" \").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/1999/xlink\",!1,!1)});[\"xml:base\",\"xml:lang\",\"xml:space\"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});\nz.xlinkHref=new v(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k=\"\\n\"+e[g].replace(\" at new \",\" at \");a.displayName&&k.includes(\"\")&&(k=k.replace(\"\",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Ma(a):\"\"}\nfunction Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma(\"Lazy\");case 13:return Ma(\"Suspense\");case 19:return Ma(\"SuspenseList\");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return\"\"}}\nfunction Qa(a){if(null==a)return null;if(\"function\"===typeof a)return a.displayName||a.name||null;if(\"string\"===typeof a)return a;switch(a){case ya:return\"Fragment\";case wa:return\"Portal\";case Aa:return\"Profiler\";case za:return\"StrictMode\";case Ea:return\"Suspense\";case Fa:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||\"Context\")+\".Consumer\";case Ba:return(a._context.displayName||\"Context\")+\".Provider\";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||\nb.name||\"\",a=\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||\"Memo\";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}\nfunction Ra(a){var b=a.type;switch(a.tag){case 24:return\"Cache\";case 9:return(b.displayName||\"Context\")+\".Consumer\";case 10:return(b._context.displayName||\"Context\")+\".Provider\";case 18:return\"DehydratedFragment\";case 11:return a=b.render,a=a.displayName||a.name||\"\",b.displayName||(\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");case 7:return\"Fragment\";case 5:return b;case 4:return\"Portal\";case 3:return\"Root\";case 6:return\"Text\";case 16:return Qa(b);case 8:return b===za?\"StrictMode\":\"Mode\";case 22:return\"Offscreen\";\ncase 12:return\"Profiler\";case 21:return\"Scope\";case 13:return\"Suspense\";case 19:return\"SuspenseList\";case 25:return\"TracingMarker\";case 1:case 0:case 17:case 2:case 14:case 15:if(\"function\"===typeof b)return b.displayName||b.name||null;if(\"string\"===typeof b)return b}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"string\":case \"undefined\":return a;case \"object\":return a;default:return\"\"}}\nfunction Ta(a){var b=a.type;return(a=a.nodeName)&&\"input\"===a.toLowerCase()&&(\"checkbox\"===b||\"radio\"===b)}\nfunction Ua(a){var b=Ta(a)?\"checked\":\"value\",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=\"\"+a[b];if(!a.hasOwnProperty(b)&&\"undefined\"!==typeof c&&\"function\"===typeof c.get&&\"function\"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=\"\"+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=\"\"+a},stopTracking:function(){a._valueTracker=\nnull;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d=\"\";a&&(d=Ta(a)?a.checked?\"true\":\"false\":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||(\"undefined\"!==typeof document?document:void 0);if(\"undefined\"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}\nfunction Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?\"\":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:\"checkbox\"===b.type||\"radio\"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,\"checked\",b,!1)}\nfunction bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if(\"number\"===d){if(0===c&&\"\"===a.value||a.value!=c)a.value=\"\"+c}else a.value!==\"\"+c&&(a.value=\"\"+c);else if(\"submit\"===d||\"reset\"===d){a.removeAttribute(\"value\");return}b.hasOwnProperty(\"value\")?cb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction db(a,b,c){if(b.hasOwnProperty(\"value\")||b.hasOwnProperty(\"defaultValue\")){var d=b.type;if(!(\"submit\"!==d&&\"reset\"!==d||void 0!==b.value&&null!==b.value))return;b=\"\"+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;\"\"!==c&&(a.name=\"\");a.defaultChecked=!!a._wrapperState.initialChecked;\"\"!==c&&(a.name=c)}\nfunction cb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}var eb=Array.isArray;\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e\"+b.valueOf().toString()+\"\";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,\nzoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(\"\"+b).trim():b+\"px\"}\nfunction sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=rb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});\nfunction ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if(\"object\"!==typeof b.dangerouslySetInnerHTML||!(\"__html\"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(p(62));}}\nfunction vb(a,b){if(-1===a.indexOf(\"-\"))return\"string\"===typeof b.is;switch(a){case \"annotation-xml\":case \"color-profile\":case \"font-face\":case \"font-face-src\":case \"font-face-uri\":case \"font-face-format\":case \"font-face-name\":case \"missing-glyph\":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;\nfunction Bb(a){if(a=Cb(a)){if(\"function\"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;\nfunction tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;\ndefault:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}\nfunction Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be),ee=String.fromCharCode(32),fe=!1;\nfunction ge(a,b){switch(a){case \"keyup\":return-1!==$d.indexOf(b.keyCode);case \"keydown\":return 229!==b.keyCode;case \"keypress\":case \"mousedown\":case \"focusout\":return!0;default:return!1}}function he(a){a=a.detail;return\"object\"===typeof a&&\"data\"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case \"compositionend\":return he(b);case \"keypress\":if(32!==b.which)return null;fe=!0;return ee;case \"textInput\":return a=b.data,a===ee&&fe?null:a;default:return null}}\nfunction ke(a,b){if(ie)return\"compositionend\"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case \"paste\":return null;case \"keypress\":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c=\"string\"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&(\"input\"===b&&(\"text\"===a.type||\"search\"===a.type||\"tel\"===a.type||\"url\"===a.type||\"password\"===a.type)||\"textarea\"===b||\"true\"===a.contentEditable)}\nfunction Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),\"selectionStart\"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,\nd);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});\"function\"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;\nfunction Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,\"selectionStart\"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}\nfunction Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||\"Unknown\",e));return A({},c,d)}\nfunction cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}\nfunction jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,\nm),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){\"object\"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if(\"object\"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=\nf.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||\"object\"===typeof k&&null!==k&&k.$$typeof===Ha&&uh(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=sh(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Ah(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=yh(f.type,f.key,f.props,null,a.mode,h),h.ref=sh(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!==\nd;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=zh(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);th(a,f)}return\"string\"===typeof f&&\"\"!==f||\"number\"===typeof f?(f=\"\"+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):\n(c(a,d),d=xh(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Bh=vh(!0),Ch=vh(!1),Dh={},Eh=Uf(Dh),Fh=Uf(Dh),Gh=Uf(Dh);function Hh(a){if(a===Dh)throw Error(p(174));return a}function Ih(a,b){G(Gh,b);G(Fh,a);G(Eh,Dh);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:lb(null,\"\");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=lb(b,a)}E(Eh);G(Eh,b)}function Jh(){E(Eh);E(Fh);E(Gh)}\nfunction Kh(a){Hh(Gh.current);var b=Hh(Eh.current);var c=lb(b,a.type);b!==c&&(G(Fh,a),G(Eh,c))}function Lh(a){Fh.current===a&&(E(Eh),E(Fh))}var M=Uf(0);\nfunction Mh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||\"$?\"===c.data||\"$!\"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}var Nh=[];\nfunction Oh(){for(var a=0;ac?c:4;a(!0);var d=Qh.transition;Qh.transition={};try{a(!1),b()}finally{C=c,Qh.transition=d}}function Fi(){return di().memoizedState}\nfunction Gi(a,b,c){var d=lh(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,c);else if(c=Yg(a,b,c,d),null!==c){var e=L();mh(c,a,d,e);Ji(c,b,d)}}\nfunction ri(a,b,c){var d=lh(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,Xg(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=Yg(a,b,e,d);null!==c&&(e=L(),mh(c,a,d,e),Ji(c,b,d))}}\nfunction Hi(a){var b=a.alternate;return a===N||null!==b&&b===N}function Ii(a,b){Th=Sh=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Ji(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nvar ai={readContext:Vg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useInsertionEffect:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useDeferredValue:Q,useTransition:Q,useMutableSource:Q,useSyncExternalStore:Q,useId:Q,unstable_isNewReconciler:!1},Yh={readContext:Vg,useCallback:function(a,b){ci().memoizedState=[a,void 0===b?null:b];return a},useContext:Vg,useEffect:vi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ti(4194308,\n4,yi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ti(4194308,4,a,b)},useInsertionEffect:function(a,b){return ti(4,2,a,b)},useMemo:function(a,b){var c=ci();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=ci();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=Gi.bind(null,N,a);return[d.memoizedState,a]},useRef:function(a){var b=\nci();a={current:a};return b.memoizedState=a},useState:qi,useDebugValue:Ai,useDeferredValue:function(a){return ci().memoizedState=a},useTransition:function(){var a=qi(!1),b=a[0];a=Ei.bind(null,a[1]);ci().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=N,e=ci();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===R)throw Error(p(349));0!==(Rh&30)||ni(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;vi(ki.bind(null,d,\nf,a),[a]);d.flags|=2048;li(9,mi.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=ci(),b=R.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=\":\"+b+\"R\"+c;c=Uh++;0\\x3c/script>\",a=a.removeChild(a.firstChild)):\n\"string\"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),\"select\"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;Aj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case \"dialog\":D(\"cancel\",a);D(\"close\",a);e=d;break;case \"iframe\":case \"object\":case \"embed\":D(\"load\",a);e=d;break;case \"video\":case \"audio\":for(e=0;eHj&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304)}else{if(!d)if(a=Mh(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Ej(f,!0),null===f.tail&&\"hidden\"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Hj&&1073741824!==c&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=\nb,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=M.current,G(M,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Ij(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(gj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}\nfunction Jj(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return Jh(),E(Wf),E(H),Oh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Lh(b),null;case 13:E(M);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(M),null;case 4:return Jh(),null;case 10:return Rg(b.type._context),null;case 22:case 23:return Ij(),\nnull;case 24:return null;default:return null}}var Kj=!1,U=!1,Lj=\"function\"===typeof WeakSet?WeakSet:Set,V=null;function Mj(a,b){var c=a.ref;if(null!==c)if(\"function\"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Nj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Oj=!1;\nfunction Pj(a,b){Cf=dd;a=Me();if(Ne(a)){if(\"selectionStart\"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=\nq.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;\ncase 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Lg(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent=\"\":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Oj;Oj=!1;return n}\nfunction Qj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Nj(b,c,f)}e=e.next}while(e!==d)}}function Rj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Sj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}\"function\"===typeof b?b(a):b.current=a}}\nfunction Tj(a){var b=a.alternate;null!==b&&(a.alternate=null,Tj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Uj(a){return 5===a.tag||3===a.tag||4===a.tag}\nfunction Vj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Uj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}\nfunction Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling}\nfunction Xj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Xj(a,b,c),a=a.sibling;null!==a;)Xj(a,b,c),a=a.sibling}var X=null,Yj=!1;function Zj(a,b,c){for(c=c.child;null!==c;)ak(a,b,c),c=c.sibling}\nfunction ak(a,b,c){if(lc&&\"function\"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Mj(c,b);case 6:var d=X,e=Yj;X=null;Zj(a,b,c);X=d;Yj=e;null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Yj;X=c.stateNode.containerInfo;Yj=!0;\nZj(a,b,c);X=d;Yj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Nj(c,b,g):0!==(f&4)&&Nj(c,b,g));e=e.next}while(e!==d)}Zj(a,b,c);break;case 1:if(!U&&(Mj(c,b),d=c.stateNode,\"function\"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Zj(a,b,c);break;case 21:Zj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==\nc.memoizedState,Zj(a,b,c),U=d):Zj(a,b,c);break;default:Zj(a,b,c)}}function bk(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Lj);b.forEach(function(b){var d=ck.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}\nfunction dk(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*mk(d/1960))-d;if(10a?16:a;if(null===xk)var d=!1;else{a=xk;xk=null;yk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-gk?Lk(a,0):sk|=c);Ek(a,b)}function Zk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=L();a=Zg(a,b);null!==a&&(Ac(a,b,c),Ek(a,c))}function vj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Zk(a,c)}\nfunction ck(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Zk(a,c)}var Wk;\nWk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)Ug=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return Ug=!1,zj(a,b,c);Ug=0!==(a.flags&131072)?!0:!1}else Ug=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;jj(a,b);a=b.pendingProps;var e=Yf(b,H.current);Tg(b,c);e=Xh(null,b,d,a,e,c);var f=bi();b.flags|=1;\"object\"===typeof e&&null!==e&&\"function\"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=\nnull,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,ah(b),e.updater=nh,b.stateNode=e,e._reactInternals=b,rh(b,d,a,c),b=kj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Yi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{jj(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=$k(d);a=Lg(d,a);switch(e){case 0:b=dj(null,b,d,a,c);break a;case 1:b=ij(null,b,d,a,c);break a;case 11:b=Zi(null,b,d,a,c);break a;case 14:b=aj(null,b,d,Lg(d.type,a),c);break a}throw Error(p(306,\nd,\"\"));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),dj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),ij(a,b,d,e,c);case 3:a:{lj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;bh(a,b);gh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=\nf,b.memoizedState=f,b.flags&256){e=Ki(Error(p(423)),b);b=mj(a,b,d,c,e);break a}else if(d!==e){e=Ki(Error(p(424)),b);b=mj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Ch(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=$i(a,b,c);break a}Yi(a,b,d,c)}b=b.child}return b;case 5:return Kh(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),\nhj(a,b),Yi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return pj(a,b,c);case 4:return Ih(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Bh(b,null,d,c):Yi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),Zi(a,b,d,e,c);case 7:return Yi(a,b,b.pendingProps,c),b.child;case 8:return Yi(a,b,b.pendingProps.children,c),b.child;case 12:return Yi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;\ng=e.value;G(Mg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=$i(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=ch(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);Sg(f.return,\nc,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);Sg(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Yi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,Tg(b,c),e=Vg(e),d=d(e),b.flags|=1,Yi(a,b,d,c),\nb.child;case 14:return d=b.type,e=Lg(d,b.pendingProps),e=Lg(d.type,e),aj(a,b,d,e,c);case 15:return cj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),jj(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,Tg(b,c),ph(b,d,e),rh(b,d,e,c),kj(null,b,d,!0,a,c);case 19:return yj(a,b,c);case 22:return ej(a,b,c)}throw Error(p(156,b.tag));};function Gk(a,b){return ac(a,b)}\nfunction al(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new al(a,b,c,d)}function bj(a){a=a.prototype;return!(!a||!a.isReactComponent)}\nfunction $k(a){if(\"function\"===typeof a)return bj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}\nfunction wh(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};\nc.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}\nfunction yh(a,b,c,d,e,f){var g=2;d=a;if(\"function\"===typeof a)bj(a)&&(g=1);else if(\"string\"===typeof a)g=5;else a:switch(a){case ya:return Ah(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return qj(c,e,f,b);default:if(\"object\"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;\nbreak a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,\"\"));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Ah(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function qj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function xh(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}\nfunction zh(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}\nfunction bl(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=\nnull}function cl(a,b,c,d,e,f,g,h,k){a=new bl(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};ah(f);return a}function dl(a,b,c){var d=3 0 ? this.queries.filter(function (query) {\n return matchQuery(filters, query);\n }) : this.queries;\n };\n\n _proto.notify = function notify(event) {\n var _this3 = this;\n\n notifyManager.batch(function () {\n _this3.listeners.forEach(function (listener) {\n listener(event);\n });\n });\n };\n\n _proto.onFocus = function onFocus() {\n var _this4 = this;\n\n notifyManager.batch(function () {\n _this4.queries.forEach(function (query) {\n query.onFocus();\n });\n });\n };\n\n _proto.onOnline = function onOnline() {\n var _this5 = this;\n\n notifyManager.batch(function () {\n _this5.queries.forEach(function (query) {\n query.onOnline();\n });\n });\n };\n\n return QueryCache;\n}(Subscribable);","import _inheritsLoose from \"@babel/runtime/helpers/esm/inheritsLoose\";\nimport { notifyManager } from './notifyManager';\nimport { Mutation } from './mutation';\nimport { matchMutation, noop } from './utils';\nimport { Subscribable } from './subscribable'; // TYPES\n\n// CLASS\nexport var MutationCache = /*#__PURE__*/function (_Subscribable) {\n _inheritsLoose(MutationCache, _Subscribable);\n\n function MutationCache(config) {\n var _this;\n\n _this = _Subscribable.call(this) || this;\n _this.config = config || {};\n _this.mutations = [];\n _this.mutationId = 0;\n return _this;\n }\n\n var _proto = MutationCache.prototype;\n\n _proto.build = function build(client, options, state) {\n var mutation = new Mutation({\n mutationCache: this,\n mutationId: ++this.mutationId,\n options: client.defaultMutationOptions(options),\n state: state,\n defaultOptions: options.mutationKey ? client.getMutationDefaults(options.mutationKey) : undefined,\n meta: options.meta\n });\n this.add(mutation);\n return mutation;\n };\n\n _proto.add = function add(mutation) {\n this.mutations.push(mutation);\n this.notify(mutation);\n };\n\n _proto.remove = function remove(mutation) {\n this.mutations = this.mutations.filter(function (x) {\n return x !== mutation;\n });\n mutation.cancel();\n this.notify(mutation);\n };\n\n _proto.clear = function clear() {\n var _this2 = this;\n\n notifyManager.batch(function () {\n _this2.mutations.forEach(function (mutation) {\n _this2.remove(mutation);\n });\n });\n };\n\n _proto.getAll = function getAll() {\n return this.mutations;\n };\n\n _proto.find = function find(filters) {\n if (typeof filters.exact === 'undefined') {\n filters.exact = true;\n }\n\n return this.mutations.find(function (mutation) {\n return matchMutation(filters, mutation);\n });\n };\n\n _proto.findAll = function findAll(filters) {\n return this.mutations.filter(function (mutation) {\n return matchMutation(filters, mutation);\n });\n };\n\n _proto.notify = function notify(mutation) {\n var _this3 = this;\n\n notifyManager.batch(function () {\n _this3.listeners.forEach(function (listener) {\n listener(mutation);\n });\n });\n };\n\n _proto.onFocus = function onFocus() {\n this.resumePausedMutations();\n };\n\n _proto.onOnline = function onOnline() {\n this.resumePausedMutations();\n };\n\n _proto.resumePausedMutations = function resumePausedMutations() {\n var pausedMutations = this.mutations.filter(function (x) {\n return x.state.isPaused;\n });\n return notifyManager.batch(function () {\n return pausedMutations.reduce(function (promise, mutation) {\n return promise.then(function () {\n return mutation.continue().catch(noop);\n });\n }, Promise.resolve());\n });\n };\n\n return MutationCache;\n}(Subscribable);","import { isCancelable } from './retryer';\nimport { getAbortController } from './utils';\nexport function infiniteQueryBehavior() {\n return {\n onFetch: function onFetch(context) {\n context.fetchFn = function () {\n var _context$fetchOptions, _context$fetchOptions2, _context$fetchOptions3, _context$fetchOptions4, _context$state$data, _context$state$data2;\n\n var refetchPage = (_context$fetchOptions = context.fetchOptions) == null ? void 0 : (_context$fetchOptions2 = _context$fetchOptions.meta) == null ? void 0 : _context$fetchOptions2.refetchPage;\n var fetchMore = (_context$fetchOptions3 = context.fetchOptions) == null ? void 0 : (_context$fetchOptions4 = _context$fetchOptions3.meta) == null ? void 0 : _context$fetchOptions4.fetchMore;\n var pageParam = fetchMore == null ? void 0 : fetchMore.pageParam;\n var isFetchingNextPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'forward';\n var isFetchingPreviousPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'backward';\n var oldPages = ((_context$state$data = context.state.data) == null ? void 0 : _context$state$data.pages) || [];\n var oldPageParams = ((_context$state$data2 = context.state.data) == null ? void 0 : _context$state$data2.pageParams) || [];\n var abortController = getAbortController();\n var abortSignal = abortController == null ? void 0 : abortController.signal;\n var newPageParams = oldPageParams;\n var cancelled = false; // Get query function\n\n var queryFn = context.options.queryFn || function () {\n return Promise.reject('Missing queryFn');\n };\n\n var buildNewPages = function buildNewPages(pages, param, page, previous) {\n newPageParams = previous ? [param].concat(newPageParams) : [].concat(newPageParams, [param]);\n return previous ? [page].concat(pages) : [].concat(pages, [page]);\n }; // Create function to fetch a page\n\n\n var fetchPage = function fetchPage(pages, manual, param, previous) {\n if (cancelled) {\n return Promise.reject('Cancelled');\n }\n\n if (typeof param === 'undefined' && !manual && pages.length) {\n return Promise.resolve(pages);\n }\n\n var queryFnContext = {\n queryKey: context.queryKey,\n signal: abortSignal,\n pageParam: param,\n meta: context.meta\n };\n var queryFnResult = queryFn(queryFnContext);\n var promise = Promise.resolve(queryFnResult).then(function (page) {\n return buildNewPages(pages, param, page, previous);\n });\n\n if (isCancelable(queryFnResult)) {\n var promiseAsAny = promise;\n promiseAsAny.cancel = queryFnResult.cancel;\n }\n\n return promise;\n };\n\n var promise; // Fetch first page?\n\n if (!oldPages.length) {\n promise = fetchPage([]);\n } // Fetch next page?\n else if (isFetchingNextPage) {\n var manual = typeof pageParam !== 'undefined';\n var param = manual ? pageParam : getNextPageParam(context.options, oldPages);\n promise = fetchPage(oldPages, manual, param);\n } // Fetch previous page?\n else if (isFetchingPreviousPage) {\n var _manual = typeof pageParam !== 'undefined';\n\n var _param = _manual ? pageParam : getPreviousPageParam(context.options, oldPages);\n\n promise = fetchPage(oldPages, _manual, _param, true);\n } // Refetch pages\n else {\n (function () {\n newPageParams = [];\n var manual = typeof context.options.getNextPageParam === 'undefined';\n var shouldFetchFirstPage = refetchPage && oldPages[0] ? refetchPage(oldPages[0], 0, oldPages) : true; // Fetch first page\n\n promise = shouldFetchFirstPage ? fetchPage([], manual, oldPageParams[0]) : Promise.resolve(buildNewPages([], oldPageParams[0], oldPages[0])); // Fetch remaining pages\n\n var _loop = function _loop(i) {\n promise = promise.then(function (pages) {\n var shouldFetchNextPage = refetchPage && oldPages[i] ? refetchPage(oldPages[i], i, oldPages) : true;\n\n if (shouldFetchNextPage) {\n var _param2 = manual ? oldPageParams[i] : getNextPageParam(context.options, pages);\n\n return fetchPage(pages, manual, _param2);\n }\n\n return Promise.resolve(buildNewPages(pages, oldPageParams[i], oldPages[i]));\n });\n };\n\n for (var i = 1; i < oldPages.length; i++) {\n _loop(i);\n }\n })();\n }\n\n var finalPromise = promise.then(function (pages) {\n return {\n pages: pages,\n pageParams: newPageParams\n };\n });\n var finalPromiseAsAny = finalPromise;\n\n finalPromiseAsAny.cancel = function () {\n cancelled = true;\n abortController == null ? void 0 : abortController.abort();\n\n if (isCancelable(promise)) {\n promise.cancel();\n }\n };\n\n return finalPromise;\n };\n }\n };\n}\nexport function getNextPageParam(options, pages) {\n return options.getNextPageParam == null ? void 0 : options.getNextPageParam(pages[pages.length - 1], pages);\n}\nexport function getPreviousPageParam(options, pages) {\n return options.getPreviousPageParam == null ? void 0 : options.getPreviousPageParam(pages[0], pages);\n}\n/**\n * Checks if there is a next page.\n * Returns `undefined` if it cannot be determined.\n */\n\nexport function hasNextPage(options, pages) {\n if (options.getNextPageParam && Array.isArray(pages)) {\n var nextPageParam = getNextPageParam(options, pages);\n return typeof nextPageParam !== 'undefined' && nextPageParam !== null && nextPageParam !== false;\n }\n}\n/**\n * Checks if there is a previous page.\n * Returns `undefined` if it cannot be determined.\n */\n\nexport function hasPreviousPage(options, pages) {\n if (options.getPreviousPageParam && Array.isArray(pages)) {\n var previousPageParam = getPreviousPageParam(options, pages);\n return typeof previousPageParam !== 'undefined' && previousPageParam !== null && previousPageParam !== false;\n }\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport { hashQueryKey, noop, parseFilterArgs, parseQueryArgs, partialMatchKey, hashQueryKeyByOptions } from './utils';\nimport { QueryCache } from './queryCache';\nimport { MutationCache } from './mutationCache';\nimport { focusManager } from './focusManager';\nimport { onlineManager } from './onlineManager';\nimport { notifyManager } from './notifyManager';\nimport { infiniteQueryBehavior } from './infiniteQueryBehavior';\n// CLASS\nexport var QueryClient = /*#__PURE__*/function () {\n function QueryClient(config) {\n if (config === void 0) {\n config = {};\n }\n\n this.queryCache = config.queryCache || new QueryCache();\n this.mutationCache = config.mutationCache || new MutationCache();\n this.defaultOptions = config.defaultOptions || {};\n this.queryDefaults = [];\n this.mutationDefaults = [];\n }\n\n var _proto = QueryClient.prototype;\n\n _proto.mount = function mount() {\n var _this = this;\n\n this.unsubscribeFocus = focusManager.subscribe(function () {\n if (focusManager.isFocused() && onlineManager.isOnline()) {\n _this.mutationCache.onFocus();\n\n _this.queryCache.onFocus();\n }\n });\n this.unsubscribeOnline = onlineManager.subscribe(function () {\n if (focusManager.isFocused() && onlineManager.isOnline()) {\n _this.mutationCache.onOnline();\n\n _this.queryCache.onOnline();\n }\n });\n };\n\n _proto.unmount = function unmount() {\n var _this$unsubscribeFocu, _this$unsubscribeOnli;\n\n (_this$unsubscribeFocu = this.unsubscribeFocus) == null ? void 0 : _this$unsubscribeFocu.call(this);\n (_this$unsubscribeOnli = this.unsubscribeOnline) == null ? void 0 : _this$unsubscribeOnli.call(this);\n };\n\n _proto.isFetching = function isFetching(arg1, arg2) {\n var _parseFilterArgs = parseFilterArgs(arg1, arg2),\n filters = _parseFilterArgs[0];\n\n filters.fetching = true;\n return this.queryCache.findAll(filters).length;\n };\n\n _proto.isMutating = function isMutating(filters) {\n return this.mutationCache.findAll(_extends({}, filters, {\n fetching: true\n })).length;\n };\n\n _proto.getQueryData = function getQueryData(queryKey, filters) {\n var _this$queryCache$find;\n\n return (_this$queryCache$find = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find.state.data;\n };\n\n _proto.getQueriesData = function getQueriesData(queryKeyOrFilters) {\n return this.getQueryCache().findAll(queryKeyOrFilters).map(function (_ref) {\n var queryKey = _ref.queryKey,\n state = _ref.state;\n var data = state.data;\n return [queryKey, data];\n });\n };\n\n _proto.setQueryData = function setQueryData(queryKey, updater, options) {\n var parsedOptions = parseQueryArgs(queryKey);\n var defaultedOptions = this.defaultQueryOptions(parsedOptions);\n return this.queryCache.build(this, defaultedOptions).setData(updater, options);\n };\n\n _proto.setQueriesData = function setQueriesData(queryKeyOrFilters, updater, options) {\n var _this2 = this;\n\n return notifyManager.batch(function () {\n return _this2.getQueryCache().findAll(queryKeyOrFilters).map(function (_ref2) {\n var queryKey = _ref2.queryKey;\n return [queryKey, _this2.setQueryData(queryKey, updater, options)];\n });\n });\n };\n\n _proto.getQueryState = function getQueryState(queryKey, filters) {\n var _this$queryCache$find2;\n\n return (_this$queryCache$find2 = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find2.state;\n };\n\n _proto.removeQueries = function removeQueries(arg1, arg2) {\n var _parseFilterArgs2 = parseFilterArgs(arg1, arg2),\n filters = _parseFilterArgs2[0];\n\n var queryCache = this.queryCache;\n notifyManager.batch(function () {\n queryCache.findAll(filters).forEach(function (query) {\n queryCache.remove(query);\n });\n });\n };\n\n _proto.resetQueries = function resetQueries(arg1, arg2, arg3) {\n var _this3 = this;\n\n var _parseFilterArgs3 = parseFilterArgs(arg1, arg2, arg3),\n filters = _parseFilterArgs3[0],\n options = _parseFilterArgs3[1];\n\n var queryCache = this.queryCache;\n\n var refetchFilters = _extends({}, filters, {\n active: true\n });\n\n return notifyManager.batch(function () {\n queryCache.findAll(filters).forEach(function (query) {\n query.reset();\n });\n return _this3.refetchQueries(refetchFilters, options);\n });\n };\n\n _proto.cancelQueries = function cancelQueries(arg1, arg2, arg3) {\n var _this4 = this;\n\n var _parseFilterArgs4 = parseFilterArgs(arg1, arg2, arg3),\n filters = _parseFilterArgs4[0],\n _parseFilterArgs4$ = _parseFilterArgs4[1],\n cancelOptions = _parseFilterArgs4$ === void 0 ? {} : _parseFilterArgs4$;\n\n if (typeof cancelOptions.revert === 'undefined') {\n cancelOptions.revert = true;\n }\n\n var promises = notifyManager.batch(function () {\n return _this4.queryCache.findAll(filters).map(function (query) {\n return query.cancel(cancelOptions);\n });\n });\n return Promise.all(promises).then(noop).catch(noop);\n };\n\n _proto.invalidateQueries = function invalidateQueries(arg1, arg2, arg3) {\n var _ref3,\n _filters$refetchActiv,\n _filters$refetchInact,\n _this5 = this;\n\n var _parseFilterArgs5 = parseFilterArgs(arg1, arg2, arg3),\n filters = _parseFilterArgs5[0],\n options = _parseFilterArgs5[1];\n\n var refetchFilters = _extends({}, filters, {\n // if filters.refetchActive is not provided and filters.active is explicitly false,\n // e.g. invalidateQueries({ active: false }), we don't want to refetch active queries\n active: (_ref3 = (_filters$refetchActiv = filters.refetchActive) != null ? _filters$refetchActiv : filters.active) != null ? _ref3 : true,\n inactive: (_filters$refetchInact = filters.refetchInactive) != null ? _filters$refetchInact : false\n });\n\n return notifyManager.batch(function () {\n _this5.queryCache.findAll(filters).forEach(function (query) {\n query.invalidate();\n });\n\n return _this5.refetchQueries(refetchFilters, options);\n });\n };\n\n _proto.refetchQueries = function refetchQueries(arg1, arg2, arg3) {\n var _this6 = this;\n\n var _parseFilterArgs6 = parseFilterArgs(arg1, arg2, arg3),\n filters = _parseFilterArgs6[0],\n options = _parseFilterArgs6[1];\n\n var promises = notifyManager.batch(function () {\n return _this6.queryCache.findAll(filters).map(function (query) {\n return query.fetch(undefined, _extends({}, options, {\n meta: {\n refetchPage: filters == null ? void 0 : filters.refetchPage\n }\n }));\n });\n });\n var promise = Promise.all(promises).then(noop);\n\n if (!(options == null ? void 0 : options.throwOnError)) {\n promise = promise.catch(noop);\n }\n\n return promise;\n };\n\n _proto.fetchQuery = function fetchQuery(arg1, arg2, arg3) {\n var parsedOptions = parseQueryArgs(arg1, arg2, arg3);\n var defaultedOptions = this.defaultQueryOptions(parsedOptions); // https://github.com/tannerlinsley/react-query/issues/652\n\n if (typeof defaultedOptions.retry === 'undefined') {\n defaultedOptions.retry = false;\n }\n\n var query = this.queryCache.build(this, defaultedOptions);\n return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);\n };\n\n _proto.prefetchQuery = function prefetchQuery(arg1, arg2, arg3) {\n return this.fetchQuery(arg1, arg2, arg3).then(noop).catch(noop);\n };\n\n _proto.fetchInfiniteQuery = function fetchInfiniteQuery(arg1, arg2, arg3) {\n var parsedOptions = parseQueryArgs(arg1, arg2, arg3);\n parsedOptions.behavior = infiniteQueryBehavior();\n return this.fetchQuery(parsedOptions);\n };\n\n _proto.prefetchInfiniteQuery = function prefetchInfiniteQuery(arg1, arg2, arg3) {\n return this.fetchInfiniteQuery(arg1, arg2, arg3).then(noop).catch(noop);\n };\n\n _proto.cancelMutations = function cancelMutations() {\n var _this7 = this;\n\n var promises = notifyManager.batch(function () {\n return _this7.mutationCache.getAll().map(function (mutation) {\n return mutation.cancel();\n });\n });\n return Promise.all(promises).then(noop).catch(noop);\n };\n\n _proto.resumePausedMutations = function resumePausedMutations() {\n return this.getMutationCache().resumePausedMutations();\n };\n\n _proto.executeMutation = function executeMutation(options) {\n return this.mutationCache.build(this, options).execute();\n };\n\n _proto.getQueryCache = function getQueryCache() {\n return this.queryCache;\n };\n\n _proto.getMutationCache = function getMutationCache() {\n return this.mutationCache;\n };\n\n _proto.getDefaultOptions = function getDefaultOptions() {\n return this.defaultOptions;\n };\n\n _proto.setDefaultOptions = function setDefaultOptions(options) {\n this.defaultOptions = options;\n };\n\n _proto.setQueryDefaults = function setQueryDefaults(queryKey, options) {\n var result = this.queryDefaults.find(function (x) {\n return hashQueryKey(queryKey) === hashQueryKey(x.queryKey);\n });\n\n if (result) {\n result.defaultOptions = options;\n } else {\n this.queryDefaults.push({\n queryKey: queryKey,\n defaultOptions: options\n });\n }\n };\n\n _proto.getQueryDefaults = function getQueryDefaults(queryKey) {\n var _this$queryDefaults$f;\n\n return queryKey ? (_this$queryDefaults$f = this.queryDefaults.find(function (x) {\n return partialMatchKey(queryKey, x.queryKey);\n })) == null ? void 0 : _this$queryDefaults$f.defaultOptions : undefined;\n };\n\n _proto.setMutationDefaults = function setMutationDefaults(mutationKey, options) {\n var result = this.mutationDefaults.find(function (x) {\n return hashQueryKey(mutationKey) === hashQueryKey(x.mutationKey);\n });\n\n if (result) {\n result.defaultOptions = options;\n } else {\n this.mutationDefaults.push({\n mutationKey: mutationKey,\n defaultOptions: options\n });\n }\n };\n\n _proto.getMutationDefaults = function getMutationDefaults(mutationKey) {\n var _this$mutationDefault;\n\n return mutationKey ? (_this$mutationDefault = this.mutationDefaults.find(function (x) {\n return partialMatchKey(mutationKey, x.mutationKey);\n })) == null ? void 0 : _this$mutationDefault.defaultOptions : undefined;\n };\n\n _proto.defaultQueryOptions = function defaultQueryOptions(options) {\n if (options == null ? void 0 : options._defaulted) {\n return options;\n }\n\n var defaultedOptions = _extends({}, this.defaultOptions.queries, this.getQueryDefaults(options == null ? void 0 : options.queryKey), options, {\n _defaulted: true\n });\n\n if (!defaultedOptions.queryHash && defaultedOptions.queryKey) {\n defaultedOptions.queryHash = hashQueryKeyByOptions(defaultedOptions.queryKey, defaultedOptions);\n }\n\n return defaultedOptions;\n };\n\n _proto.defaultQueryObserverOptions = function defaultQueryObserverOptions(options) {\n return this.defaultQueryOptions(options);\n };\n\n _proto.defaultMutationOptions = function defaultMutationOptions(options) {\n if (options == null ? void 0 : options._defaulted) {\n return options;\n }\n\n return _extends({}, this.defaultOptions.mutations, this.getMutationDefaults(options == null ? void 0 : options.mutationKey), options, {\n _defaulted: true\n });\n };\n\n _proto.clear = function clear() {\n this.queryCache.clear();\n this.mutationCache.clear();\n };\n\n return QueryClient;\n}();","import { focusManager } from './focusManager';\nimport { onlineManager } from './onlineManager';\nimport { sleep } from './utils';\n\nfunction defaultRetryDelay(failureCount) {\n return Math.min(1000 * Math.pow(2, failureCount), 30000);\n}\n\nexport function isCancelable(value) {\n return typeof (value == null ? void 0 : value.cancel) === 'function';\n}\nexport var CancelledError = function CancelledError(options) {\n this.revert = options == null ? void 0 : options.revert;\n this.silent = options == null ? void 0 : options.silent;\n};\nexport function isCancelledError(value) {\n return value instanceof CancelledError;\n} // CLASS\n\nexport var Retryer = function Retryer(config) {\n var _this = this;\n\n var cancelRetry = false;\n var cancelFn;\n var continueFn;\n var promiseResolve;\n var promiseReject;\n this.abort = config.abort;\n\n this.cancel = function (cancelOptions) {\n return cancelFn == null ? void 0 : cancelFn(cancelOptions);\n };\n\n this.cancelRetry = function () {\n cancelRetry = true;\n };\n\n this.continueRetry = function () {\n cancelRetry = false;\n };\n\n this.continue = function () {\n return continueFn == null ? void 0 : continueFn();\n };\n\n this.failureCount = 0;\n this.isPaused = false;\n this.isResolved = false;\n this.isTransportCancelable = false;\n this.promise = new Promise(function (outerResolve, outerReject) {\n promiseResolve = outerResolve;\n promiseReject = outerReject;\n });\n\n var resolve = function resolve(value) {\n if (!_this.isResolved) {\n _this.isResolved = true;\n config.onSuccess == null ? void 0 : config.onSuccess(value);\n continueFn == null ? void 0 : continueFn();\n promiseResolve(value);\n }\n };\n\n var reject = function reject(value) {\n if (!_this.isResolved) {\n _this.isResolved = true;\n config.onError == null ? void 0 : config.onError(value);\n continueFn == null ? void 0 : continueFn();\n promiseReject(value);\n }\n };\n\n var pause = function pause() {\n return new Promise(function (continueResolve) {\n continueFn = continueResolve;\n _this.isPaused = true;\n config.onPause == null ? void 0 : config.onPause();\n }).then(function () {\n continueFn = undefined;\n _this.isPaused = false;\n config.onContinue == null ? void 0 : config.onContinue();\n });\n }; // Create loop function\n\n\n var run = function run() {\n // Do nothing if already resolved\n if (_this.isResolved) {\n return;\n }\n\n var promiseOrValue; // Execute query\n\n try {\n promiseOrValue = config.fn();\n } catch (error) {\n promiseOrValue = Promise.reject(error);\n } // Create callback to cancel this fetch\n\n\n cancelFn = function cancelFn(cancelOptions) {\n if (!_this.isResolved) {\n reject(new CancelledError(cancelOptions));\n _this.abort == null ? void 0 : _this.abort(); // Cancel transport if supported\n\n if (isCancelable(promiseOrValue)) {\n try {\n promiseOrValue.cancel();\n } catch (_unused) {}\n }\n }\n }; // Check if the transport layer support cancellation\n\n\n _this.isTransportCancelable = isCancelable(promiseOrValue);\n Promise.resolve(promiseOrValue).then(resolve).catch(function (error) {\n var _config$retry, _config$retryDelay;\n\n // Stop if the fetch is already resolved\n if (_this.isResolved) {\n return;\n } // Do we need to retry the request?\n\n\n var retry = (_config$retry = config.retry) != null ? _config$retry : 3;\n var retryDelay = (_config$retryDelay = config.retryDelay) != null ? _config$retryDelay : defaultRetryDelay;\n var delay = typeof retryDelay === 'function' ? retryDelay(_this.failureCount, error) : retryDelay;\n var shouldRetry = retry === true || typeof retry === 'number' && _this.failureCount < retry || typeof retry === 'function' && retry(_this.failureCount, error);\n\n if (cancelRetry || !shouldRetry) {\n // We are done if the query does not need to be retried\n reject(error);\n return;\n }\n\n _this.failureCount++; // Notify on fail\n\n config.onFail == null ? void 0 : config.onFail(_this.failureCount, error); // Delay\n\n sleep(delay) // Pause if the document is not visible or when the device is offline\n .then(function () {\n if (!focusManager.isFocused() || !onlineManager.isOnline()) {\n return pause();\n }\n }).then(function () {\n if (cancelRetry) {\n reject(error);\n } else {\n run();\n }\n });\n });\n }; // Start loop\n\n\n run();\n};","export var Subscribable = /*#__PURE__*/function () {\n function Subscribable() {\n this.listeners = [];\n }\n\n var _proto = Subscribable.prototype;\n\n _proto.subscribe = function subscribe(listener) {\n var _this = this;\n\n var callback = listener || function () {\n return undefined;\n };\n\n this.listeners.push(callback);\n this.onSubscribe();\n return function () {\n _this.listeners = _this.listeners.filter(function (x) {\n return x !== callback;\n });\n\n _this.onUnsubscribe();\n };\n };\n\n _proto.hasListeners = function hasListeners() {\n return this.listeners.length > 0;\n };\n\n _proto.onSubscribe = function onSubscribe() {// Do nothing\n };\n\n _proto.onUnsubscribe = function onUnsubscribe() {// Do nothing\n };\n\n return Subscribable;\n}();","import _extends from \"@babel/runtime/helpers/esm/extends\";\n// TYPES\n// UTILS\nexport var isServer = typeof window === 'undefined';\nexport function noop() {\n return undefined;\n}\nexport function functionalUpdate(updater, input) {\n return typeof updater === 'function' ? updater(input) : updater;\n}\nexport function isValidTimeout(value) {\n return typeof value === 'number' && value >= 0 && value !== Infinity;\n}\nexport function ensureQueryKeyArray(value) {\n return Array.isArray(value) ? value : [value];\n}\nexport function difference(array1, array2) {\n return array1.filter(function (x) {\n return array2.indexOf(x) === -1;\n });\n}\nexport function replaceAt(array, index, value) {\n var copy = array.slice(0);\n copy[index] = value;\n return copy;\n}\nexport function timeUntilStale(updatedAt, staleTime) {\n return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);\n}\nexport function parseQueryArgs(arg1, arg2, arg3) {\n if (!isQueryKey(arg1)) {\n return arg1;\n }\n\n if (typeof arg2 === 'function') {\n return _extends({}, arg3, {\n queryKey: arg1,\n queryFn: arg2\n });\n }\n\n return _extends({}, arg2, {\n queryKey: arg1\n });\n}\nexport function parseMutationArgs(arg1, arg2, arg3) {\n if (isQueryKey(arg1)) {\n if (typeof arg2 === 'function') {\n return _extends({}, arg3, {\n mutationKey: arg1,\n mutationFn: arg2\n });\n }\n\n return _extends({}, arg2, {\n mutationKey: arg1\n });\n }\n\n if (typeof arg1 === 'function') {\n return _extends({}, arg2, {\n mutationFn: arg1\n });\n }\n\n return _extends({}, arg1);\n}\nexport function parseFilterArgs(arg1, arg2, arg3) {\n return isQueryKey(arg1) ? [_extends({}, arg2, {\n queryKey: arg1\n }), arg3] : [arg1 || {}, arg2];\n}\nexport function parseMutationFilterArgs(arg1, arg2) {\n return isQueryKey(arg1) ? _extends({}, arg2, {\n mutationKey: arg1\n }) : arg1;\n}\nexport function mapQueryStatusFilter(active, inactive) {\n if (active === true && inactive === true || active == null && inactive == null) {\n return 'all';\n } else if (active === false && inactive === false) {\n return 'none';\n } else {\n // At this point, active|inactive can only be true|false or false|true\n // so, when only one value is provided, the missing one has to be the negated value\n var isActive = active != null ? active : !inactive;\n return isActive ? 'active' : 'inactive';\n }\n}\nexport function matchQuery(filters, query) {\n var active = filters.active,\n exact = filters.exact,\n fetching = filters.fetching,\n inactive = filters.inactive,\n predicate = filters.predicate,\n queryKey = filters.queryKey,\n stale = filters.stale;\n\n if (isQueryKey(queryKey)) {\n if (exact) {\n if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {\n return false;\n }\n } else if (!partialMatchKey(query.queryKey, queryKey)) {\n return false;\n }\n }\n\n var queryStatusFilter = mapQueryStatusFilter(active, inactive);\n\n if (queryStatusFilter === 'none') {\n return false;\n } else if (queryStatusFilter !== 'all') {\n var isActive = query.isActive();\n\n if (queryStatusFilter === 'active' && !isActive) {\n return false;\n }\n\n if (queryStatusFilter === 'inactive' && isActive) {\n return false;\n }\n }\n\n if (typeof stale === 'boolean' && query.isStale() !== stale) {\n return false;\n }\n\n if (typeof fetching === 'boolean' && query.isFetching() !== fetching) {\n return false;\n }\n\n if (predicate && !predicate(query)) {\n return false;\n }\n\n return true;\n}\nexport function matchMutation(filters, mutation) {\n var exact = filters.exact,\n fetching = filters.fetching,\n predicate = filters.predicate,\n mutationKey = filters.mutationKey;\n\n if (isQueryKey(mutationKey)) {\n if (!mutation.options.mutationKey) {\n return false;\n }\n\n if (exact) {\n if (hashQueryKey(mutation.options.mutationKey) !== hashQueryKey(mutationKey)) {\n return false;\n }\n } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {\n return false;\n }\n }\n\n if (typeof fetching === 'boolean' && mutation.state.status === 'loading' !== fetching) {\n return false;\n }\n\n if (predicate && !predicate(mutation)) {\n return false;\n }\n\n return true;\n}\nexport function hashQueryKeyByOptions(queryKey, options) {\n var hashFn = (options == null ? void 0 : options.queryKeyHashFn) || hashQueryKey;\n return hashFn(queryKey);\n}\n/**\n * Default query keys hash function.\n */\n\nexport function hashQueryKey(queryKey) {\n var asArray = ensureQueryKeyArray(queryKey);\n return stableValueHash(asArray);\n}\n/**\n * Hashes the value into a stable hash.\n */\n\nexport function stableValueHash(value) {\n return JSON.stringify(value, function (_, val) {\n return isPlainObject(val) ? Object.keys(val).sort().reduce(function (result, key) {\n result[key] = val[key];\n return result;\n }, {}) : val;\n });\n}\n/**\n * Checks if key `b` partially matches with key `a`.\n */\n\nexport function partialMatchKey(a, b) {\n return partialDeepEqual(ensureQueryKeyArray(a), ensureQueryKeyArray(b));\n}\n/**\n * Checks if `b` partially matches with `a`.\n */\n\nexport function partialDeepEqual(a, b) {\n if (a === b) {\n return true;\n }\n\n if (typeof a !== typeof b) {\n return false;\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n return !Object.keys(b).some(function (key) {\n return !partialDeepEqual(a[key], b[key]);\n });\n }\n\n return false;\n}\n/**\n * This function returns `a` if `b` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between JSON values for example.\n */\n\nexport function replaceEqualDeep(a, b) {\n if (a === b) {\n return a;\n }\n\n var array = Array.isArray(a) && Array.isArray(b);\n\n if (array || isPlainObject(a) && isPlainObject(b)) {\n var aSize = array ? a.length : Object.keys(a).length;\n var bItems = array ? b : Object.keys(b);\n var bSize = bItems.length;\n var copy = array ? [] : {};\n var equalItems = 0;\n\n for (var i = 0; i < bSize; i++) {\n var key = array ? i : bItems[i];\n copy[key] = replaceEqualDeep(a[key], b[key]);\n\n if (copy[key] === a[key]) {\n equalItems++;\n }\n }\n\n return aSize === bSize && equalItems === aSize ? a : copy;\n }\n\n return b;\n}\n/**\n * Shallow compare objects. Only works with objects that always have the same properties.\n */\n\nexport function shallowEqualObjects(a, b) {\n if (a && !b || b && !a) {\n return false;\n }\n\n for (var key in a) {\n if (a[key] !== b[key]) {\n return false;\n }\n }\n\n return true;\n} // Copied from: https://github.com/jonschlinkert/is-plain-object\n\nexport function isPlainObject(o) {\n if (!hasObjectPrototype(o)) {\n return false;\n } // If has modified constructor\n\n\n var ctor = o.constructor;\n\n if (typeof ctor === 'undefined') {\n return true;\n } // If has modified prototype\n\n\n var prot = ctor.prototype;\n\n if (!hasObjectPrototype(prot)) {\n return false;\n } // If constructor does not have an Object-specific method\n\n\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false;\n } // Most likely a plain Object\n\n\n return true;\n}\n\nfunction hasObjectPrototype(o) {\n return Object.prototype.toString.call(o) === '[object Object]';\n}\n\nexport function isQueryKey(value) {\n return typeof value === 'string' || Array.isArray(value);\n}\nexport function isError(value) {\n return value instanceof Error;\n}\nexport function sleep(timeout) {\n return new Promise(function (resolve) {\n setTimeout(resolve, timeout);\n });\n}\n/**\n * Schedules a microtask.\n * This can be useful to schedule state updates after rendering.\n */\n\nexport function scheduleMicrotask(callback) {\n Promise.resolve().then(callback).catch(function (error) {\n return setTimeout(function () {\n throw error;\n });\n });\n}\nexport function getAbortController() {\n if (typeof AbortController === 'function') {\n return new AbortController();\n }\n}","import ReactDOM from 'react-dom';\nexport var unstable_batchedUpdates = ReactDOM.unstable_batchedUpdates;","import { notifyManager } from '../core';\nimport { unstable_batchedUpdates } from './reactBatchedUpdates';\nnotifyManager.setBatchNotifyFunction(unstable_batchedUpdates);","export var logger = console;","import { setLogger } from '../core';\nimport { logger } from './logger';\nsetLogger(logger);","import React from 'react';\nvar defaultContext = /*#__PURE__*/React.createContext(undefined);\nvar QueryClientSharingContext = /*#__PURE__*/React.createContext(false); // if contextSharing is on, we share the first and at least one\n// instance of the context across the window\n// to ensure that if React Query is used across\n// different bundles or microfrontends they will\n// all use the same **instance** of context, regardless\n// of module scoping.\n\nfunction getQueryClientContext(contextSharing) {\n if (contextSharing && typeof window !== 'undefined') {\n if (!window.ReactQueryClientContext) {\n window.ReactQueryClientContext = defaultContext;\n }\n\n return window.ReactQueryClientContext;\n }\n\n return defaultContext;\n}\n\nexport var useQueryClient = function useQueryClient() {\n var queryClient = React.useContext(getQueryClientContext(React.useContext(QueryClientSharingContext)));\n\n if (!queryClient) {\n throw new Error('No QueryClient set, use QueryClientProvider to set one');\n }\n\n return queryClient;\n};\nexport var QueryClientProvider = function QueryClientProvider(_ref) {\n var client = _ref.client,\n _ref$contextSharing = _ref.contextSharing,\n contextSharing = _ref$contextSharing === void 0 ? false : _ref$contextSharing,\n children = _ref.children;\n React.useEffect(function () {\n client.mount();\n return function () {\n client.unmount();\n };\n }, [client]);\n var Context = getQueryClientContext(contextSharing);\n return /*#__PURE__*/React.createElement(QueryClientSharingContext.Provider, {\n value: contextSharing\n }, /*#__PURE__*/React.createElement(Context.Provider, {\n value: client\n }, children));\n};","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _inheritsLoose from \"@babel/runtime/helpers/esm/inheritsLoose\";\nimport { getDefaultState } from './mutation';\nimport { notifyManager } from './notifyManager';\nimport { Subscribable } from './subscribable';\n// CLASS\nexport var MutationObserver = /*#__PURE__*/function (_Subscribable) {\n _inheritsLoose(MutationObserver, _Subscribable);\n\n function MutationObserver(client, options) {\n var _this;\n\n _this = _Subscribable.call(this) || this;\n _this.client = client;\n\n _this.setOptions(options);\n\n _this.bindMethods();\n\n _this.updateResult();\n\n return _this;\n }\n\n var _proto = MutationObserver.prototype;\n\n _proto.bindMethods = function bindMethods() {\n this.mutate = this.mutate.bind(this);\n this.reset = this.reset.bind(this);\n };\n\n _proto.setOptions = function setOptions(options) {\n this.options = this.client.defaultMutationOptions(options);\n };\n\n _proto.onUnsubscribe = function onUnsubscribe() {\n if (!this.listeners.length) {\n var _this$currentMutation;\n\n (_this$currentMutation = this.currentMutation) == null ? void 0 : _this$currentMutation.removeObserver(this);\n }\n };\n\n _proto.onMutationUpdate = function onMutationUpdate(action) {\n this.updateResult(); // Determine which callbacks to trigger\n\n var notifyOptions = {\n listeners: true\n };\n\n if (action.type === 'success') {\n notifyOptions.onSuccess = true;\n } else if (action.type === 'error') {\n notifyOptions.onError = true;\n }\n\n this.notify(notifyOptions);\n };\n\n _proto.getCurrentResult = function getCurrentResult() {\n return this.currentResult;\n };\n\n _proto.reset = function reset() {\n this.currentMutation = undefined;\n this.updateResult();\n this.notify({\n listeners: true\n });\n };\n\n _proto.mutate = function mutate(variables, options) {\n this.mutateOptions = options;\n\n if (this.currentMutation) {\n this.currentMutation.removeObserver(this);\n }\n\n this.currentMutation = this.client.getMutationCache().build(this.client, _extends({}, this.options, {\n variables: typeof variables !== 'undefined' ? variables : this.options.variables\n }));\n this.currentMutation.addObserver(this);\n return this.currentMutation.execute();\n };\n\n _proto.updateResult = function updateResult() {\n var state = this.currentMutation ? this.currentMutation.state : getDefaultState();\n\n var result = _extends({}, state, {\n isLoading: state.status === 'loading',\n isSuccess: state.status === 'success',\n isError: state.status === 'error',\n isIdle: state.status === 'idle',\n mutate: this.mutate,\n reset: this.reset\n });\n\n this.currentResult = result;\n };\n\n _proto.notify = function notify(options) {\n var _this2 = this;\n\n notifyManager.batch(function () {\n // First trigger the mutate callbacks\n if (_this2.mutateOptions) {\n if (options.onSuccess) {\n _this2.mutateOptions.onSuccess == null ? void 0 : _this2.mutateOptions.onSuccess(_this2.currentResult.data, _this2.currentResult.variables, _this2.currentResult.context);\n _this2.mutateOptions.onSettled == null ? void 0 : _this2.mutateOptions.onSettled(_this2.currentResult.data, null, _this2.currentResult.variables, _this2.currentResult.context);\n } else if (options.onError) {\n _this2.mutateOptions.onError == null ? void 0 : _this2.mutateOptions.onError(_this2.currentResult.error, _this2.currentResult.variables, _this2.currentResult.context);\n _this2.mutateOptions.onSettled == null ? void 0 : _this2.mutateOptions.onSettled(undefined, _this2.currentResult.error, _this2.currentResult.variables, _this2.currentResult.context);\n }\n } // Then trigger the listeners\n\n\n if (options.listeners) {\n _this2.listeners.forEach(function (listener) {\n listener(_this2.currentResult);\n });\n }\n });\n };\n\n return MutationObserver;\n}(Subscribable);","export function shouldThrowError(suspense, _useErrorBoundary, params) {\n // Allow useErrorBoundary function to override throwing behavior on a per-error basis\n if (typeof _useErrorBoundary === 'function') {\n return _useErrorBoundary.apply(void 0, params);\n } // Allow useErrorBoundary to override suspense's throwing behavior\n\n\n if (typeof _useErrorBoundary === 'boolean') return _useErrorBoundary; // If suspense is enabled default to throwing errors\n\n return !!suspense;\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport React from 'react';\nimport { notifyManager } from '../core/notifyManager';\nimport { noop, parseMutationArgs } from '../core/utils';\nimport { MutationObserver } from '../core/mutationObserver';\nimport { useQueryClient } from './QueryClientProvider';\nimport { shouldThrowError } from './utils'; // HOOK\n\nexport function useMutation(arg1, arg2, arg3) {\n var mountedRef = React.useRef(false);\n\n var _React$useState = React.useState(0),\n forceUpdate = _React$useState[1];\n\n var options = parseMutationArgs(arg1, arg2, arg3);\n var queryClient = useQueryClient();\n var obsRef = React.useRef();\n\n if (!obsRef.current) {\n obsRef.current = new MutationObserver(queryClient, options);\n } else {\n obsRef.current.setOptions(options);\n }\n\n var currentResult = obsRef.current.getCurrentResult();\n React.useEffect(function () {\n mountedRef.current = true;\n var unsubscribe = obsRef.current.subscribe(notifyManager.batchCalls(function () {\n if (mountedRef.current) {\n forceUpdate(function (x) {\n return x + 1;\n });\n }\n }));\n return function () {\n mountedRef.current = false;\n unsubscribe();\n };\n }, []);\n var mutate = React.useCallback(function (variables, mutateOptions) {\n obsRef.current.mutate(variables, mutateOptions).catch(noop);\n }, []);\n\n if (currentResult.error && shouldThrowError(undefined, obsRef.current.options.useErrorBoundary, [currentResult.error])) {\n throw currentResult.error;\n }\n\n return _extends({}, currentResult, {\n mutate: mutate,\n mutateAsync: currentResult.mutate\n });\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _inheritsLoose from \"@babel/runtime/helpers/esm/inheritsLoose\";\nimport { isServer, isValidTimeout, noop, replaceEqualDeep, shallowEqualObjects, timeUntilStale } from './utils';\nimport { notifyManager } from './notifyManager';\nimport { focusManager } from './focusManager';\nimport { Subscribable } from './subscribable';\nimport { getLogger } from './logger';\nimport { isCancelledError } from './retryer';\nexport var QueryObserver = /*#__PURE__*/function (_Subscribable) {\n _inheritsLoose(QueryObserver, _Subscribable);\n\n function QueryObserver(client, options) {\n var _this;\n\n _this = _Subscribable.call(this) || this;\n _this.client = client;\n _this.options = options;\n _this.trackedProps = [];\n _this.selectError = null;\n\n _this.bindMethods();\n\n _this.setOptions(options);\n\n return _this;\n }\n\n var _proto = QueryObserver.prototype;\n\n _proto.bindMethods = function bindMethods() {\n this.remove = this.remove.bind(this);\n this.refetch = this.refetch.bind(this);\n };\n\n _proto.onSubscribe = function onSubscribe() {\n if (this.listeners.length === 1) {\n this.currentQuery.addObserver(this);\n\n if (shouldFetchOnMount(this.currentQuery, this.options)) {\n this.executeFetch();\n }\n\n this.updateTimers();\n }\n };\n\n _proto.onUnsubscribe = function onUnsubscribe() {\n if (!this.listeners.length) {\n this.destroy();\n }\n };\n\n _proto.shouldFetchOnReconnect = function shouldFetchOnReconnect() {\n return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnReconnect);\n };\n\n _proto.shouldFetchOnWindowFocus = function shouldFetchOnWindowFocus() {\n return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnWindowFocus);\n };\n\n _proto.destroy = function destroy() {\n this.listeners = [];\n this.clearTimers();\n this.currentQuery.removeObserver(this);\n };\n\n _proto.setOptions = function setOptions(options, notifyOptions) {\n var prevOptions = this.options;\n var prevQuery = this.currentQuery;\n this.options = this.client.defaultQueryObserverOptions(options);\n\n if (typeof this.options.enabled !== 'undefined' && typeof this.options.enabled !== 'boolean') {\n throw new Error('Expected enabled to be a boolean');\n } // Keep previous query key if the user does not supply one\n\n\n if (!this.options.queryKey) {\n this.options.queryKey = prevOptions.queryKey;\n }\n\n this.updateQuery();\n var mounted = this.hasListeners(); // Fetch if there are subscribers\n\n if (mounted && shouldFetchOptionally(this.currentQuery, prevQuery, this.options, prevOptions)) {\n this.executeFetch();\n } // Update result\n\n\n this.updateResult(notifyOptions); // Update stale interval if needed\n\n if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) {\n this.updateStaleTimeout();\n }\n\n var nextRefetchInterval = this.computeRefetchInterval(); // Update refetch interval if needed\n\n if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.currentRefetchInterval)) {\n this.updateRefetchInterval(nextRefetchInterval);\n }\n };\n\n _proto.getOptimisticResult = function getOptimisticResult(options) {\n var defaultedOptions = this.client.defaultQueryObserverOptions(options);\n var query = this.client.getQueryCache().build(this.client, defaultedOptions);\n return this.createResult(query, defaultedOptions);\n };\n\n _proto.getCurrentResult = function getCurrentResult() {\n return this.currentResult;\n };\n\n _proto.trackResult = function trackResult(result, defaultedOptions) {\n var _this2 = this;\n\n var trackedResult = {};\n\n var trackProp = function trackProp(key) {\n if (!_this2.trackedProps.includes(key)) {\n _this2.trackedProps.push(key);\n }\n };\n\n Object.keys(result).forEach(function (key) {\n Object.defineProperty(trackedResult, key, {\n configurable: false,\n enumerable: true,\n get: function get() {\n trackProp(key);\n return result[key];\n }\n });\n });\n\n if (defaultedOptions.useErrorBoundary || defaultedOptions.suspense) {\n trackProp('error');\n }\n\n return trackedResult;\n };\n\n _proto.getNextResult = function getNextResult(options) {\n var _this3 = this;\n\n return new Promise(function (resolve, reject) {\n var unsubscribe = _this3.subscribe(function (result) {\n if (!result.isFetching) {\n unsubscribe();\n\n if (result.isError && (options == null ? void 0 : options.throwOnError)) {\n reject(result.error);\n } else {\n resolve(result);\n }\n }\n });\n });\n };\n\n _proto.getCurrentQuery = function getCurrentQuery() {\n return this.currentQuery;\n };\n\n _proto.remove = function remove() {\n this.client.getQueryCache().remove(this.currentQuery);\n };\n\n _proto.refetch = function refetch(options) {\n return this.fetch(_extends({}, options, {\n meta: {\n refetchPage: options == null ? void 0 : options.refetchPage\n }\n }));\n };\n\n _proto.fetchOptimistic = function fetchOptimistic(options) {\n var _this4 = this;\n\n var defaultedOptions = this.client.defaultQueryObserverOptions(options);\n var query = this.client.getQueryCache().build(this.client, defaultedOptions);\n return query.fetch().then(function () {\n return _this4.createResult(query, defaultedOptions);\n });\n };\n\n _proto.fetch = function fetch(fetchOptions) {\n var _this5 = this;\n\n return this.executeFetch(fetchOptions).then(function () {\n _this5.updateResult();\n\n return _this5.currentResult;\n });\n };\n\n _proto.executeFetch = function executeFetch(fetchOptions) {\n // Make sure we reference the latest query as the current one might have been removed\n this.updateQuery(); // Fetch\n\n var promise = this.currentQuery.fetch(this.options, fetchOptions);\n\n if (!(fetchOptions == null ? void 0 : fetchOptions.throwOnError)) {\n promise = promise.catch(noop);\n }\n\n return promise;\n };\n\n _proto.updateStaleTimeout = function updateStaleTimeout() {\n var _this6 = this;\n\n this.clearStaleTimeout();\n\n if (isServer || this.currentResult.isStale || !isValidTimeout(this.options.staleTime)) {\n return;\n }\n\n var time = timeUntilStale(this.currentResult.dataUpdatedAt, this.options.staleTime); // The timeout is sometimes triggered 1 ms before the stale time expiration.\n // To mitigate this issue we always add 1 ms to the timeout.\n\n var timeout = time + 1;\n this.staleTimeoutId = setTimeout(function () {\n if (!_this6.currentResult.isStale) {\n _this6.updateResult();\n }\n }, timeout);\n };\n\n _proto.computeRefetchInterval = function computeRefetchInterval() {\n var _this$options$refetch;\n\n return typeof this.options.refetchInterval === 'function' ? this.options.refetchInterval(this.currentResult.data, this.currentQuery) : (_this$options$refetch = this.options.refetchInterval) != null ? _this$options$refetch : false;\n };\n\n _proto.updateRefetchInterval = function updateRefetchInterval(nextInterval) {\n var _this7 = this;\n\n this.clearRefetchInterval();\n this.currentRefetchInterval = nextInterval;\n\n if (isServer || this.options.enabled === false || !isValidTimeout(this.currentRefetchInterval) || this.currentRefetchInterval === 0) {\n return;\n }\n\n this.refetchIntervalId = setInterval(function () {\n if (_this7.options.refetchIntervalInBackground || focusManager.isFocused()) {\n _this7.executeFetch();\n }\n }, this.currentRefetchInterval);\n };\n\n _proto.updateTimers = function updateTimers() {\n this.updateStaleTimeout();\n this.updateRefetchInterval(this.computeRefetchInterval());\n };\n\n _proto.clearTimers = function clearTimers() {\n this.clearStaleTimeout();\n this.clearRefetchInterval();\n };\n\n _proto.clearStaleTimeout = function clearStaleTimeout() {\n if (this.staleTimeoutId) {\n clearTimeout(this.staleTimeoutId);\n this.staleTimeoutId = undefined;\n }\n };\n\n _proto.clearRefetchInterval = function clearRefetchInterval() {\n if (this.refetchIntervalId) {\n clearInterval(this.refetchIntervalId);\n this.refetchIntervalId = undefined;\n }\n };\n\n _proto.createResult = function createResult(query, options) {\n var prevQuery = this.currentQuery;\n var prevOptions = this.options;\n var prevResult = this.currentResult;\n var prevResultState = this.currentResultState;\n var prevResultOptions = this.currentResultOptions;\n var queryChange = query !== prevQuery;\n var queryInitialState = queryChange ? query.state : this.currentQueryInitialState;\n var prevQueryResult = queryChange ? this.currentResult : this.previousQueryResult;\n var state = query.state;\n var dataUpdatedAt = state.dataUpdatedAt,\n error = state.error,\n errorUpdatedAt = state.errorUpdatedAt,\n isFetching = state.isFetching,\n status = state.status;\n var isPreviousData = false;\n var isPlaceholderData = false;\n var data; // Optimistically set result in fetching state if needed\n\n if (options.optimisticResults) {\n var mounted = this.hasListeners();\n var fetchOnMount = !mounted && shouldFetchOnMount(query, options);\n var fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);\n\n if (fetchOnMount || fetchOptionally) {\n isFetching = true;\n\n if (!dataUpdatedAt) {\n status = 'loading';\n }\n }\n } // Keep previous data if needed\n\n\n if (options.keepPreviousData && !state.dataUpdateCount && (prevQueryResult == null ? void 0 : prevQueryResult.isSuccess) && status !== 'error') {\n data = prevQueryResult.data;\n dataUpdatedAt = prevQueryResult.dataUpdatedAt;\n status = prevQueryResult.status;\n isPreviousData = true;\n } // Select data if needed\n else if (options.select && typeof state.data !== 'undefined') {\n // Memoize select result\n if (prevResult && state.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === this.selectFn) {\n data = this.selectResult;\n } else {\n try {\n this.selectFn = options.select;\n data = options.select(state.data);\n\n if (options.structuralSharing !== false) {\n data = replaceEqualDeep(prevResult == null ? void 0 : prevResult.data, data);\n }\n\n this.selectResult = data;\n this.selectError = null;\n } catch (selectError) {\n getLogger().error(selectError);\n this.selectError = selectError;\n }\n }\n } // Use query data\n else {\n data = state.data;\n } // Show placeholder data if needed\n\n\n if (typeof options.placeholderData !== 'undefined' && typeof data === 'undefined' && (status === 'loading' || status === 'idle')) {\n var placeholderData; // Memoize placeholder data\n\n if ((prevResult == null ? void 0 : prevResult.isPlaceholderData) && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {\n placeholderData = prevResult.data;\n } else {\n placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData() : options.placeholderData;\n\n if (options.select && typeof placeholderData !== 'undefined') {\n try {\n placeholderData = options.select(placeholderData);\n\n if (options.structuralSharing !== false) {\n placeholderData = replaceEqualDeep(prevResult == null ? void 0 : prevResult.data, placeholderData);\n }\n\n this.selectError = null;\n } catch (selectError) {\n getLogger().error(selectError);\n this.selectError = selectError;\n }\n }\n }\n\n if (typeof placeholderData !== 'undefined') {\n status = 'success';\n data = placeholderData;\n isPlaceholderData = true;\n }\n }\n\n if (this.selectError) {\n error = this.selectError;\n data = this.selectResult;\n errorUpdatedAt = Date.now();\n status = 'error';\n }\n\n var result = {\n status: status,\n isLoading: status === 'loading',\n isSuccess: status === 'success',\n isError: status === 'error',\n isIdle: status === 'idle',\n data: data,\n dataUpdatedAt: dataUpdatedAt,\n error: error,\n errorUpdatedAt: errorUpdatedAt,\n failureCount: state.fetchFailureCount,\n errorUpdateCount: state.errorUpdateCount,\n isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,\n isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount,\n isFetching: isFetching,\n isRefetching: isFetching && status !== 'loading',\n isLoadingError: status === 'error' && state.dataUpdatedAt === 0,\n isPlaceholderData: isPlaceholderData,\n isPreviousData: isPreviousData,\n isRefetchError: status === 'error' && state.dataUpdatedAt !== 0,\n isStale: isStale(query, options),\n refetch: this.refetch,\n remove: this.remove\n };\n return result;\n };\n\n _proto.shouldNotifyListeners = function shouldNotifyListeners(result, prevResult) {\n if (!prevResult) {\n return true;\n }\n\n var _this$options = this.options,\n notifyOnChangeProps = _this$options.notifyOnChangeProps,\n notifyOnChangePropsExclusions = _this$options.notifyOnChangePropsExclusions;\n\n if (!notifyOnChangeProps && !notifyOnChangePropsExclusions) {\n return true;\n }\n\n if (notifyOnChangeProps === 'tracked' && !this.trackedProps.length) {\n return true;\n }\n\n var includedProps = notifyOnChangeProps === 'tracked' ? this.trackedProps : notifyOnChangeProps;\n return Object.keys(result).some(function (key) {\n var typedKey = key;\n var changed = result[typedKey] !== prevResult[typedKey];\n var isIncluded = includedProps == null ? void 0 : includedProps.some(function (x) {\n return x === key;\n });\n var isExcluded = notifyOnChangePropsExclusions == null ? void 0 : notifyOnChangePropsExclusions.some(function (x) {\n return x === key;\n });\n return changed && !isExcluded && (!includedProps || isIncluded);\n });\n };\n\n _proto.updateResult = function updateResult(notifyOptions) {\n var prevResult = this.currentResult;\n this.currentResult = this.createResult(this.currentQuery, this.options);\n this.currentResultState = this.currentQuery.state;\n this.currentResultOptions = this.options; // Only notify if something has changed\n\n if (shallowEqualObjects(this.currentResult, prevResult)) {\n return;\n } // Determine which callbacks to trigger\n\n\n var defaultNotifyOptions = {\n cache: true\n };\n\n if ((notifyOptions == null ? void 0 : notifyOptions.listeners) !== false && this.shouldNotifyListeners(this.currentResult, prevResult)) {\n defaultNotifyOptions.listeners = true;\n }\n\n this.notify(_extends({}, defaultNotifyOptions, notifyOptions));\n };\n\n _proto.updateQuery = function updateQuery() {\n var query = this.client.getQueryCache().build(this.client, this.options);\n\n if (query === this.currentQuery) {\n return;\n }\n\n var prevQuery = this.currentQuery;\n this.currentQuery = query;\n this.currentQueryInitialState = query.state;\n this.previousQueryResult = this.currentResult;\n\n if (this.hasListeners()) {\n prevQuery == null ? void 0 : prevQuery.removeObserver(this);\n query.addObserver(this);\n }\n };\n\n _proto.onQueryUpdate = function onQueryUpdate(action) {\n var notifyOptions = {};\n\n if (action.type === 'success') {\n notifyOptions.onSuccess = true;\n } else if (action.type === 'error' && !isCancelledError(action.error)) {\n notifyOptions.onError = true;\n }\n\n this.updateResult(notifyOptions);\n\n if (this.hasListeners()) {\n this.updateTimers();\n }\n };\n\n _proto.notify = function notify(notifyOptions) {\n var _this8 = this;\n\n notifyManager.batch(function () {\n // First trigger the configuration callbacks\n if (notifyOptions.onSuccess) {\n _this8.options.onSuccess == null ? void 0 : _this8.options.onSuccess(_this8.currentResult.data);\n _this8.options.onSettled == null ? void 0 : _this8.options.onSettled(_this8.currentResult.data, null);\n } else if (notifyOptions.onError) {\n _this8.options.onError == null ? void 0 : _this8.options.onError(_this8.currentResult.error);\n _this8.options.onSettled == null ? void 0 : _this8.options.onSettled(undefined, _this8.currentResult.error);\n } // Then trigger the listeners\n\n\n if (notifyOptions.listeners) {\n _this8.listeners.forEach(function (listener) {\n listener(_this8.currentResult);\n });\n } // Then the cache listeners\n\n\n if (notifyOptions.cache) {\n _this8.client.getQueryCache().notify({\n query: _this8.currentQuery,\n type: 'observerResultsUpdated'\n });\n }\n });\n };\n\n return QueryObserver;\n}(Subscribable);\n\nfunction shouldLoadOnMount(query, options) {\n return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === 'error' && options.retryOnMount === false);\n}\n\nfunction shouldFetchOnMount(query, options) {\n return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount);\n}\n\nfunction shouldFetchOn(query, options, field) {\n if (options.enabled !== false) {\n var value = typeof field === 'function' ? field(query) : field;\n return value === 'always' || value !== false && isStale(query, options);\n }\n\n return false;\n}\n\nfunction shouldFetchOptionally(query, prevQuery, options, prevOptions) {\n return options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== 'error') && isStale(query, options);\n}\n\nfunction isStale(query, options) {\n return query.isStaleByTime(options.staleTime);\n}","import React from 'react'; // CONTEXT\n\nfunction createValue() {\n var _isReset = false;\n return {\n clearReset: function clearReset() {\n _isReset = false;\n },\n reset: function reset() {\n _isReset = true;\n },\n isReset: function isReset() {\n return _isReset;\n }\n };\n}\n\nvar QueryErrorResetBoundaryContext = /*#__PURE__*/React.createContext(createValue()); // HOOK\n\nexport var useQueryErrorResetBoundary = function useQueryErrorResetBoundary() {\n return React.useContext(QueryErrorResetBoundaryContext);\n}; // COMPONENT\n\nexport var QueryErrorResetBoundary = function QueryErrorResetBoundary(_ref) {\n var children = _ref.children;\n var value = React.useMemo(function () {\n return createValue();\n }, []);\n return /*#__PURE__*/React.createElement(QueryErrorResetBoundaryContext.Provider, {\n value: value\n }, typeof children === 'function' ? children(value) : children);\n};","import { QueryObserver } from '../core';\nimport { parseQueryArgs } from '../core/utils';\nimport { useBaseQuery } from './useBaseQuery'; // HOOK\n\nexport function useQuery(arg1, arg2, arg3) {\n var parsedOptions = parseQueryArgs(arg1, arg2, arg3);\n return useBaseQuery(parsedOptions, QueryObserver);\n}","import React from 'react';\nimport { notifyManager } from '../core/notifyManager';\nimport { useQueryErrorResetBoundary } from './QueryErrorResetBoundary';\nimport { useQueryClient } from './QueryClientProvider';\nimport { shouldThrowError } from './utils';\nexport function useBaseQuery(options, Observer) {\n var mountedRef = React.useRef(false);\n\n var _React$useState = React.useState(0),\n forceUpdate = _React$useState[1];\n\n var queryClient = useQueryClient();\n var errorResetBoundary = useQueryErrorResetBoundary();\n var defaultedOptions = queryClient.defaultQueryObserverOptions(options); // Make sure results are optimistically set in fetching state before subscribing or updating options\n\n defaultedOptions.optimisticResults = true; // Include callbacks in batch renders\n\n if (defaultedOptions.onError) {\n defaultedOptions.onError = notifyManager.batchCalls(defaultedOptions.onError);\n }\n\n if (defaultedOptions.onSuccess) {\n defaultedOptions.onSuccess = notifyManager.batchCalls(defaultedOptions.onSuccess);\n }\n\n if (defaultedOptions.onSettled) {\n defaultedOptions.onSettled = notifyManager.batchCalls(defaultedOptions.onSettled);\n }\n\n if (defaultedOptions.suspense) {\n // Always set stale time when using suspense to prevent\n // fetching again when directly mounting after suspending\n if (typeof defaultedOptions.staleTime !== 'number') {\n defaultedOptions.staleTime = 1000;\n } // Set cache time to 1 if the option has been set to 0\n // when using suspense to prevent infinite loop of fetches\n\n\n if (defaultedOptions.cacheTime === 0) {\n defaultedOptions.cacheTime = 1;\n }\n }\n\n if (defaultedOptions.suspense || defaultedOptions.useErrorBoundary) {\n // Prevent retrying failed query if the error boundary has not been reset yet\n if (!errorResetBoundary.isReset()) {\n defaultedOptions.retryOnMount = false;\n }\n }\n\n var _React$useState2 = React.useState(function () {\n return new Observer(queryClient, defaultedOptions);\n }),\n observer = _React$useState2[0];\n\n var result = observer.getOptimisticResult(defaultedOptions);\n React.useEffect(function () {\n mountedRef.current = true;\n errorResetBoundary.clearReset();\n var unsubscribe = observer.subscribe(notifyManager.batchCalls(function () {\n if (mountedRef.current) {\n forceUpdate(function (x) {\n return x + 1;\n });\n }\n })); // Update result to make sure we did not miss any query updates\n // between creating the observer and subscribing to it.\n\n observer.updateResult();\n return function () {\n mountedRef.current = false;\n unsubscribe();\n };\n }, [errorResetBoundary, observer]);\n React.useEffect(function () {\n // Do not notify on updates because of changes in the options because\n // these changes should already be reflected in the optimistic result.\n observer.setOptions(defaultedOptions, {\n listeners: false\n });\n }, [defaultedOptions, observer]); // Handle suspense\n\n if (defaultedOptions.suspense && result.isLoading) {\n throw observer.fetchOptimistic(defaultedOptions).then(function (_ref) {\n var data = _ref.data;\n defaultedOptions.onSuccess == null ? void 0 : defaultedOptions.onSuccess(data);\n defaultedOptions.onSettled == null ? void 0 : defaultedOptions.onSettled(data, null);\n }).catch(function (error) {\n errorResetBoundary.clearReset();\n defaultedOptions.onError == null ? void 0 : defaultedOptions.onError(error);\n defaultedOptions.onSettled == null ? void 0 : defaultedOptions.onSettled(undefined, error);\n });\n } // Handle error boundary\n\n\n if (result.isError && !errorResetBoundary.isReset() && !result.isFetching && shouldThrowError(defaultedOptions.suspense, defaultedOptions.useErrorBoundary, [result.error, observer.getCurrentQuery()])) {\n throw result.error;\n } // Handle result property usage tracking\n\n\n if (defaultedOptions.notifyOnChangeProps === 'tracked') {\n result = observer.trackResult(result, defaultedOptions);\n }\n\n return result;\n}","/**\n * @license React\n * react-jsx-runtime.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var f=require(\"react\"),k=Symbol.for(\"react.element\"),l=Symbol.for(\"react.fragment\"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};\nfunction q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=\"\"+g);void 0!==a.key&&(e=\"\"+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}exports.Fragment=l;exports.jsx=q;exports.jsxs=q;\n","/**\n * @license React\n * react.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var l=Symbol.for(\"react.element\"),n=Symbol.for(\"react.portal\"),p=Symbol.for(\"react.fragment\"),q=Symbol.for(\"react.strict_mode\"),r=Symbol.for(\"react.profiler\"),t=Symbol.for(\"react.provider\"),u=Symbol.for(\"react.context\"),v=Symbol.for(\"react.forward_ref\"),w=Symbol.for(\"react.suspense\"),x=Symbol.for(\"react.memo\"),y=Symbol.for(\"react.lazy\"),z=Symbol.iterator;function A(a){if(null===a||\"object\"!==typeof a)return null;a=z&&a[z]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}\nvar B={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}E.prototype.isReactComponent={};\nE.prototype.setState=function(a,b){if(\"object\"!==typeof a&&\"function\"!==typeof a&&null!=a)throw Error(\"setState(...): takes an object of state variables to update or a function which returns an object of state variables.\");this.updater.enqueueSetState(this,a,b,\"setState\")};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,\"forceUpdate\")};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}var H=G.prototype=new F;\nH.constructor=G;C(H,E.prototype);H.isPureReactComponent=!0;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:!0,ref:!0,__self:!0,__source:!0};\nfunction M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=\"\"+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}\nfunction g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if(\"object\"===typeof performance&&\"function\"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D=\"function\"===typeof setTimeout?setTimeout:null,E=\"function\"===typeof clearTimeout?clearTimeout:null,F=\"undefined\"!==typeof setImmediate?setImmediate:null;\n\"undefined\"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}\nfunction J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if(\"function\"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;\nfunction M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};\nexports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n","export default function _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n}","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = function(module) {\n\tvar getter = module && module.__esModule ?\n\t\tfunction() { return module['default']; } :\n\t\tfunction() { return module; };\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","var getProto = Object.getPrototypeOf ? function(obj) { return Object.getPrototypeOf(obj); } : function(obj) { return obj.__proto__; };\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach(function(key) { def[key] = function() { return value[key]; }; });\n\t}\n\tdef['default'] = function() { return value; };\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","// define getter functions for harmony exports\n__webpack_require__.d = function(exports, definition) {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = function(chunkId) {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce(function(promises, key) {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = function(chunkId) {\n\t// return url for filenames based on template\n\treturn \"static/js/\" + chunkId + \".\" + \"545aecf5\" + \".chunk.js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = function(chunkId) {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.hmd = function(module) {\n\tmodule = Object.create(module);\n\tif (!module.children) module.children = [];\n\tObject.defineProperty(module, 'exports', {\n\t\tenumerable: true,\n\t\tset: function() {\n\t\t\tthrow new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id);\n\t\t}\n\t});\n\treturn module;\n};","__webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }","var inProgress = {};\nvar dataWebpackPrefix = \"dashboard:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = function(url, done, key, chunkId) {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tscript.timeout = 120;\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\t\tscript.src = url;\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = function(prev, event) {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach(function(fn) { return fn(event); });\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","// define __esModule on exports\n__webpack_require__.r = function(exports) {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.p = \"/\";","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t179: 0\n};\n\n__webpack_require__.f.j = function(chunkId, promises) {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise(function(resolve, reject) { installedChunkData = installedChunks[chunkId] = [resolve, reject]; });\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = function(event) {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t} else installedChunks[chunkId] = 0;\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n// no on chunks loaded\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = function(parentChunkLoadingFunction, data) {\n\tvar chunkIds = data[0];\n\tvar moreModules = data[1];\n\tvar runtime = data[2];\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some(function(id) { return installedChunks[id] !== 0; })) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkdashboard\"] = self[\"webpackChunkdashboard\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","__webpack_require__.nc = undefined;","export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}","import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nexport default function _toPropertyKey(arg) {\n var key = toPrimitive(arg, \"string\");\n return _typeof(key) === \"symbol\" ? key : String(key);\n}","import _typeof from \"./typeof.js\";\nexport default function _toPrimitive(input, hint) {\n if (_typeof(input) !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (_typeof(res) !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n}","import toPropertyKey from \"./toPropertyKey.js\";\nexport default function _defineProperty(obj, key, value) {\n key = toPropertyKey(key);\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}","import defineProperty from \"./defineProperty.js\";\nfunction ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n enumerableOnly && (symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n })), keys.push.apply(keys, symbols);\n }\n return keys;\n}\nexport default function _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = null != arguments[i] ? arguments[i] : {};\n i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {\n defineProperty(target, key, source[key]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n return target;\n}","export default function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n return arr2;\n}","export default function _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter);\n}","import arrayLikeToArray from \"./arrayLikeToArray.js\";\nexport default function _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}","import arrayWithoutHoles from \"./arrayWithoutHoles.js\";\nimport iterableToArray from \"./iterableToArray.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableSpread from \"./nonIterableSpread.js\";\nexport default function _toConsumableArray(arr) {\n return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();\n}","import arrayLikeToArray from \"./arrayLikeToArray.js\";\nexport default function _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return arrayLikeToArray(arr);\n}","export default function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n *\n * Note: This file was originally called `global.ts`, but was changed to unblock users which might be doing\n * string replaces with bundlers like Vite for `global` (would break imports that rely on importing from utils/src/global).\n *\n * Why worldwide?\n *\n * Why not?\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { Integration } from '@sentry/types';\n\nimport type { SdkSource } from './env';\n\n/** Internal global with common properties and Sentry extensions */\nexport interface InternalGlobal {\n navigator?: { userAgent?: string };\n console: Console;\n Sentry?: {\n Integrations?: Integration[];\n };\n onerror?: {\n (event: object | string, source?: string, lineno?: number, colno?: number, error?: Error): any;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n onunhandledrejection?: {\n (event: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n SENTRY_SDK_SOURCE?: SdkSource;\n /**\n * Debug IDs are indirectly injected by Sentry CLI or bundler plugins to directly reference a particular source map\n * for resolving of a source file. The injected code will place an entry into the record for each loaded bundle/JS\n * file.\n */\n _sentryDebugIds?: Record;\n __SENTRY__: {\n globalEventProcessors: any;\n hub: any;\n logger: any;\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n /**\n * Raw module metadata that is injected by bundler plugins.\n *\n * Keys are `error.stack` strings, values are the metadata.\n */\n _sentryModuleMetadata?: Record;\n}\n\n// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification\n// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js\n// core-js has the following licence:\n//\n// Copyright (c) 2014-2022 Denis Pushkarev\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/** Returns 'obj' if it's the global object, otherwise returns undefined */\nfunction isGlobalObj(obj: { Math?: Math }): any | undefined {\n return obj && obj.Math == Math ? obj : undefined;\n}\n\n/** Get's the global object for the current JavaScript runtime */\nexport const GLOBAL_OBJ: InternalGlobal =\n (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||\n // eslint-disable-next-line no-restricted-globals\n (typeof window == 'object' && isGlobalObj(window)) ||\n (typeof self == 'object' && isGlobalObj(self)) ||\n (typeof global == 'object' && isGlobalObj(global)) ||\n (function (this: any) {\n return this;\n })() ||\n {};\n\n/**\n * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8\n */\nexport function getGlobalObject(): T & InternalGlobal {\n return GLOBAL_OBJ as T & InternalGlobal;\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nexport function getGlobalSingleton(name: keyof InternalGlobal['__SENTRY__'], creator: () => T, obj?: unknown): T {\n const gbl = (obj || GLOBAL_OBJ) as InternalGlobal;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n","import type { ConsoleLevel } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { GLOBAL_OBJ } from './worldwide';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nexport const CONSOLE_LEVELS: readonly ConsoleLevel[] = [\n 'debug',\n 'info',\n 'warn',\n 'error',\n 'log',\n 'assert',\n 'trace',\n] as const;\n\ntype LoggerMethod = (...args: unknown[]) => void;\ntype LoggerConsoleMethods = Record;\n\n/** This may be mutated by the console instrumentation. */\nexport const originalConsoleMethods: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key in ConsoleLevel]?: (...args: any[]) => void;\n} = {};\n\n/** JSDoc */\ninterface Logger extends LoggerConsoleMethods {\n disable(): void;\n enable(): void;\n isEnabled(): boolean;\n}\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox(callback: () => T): T {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const console = GLOBAL_OBJ.console as Console;\n const wrappedFuncs: Partial = {};\n\n const wrappedLevels = Object.keys(originalConsoleMethods) as ConsoleLevel[];\n\n // Restore all wrapped console methods\n wrappedLevels.forEach(level => {\n const originalConsoleMethod = originalConsoleMethods[level] as LoggerMethod;\n wrappedFuncs[level] = console[level] as LoggerMethod | undefined;\n console[level] = originalConsoleMethod;\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n wrappedLevels.forEach(level => {\n console[level] = wrappedFuncs[level] as LoggerMethod;\n });\n }\n}\n\nfunction makeLogger(): Logger {\n let enabled = false;\n const logger: Partial = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n isEnabled: () => enabled,\n };\n\n if (DEBUG_BUILD) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logger[name] = (...args: any[]) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger as Logger;\n}\n\nexport const logger = makeLogger();\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport type { ParameterizedString, PolymorphicEvent, Primitive } from '@sentry/types';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: unknown): wat is Error {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat: unknown, className: string): boolean {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: unknown): boolean {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: unknown): wat is string {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given string is parameterized\n * {@link isParameterizedString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isParameterizedString(wat: unknown): wat is ParameterizedString {\n return (\n typeof wat === 'object' &&\n wat !== null &&\n '__sentry_template_string__' in wat &&\n '__sentry_template_values__' in wat\n );\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: unknown): wat is Primitive {\n return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal, or a class instance.\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: unknown): wat is Record {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isEvent(wat: unknown): wat is PolymorphicEvent {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: unknown): boolean {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: unknown): wat is RegExp {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): wat is PromiseLike {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isSyntheticEvent(wat: unknown): boolean {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value is NaN\n * {@link isNaN}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isNaN(wat: unknown): boolean {\n return typeof wat === 'number' && wat !== wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nexport function isInstanceOf(wat: any, base: any): boolean {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n\ninterface VueViewModel {\n // Vue3\n __isVue?: boolean;\n // Vue2\n _isVue?: boolean;\n}\n/**\n * Checks whether given value's type is a Vue ViewModel.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isVueViewModel(wat: unknown): boolean {\n // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.\n return !!(typeof wat === 'object' && wat !== null && ((wat as VueViewModel).__isVue || (wat as VueViewModel)._isVue));\n}\n","import { isString } from './is';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\ntype SimpleNode = {\n parentNode: SimpleNode;\n} | null;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(\n elem: unknown,\n options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},\n): string {\n if (!elem) {\n return '';\n }\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {\n const elem = el as {\n tagName?: string;\n id?: string;\n className?: string;\n getAttribute(key: string): string;\n };\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n // @ts-expect-error WINDOW has HTMLElement\n if (WINDOW.HTMLElement) {\n // If using the component name annotation plugin, this value may be available on the DOM node\n if (elem instanceof HTMLElement && elem.dataset && elem.dataset['sentryComponent']) {\n return elem.dataset['sentryComponent'];\n }\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nexport function getLocationHref(): string {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existance of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getDomElement(selector: string): E | null {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) as unknown as E;\n }\n return null;\n}\n\n/**\n * Given a DOM element, traverses up the tree until it finds the first ancestor node\n * that has the `data-sentry-component` attribute. This attribute is added at build-time\n * by projects that have the component name annotation plugin installed.\n *\n * @returns a string representation of the component for the provided DOM element, or `null` if not found\n */\nexport function getComponentName(elem: unknown): string | null {\n // @ts-expect-error WINDOW has HTMLElement\n if (!WINDOW.HTMLElement) {\n return null;\n }\n\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) {\n if (!currentElem) {\n return null;\n }\n\n if (currentElem instanceof HTMLElement && currentElem.dataset['sentryComponent']) {\n return currentElem.dataset['sentryComponent'];\n }\n\n currentElem = currentElem.parentNode;\n }\n\n return null;\n}\n","import { isRegExp, isString, isVueViewModel } from './is';\n\nexport { escapeStringForRegex } from './vendor/escapeStringForRegex';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str: string, max: number = 0): string {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line: string, colno: number): string {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function safeJoin(input: any[], delimiter?: string): string {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/8981\n if (isVueViewModel(value)) {\n output.push('[VueViewModel]');\n } else {\n output.push(String(value));\n }\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nexport function isMatchingPattern(\n value: string,\n pattern: RegExp | string,\n requireExactStringMatch: boolean = false,\n): boolean {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nexport function stringMatchesSomePattern(\n testString: string,\n patterns: Array = [],\n requireExactStringMatch: boolean = false,\n): boolean {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { DEBUG_BUILD } from './debug-build';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive } from './is';\nimport { logger } from './logger';\nimport { truncate } from './string';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] as () => any;\n const wrapped = replacementFactory(original) as WrappedFunction;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n markFunctionWrapped(wrapped, original);\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nexport function addNonEnumerableProperty(obj: object, name: string, value: unknown): void {\n try {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n } catch (o_O) {\n DEBUG_BUILD && logger.log(`Failed to add non-enumerable property \"${name}\" to object`, obj);\n }\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\n try {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n } catch (o_O) {} // eslint-disable-line no-empty\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nexport function getOriginalFunction(func: WrappedFunction): WrappedFunction | undefined {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor\n * an Error.\n */\nexport function convertToPlainObject(\n value: V,\n):\n | {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n }\n | {\n [ownProps: string]: unknown;\n message: string;\n name: string;\n stack?: string;\n }\n | V {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj: {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n } = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target: unknown): string {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj: unknown): { [key: string]: unknown } {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps: { [key: string]: unknown } = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj as Record)[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nexport function extractExceptionKeysForMessage(exception: Record, maxLength: number = 40): string {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nexport function dropUndefinedKeys(inputValue: T): T {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue: T, memoizationMap: Map): T {\n if (isPojo(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: { [key: string]: any } = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.keys(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue as T;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: unknown[] = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item: unknown) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue as unknown as T;\n }\n\n return inputValue;\n}\n\nfunction isPojo(input: unknown): input is Record {\n if (!isPlainObject(input)) {\n return false;\n }\n\n try {\n const name = (Object.getPrototypeOf(input) as { constructor: { name: string } }).constructor.name;\n return !name || name === 'Object';\n } catch {\n return true;\n }\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat as any).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Event, Exception, Mechanism, StackFrame } from '@sentry/types';\n\nimport { addNonEnumerableProperty } from './object';\nimport { snipLine } from './string';\nimport { GLOBAL_OBJ } from './worldwide';\n\ninterface CryptoInternal {\n getRandomValues(array: Uint8Array): Uint8Array;\n randomUUID?(): string;\n}\n\n/** An interface for common properties on global */\ninterface CryptoGlobal {\n msCrypto?: CryptoInternal;\n crypto?: CryptoInternal;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const gbl = GLOBAL_OBJ as typeof GLOBAL_OBJ & CryptoGlobal;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n let getRandomByte = (): number => Math.random() * 16;\n try {\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n if (crypto && crypto.getRandomValues) {\n getRandomByte = () => {\n // crypto.getRandomValues might return undefined instead of the typed array\n // in old Chromium versions (e.g. 23.0.1235.0 (151422))\n // However, `typedArray` is still filled in-place.\n // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray\n const typedArray = new Uint8Array(1);\n crypto.getRandomValues(typedArray);\n return typedArray[0];\n };\n }\n } catch (_) {\n // some runtimes can crash invoking crypto\n // https://github.com/getsentry/sentry-javascript/issues/8935\n }\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c as unknown as number) ^ ((getRandomByte() & 15) >> ((c as unknown as number) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event: Event): Exception | undefined {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event: Event, value?: string, type?: string): void {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event: Event, newMechanism?: Partial): void {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\ninterface SemVer {\n major?: number;\n minor?: number;\n patch?: number;\n prerelease?: string;\n buildmetadata?: string;\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input: string): SemVer {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line: string) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line: string) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception as any).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception as { [key: string]: unknown }, '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nexport function arrayify(maybeArray: T | T[]): T[] {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n","/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/typedef */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst enum States {\n /** Pending */\n PENDING = 0,\n /** Resolved / OK */\n RESOLVED = 1,\n /** Rejected / Error */\n REJECTED = 2,\n}\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\nexport function resolvedSyncPromise(): PromiseLike;\nexport function resolvedSyncPromise(value: T | PromiseLike): PromiseLike;\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nexport function resolvedSyncPromise(value?: T | PromiseLike): PromiseLike {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nexport function rejectedSyncPromise(reason?: any): PromiseLike {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise implements PromiseLike {\n private _state: States;\n private _handlers: Array<[boolean, (value: T) => void, (reason: any) => any]>;\n private _value: any;\n\n public constructor(\n executor: (resolve: (value?: T | PromiseLike | null) => void, reject: (reason?: any) => void) => void,\n ) {\n this._state = States.PENDING;\n this._handlers = [];\n\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n public then(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike) | null,\n ): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result as any);\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n public catch(\n onrejected?: ((reason: any) => TResult | PromiseLike) | null,\n ): PromiseLike {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n public finally(onfinally?: (() => void) | null): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let val: TResult | any;\n let isRejected: boolean;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val as unknown as any);\n });\n });\n }\n\n /** JSDoc */\n private readonly _resolve = (value?: T | PromiseLike | null) => {\n this._setResult(States.RESOLVED, value);\n };\n\n /** JSDoc */\n private readonly _reject = (reason?: any) => {\n this._setResult(States.REJECTED, reason);\n };\n\n /** JSDoc */\n private readonly _setResult = (state: States, value?: T | PromiseLike | any) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value as PromiseLike).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n /** JSDoc */\n private readonly _executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler[1](this._value as unknown as any);\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };\n}\n\nexport { SyncPromise };\n","import unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nexport default function _createForOfIteratorHelper(o, allowArrayLike) {\n var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"];\n if (!it) {\n if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") {\n if (it) o = it;\n var i = 0;\n var F = function F() {};\n return {\n s: F,\n n: function n() {\n if (i >= o.length) return {\n done: true\n };\n return {\n done: false,\n value: o[i++]\n };\n },\n e: function e(_e) {\n throw _e;\n },\n f: F\n };\n }\n throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n }\n var normalCompletion = true,\n didErr = false,\n err;\n return {\n s: function s() {\n it = it.call(o);\n },\n n: function n() {\n var step = it.next();\n normalCompletion = step.done;\n return step;\n },\n e: function e(_e2) {\n didErr = true;\n err = _e2;\n },\n f: function f() {\n try {\n if (!normalCompletion && it[\"return\"] != null) it[\"return\"]();\n } finally {\n if (didErr) throw err;\n }\n }\n };\n}","export default function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}","export default function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}","import arrayWithHoles from \"./arrayWithHoles.js\";\nimport iterableToArrayLimit from \"./iterableToArrayLimit.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableRest from \"./nonIterableRest.js\";\nexport default function _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}","export default function _iterableToArrayLimit(arr, i) {\n var _i = null == arr ? null : \"undefined\" != typeof Symbol && arr[Symbol.iterator] || arr[\"@@iterator\"];\n if (null != _i) {\n var _s,\n _e,\n _x,\n _r,\n _arr = [],\n _n = !0,\n _d = !1;\n try {\n if (_x = (_i = _i.call(arr)).next, 0 === i) {\n if (Object(_i) !== _i) return;\n _n = !1;\n } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);\n } catch (err) {\n _d = !0, _e = err;\n } finally {\n try {\n if (!_n && null != _i[\"return\"] && (_r = _i[\"return\"](), Object(_r) !== _r)) return;\n } finally {\n if (_d) throw _e;\n }\n }\n return _arr;\n }\n}","export default function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}","import toPropertyKey from \"./toPropertyKey.js\";\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor);\n }\n}\nexport default function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}","import type { Event, EventHint, EventProcessor } from '@sentry/types';\nimport { SyncPromise, getGlobalSingleton, isThenable, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\n\n/**\n * Returns the global event processors.\n * @deprecated Global event processors will be removed in v8.\n */\nexport function getGlobalEventProcessors(): EventProcessor[] {\n return getGlobalSingleton('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @deprecated Use `addEventProcessor` instead. Global event processors will be removed in v8.\n */\nexport function addGlobalEventProcessor(callback: EventProcessor): void {\n // eslint-disable-next-line deprecation/deprecation\n getGlobalEventProcessors().push(callback);\n}\n\n/**\n * Process an array of event processors, returning the processed event (or `null` if the event was dropped).\n */\nexport function notifyEventProcessors(\n processors: EventProcessor[],\n event: Event | null,\n hint: EventHint,\n index: number = 0,\n): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) as Event | null;\n\n DEBUG_BUILD && processor.id && result === null && logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n}\n","import { GLOBAL_OBJ } from './worldwide';\n\nconst ONE_SECOND_IN_MS = 1000;\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\ninterface Performance {\n /**\n * The millisecond timestamp at which measurement began, measured in Unix time.\n */\n timeOrigin: number;\n /**\n * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n */\n now(): number;\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n *\n * TODO(v8): Return type should be rounded.\n */\nexport function dateTimestampInSeconds(): number {\n return Date.now() / ONE_SECOND_IN_MS;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction createUnixTimestampInSecondsFunc(): () => number {\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & { performance?: Performance };\n if (!performance || !performance.now) {\n return dateTimestampInSeconds;\n }\n\n // Some browser and environments don't have a timeOrigin, so we fallback to\n // using Date.now() to compute the starting time.\n const approxStartingTimeOrigin = Date.now() - performance.now();\n const timeOrigin = performance.timeOrigin == undefined ? approxStartingTimeOrigin : performance.timeOrigin;\n\n // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current\n // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.\n //\n // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the\n // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and\n // correct for this.\n // See: https://github.com/getsentry/sentry-javascript/issues/2590\n // See: https://github.com/mdn/content/issues/4713\n // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6\n return () => {\n return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;\n };\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport const timestampInSeconds = createUnixTimestampInSecondsFunc();\n\n/**\n * Re-exported with an old name for backwards-compatibility.\n * TODO (v8): Remove this\n *\n * @deprecated Use `timestampInSeconds` instead.\n */\nexport const timestampWithMs = timestampInSeconds;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport let _browserPerformanceTimeOriginMode: string;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport const browserPerformanceTimeOrigin = ((): number | undefined => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n","export const DEFAULT_ENVIRONMENT = 'production';\n","import type { SerializedSession, Session, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nexport function makeSession(context?: Omit): Session {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session: Session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nexport function updateSession(session: Session, context: SessionContext = {}): void {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.abnormal_mechanism) {\n session.abnormal_mechanism = context.abnormal_mechanism;\n }\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nexport function closeSession(session: Session, status?: Exclude): void {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session: Session): SerializedSession {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n abnormal_mechanism: session.abnormal_mechanism,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n","import type { StackFrame, StackLineParser, StackParser } from '@sentry/types';\n\nimport type { GetModuleFn } from './node-stack-trace';\nimport { filenameIsInApp, node } from './node-stack-trace';\n\nexport { filenameIsInApp };\n\nconst STACKTRACE_FRAME_LIMIT = 50;\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STRIP_FRAME_REGEXP = /captureMessage|captureException/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nexport function createStackParser(...parsers: StackLineParser[]): StackParser {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack: string, skipFirst: number = 0): StackFrame[] => {\n const frames: StackFrame[] = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirst; i < lines.length; i++) {\n const line = lines[i];\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nexport function stackParserFromStackParserOptions(stackParser: StackParser | StackLineParser[]): StackParser {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nexport function stripSentryFramesAndReverse(stack: ReadonlyArray): StackFrame[] {\n if (!stack.length) {\n return [];\n }\n\n const localStack = Array.from(stack);\n\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (/sentryWrapped/.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n\n // Reversing in the middle of the procedure allows us to just pop the values off the stack\n localStack.reverse();\n\n // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call)\n if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n\n // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')`\n // is produced within the hub itself, making it:\n //\n // Sentry.captureException()\n // getCurrentHub().captureException()\n //\n // instead of just the top `Sentry` call itself.\n // This forces us to possibly strip an additional frame in the exact same was as above.\n if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n }\n\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({\n ...frame,\n filename: frame.filename || localStack[localStack.length - 1].filename,\n function: frame.function || '?',\n }));\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nexport function getFunctionName(fn: unknown): string {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nexport function nodeStackLineParser(getModule?: GetModuleFn): StackLineParser {\n return [90, node(getModule)];\n}\n","import type { Primitive } from '@sentry/types';\n\nimport { isNaN, isSyntheticEvent, isVueViewModel } from './is';\nimport type { MemoFunc } from './memo';\nimport { memoBuilder } from './memo';\nimport { convertToPlainObject } from './object';\nimport { getFunctionName } from './stacktrace';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n// This is a hack to placate TS, relying on the fact that technically, arrays are objects with integer keys. Normally we\n// think of those keys as actual numbers, but `arr['0']` turns out to work just as well as `arr[0]`, and doing it this\n// way lets us use a single type in the places where behave as if we are only dealing with objects, even if some of them\n// might be arrays.\ntype ObjOrArray = { [key: string]: T };\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normallized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function normalize(input: unknown, depth: number = 100, maxProperties: number = +Infinity): any {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nexport function normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object: { [key: string]: any },\n // Default Node.js REPL depth\n depth: number = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize: number = 100 * 1024,\n): T {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized as T;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key: string,\n value: unknown,\n depth: number = +Infinity,\n maxProperties: number = +Infinity,\n memo: MemoFunc = memoBuilder(),\n): Primitive | ObjOrArray {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (\n value == null || // this matches null and undefined -> eqeq not eqeqeq\n (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(value))\n ) {\n return value as Primitive;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value as ObjOrArray)['__sentry_skip_normalization__']) {\n return value as ObjOrArray;\n }\n\n // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there\n // We keep a certain amount of depth.\n // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.\n const remainingDepth =\n typeof (value as ObjOrArray)['__sentry_override_normalization_depth__'] === 'number'\n ? ((value as ObjOrArray)['__sentry_override_normalization_depth__'] as number)\n : depth;\n\n // We're also done if we've reached the max depth\n if (remainingDepth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value as unknown & { toJSON?: () => unknown };\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) as ObjOrArray;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = convertToPlainObject(value as ObjOrArray);\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n/**\n * @deprecated This export will be removed in v8.\n */\nexport { visit as walk };\n\n/* eslint-disable complexity */\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key: unknown,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value: Exclude,\n): string {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value as { _events: unknown })._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n if (isVueViewModel(value)) {\n return '[VueViewModel]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n const objName = getConstructorName(value);\n\n // Handle HTML Elements\n if (/^HTML(\\w*)Element$/.test(objName)) {\n return `[HTMLElement: ${objName}]`;\n }\n\n return `[object ${objName}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n/* eslint-enable complexity */\n\nfunction getConstructorName(value: unknown): string {\n const prototype: Prototype | null = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value: string): number {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value: any): number {\n return utf8Length(JSON.stringify(value));\n}\n\n/**\n * Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint\n * across platforms and working directory.\n *\n * @param url The URL to be normalized.\n * @param basePath The application base path.\n * @returns The normalized URL.\n */\nexport function normalizeUrlToBase(url: string, basePath: string): string {\n const escapedBase = basePath\n // Backslash to forward\n .replace(/\\\\/g, '/')\n // Escape RegExp special characters\n .replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&');\n\n let newUrl = url;\n try {\n newUrl = decodeURI(url);\n } catch (_Oo) {\n // Sometime this breaks\n }\n return (\n newUrl\n .replace(/\\\\/g, '/')\n .replace(/webpack:\\/?/g, '') // Remove intermediate base path\n // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor\n .replace(new RegExp(`(file://)?/*${escapedBase}/*`, 'ig'), 'app:///')\n );\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport type MemoFunc = [\n // memoize\n (obj: any) => boolean,\n // unmemoize\n (obj: any) => void,\n];\n\n/**\n * Helper to decycle json objects\n */\nexport function memoBuilder(): MemoFunc {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner: any = hasWeakSet ? new WeakSet() : [];\n function memoize(obj: any): boolean {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj: any): void {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n","import type { DynamicSamplingContext } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { isString } from './is';\nimport { logger } from './logger';\n\nexport const BAGGAGE_HEADER_NAME = 'baggage';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;\n\n/**\n * Max length of a serialized baggage string\n *\n * https://www.w3.org/TR/baggage/#limits\n */\nexport const MAX_BAGGAGE_STRING_LENGTH = 8192;\n\n/**\n * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the \"sentry-\" prefixed values\n * from it.\n *\n * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.\n * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.\n */\nexport function baggageHeaderToDynamicSamplingContext(\n // Very liberal definition of what any incoming header might look like\n baggageHeader: string | string[] | number | null | undefined | boolean,\n): Partial | undefined {\n if (!isString(baggageHeader) && !Array.isArray(baggageHeader)) {\n return undefined;\n }\n\n // Intermediary object to store baggage key value pairs of incoming baggage headers on.\n // It is later used to read Sentry-DSC-values from.\n let baggageObject: Readonly> = {};\n\n if (Array.isArray(baggageHeader)) {\n // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it\n baggageObject = baggageHeader.reduce>((acc, curr) => {\n const currBaggageObject = baggageHeaderToObject(curr);\n for (const key of Object.keys(currBaggageObject)) {\n acc[key] = currBaggageObject[key];\n }\n return acc;\n }, {});\n } else {\n // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but\n // this is how we choose to handle it)\n if (!baggageHeader) {\n return undefined;\n }\n\n baggageObject = baggageHeaderToObject(baggageHeader);\n }\n\n // Read all \"sentry-\" prefixed values out of the baggage object and put it onto a dynamic sampling context object.\n const dynamicSamplingContext = Object.entries(baggageObject).reduce>((acc, [key, value]) => {\n if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {\n const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);\n acc[nonPrefixedKey] = value;\n }\n return acc;\n }, {});\n\n // Only return a dynamic sampling context object if there are keys in it.\n // A keyless object means there were no sentry values on the header, which means that there is no DSC.\n if (Object.keys(dynamicSamplingContext).length > 0) {\n return dynamicSamplingContext as Partial;\n } else {\n return undefined;\n }\n}\n\n/**\n * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with \"sentry-\".\n *\n * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility\n * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is\n * `undefined` the function will return `undefined`.\n * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext`\n * was `undefined`, or if `dynamicSamplingContext` didn't contain any values.\n */\nexport function dynamicSamplingContextToSentryBaggageHeader(\n // this also takes undefined for convenience and bundle size in other places\n dynamicSamplingContext?: Partial,\n): string | undefined {\n if (!dynamicSamplingContext) {\n return undefined;\n }\n\n // Prefix all DSC keys with \"sentry-\" and put them into a new object\n const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce>(\n (acc, [dscKey, dscValue]) => {\n if (dscValue) {\n acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;\n }\n return acc;\n },\n {},\n );\n\n return objectToBaggageHeader(sentryPrefixedDSC);\n}\n\n/**\n * Will parse a baggage header, which is a simple key-value map, into a flat object.\n *\n * @param baggageHeader The baggage header to parse.\n * @returns a flat object containing all the key-value pairs from `baggageHeader`.\n */\nfunction baggageHeaderToObject(baggageHeader: string): Record {\n return baggageHeader\n .split(',')\n .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim())))\n .reduce>((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {});\n}\n\n/**\n * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs.\n *\n * @param object The object to turn into a baggage header.\n * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header\n * is not spec compliant.\n */\nfunction objectToBaggageHeader(object: Record): string | undefined {\n if (Object.keys(object).length === 0) {\n // An empty baggage header is not spec compliant: We return undefined.\n return undefined;\n }\n\n return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {\n const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;\n const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;\n if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`,\n );\n return baggageHeader;\n } else {\n return newBaggageHeader;\n }\n }, '');\n}\n","import type { PropagationContext, TraceparentData } from '@sentry/types';\n\nimport { baggageHeaderToDynamicSamplingContext } from './baggage';\nimport { uuid4 } from './misc';\n\n// eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- RegExp is used for readability here\nexport const TRACEPARENT_REGEXP = new RegExp(\n '^[ \\\\t]*' + // whitespace\n '([0-9a-f]{32})?' + // trace_id\n '-?([0-9a-f]{16})?' + // span_id\n '-?([01])?' + // sampled\n '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nexport function extractTraceparentData(traceparent?: string): TraceparentData | undefined {\n if (!traceparent) {\n return undefined;\n }\n\n const matches = traceparent.match(TRACEPARENT_REGEXP);\n if (!matches) {\n return undefined;\n }\n\n let parentSampled: boolean | undefined;\n if (matches[3] === '1') {\n parentSampled = true;\n } else if (matches[3] === '0') {\n parentSampled = false;\n }\n\n return {\n traceId: matches[1],\n parentSampled,\n parentSpanId: matches[2],\n };\n}\n\n/**\n * Create tracing context from incoming headers.\n *\n * @deprecated Use `propagationContextFromHeaders` instead.\n */\n// TODO(v8): Remove this function\nexport function tracingContextFromHeaders(\n sentryTrace: Parameters[0],\n baggage: Parameters[0],\n): {\n traceparentData: ReturnType;\n dynamicSamplingContext: ReturnType;\n propagationContext: PropagationContext;\n} {\n const traceparentData = extractTraceparentData(sentryTrace);\n const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n const { traceId, parentSpanId, parentSampled } = traceparentData || {};\n\n if (!traceparentData) {\n return {\n traceparentData,\n dynamicSamplingContext: undefined,\n propagationContext: {\n traceId: traceId || uuid4(),\n spanId: uuid4().substring(16),\n },\n };\n } else {\n return {\n traceparentData,\n dynamicSamplingContext: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n propagationContext: {\n traceId: traceId || uuid4(),\n parentSpanId: parentSpanId || uuid4().substring(16),\n spanId: uuid4().substring(16),\n sampled: parentSampled,\n dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n },\n };\n }\n}\n\n/**\n * Create a propagation context from incoming headers.\n */\nexport function propagationContextFromHeaders(\n sentryTrace: string | undefined,\n baggage: string | number | boolean | string[] | null | undefined,\n): PropagationContext {\n const traceparentData = extractTraceparentData(sentryTrace);\n const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n const { traceId, parentSpanId, parentSampled } = traceparentData || {};\n\n if (!traceparentData) {\n return {\n traceId: traceId || uuid4(),\n spanId: uuid4().substring(16),\n };\n } else {\n return {\n traceId: traceId || uuid4(),\n parentSpanId: parentSpanId || uuid4().substring(16),\n spanId: uuid4().substring(16),\n sampled: parentSampled,\n dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n };\n }\n}\n\n/**\n * Create sentry-trace header from span context values.\n */\nexport function generateSentryTraceHeader(\n traceId: string = uuid4(),\n spanId: string = uuid4().substring(16),\n sampled?: boolean,\n): string {\n let sampledString = '';\n if (sampled !== undefined) {\n sampledString = sampled ? '-1' : '-0';\n }\n return `${traceId}-${spanId}${sampledString}`;\n}\n","import type { Span, SpanJSON, SpanTimeInput, TraceContext } from '@sentry/types';\nimport { dropUndefinedKeys, generateSentryTraceHeader, timestampInSeconds } from '@sentry/utils';\nimport type { Span as SpanClass } from '../tracing/span';\n\n// These are aligned with OpenTelemetry trace flags\nexport const TRACE_FLAG_NONE = 0x0;\nexport const TRACE_FLAG_SAMPLED = 0x1;\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in an event.\n */\nexport function spanToTraceContext(span: Span): TraceContext {\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n const { data, op, parent_span_id, status, tags, origin } = spanToJSON(span);\n\n return dropUndefinedKeys({\n data,\n op,\n parent_span_id,\n span_id,\n status,\n tags,\n trace_id,\n origin,\n });\n}\n\n/**\n * Convert a Span to a Sentry trace header.\n */\nexport function spanToTraceHeader(span: Span): string {\n const { traceId, spanId } = span.spanContext();\n const sampled = spanIsSampled(span);\n return generateSentryTraceHeader(traceId, spanId, sampled);\n}\n\n/**\n * Convert a span time input intp a timestamp in seconds.\n */\nexport function spanTimeInputToSeconds(input: SpanTimeInput | undefined): number {\n if (typeof input === 'number') {\n return ensureTimestampInSeconds(input);\n }\n\n if (Array.isArray(input)) {\n // See {@link HrTime} for the array-based time format\n return input[0] + input[1] / 1e9;\n }\n\n if (input instanceof Date) {\n return ensureTimestampInSeconds(input.getTime());\n }\n\n return timestampInSeconds();\n}\n\n/**\n * Converts a timestamp to second, if it was in milliseconds, or keeps it as second.\n */\nfunction ensureTimestampInSeconds(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n\n/**\n * Convert a span to a JSON representation.\n * Note that all fields returned here are optional and need to be guarded against.\n *\n * Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json).\n * This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility.\n * And `spanToJSON` needs the Span class from `span.ts` to check here.\n * TODO v8: When we remove the deprecated stuff from `span.ts`, we can remove the circular dependency again.\n */\nexport function spanToJSON(span: Span): Partial {\n if (spanIsSpanClass(span)) {\n return span.getSpanJSON();\n }\n\n // Fallback: We also check for `.toJSON()` here...\n // eslint-disable-next-line deprecation/deprecation\n if (typeof span.toJSON === 'function') {\n // eslint-disable-next-line deprecation/deprecation\n return span.toJSON();\n }\n\n return {};\n}\n\n/**\n * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof.\n * :( So instead we approximate this by checking if it has the `getSpanJSON` method.\n */\nfunction spanIsSpanClass(span: Span): span is SpanClass {\n return typeof (span as SpanClass).getSpanJSON === 'function';\n}\n\n/**\n * Returns true if a span is sampled.\n * In most cases, you should just use `span.isRecording()` instead.\n * However, this has a slightly different semantic, as it also returns false if the span is finished.\n * So in the case where this distinction is important, use this method.\n */\nexport function spanIsSampled(span: Span): boolean {\n // We align our trace flags with the ones OpenTelemetry use\n // So we also check for sampled the same way they do.\n const { traceFlags } = span.spanContext();\n // eslint-disable-next-line no-bitwise\n return Boolean(traceFlags & TRACE_FLAG_SAMPLED);\n}\n","import type {\n CaptureContext,\n Client,\n ClientOptions,\n Event,\n EventHint,\n Scope as ScopeInterface,\n ScopeContext,\n StackFrame,\n StackParser,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, addExceptionMechanism, dateTimestampInSeconds, normalize, truncate, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getGlobalEventProcessors, notifyEventProcessors } from '../eventProcessors';\nimport { Scope, getGlobalScope } from '../scope';\nimport { applyScopeDataToEvent, mergeScopeData } from './applyScopeDataToEvent';\nimport { spanToJSON } from './spanUtils';\n\n/**\n * This type makes sure that we get either a CaptureContext, OR an EventHint.\n * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed:\n * { user: { id: '123' }, mechanism: { handled: false } }\n */\nexport type ExclusiveEventHintOrCaptureContext =\n | (CaptureContext & Partial<{ [key in keyof EventHint]: never }>)\n | (EventHint & Partial<{ [key in keyof ScopeContext]: never }>);\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nexport function prepareEvent(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n scope?: Scope,\n client?: Client,\n isolationScope?: Scope,\n): PromiseLike {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = options;\n const prepared: Event = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n // Only put debug IDs onto frames for error events.\n if (event.type === undefined) {\n applyDebugIds(prepared, options.stackParser);\n }\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n const finalScope = getFinalScope(scope, hint.captureContext);\n\n if (hint.mechanism) {\n addExceptionMechanism(prepared, hint.mechanism);\n }\n\n const clientEventProcessors = client && client.getEventProcessors ? client.getEventProcessors() : [];\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n // Merge scope data together\n const data = getGlobalScope().getScopeData();\n\n if (isolationScope) {\n const isolationData = isolationScope.getScopeData();\n mergeScopeData(data, isolationData);\n }\n\n if (finalScope) {\n const finalScopeData = finalScope.getScopeData();\n mergeScopeData(data, finalScopeData);\n }\n\n const attachments = [...(hint.attachments || []), ...data.attachments];\n if (attachments.length) {\n hint.attachments = attachments;\n }\n\n applyScopeDataToEvent(prepared, data);\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors = [\n ...clientEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n // Run scope event processors _after_ all other processors\n ...data.eventProcessors,\n ];\n\n const result = notifyEventProcessors(eventProcessors, prepared, hint);\n\n return result.then(evt => {\n if (evt) {\n // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified\n // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.\n // This should not cause any PII issues, since we're only moving data that is already on the event and not adding\n // any new data\n applyDebugMeta(evt);\n }\n\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event: Event, options: ClientOptions): void {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : DEFAULT_ENVIRONMENT;\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\nconst debugIdStackParserCache = new WeakMap>();\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nexport function applyDebugIds(event: Event, stackParser: StackParser): void {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n\n if (!debugIdMap) {\n return;\n }\n\n let debugIdStackFramesCache: Map;\n const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);\n if (cachedDebugIdStackFrameCache) {\n debugIdStackFramesCache = cachedDebugIdStackFrameCache;\n } else {\n debugIdStackFramesCache = new Map();\n debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);\n }\n\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = Object.keys(debugIdMap).reduce>((acc, debugIdStackTrace) => {\n let parsedStack: StackFrame[];\n const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);\n if (cachedParsedStack) {\n parsedStack = cachedParsedStack;\n } else {\n parsedStack = stackParser(debugIdStackTrace);\n debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);\n }\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n if (stackFrame.filename) {\n acc[stackFrame.filename] = debugIdMap[debugIdStackTrace];\n break;\n }\n }\n return acc;\n }, {});\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event!.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nexport function applyDebugMeta(event: Event): void {\n // Extract debug IDs and filenames from the stack frames on the event.\n const filenameDebugIdMap: Record = {};\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.debug_id) {\n if (frame.abs_path) {\n filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n } else if (frame.filename) {\n filenameDebugIdMap[frame.filename] = frame.debug_id;\n }\n delete frame.debug_id;\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n\n if (Object.keys(filenameDebugIdMap).length === 0) {\n return;\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n Object.keys(filenameDebugIdMap).forEach(filename => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id: filenameDebugIdMap[filename],\n });\n });\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event: Event, integrationNames: string[]): void {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event: Event | null, depth: number, maxBreadth: number): Event | null {\n if (!event) {\n return null;\n }\n\n const normalized: Event = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n const data = spanToJSON(span).data;\n\n if (data) {\n // This is a bit weird, as we generally have `Span` instances here, but to be safe we do not assume so\n // eslint-disable-next-line deprecation/deprecation\n span.data = normalize(data, depth, maxBreadth);\n }\n\n return span;\n });\n }\n\n return normalized;\n}\n\nfunction getFinalScope(scope: Scope | undefined, captureContext: CaptureContext | undefined): Scope | undefined {\n if (!captureContext) {\n return scope;\n }\n\n const finalScope = scope ? scope.clone() : new Scope();\n finalScope.update(captureContext);\n return finalScope;\n}\n\n/**\n * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`.\n * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`.\n */\nexport function parseEventHintOrCaptureContext(\n hint: ExclusiveEventHintOrCaptureContext | undefined,\n): EventHint | undefined {\n if (!hint) {\n return undefined;\n }\n\n // If you pass a Scope or `() => Scope` as CaptureContext, we just return this as captureContext\n if (hintIsScopeOrFunction(hint)) {\n return { captureContext: hint };\n }\n\n if (hintIsScopeContext(hint)) {\n return {\n captureContext: hint,\n };\n }\n\n return hint;\n}\n\nfunction hintIsScopeOrFunction(\n hint: CaptureContext | EventHint,\n): hint is ScopeInterface | ((scope: ScopeInterface) => ScopeInterface) {\n return hint instanceof Scope || typeof hint === 'function';\n}\n\ntype ScopeContextProperty = keyof ScopeContext;\nconst captureContextKeys: readonly ScopeContextProperty[] = [\n 'user',\n 'level',\n 'extra',\n 'contexts',\n 'tags',\n 'fingerprint',\n 'requestSession',\n 'propagationContext',\n] as const;\n\nfunction hintIsScopeContext(hint: Partial | EventHint): hint is Partial {\n return Object.keys(hint).some(key => captureContextKeys.includes(key as ScopeContextProperty));\n}\n","/* eslint-disable max-lines */\nimport type {\n Attachment,\n Breadcrumb,\n CaptureContext,\n Client,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n PropagationContext,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n ScopeData,\n Session,\n Severity,\n SeverityLevel,\n Span,\n Transaction,\n User,\n} from '@sentry/types';\nimport { dateTimestampInSeconds, isPlainObject, logger, uuid4 } from '@sentry/utils';\n\nimport { getGlobalEventProcessors, notifyEventProcessors } from './eventProcessors';\nimport { updateSession } from './session';\nimport { applyScopeDataToEvent } from './utils/applyScopeDataToEvent';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * The global scope is kept in this module.\n * When accessing this via `getGlobalScope()` we'll make sure to set one if none is currently present.\n */\nlet globalScope: ScopeInterface | undefined;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nexport class Scope implements ScopeInterface {\n /** Flag if notifying is happening. */\n protected _notifyingListeners: boolean;\n\n /** Callback for client to receive scope changes. */\n protected _scopeListeners: Array<(scope: Scope) => void>;\n\n /** Callback list that will be called after {@link applyToEvent}. */\n protected _eventProcessors: EventProcessor[];\n\n /** Array of breadcrumbs. */\n protected _breadcrumbs: Breadcrumb[];\n\n /** User */\n protected _user: User;\n\n /** Tags */\n protected _tags: { [key: string]: Primitive };\n\n /** Extra */\n protected _extra: Extras;\n\n /** Contexts */\n protected _contexts: Contexts;\n\n /** Attachments */\n protected _attachments: Attachment[];\n\n /** Propagation Context for distributed tracing */\n protected _propagationContext: PropagationContext;\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n protected _sdkProcessingMetadata: { [key: string]: unknown };\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n // eslint-disable-next-line deprecation/deprecation\n protected _level?: Severity | SeverityLevel;\n\n /**\n * Transaction Name\n */\n protected _transactionName?: string;\n\n /** Span */\n protected _span?: Span;\n\n /** Session */\n protected _session?: Session;\n\n /** Request Mode Session Status */\n protected _requestSession?: RequestSession;\n\n /** The client on this scope */\n protected _client?: Client;\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n public constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n this._propagationContext = generatePropagationContext();\n }\n\n /**\n * Inherit values from the parent scope.\n * @deprecated Use `scope.clone()` and `new Scope()` instead.\n */\n public static clone(scope?: Scope): Scope {\n return scope ? scope.clone() : new Scope();\n }\n\n /**\n * Clone this scope instance.\n */\n public clone(): Scope {\n const newScope = new Scope();\n newScope._breadcrumbs = [...this._breadcrumbs];\n newScope._tags = { ...this._tags };\n newScope._extra = { ...this._extra };\n newScope._contexts = { ...this._contexts };\n newScope._user = this._user;\n newScope._level = this._level;\n newScope._span = this._span;\n newScope._session = this._session;\n newScope._transactionName = this._transactionName;\n newScope._fingerprint = this._fingerprint;\n newScope._eventProcessors = [...this._eventProcessors];\n newScope._requestSession = this._requestSession;\n newScope._attachments = [...this._attachments];\n newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };\n newScope._propagationContext = { ...this._propagationContext };\n newScope._client = this._client;\n\n return newScope;\n }\n\n /** Update the client on the scope. */\n public setClient(client: Client | undefined): void {\n this._client = client;\n }\n\n /**\n * Get the client assigned to this scope.\n *\n * It is generally recommended to use the global function `Sentry.getClient()` instead, unless you know what you are doing.\n */\n public getClient(): Client | undefined {\n return this._client;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): this {\n // If null is passed we want to unset everything, but still define keys,\n // so that later down in the pipeline any existing values are cleared.\n this._user = user || {\n email: undefined,\n id: undefined,\n ip_address: undefined,\n segment: undefined,\n username: undefined,\n };\n\n if (this._session) {\n updateSession(this._session, { user });\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n public getRequestSession(): RequestSession | undefined {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n public setRequestSession(requestSession?: RequestSession): this {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): this {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): this {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): this {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setLevel(\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel,\n ): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the transaction name on the scope for future events.\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): this {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the Span on the scope.\n * @param span Span\n * @deprecated Instead of setting a span on a scope, use `startSpan()`/`startSpanManual()` instead.\n */\n public setSpan(span?: Span): this {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Returns the `Span` if there is one.\n * @deprecated Use `getActiveSpan()` instead.\n */\n public getSpan(): Span | undefined {\n return this._span;\n }\n\n /**\n * Returns the `Transaction` attached to the scope (if there is one).\n * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead.\n */\n public getTransaction(): Transaction | undefined {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this._span;\n // Cannot replace with getRootSpan because getRootSpan returns a span, not a transaction\n // Also, this method will be removed anyway.\n // eslint-disable-next-line deprecation/deprecation\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\n */\n public setSession(session?: Session): this {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n public update(captureContext?: CaptureContext): this {\n if (!captureContext) {\n return this;\n }\n\n const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext;\n\n if (scopeToMerge instanceof Scope) {\n const scopeData = scopeToMerge.getScopeData();\n\n this._tags = { ...this._tags, ...scopeData.tags };\n this._extra = { ...this._extra, ...scopeData.extra };\n this._contexts = { ...this._contexts, ...scopeData.contexts };\n if (scopeData.user && Object.keys(scopeData.user).length) {\n this._user = scopeData.user;\n }\n if (scopeData.level) {\n this._level = scopeData.level;\n }\n if (scopeData.fingerprint.length) {\n this._fingerprint = scopeData.fingerprint;\n }\n if (scopeToMerge.getRequestSession()) {\n this._requestSession = scopeToMerge.getRequestSession();\n }\n if (scopeData.propagationContext) {\n this._propagationContext = scopeData.propagationContext;\n }\n } else if (isPlainObject(scopeToMerge)) {\n const scopeContext = captureContext as ScopeContext;\n this._tags = { ...this._tags, ...scopeContext.tags };\n this._extra = { ...this._extra, ...scopeContext.extra };\n this._contexts = { ...this._contexts, ...scopeContext.contexts };\n if (scopeContext.user) {\n this._user = scopeContext.user;\n }\n if (scopeContext.level) {\n this._level = scopeContext.level;\n }\n if (scopeContext.fingerprint) {\n this._fingerprint = scopeContext.fingerprint;\n }\n if (scopeContext.requestSession) {\n this._requestSession = scopeContext.requestSession;\n }\n if (scopeContext.propagationContext) {\n this._propagationContext = scopeContext.propagationContext;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clear(): this {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n this._attachments = [];\n this._propagationContext = generatePropagationContext();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n\n const breadcrumbs = this._breadcrumbs;\n breadcrumbs.push(mergedBreadcrumb);\n this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs;\n\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getLastBreadcrumb(): Breadcrumb | undefined {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addAttachment(attachment: Attachment): this {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `getScopeData()` instead.\n */\n public getAttachments(): Attachment[] {\n const data = this.getScopeData();\n\n return data.attachments;\n }\n\n /**\n * @inheritDoc\n */\n public clearAttachments(): this {\n this._attachments = [];\n return this;\n }\n\n /** @inheritDoc */\n public getScopeData(): ScopeData {\n const {\n _breadcrumbs,\n _attachments,\n _contexts,\n _tags,\n _extra,\n _user,\n _level,\n _fingerprint,\n _eventProcessors,\n _propagationContext,\n _sdkProcessingMetadata,\n _transactionName,\n _span,\n } = this;\n\n return {\n breadcrumbs: _breadcrumbs,\n attachments: _attachments,\n contexts: _contexts,\n tags: _tags,\n extra: _extra,\n user: _user,\n level: _level,\n fingerprint: _fingerprint || [],\n eventProcessors: _eventProcessors,\n propagationContext: _propagationContext,\n sdkProcessingMetadata: _sdkProcessingMetadata,\n transactionName: _transactionName,\n span: _span,\n };\n }\n\n /**\n * Applies data from the scope to the event and runs all event processors on it.\n *\n * @param event Event\n * @param hint Object containing additional information about the original exception, for use by the event processors.\n * @hidden\n * @deprecated Use `applyScopeDataToEvent()` directly\n */\n public applyToEvent(\n event: Event,\n hint: EventHint = {},\n additionalEventProcessors: EventProcessor[] = [],\n ): PromiseLike {\n applyScopeDataToEvent(event, this.getScopeData());\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors: EventProcessor[] = [\n ...additionalEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n ...this._eventProcessors,\n ];\n\n return notifyEventProcessors(eventProcessors, event, hint);\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry\n */\n public setSDKProcessingMetadata(newData: { [key: string]: unknown }): this {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setPropagationContext(context: PropagationContext): this {\n this._propagationContext = context;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getPropagationContext(): PropagationContext {\n return this._propagationContext;\n }\n\n /**\n * Capture an exception for this scope.\n *\n * @param exception The exception to capture.\n * @param hint Optinal additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture exception!');\n return eventId;\n }\n\n const syntheticException = new Error('Sentry syntheticException');\n\n this._client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Capture a message for this scope.\n *\n * @param message The message to capture.\n * @param level An optional severity level to report the message with.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured message.\n */\n public captureMessage(message: string, level?: SeverityLevel, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture message!');\n return eventId;\n }\n\n const syntheticException = new Error(message);\n\n this._client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Captures a manually created event for this scope and sends it to Sentry.\n *\n * @param exception The event to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture event!');\n return eventId;\n }\n\n this._client.captureEvent(event, { ...hint, event_id: eventId }, this);\n\n return eventId;\n }\n\n /**\n * This will be called on every set call.\n */\n protected _notifyScopeListeners(): void {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n}\n\n/**\n * Get the global scope.\n * This scope is applied to _all_ events.\n */\nexport function getGlobalScope(): ScopeInterface {\n if (!globalScope) {\n globalScope = new Scope();\n }\n\n return globalScope;\n}\n\n/**\n * This is mainly needed for tests.\n * DO NOT USE this, as this is an internal API and subject to change.\n * @hidden\n */\nexport function setGlobalScope(scope: ScopeInterface | undefined): void {\n globalScope = scope;\n}\n\nfunction generatePropagationContext(): PropagationContext {\n return {\n traceId: uuid4(),\n spanId: uuid4().substring(16),\n };\n}\n","import type {\n Breadcrumb,\n BreadcrumbHint,\n CaptureContext,\n CheckIn,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n FinishedCheckIn,\n MonitorConfig,\n Primitive,\n Scope as ScopeInterface,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Span,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, isThenable, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { Hub } from './hub';\nimport { runWithAsyncContext } from './hub';\nimport { getCurrentHub, getIsolationScope } from './hub';\nimport type { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport type { ExclusiveEventHintOrCaptureContext } from './utils/prepareEvent';\nimport { parseEventHintOrCaptureContext } from './utils/prepareEvent';\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\nexport function captureException(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exception: any,\n hint?: ExclusiveEventHintOrCaptureContext,\n): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureException(exception, parseEventHintOrCaptureContext(hint));\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param captureContext Define the level of the message or pass in additional data to attach to the message.\n * @returns the id of the captured message.\n */\nexport function captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n captureContext?: CaptureContext | Severity | SeverityLevel,\n): string {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param exception The event to send to Sentry.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\nexport function captureEvent(event: Event, hint?: EventHint): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureEvent(event, hint);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n *\n * @deprecated Use getCurrentScope() directly.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function configureScope(callback: (scope: Scope) => void): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().configureScope(callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().addBreadcrumb(breadcrumb, hint);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, deprecation/deprecation\nexport function setContext(name: string, context: { [key: string]: any } | null): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setExtras(extras: Extras): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setExtra(key: string, extra: Extra): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setTags(tags: { [key: string]: Primitive }): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setTag(key: string, value: Primitive): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setUser(user: User | null): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setUser(user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n */\nexport function withScope(callback: (scope: Scope) => T): T;\n/**\n * Set the given scope as the active scope in the callback.\n */\nexport function withScope(scope: ScopeInterface | undefined, callback: (scope: Scope) => T): T;\n/**\n * Either creates a new active scope, or sets the given scope as active scope in the given callback.\n */\nexport function withScope(\n ...rest: [callback: (scope: Scope) => T] | [scope: ScopeInterface | undefined, callback: (scope: Scope) => T]\n): T {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n\n // If a scope is defined, we want to make this the active scope instead of the default one\n if (rest.length === 2) {\n const [scope, callback] = rest;\n if (!scope) {\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(callback);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(() => {\n // eslint-disable-next-line deprecation/deprecation\n hub.getStackTop().scope = scope as Scope;\n return callback(scope as Scope);\n });\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(rest[0]);\n}\n\n/**\n * Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no\n * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the\n * case, for example, in the browser).\n *\n * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.\n *\n * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in \"normal\"\n * applications directly because it comes with pitfalls. Use at your own risk!\n *\n * @param callback The callback in which the passed isolation scope is active. (Note: In environments without async\n * context strategy, the currently active isolation scope may change within execution of the callback.)\n * @returns The same value that `callback` returns.\n */\nexport function withIsolationScope(callback: (isolationScope: Scope) => T): T {\n return runWithAsyncContext(() => {\n return callback(getIsolationScope());\n });\n}\n\n/**\n * Forks the current scope and sets the provided span as active span in the context of the provided callback.\n *\n * @param span Spans started in the context of the provided callback will be children of this span.\n * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.\n * @returns the value returned from the provided callback function.\n */\nexport function withActiveSpan(span: Span, callback: (scope: Scope) => T): T {\n return withScope(scope => {\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(span);\n return callback(scope);\n });\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call\n * `startTransaction` directly on the hub.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\nexport function startTransaction(\n context: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n // eslint-disable-next-line deprecation/deprecation\n): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().startTransaction({ ...context }, customSamplingContext);\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string {\n const scope = getCurrentScope();\n const client = getClient();\n if (!client) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);\n }\n\n return uuid4();\n}\n\n/**\n * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.\n *\n * @param monitorSlug The distinct slug of the monitor.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function withMonitor(\n monitorSlug: CheckIn['monitorSlug'],\n callback: () => T,\n upsertMonitorConfig?: MonitorConfig,\n): T {\n const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig);\n const now = timestampInSeconds();\n\n function finishCheckIn(status: FinishedCheckIn['status']): void {\n captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now });\n }\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback();\n } catch (e) {\n finishCheckIn('error');\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n Promise.resolve(maybePromiseResult).then(\n () => {\n finishCheckIn('ok');\n },\n () => {\n finishCheckIn('error');\n },\n );\n } else {\n finishCheckIn('ok');\n }\n\n return maybePromiseResult;\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function flush(timeout?: number): Promise {\n const client = getClient();\n if (client) {\n return client.flush(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function close(timeout?: number): Promise {\n const client = getClient();\n if (client) {\n return client.close(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nexport function lastEventId(): string | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().lastEventId();\n}\n\n/**\n * Get the currently active client.\n */\nexport function getClient(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getClient();\n}\n\n/**\n * Returns true if Sentry has been properly initialized.\n */\nexport function isInitialized(): boolean {\n return !!getClient();\n}\n\n/**\n * Get the currently active scope.\n */\nexport function getCurrentScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getScope();\n}\n\n/**\n * Start a session on the current isolation scope.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns the new active session\n */\nexport function startSession(context?: SessionContext): Session {\n const client = getClient();\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: currentScope.getUser() || isolationScope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = isolationScope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n\n endSession();\n\n // Afterwards we set the new session on the scope\n isolationScope.setSession(session);\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession(session);\n\n return session;\n}\n\n/**\n * End the session on the current isolation scope.\n */\nexport function endSession(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session) {\n closeSession(session);\n }\n _sendSessionUpdate();\n\n // the session is over; take it off of the scope\n isolationScope.setSession();\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession();\n}\n\n/**\n * Sends the current Session on the scope\n */\nfunction _sendSessionUpdate(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n const client = getClient();\n // TODO (v8): Remove currentScope and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n}\n\n/**\n * Sends the current session on the scope to Sentry\n *\n * @param end If set the session will be marked as exited and removed from the scope.\n * Defaults to `false`.\n */\nexport function captureSession(end: boolean = false): void {\n // both send the update and pull the session from the scope\n if (end) {\n endSession();\n return;\n }\n\n // only send the update\n _sendSessionUpdate();\n}\n","import type { Span } from '@sentry/types';\n\n/**\n * Returns the root span of a given span.\n *\n * As long as we use `Transaction`s internally, the returned root span\n * will be a `Transaction` but be aware that this might change in the future.\n *\n * If the given span has no root span or transaction, `undefined` is returned.\n */\nexport function getRootSpan(span: Span): Span | undefined {\n // TODO (v8): Remove this check and just return span\n // eslint-disable-next-line deprecation/deprecation\n return span.transaction;\n}\n","import type { Client, DynamicSamplingContext, Scope, Span, Transaction } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getClient, getCurrentScope } from '../exports';\nimport { getRootSpan } from '../utils/getRootSpan';\nimport { spanIsSampled, spanToJSON } from '../utils/spanUtils';\n\n/**\n * Creates a dynamic sampling context from a client.\n *\n * Dispatches the `createDsc` lifecycle hook as a side effect.\n */\nexport function getDynamicSamplingContextFromClient(\n trace_id: string,\n client: Client,\n scope?: Scope,\n): DynamicSamplingContext {\n const options = client.getOptions();\n\n const { publicKey: public_key } = client.getDsn() || {};\n // TODO(v8): Remove segment from User\n // eslint-disable-next-line deprecation/deprecation\n const { segment: user_segment } = (scope && scope.getUser()) || {};\n\n const dsc = dropUndefinedKeys({\n environment: options.environment || DEFAULT_ENVIRONMENT,\n release: options.release,\n user_segment,\n public_key,\n trace_id,\n }) as DynamicSamplingContext;\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n\n/**\n * A Span with a frozen dynamic sampling context.\n */\ntype TransactionWithV7FrozenDsc = Transaction & { _frozenDynamicSamplingContext?: DynamicSamplingContext };\n\n/**\n * Creates a dynamic sampling context from a span (and client and scope)\n *\n * @param span the span from which a few values like the root span name and sample rate are extracted.\n *\n * @returns a dynamic sampling context\n */\nexport function getDynamicSamplingContextFromSpan(span: Span): Readonly> {\n const client = getClient();\n if (!client) {\n return {};\n }\n\n // passing emit=false here to only emit later once the DSC is actually populated\n const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client, getCurrentScope());\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n const txn = getRootSpan(span) as TransactionWithV7FrozenDsc | undefined;\n if (!txn) {\n return dsc;\n }\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n // For now we need to avoid breaking users who directly created a txn with a DSC, where this field is still set.\n // @see Transaction class constructor\n const v7FrozenDsc = txn && txn._frozenDynamicSamplingContext;\n if (v7FrozenDsc) {\n return v7FrozenDsc;\n }\n\n // TODO (v8): Replace txn.metadata with txn.attributes[]\n // We can't do this yet because attributes aren't always set yet.\n // eslint-disable-next-line deprecation/deprecation\n const { sampleRate: maybeSampleRate, source } = txn.metadata;\n if (maybeSampleRate != null) {\n dsc.sample_rate = `${maybeSampleRate}`;\n }\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const jsonSpan = spanToJSON(txn);\n\n // after JSON conversion, txn.name becomes jsonSpan.description\n if (source && source !== 'url') {\n dsc.transaction = jsonSpan.description;\n }\n\n dsc.sampled = String(spanIsSampled(txn));\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n","import type { Breadcrumb, Event, ScopeData, Span } from '@sentry/types';\nimport { arrayify, dropUndefinedKeys } from '@sentry/utils';\nimport { getDynamicSamplingContextFromSpan } from '../tracing/dynamicSamplingContext';\nimport { getRootSpan } from './getRootSpan';\nimport { spanToJSON, spanToTraceContext } from './spanUtils';\n\n/**\n * Applies data from the scope to the event and runs all event processors on it.\n */\nexport function applyScopeDataToEvent(event: Event, data: ScopeData): void {\n const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;\n\n // Apply general data\n applyDataToEvent(event, data);\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (span) {\n applySpanToEvent(event, span);\n }\n\n applyFingerprintToEvent(event, fingerprint);\n applyBreadcrumbsToEvent(event, breadcrumbs);\n applySdkMetadataToEvent(event, sdkProcessingMetadata);\n}\n\n/** Merge data of two scopes together. */\nexport function mergeScopeData(data: ScopeData, mergeData: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n sdkProcessingMetadata,\n breadcrumbs,\n fingerprint,\n eventProcessors,\n attachments,\n propagationContext,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n span,\n } = mergeData;\n\n mergeAndOverwriteScopeData(data, 'extra', extra);\n mergeAndOverwriteScopeData(data, 'tags', tags);\n mergeAndOverwriteScopeData(data, 'user', user);\n mergeAndOverwriteScopeData(data, 'contexts', contexts);\n mergeAndOverwriteScopeData(data, 'sdkProcessingMetadata', sdkProcessingMetadata);\n\n if (level) {\n data.level = level;\n }\n\n if (transactionName) {\n // eslint-disable-next-line deprecation/deprecation\n data.transactionName = transactionName;\n }\n\n if (span) {\n data.span = span;\n }\n\n if (breadcrumbs.length) {\n data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];\n }\n\n if (fingerprint.length) {\n data.fingerprint = [...data.fingerprint, ...fingerprint];\n }\n\n if (eventProcessors.length) {\n data.eventProcessors = [...data.eventProcessors, ...eventProcessors];\n }\n\n if (attachments.length) {\n data.attachments = [...data.attachments, ...attachments];\n }\n\n data.propagationContext = { ...data.propagationContext, ...propagationContext };\n}\n\n/**\n * Merges certain scope data. Undefined values will overwrite any existing values.\n * Exported only for tests.\n */\nexport function mergeAndOverwriteScopeData<\n Prop extends 'extra' | 'tags' | 'user' | 'contexts' | 'sdkProcessingMetadata',\n Data extends ScopeData,\n>(data: Data, prop: Prop, mergeVal: Data[Prop]): void {\n if (mergeVal && Object.keys(mergeVal).length) {\n // Clone object\n data[prop] = { ...data[prop] };\n for (const key in mergeVal) {\n if (Object.prototype.hasOwnProperty.call(mergeVal, key)) {\n data[prop][key] = mergeVal[key];\n }\n }\n }\n}\n\n/** Exported only for tests */\nexport function mergeArray(\n event: Event,\n prop: Prop,\n mergeVal: ScopeData[Prop],\n): void {\n const prevVal = event[prop];\n // If we are not merging any new values,\n // we only need to proceed if there was an empty array before (as we want to replace it with undefined)\n if (!mergeVal.length && (!prevVal || prevVal.length)) {\n return;\n }\n\n const merged = [...(prevVal || []), ...mergeVal] as ScopeData[Prop];\n event[prop] = merged.length ? merged : undefined;\n}\n\nfunction applyDataToEvent(event: Event, data: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n } = data;\n\n const cleanedExtra = dropUndefinedKeys(extra);\n if (cleanedExtra && Object.keys(cleanedExtra).length) {\n event.extra = { ...cleanedExtra, ...event.extra };\n }\n\n const cleanedTags = dropUndefinedKeys(tags);\n if (cleanedTags && Object.keys(cleanedTags).length) {\n event.tags = { ...cleanedTags, ...event.tags };\n }\n\n const cleanedUser = dropUndefinedKeys(user);\n if (cleanedUser && Object.keys(cleanedUser).length) {\n event.user = { ...cleanedUser, ...event.user };\n }\n\n const cleanedContexts = dropUndefinedKeys(contexts);\n if (cleanedContexts && Object.keys(cleanedContexts).length) {\n event.contexts = { ...cleanedContexts, ...event.contexts };\n }\n\n if (level) {\n event.level = level;\n }\n\n if (transactionName) {\n event.transaction = transactionName;\n }\n}\n\nfunction applyBreadcrumbsToEvent(event: Event, breadcrumbs: Breadcrumb[]): void {\n const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs];\n event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined;\n}\n\nfunction applySdkMetadataToEvent(event: Event, sdkProcessingMetadata: ScopeData['sdkProcessingMetadata']): void {\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n ...sdkProcessingMetadata,\n };\n}\n\nfunction applySpanToEvent(event: Event, span: Span): void {\n event.contexts = { trace: spanToTraceContext(span), ...event.contexts };\n const rootSpan = getRootSpan(span);\n if (rootSpan) {\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),\n ...event.sdkProcessingMetadata,\n };\n const transactionName = spanToJSON(rootSpan).description;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n}\n\n/**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\nfunction applyFingerprintToEvent(event: Event, fingerprint: ScopeData['fingerprint'] | undefined): void {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];\n\n // If we have something on the scope, then merge it with event\n if (fingerprint) {\n event.fingerprint = event.fingerprint.concat(fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n}\n","export const SDK_VERSION = '7.119.0';\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n Hub as HubInterface,\n Integration,\n IntegrationClass,\n Primitive,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n consoleSandbox,\n dateTimestampInSeconds,\n getGlobalSingleton,\n isThenable,\n logger,\n uuid4,\n} from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport { SDK_VERSION } from './version';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nexport const API_VERSION = parseFloat(SDK_VERSION);\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\nexport interface RunWithAsyncContextOptions {\n /** Whether to reuse an existing async context if one exists. Defaults to false. */\n reuseExisting?: boolean;\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Strategy used to track async context.\n */\nexport interface AsyncContextStrategy {\n /**\n * Gets the current async context. Returns undefined if there is no current async context.\n */\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub: () => Hub | undefined;\n /**\n * Runs the supplied callback in its own async context.\n */\n runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions): T;\n}\n\n/**\n * A layer in the process stack.\n * @hidden\n */\nexport interface Layer {\n client?: Client;\n scope: Scope;\n}\n\n/**\n * An object that contains a hub and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: {\n // eslint-disable-next-line deprecation/deprecation\n hub?: Hub;\n acs?: AsyncContextStrategy;\n /**\n * Extra Hub properties injected by various SDKs\n */\n integrations?: Integration[];\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n/**\n * @deprecated The `Hub` class will be removed in version 8 of the SDK in favour of `Scope` and `Client` objects.\n *\n * If you previously used the `Hub` class directly, replace it with `Scope` and `Client` objects. More information:\n * - [Multiple Sentry Instances](https://docs.sentry.io/platforms/javascript/best-practices/multiple-sentry-instances/)\n * - [Browser Extensions](https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/)\n *\n * Some of our APIs are typed with the Hub class instead of the interface (e.g. `getCurrentHub`). Most of them are deprecated\n * themselves and will also be removed in version 8. More information:\n * - [Migration Guide](https://github.com/getsentry/sentry-javascript/blob/develop/MIGRATION.md#deprecate-hub)\n */\n// eslint-disable-next-line deprecation/deprecation\nexport class Hub implements HubInterface {\n /** Is a {@link Layer}[] containing the client and scope */\n private readonly _stack: Layer[];\n\n /** Contains the last event id of a captured event. */\n private _lastEventId?: string;\n\n private _isolationScope: Scope;\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n *\n * @deprecated Instantiation of Hub objects is deprecated and the constructor will be removed in version 8 of the SDK.\n *\n * If you are currently using the Hub for multi-client use like so:\n *\n * ```\n * // OLD\n * const hub = new Hub();\n * hub.bindClient(client);\n * makeMain(hub)\n * ```\n *\n * instead initialize the client as follows:\n *\n * ```\n * // NEW\n * Sentry.withIsolationScope(() => {\n * Sentry.setCurrentClient(client);\n * client.init();\n * });\n * ```\n *\n * If you are using the Hub to capture events like so:\n *\n * ```\n * // OLD\n * const client = new Client();\n * const hub = new Hub(client);\n * hub.captureException()\n * ```\n *\n * instead capture isolated events as follows:\n *\n * ```\n * // NEW\n * const client = new Client();\n * const scope = new Scope();\n * scope.setClient(client);\n * scope.captureException();\n * ```\n */\n public constructor(\n client?: Client,\n scope?: Scope,\n isolationScope?: Scope,\n private readonly _version: number = API_VERSION,\n ) {\n let assignedScope;\n if (!scope) {\n assignedScope = new Scope();\n assignedScope.setClient(client);\n } else {\n assignedScope = scope;\n }\n\n let assignedIsolationScope;\n if (!isolationScope) {\n assignedIsolationScope = new Scope();\n assignedIsolationScope.setClient(client);\n } else {\n assignedIsolationScope = isolationScope;\n }\n\n this._stack = [{ scope: assignedScope }];\n\n if (client) {\n // eslint-disable-next-line deprecation/deprecation\n this.bindClient(client);\n }\n\n this._isolationScope = assignedIsolationScope;\n }\n\n /**\n * Checks if this hub's version is older than the given version.\n *\n * @param version A version number to compare to.\n * @return True if the given version is newer; otherwise false.\n *\n * @deprecated This will be removed in v8.\n */\n public isOlderThan(version: number): boolean {\n return this._version < version;\n }\n\n /**\n * This binds the given client to the current scope.\n * @param client An SDK client (client) instance.\n *\n * @deprecated Use `initAndBind()` directly, or `setCurrentClient()` and/or `client.init()` instead.\n */\n public bindClient(client?: Client): void {\n // eslint-disable-next-line deprecation/deprecation\n const top = this.getStackTop();\n top.client = client;\n top.scope.setClient(client);\n // eslint-disable-next-line deprecation/deprecation\n if (client && client.setupIntegrations) {\n // eslint-disable-next-line deprecation/deprecation\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public pushScope(): Scope {\n // We want to clone the content of prev scope\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.getScope().clone();\n // eslint-disable-next-line deprecation/deprecation\n this.getStack().push({\n // eslint-disable-next-line deprecation/deprecation\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public popScope(): boolean {\n // eslint-disable-next-line deprecation/deprecation\n if (this.getStack().length <= 1) return false;\n // eslint-disable-next-line deprecation/deprecation\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.withScope()` instead.\n */\n public withScope(callback: (scope: Scope) => T): T {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.pushScope();\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback(scope);\n } catch (e) {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n // @ts-expect-error - isThenable returns the wrong type\n return maybePromiseResult.then(\n res => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return res;\n },\n e => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n },\n );\n }\n\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return maybePromiseResult;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.getClient()` instead.\n */\n public getClient(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().client as C;\n }\n\n /**\n * Returns the scope of the top stack.\n *\n * @deprecated Use `Sentry.getCurrentScope()` instead.\n */\n public getScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().scope;\n }\n\n /**\n * @deprecated Use `Sentry.getIsolationScope()` instead.\n */\n public getIsolationScope(): Scope {\n return this._isolationScope;\n }\n\n /**\n * Returns the scope stack for domains or the process.\n * @deprecated This will be removed in v8.\n */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /**\n * Returns the topmost scope layer in the order domain > local > process.\n * @deprecated This will be removed in v8.\n */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureException()` instead.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error('Sentry syntheticException');\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureException(exception, {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureMessage()` instead.\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n ): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error(message);\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureMessage(message, level, {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureEvent()` instead.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (!event.type) {\n this._lastEventId = eventId;\n }\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureEvent(event, { ...hint, event_id: eventId });\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated This will be removed in v8.\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.addBreadcrumb()` instead.\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) as Breadcrumb | null)\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n // TODO(v8): I know this comment doesn't make much sense because the hub will be deprecated but I still wanted to\n // write it down. In theory, we would have to add the breadcrumbs to the isolation scope here, however, that would\n // duplicate all of the breadcrumbs. There was the possibility of adding breadcrumbs to both, the isolation scope\n // and the normal scope, and deduplicating it down the line in the event processing pipeline. However, that would\n // have been very fragile, because the breadcrumb objects would have needed to keep their identity all throughout\n // the event processing pipeline.\n // In the new implementation, the top level `Sentry.addBreadcrumb()` should ONLY write to the isolation scope.\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setUser()` instead.\n */\n public setUser(user: User | null): void {\n // TODO(v8): The top level `Sentry.setUser()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setUser(user);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setUser(user);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTags()` instead.\n */\n public setTags(tags: { [key: string]: Primitive }): void {\n // TODO(v8): The top level `Sentry.setTags()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTags(tags);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTags(tags);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtras()` instead.\n */\n public setExtras(extras: Extras): void {\n // TODO(v8): The top level `Sentry.setExtras()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtras(extras);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtras(extras);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTag()` instead.\n */\n public setTag(key: string, value: Primitive): void {\n // TODO(v8): The top level `Sentry.setTag()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTag(key, value);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTag(key, value);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtra()` instead.\n */\n public setExtra(key: string, extra: Extra): void {\n // TODO(v8): The top level `Sentry.setExtra()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtra(key, extra);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setContext()` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setContext(name: string, context: { [key: string]: any } | null): void {\n // TODO(v8): The top level `Sentry.setContext()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setContext(name, context);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setContext(name, context);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `getScope()` directly.\n */\n public configureScope(callback: (scope: Scope) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public run(callback: (hub: Hub) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n // eslint-disable-next-line deprecation/deprecation\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.getClient().getIntegrationByName()` instead.\n */\n public getIntegration(integration: IntegrationClass): T | null {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n if (!client) return null;\n try {\n // eslint-disable-next-line deprecation/deprecation\n return client.getIntegration(integration);\n } catch (_oO) {\n DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\n public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {\n const result = this._callExtensionMethod('startTransaction', context, customSamplingContext);\n\n if (DEBUG_BUILD && !result) {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n if (!client) {\n logger.warn(\n \"Tracing extension 'startTransaction' is missing. You should 'init' the SDK before calling 'startTransaction'\",\n );\n } else {\n logger.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':\nSentry.addTracingExtensions();\nSentry.init({...});\n`);\n }\n }\n\n return result;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `spanToTraceHeader()` instead.\n */\n public traceHeaders(): { [key: string]: string } {\n return this._callExtensionMethod<{ [key: string]: string }>('traceHeaders');\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use top level `captureSession` instead.\n */\n public captureSession(endSession: boolean = false): void {\n // both send the update and pull the session from the scope\n if (endSession) {\n // eslint-disable-next-line deprecation/deprecation\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top level `endSession` instead.\n */\n public endSession(): void {\n // eslint-disable-next-line deprecation/deprecation\n const layer = this.getStackTop();\n const scope = layer.scope;\n const session = scope.getSession();\n if (session) {\n closeSession(session);\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n scope.setSession();\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top level `startSession` instead.\n */\n public startSession(context?: SessionContext): Session {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: scope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n // eslint-disable-next-line deprecation/deprecation\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n\n return session;\n }\n\n /**\n * Returns if default PII should be sent to Sentry and propagated in ourgoing requests\n * when Tracing is used.\n *\n * @deprecated Use top-level `getClient().getOptions().sendDefaultPii` instead. This function\n * only unnecessarily increased API surface but only wrapped accessing the option.\n */\n public shouldSendDefaultPii(): boolean {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n const options = client && client.getOptions();\n return Boolean(options && options.sendDefaultPii);\n }\n\n /**\n * Sends the current Session on the scope\n */\n private _sendSessionUpdate(): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n\n const session = scope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-expect-error Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _callExtensionMethod(method: string, ...args: any[]): T {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n DEBUG_BUILD && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier(): Carrier {\n GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return GLOBAL_OBJ;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n *\n * @deprecated Use `setCurrentClient()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function makeMain(hub: Hub): Hub {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n *\n * @deprecated Use the respective replacement method directly instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getCurrentHub(): Hub {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n const hub = registry.__SENTRY__.acs.getCurrentHub();\n\n if (hub) {\n return hub;\n }\n }\n\n // Return hub that lives on a global object\n return getGlobalHub(registry);\n}\n\n/**\n * Get the currently active isolation scope.\n * The isolation scope is active for the current exection context,\n * meaning that it will remain stable for the same Hub.\n */\nexport function getIsolationScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getIsolationScope();\n}\n\n// eslint-disable-next-line deprecation/deprecation\nfunction getGlobalHub(registry: Carrier = getMainCarrier()): Hub {\n // If there's no hub, or its an old API, assign a new one\n\n if (\n !hasHubOnCarrier(registry) ||\n // eslint-disable-next-line deprecation/deprecation\n getHubFromCarrier(registry).isOlderThan(API_VERSION)\n ) {\n // eslint-disable-next-line deprecation/deprecation\n setHubOnCarrier(registry, new Hub());\n }\n\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * If the carrier does not contain a hub, a new hub is created with the global hub client and scope.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function ensureHubOnCarrier(carrier: Carrier, parent: Hub = getGlobalHub()): void {\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (\n !hasHubOnCarrier(carrier) ||\n // eslint-disable-next-line deprecation/deprecation\n getHubFromCarrier(carrier).isOlderThan(API_VERSION)\n ) {\n // eslint-disable-next-line deprecation/deprecation\n const client = parent.getClient();\n // eslint-disable-next-line deprecation/deprecation\n const scope = parent.getScope();\n // eslint-disable-next-line deprecation/deprecation\n const isolationScope = parent.getIsolationScope();\n // eslint-disable-next-line deprecation/deprecation\n setHubOnCarrier(carrier, new Hub(client, scope.clone(), isolationScope.clone()));\n }\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nexport function setAsyncContextStrategy(strategy: AsyncContextStrategy | undefined): void {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n registry.__SENTRY__ = registry.__SENTRY__ || {};\n registry.__SENTRY__.acs = strategy;\n}\n\n/**\n * Runs the supplied callback in its own async context. Async Context strategies are defined per SDK.\n *\n * @param callback The callback to run in its own async context\n * @param options Options to pass to the async context strategy\n * @returns The result of the callback\n */\nexport function runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions = {}): T {\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n return registry.__SENTRY__.acs.runWithAsyncContext(callback, options);\n }\n\n // if there was no strategy, fallback to just calling the callback\n return callback();\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier: Carrier): boolean {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getHubFromCarrier(carrier: Carrier): Hub {\n // eslint-disable-next-line deprecation/deprecation\n return getGlobalSingleton('hub', () => new Hub(), carrier);\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setHubOnCarrier(carrier: Carrier, hub: Hub): boolean {\n if (!carrier) return false;\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n __SENTRY__.hub = hub;\n return true;\n}\n","import type {\n Client,\n Event,\n EventHint,\n Integration,\n IntegrationClass,\n IntegrationFn,\n IntegrationFnResult,\n Options,\n} from '@sentry/types';\nimport { arrayify, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { addGlobalEventProcessor } from './eventProcessors';\nimport { getClient } from './exports';\nimport { getCurrentHub } from './hub';\n\ndeclare module '@sentry/types' {\n interface Integration {\n isDefaultInstance?: boolean;\n }\n}\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n [key: string]: Integration;\n};\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preseve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations: Integration[]): Integration[] {\n const integrationsByName: { [key: string]: Integration } = {};\n\n integrations.forEach(currentInstance => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.keys(integrationsByName).map(k => integrationsByName[k]);\n}\n\n/** Gets integrations to install */\nexport function getIntegrationsToSetup(options: Pick): Integration[] {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach(integration => {\n integration.isDefaultInstance = true;\n });\n\n let integrations: Integration[];\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n integrations = arrayify(userIntegrations(defaultIntegrations));\n } else {\n integrations = defaultIntegrations;\n }\n\n const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = findIndex(finalIntegrations, integration => integration.name === 'Debug');\n if (debugIndex !== -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1);\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nexport function setupIntegrations(client: Client, integrations: Integration[]): IntegrationIndex {\n const integrationIndex: IntegrationIndex = {};\n\n integrations.forEach(integration => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(client, integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/**\n * Execute the `afterAllSetup` hooks of the given integrations.\n */\nexport function afterSetupIntegrations(client: Client, integrations: Integration[]): void {\n for (const integration of integrations) {\n // guard against empty provided integrations\n if (integration && integration.afterAllSetup) {\n integration.afterAllSetup(client);\n }\n }\n}\n\n/** Setup a single integration. */\nexport function setupIntegration(client: Client, integration: Integration, integrationIndex: IntegrationIndex): void {\n if (integrationIndex[integration.name]) {\n DEBUG_BUILD && logger.log(`Integration skipped because it was already installed: ${integration.name}`);\n return;\n }\n integrationIndex[integration.name] = integration;\n\n // `setupOnce` is only called the first time\n if (installedIntegrations.indexOf(integration.name) === -1) {\n // eslint-disable-next-line deprecation/deprecation\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n }\n\n // `setup` is run for each client\n if (integration.setup && typeof integration.setup === 'function') {\n integration.setup(client);\n }\n\n if (client.on && typeof integration.preprocessEvent === 'function') {\n const callback = integration.preprocessEvent.bind(integration) as typeof integration.preprocessEvent;\n client.on('preprocessEvent', (event, hint) => callback(event, hint, client));\n }\n\n if (client.addEventProcessor && typeof integration.processEvent === 'function') {\n const callback = integration.processEvent.bind(integration) as typeof integration.processEvent;\n\n const processor = Object.assign((event: Event, hint: EventHint) => callback(event, hint, client), {\n id: integration.name,\n });\n\n client.addEventProcessor(processor);\n }\n\n DEBUG_BUILD && logger.log(`Integration installed: ${integration.name}`);\n}\n\n/** Add an integration to the current hub's client. */\nexport function addIntegration(integration: Integration): void {\n const client = getClient();\n\n if (!client || !client.addIntegration) {\n DEBUG_BUILD && logger.warn(`Cannot add integration \"${integration.name}\" because no SDK Client is available.`);\n return;\n }\n\n client.addIntegration(integration);\n}\n\n// Polyfill for Array.findIndex(), which is not supported in ES5\nfunction findIndex(arr: T[], callback: (item: T) => boolean): number {\n for (let i = 0; i < arr.length; i++) {\n if (callback(arr[i]) === true) {\n return i;\n }\n }\n\n return -1;\n}\n\n/**\n * Convert a new integration function to the legacy class syntax.\n * In v8, we can remove this and instead export the integration functions directly.\n *\n * @deprecated This will be removed in v8!\n */\nexport function convertIntegrationFnToClass(\n name: string,\n fn: Fn,\n): IntegrationClass {\n return Object.assign(\n function ConvertedIntegration(...args: Parameters): Integration {\n return fn(...args);\n },\n { id: name },\n ) as unknown as IntegrationClass;\n}\n\n/**\n * Define an integration function that can be used to create an integration instance.\n * Note that this by design hides the implementation details of the integration, as they are considered internal.\n */\nexport function defineIntegration(fn: Fn): (...args: Parameters) => IntegrationFnResult {\n return fn;\n}\n","import type { Client, Event, EventHint, Integration, IntegrationClass, IntegrationFn, StackFrame } from '@sentry/types';\nimport { getEventDescription, logger, stringMatchesSomePattern } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [\n /^Script error\\.?$/,\n /^Javascript error: Script error\\.? on line 0$/,\n /^ResizeObserver loop completed with undelivered notifications.$/,\n /^Cannot redefine property: googletag$/,\n];\n\nconst DEFAULT_IGNORE_TRANSACTIONS = [\n /^.*\\/healthcheck$/,\n /^.*\\/healthy$/,\n /^.*\\/live$/,\n /^.*\\/ready$/,\n /^.*\\/heartbeat$/,\n /^.*\\/health$/,\n /^.*\\/healthz$/,\n];\n\n/** Options for the InboundFilters integration */\nexport interface InboundFiltersOptions {\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreTransactions: Array;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n}\n\nconst INTEGRATION_NAME = 'InboundFilters';\nconst _inboundFiltersIntegration = ((options: Partial = {}) => {\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(event, _hint, client) {\n const clientOptions = client.getOptions();\n const mergedOptions = _mergeOptions(options, clientOptions);\n return _shouldDropEvent(event, mergedOptions) ? null : event;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const inboundFiltersIntegration = defineIntegration(_inboundFiltersIntegration);\n\n/**\n * Inbound filters configurable by the user.\n * @deprecated Use `inboundFiltersIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const InboundFilters = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n inboundFiltersIntegration,\n) as IntegrationClass void }> & {\n new (\n options?: Partial<{\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreTransactions: Array;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n }>,\n ): Integration;\n};\n\nfunction _mergeOptions(\n internalOptions: Partial = {},\n clientOptions: Partial = {},\n): Partial {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS),\n ],\n ignoreTransactions: [\n ...(internalOptions.ignoreTransactions || []),\n ...(clientOptions.ignoreTransactions || []),\n ...(internalOptions.disableTransactionDefaults ? [] : DEFAULT_IGNORE_TRANSACTIONS),\n ],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\nfunction _shouldDropEvent(event: Event, options: Partial): boolean {\n if (options.ignoreInternal && _isSentryError(event)) {\n DEBUG_BUILD &&\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event: Event, ignoreErrors?: Array): boolean {\n // If event.type, this is not an error\n if (event.type || !ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event: Event, ignoreTransactions?: Array): boolean {\n if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event: Event, denyUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!denyUrls || !denyUrls.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event: Event, allowUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event: Event): string[] {\n const possibleMessages: string[] = [];\n\n if (event.message) {\n possibleMessages.push(event.message);\n }\n\n let lastException;\n try {\n // @ts-expect-error Try catching to save bundle size\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n lastException = event.exception.values[event.exception.values.length - 1];\n } catch (e) {\n // try catching to save bundle size checking existence of variables\n }\n\n if (lastException) {\n if (lastException.value) {\n possibleMessages.push(lastException.value);\n if (lastException.type) {\n possibleMessages.push(`${lastException.type}: ${lastException.value}`);\n }\n }\n }\n\n if (DEBUG_BUILD && possibleMessages.length === 0) {\n logger.error(`Could not extract message for event ${getEventDescription(event)}`);\n }\n\n return possibleMessages;\n}\n\nfunction _isSentryError(event: Event): boolean {\n try {\n // @ts-expect-error can't be a sentry error if undefined\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames: StackFrame[] = []): string | null {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event: Event): string | null {\n try {\n let frames;\n try {\n // @ts-expect-error we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n DEBUG_BUILD && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n","import type { Client, Integration, IntegrationClass, IntegrationFn, WrappedFunction } from '@sentry/types';\nimport { getOriginalFunction } from '@sentry/utils';\nimport { getClient } from '../exports';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\n\nlet originalFunctionToString: () => void;\n\nconst INTEGRATION_NAME = 'FunctionToString';\n\nconst SETUP_CLIENTS = new WeakMap();\n\nconst _functionToStringIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // intrinsics (like Function.prototype) might be immutable in some environments\n // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function (this: WrappedFunction, ...args: any[]): string {\n const originalFunction = getOriginalFunction(this);\n const context =\n SETUP_CLIENTS.has(getClient() as Client) && originalFunction !== undefined ? originalFunction : this;\n return originalFunctionToString.apply(context, args);\n };\n } catch {\n // ignore errors here, just don't patch this\n }\n },\n setup(client) {\n SETUP_CLIENTS.set(client, true);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * ```js\n * Sentry.init({\n * integrations: [\n * functionToStringIntegration(),\n * ],\n * });\n * ```\n */\nexport const functionToStringIntegration = defineIntegration(_functionToStringIntegration);\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * @deprecated Use `functionToStringIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const FunctionToString = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n functionToStringIntegration,\n) as IntegrationClass void }>;\n\n// eslint-disable-next-line deprecation/deprecation\nexport type FunctionToString = typeof FunctionToString;\n","import type { Client, ClientOptions } from '@sentry/types';\nimport { consoleSandbox, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { getCurrentScope } from './exports';\nimport { getCurrentHub } from './hub';\n\n/** A class object that can instantiate Client objects. */\nexport type ClientClass = new (options: O) => F;\n\n/**\n * Internal function to create a new SDK client instance. The client is\n * installed and then bound to the current scope.\n *\n * @param clientClass The client class to instantiate.\n * @param options Options to pass to the client.\n */\nexport function initAndBind(\n clientClass: ClientClass,\n options: O,\n): void {\n if (options.debug === true) {\n if (DEBUG_BUILD) {\n logger.enable();\n } else {\n // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');\n });\n }\n }\n const scope = getCurrentScope();\n scope.update(options.initialScope);\n\n const client = new clientClass(options);\n setCurrentClient(client);\n initializeClient(client);\n}\n\n/**\n * Make the given client the current client.\n */\nexport function setCurrentClient(client: Client): void {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const top = hub.getStackTop();\n top.client = client;\n top.scope.setClient(client);\n}\n\n/**\n * Initialize the client for the current scope.\n * Make sure to call this after `setCurrentClient()`.\n */\nfunction initializeClient(client: Client): void {\n if (client.init) {\n client.init();\n // TODO v8: Remove this fallback\n // eslint-disable-next-line deprecation/deprecation\n } else if (client.setupIntegrations) {\n // eslint-disable-next-line deprecation/deprecation\n client.setupIntegrations();\n }\n}\n","import type { DsnComponents, DsnLike, DsnProtocol } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { consoleSandbox, logger } from './logger';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol?: string): protocol is DsnProtocol {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nexport function dsnToString(dsn: DsnComponents, withPassword: boolean = false): string {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string\n */\nexport function dsnFromString(str: string): DsnComponents | undefined {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n // This should be logged to the console\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(`Invalid Sentry Dsn: ${str}`);\n });\n return undefined;\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() as string;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol as DsnProtocol, publicKey });\n}\n\nfunction dsnFromComponents(components: DsnComponents): DsnComponents {\n return {\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn: DsnComponents): boolean {\n if (!DEBUG_BUILD) {\n return true;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents: ReadonlyArray = ['protocol', 'publicKey', 'host', 'projectId'];\n const hasMissingRequiredComponent = requiredComponents.find(component => {\n if (!dsn[component]) {\n logger.error(`Invalid Sentry Dsn: ${component} missing`);\n return true;\n }\n return false;\n });\n\n if (hasMissingRequiredComponent) {\n return false;\n }\n\n if (!projectId.match(/^\\d+$/)) {\n logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n return false;\n }\n\n if (!isValidProtocol(protocol)) {\n logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n return false;\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.\n * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source\n */\nexport function makeDsn(from: DsnLike): DsnComponents | undefined {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n if (!components || !validateDsn(components)) {\n return undefined;\n }\n return components;\n}\n","import type { ClientOptions, DsnComponents, DsnLike, SdkInfo } from '@sentry/types';\nimport { dsnToString, makeDsn, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn: DsnComponents): string {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn: DsnComponents): string {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn: DsnComponents, sdkInfo: SdkInfo | undefined): string {\n return urlEncode({\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }),\n });\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nexport function getEnvelopeEndpointWithUrlEncodedAuth(\n dsn: DsnComponents,\n // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below\n // options: ClientOptions = {} as ClientOptions,\n tunnelOrOptions: string | ClientOptions = {} as ClientOptions,\n): string {\n // TODO (v8): Use this code instead\n // const { tunnel, _metadata = {} } = options;\n // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`;\n\n const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel;\n const sdkInfo =\n typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk;\n\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nexport function getReportDialogEndpoint(\n dsnLike: DsnLike,\n dialogOptions: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n user?: { name?: string; email?: string };\n },\n): string {\n const dsn = makeDsn(dsnLike);\n if (!dsn) {\n return '';\n }\n\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'onClose') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n","import { DEBUG_BUILD } from './debug-build';\nimport { logger } from './logger';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\ndeclare const EdgeRuntime: string | undefined;\n\nexport { supportsHistory } from './vendor/supportsHistory';\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsErrorEvent(): boolean {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMError(): boolean {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-expect-error It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMException(): boolean {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsFetch(): boolean {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFetch(func: Function): boolean {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nexport function supportsNativeFetch(): boolean {\n if (typeof EdgeRuntime === 'string') {\n return true;\n }\n\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement as unknown) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n DEBUG_BUILD &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReportingObserver(): boolean {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReferrerPolicy(): boolean {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' as ReferrerPolicy,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n","// Based on https://github.com/angular/angular.js/pull/13945/files\n// The MIT License\n\n// Copyright (c) 2010-2016 Google, Inc. http://angularjs.org\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport { getGlobalObject } from '../worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsHistory(): boolean {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chromeVar = (WINDOW as any).chrome;\n const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport { logger } from '../logger';\nimport { getFunctionName } from '../stacktrace';\n\nexport type InstrumentHandlerType = 'console' | 'dom' | 'fetch' | 'history' | 'xhr' | 'error' | 'unhandledrejection';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type InstrumentHandlerCallback = (data: any) => void;\n\n// We keep the handlers globally\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Add a handler function. */\nexport function addHandler(type: InstrumentHandlerType, handler: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(handler);\n}\n\n/**\n * Reset all instrumentation handlers.\n * This can be used by tests to ensure we have a clean slate of instrumentation handlers.\n */\nexport function resetInstrumentationHandlers(): void {\n Object.keys(handlers).forEach(key => {\n handlers[key as InstrumentHandlerType] = undefined;\n });\n}\n\n/** Maybe run an instrumentation function, unless it was already called. */\nexport function maybeInstrument(type: InstrumentHandlerType, instrumentFn: () => void): void {\n if (!instrumented[type]) {\n instrumentFn();\n instrumented[type] = true;\n }\n}\n\n/** Trigger handlers for a given instrumentation type. */\nexport function triggerHandlers(type: InstrumentHandlerType, data: unknown): void {\n const typeHandlers = type && handlers[type];\n if (!typeHandlers) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataHistory } from '@sentry/types';\n\nimport { fill } from '../object';\nimport { supportsHistory } from '../supports';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nlet lastHref: string | undefined;\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addHistoryInstrumentationHandler(handler: (data: HandlerDataHistory) => void): void {\n const type = 'history';\n addHandler(type, handler);\n maybeInstrument(type, instrumentHistory);\n}\n\nfunction instrumentHistory(): void {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function (this: WindowEventHandlers, ...args: any[]): any {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n const handlerData: HandlerDataHistory = { from, to };\n triggerHandlers('history', handlerData);\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n function historyReplacementFunction(originalHistoryFunction: () => void): () => void {\n return function (this: History, ...args: any[]): void {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n const handlerData: HandlerDataHistory = { from, to };\n triggerHandlers('history', handlerData);\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","import superPropBase from \"./superPropBase.js\";\nexport default function _get() {\n if (typeof Reflect !== \"undefined\" && Reflect.get) {\n _get = Reflect.get.bind();\n } else {\n _get = function _get(target, property, receiver) {\n var base = superPropBase(target, property);\n if (!base) return;\n var desc = Object.getOwnPropertyDescriptor(base, property);\n if (desc.get) {\n return desc.get.call(arguments.length < 3 ? target : receiver);\n }\n return desc.value;\n };\n }\n return _get.apply(this, arguments);\n}","import getPrototypeOf from \"./getPrototypeOf.js\";\nexport default function _superPropBase(object, property) {\n while (!Object.prototype.hasOwnProperty.call(object, property)) {\n object = getPrototypeOf(object);\n if (object === null) break;\n }\n return object;\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n Object.defineProperty(subClass, \"prototype\", {\n writable: false\n });\n if (superClass) setPrototypeOf(subClass, superClass);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n try {\n Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return self;\n}","import getPrototypeOf from \"./getPrototypeOf.js\";\nimport isNativeReflectConstruct from \"./isNativeReflectConstruct.js\";\nimport possibleConstructorReturn from \"./possibleConstructorReturn.js\";\nexport default function _createSuper(Derived) {\n var hasNativeReflectConstruct = isNativeReflectConstruct();\n return function _createSuperInternal() {\n var Super = getPrototypeOf(Derived),\n result;\n if (hasNativeReflectConstruct) {\n var NewTarget = getPrototypeOf(this).constructor;\n result = Reflect.construct(Super, arguments, NewTarget);\n } else {\n result = Super.apply(this, arguments);\n }\n return possibleConstructorReturn(this, result);\n };\n}","import _typeof from \"./typeof.js\";\nimport assertThisInitialized from \"./assertThisInitialized.js\";\nexport default function _possibleConstructorReturn(self, call) {\n if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) {\n return call;\n } else if (call !== void 0) {\n throw new TypeError(\"Derived constructors may only return object or undefined\");\n }\n return assertThisInitialized(self);\n}","import type { Options } from '@sentry/types';\nimport { SDK_VERSION } from '../version';\n\n/**\n * A builder for the SDK metadata in the options for the SDK initialization.\n *\n * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.\n * We don't extract it for bundle size reasons.\n * @see https://github.com/getsentry/sentry-javascript/pull/7404\n * @see https://github.com/getsentry/sentry-javascript/pull/4196\n *\n * If you make changes to this function consider updating the others as well.\n *\n * @param options SDK options object that gets mutated\n * @param names list of package names\n */\nexport function applySdkMetadata(options: Options, name: string, names = [name], source = 'npm'): void {\n const metadata = options._metadata || {};\n\n if (!metadata.sdk) {\n metadata.sdk = {\n name: `sentry.javascript.${name}`,\n packages: names.map(name => ({\n name: `${source}:@sentry/${name}`,\n version: SDK_VERSION,\n })),\n version: SDK_VERSION,\n };\n }\n\n options._metadata = metadata;\n}\n","import type {\n Attachment,\n AttachmentItem,\n BaseEnvelopeHeaders,\n BaseEnvelopeItemHeaders,\n DataCategory,\n DsnComponents,\n Envelope,\n EnvelopeItemType,\n Event,\n EventEnvelopeHeaders,\n SdkInfo,\n SdkMetadata,\n TextEncoderInternal,\n} from '@sentry/types';\n\nimport { dsnToString } from './dsn';\nimport { normalize } from './normalize';\nimport { dropUndefinedKeys } from './object';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function createEnvelope(headers: E[0], items: E[1] = []): E {\n return [headers, items] as E;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function addItemToEnvelope(envelope: E, newItem: E[1][number]): E {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] as unknown as E;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nexport function forEachEnvelopeItem(\n envelope: Envelope,\n callback: (envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type']) => boolean | void,\n): boolean {\n const envelopeItems = envelope[1];\n\n for (const envelopeItem of envelopeItems) {\n const envelopeItemType = envelopeItem[0].type;\n const result = callback(envelopeItem, envelopeItemType);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nexport function envelopeContainsItemType(envelope: Envelope, types: EnvelopeItemType[]): boolean {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8.\n */\nfunction encodeUTF8(input: string, textEncoder?: TextEncoderInternal): Uint8Array {\n const utf8 = textEncoder || new TextEncoder();\n return utf8.encode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nexport function serializeEnvelope(envelope: Envelope, textEncoder?: TextEncoderInternal): string | Uint8Array {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts: string | Uint8Array[] = JSON.stringify(envHeaders);\n\n function append(next: string | Uint8Array): void {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload: string;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers: Uint8Array[]): Uint8Array {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\nexport interface TextDecoderInternal {\n decode(input?: Uint8Array): string;\n}\n\n/**\n * Parses an envelope\n */\nexport function parseEnvelope(\n env: string | Uint8Array,\n textEncoder: TextEncoderInternal,\n textDecoder: TextDecoderInternal,\n): Envelope {\n let buffer = typeof env === 'string' ? textEncoder.encode(env) : env;\n\n function readBinary(length: number): Uint8Array {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson(): T {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(textDecoder.decode(readBinary(i))) as T;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items: [any, any][] = [];\n\n while (buffer.length) {\n const itemHeader = readJson();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates attachment envelope items\n */\nexport function createAttachmentEnvelopeItem(\n attachment: Attachment,\n textEncoder?: TextEncoderInternal,\n): AttachmentItem {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data;\n\n return [\n dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP: Record = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n feedback: 'feedback',\n span: 'span',\n statsd: 'metric_bucket',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nexport function envelopeItemTypeToDataCategory(type: EnvelopeItemType): DataCategory {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from the metadata or an events */\nexport function getSdkMetadataForEnvelopeHeader(metadataOrEvent?: SdkMetadata | Event): SdkInfo | undefined {\n if (!metadataOrEvent || !metadataOrEvent.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nexport function createEventEnvelopeHeaders(\n event: Event,\n sdkInfo: SdkInfo | undefined,\n tunnel: string | undefined,\n dsn?: DsnComponents,\n): EventEnvelopeHeaders {\n const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;\n return {\n event_id: event.event_id as string,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n","import setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeReflectConstruct from \"./isNativeReflectConstruct.js\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct.bind();\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n return _construct.apply(null, arguments);\n}","import getPrototypeOf from \"./getPrototypeOf.js\";\nimport setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeFunction from \"./isNativeFunction.js\";\nimport construct from \"./construct.js\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n _cache.set(Class, Wrapper);\n }\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","import type { ConsoleLevel } from '@sentry/types';\n\n/** An error emitted by Sentry SDKs and related utilities. */\nexport class SentryError extends Error {\n /** Display name of this error instance. */\n public name: string;\n\n public logLevel: ConsoleLevel;\n\n public constructor(public message: string, logLevel: ConsoleLevel = 'warn') {\n super(message);\n\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n","import type { DsnComponents, MetricBucketItem, SdkMetadata, StatsdEnvelope, StatsdItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\nimport { serializeMetricBuckets } from './utils';\n\n/**\n * Create envelope from a metric aggregate.\n */\nexport function createMetricEnvelope(\n metricBucketItems: Array,\n dsn?: DsnComponents,\n metadata?: SdkMetadata,\n tunnel?: string,\n): StatsdEnvelope {\n const headers: StatsdEnvelope[0] = {\n sent_at: new Date().toISOString(),\n };\n\n if (metadata && metadata.sdk) {\n headers.sdk = {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n };\n }\n\n if (!!tunnel && dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n const item = createMetricEnvelopeItem(metricBucketItems);\n return createEnvelope(headers, [item]);\n}\n\nfunction createMetricEnvelopeItem(metricBucketItems: MetricBucketItem[]): StatsdItem {\n const payload = serializeMetricBuckets(metricBucketItems);\n const metricHeaders: StatsdItem[0] = {\n type: 'statsd',\n length: payload.length,\n };\n return [metricHeaders, payload];\n}\n","import type { MeasurementUnit, MetricBucketItem, Primitive } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\nimport type { MetricType } from './types';\n\n/**\n * Generate bucket key from metric properties.\n */\nexport function getBucketKey(\n metricType: MetricType,\n name: string,\n unit: MeasurementUnit,\n tags: Record,\n): string {\n const stringifiedTags = Object.entries(dropUndefinedKeys(tags)).sort((a, b) => a[0].localeCompare(b[0]));\n return `${metricType}${name}${unit}${stringifiedTags}`;\n}\n\n/* eslint-disable no-bitwise */\n/**\n * Simple hash function for strings.\n */\nexport function simpleHash(s: string): number {\n let rv = 0;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n rv = (rv << 5) - rv + c;\n rv &= rv;\n }\n return rv >>> 0;\n}\n/* eslint-enable no-bitwise */\n\n/**\n * Serialize metrics buckets into a string based on statsd format.\n *\n * Example of format:\n * metric.name@second:1:1.2|d|#a:value,b:anothervalue|T12345677\n * Segments:\n * name: metric.name\n * unit: second\n * value: [1, 1.2]\n * type of metric: d (distribution)\n * tags: { a: value, b: anothervalue }\n * timestamp: 12345677\n */\nexport function serializeMetricBuckets(metricBucketItems: MetricBucketItem[]): string {\n let out = '';\n for (const item of metricBucketItems) {\n const tagEntries = Object.entries(item.tags);\n const maybeTags = tagEntries.length > 0 ? `|#${tagEntries.map(([key, value]) => `${key}:${value}`).join(',')}` : '';\n out += `${item.name}@${item.unit}:${item.metric}|${item.metricType}${maybeTags}|T${item.timestamp}\\n`;\n }\n return out;\n}\n\n/** Sanitizes units */\nexport function sanitizeUnit(unit: string): string {\n return unit.replace(/[^\\w]+/gi, '_');\n}\n\n/** Sanitizes metric keys */\nexport function sanitizeMetricKey(key: string): string {\n return key.replace(/[^\\w\\-.]+/gi, '_');\n}\n\nfunction sanitizeTagKey(key: string): string {\n return key.replace(/[^\\w\\-./]+/gi, '');\n}\n\nconst tagValueReplacements: [string, string][] = [\n ['\\n', '\\\\n'],\n ['\\r', '\\\\r'],\n ['\\t', '\\\\t'],\n ['\\\\', '\\\\\\\\'],\n ['|', '\\\\u{7c}'],\n [',', '\\\\u{2c}'],\n];\n\nfunction getCharOrReplacement(input: string): string {\n for (const [search, replacement] of tagValueReplacements) {\n if (input === search) {\n return replacement;\n }\n }\n\n return input;\n}\n\nfunction sanitizeTagValue(value: string): string {\n return [...value].reduce((acc, char) => acc + getCharOrReplacement(char), '');\n}\n\n/**\n * Sanitizes tags.\n */\nexport function sanitizeTags(unsanitizedTags: Record): Record {\n const tags: Record = {};\n for (const key in unsanitizedTags) {\n if (Object.prototype.hasOwnProperty.call(unsanitizedTags, key)) {\n const sanitizedKey = sanitizeTagKey(key);\n tags[sanitizedKey] = sanitizeTagValue(String(unsanitizedTags[key]));\n }\n }\n return tags;\n}\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n ClientOptions,\n DataCategory,\n DsnComponents,\n DynamicSamplingContext,\n Envelope,\n ErrorEvent,\n Event,\n EventDropReason,\n EventHint,\n EventProcessor,\n FeedbackEvent,\n Integration,\n IntegrationClass,\n MetricBucketItem,\n MetricsAggregator,\n Outcome,\n ParameterizedString,\n SdkMetadata,\n Session,\n SessionAggregates,\n Severity,\n SeverityLevel,\n StartSpanOptions,\n Transaction,\n TransactionEvent,\n Transport,\n TransportMakeRequestResponse,\n} from '@sentry/types';\nimport {\n SentryError,\n SyncPromise,\n addItemToEnvelope,\n checkOrSetAlreadyCaught,\n createAttachmentEnvelopeItem,\n isParameterizedString,\n isPlainObject,\n isPrimitive,\n isThenable,\n logger,\n makeDsn,\n rejectedSyncPromise,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from './api';\nimport { DEBUG_BUILD } from './debug-build';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope';\nimport { getClient } from './exports';\nimport { getIsolationScope } from './hub';\nimport type { IntegrationIndex } from './integration';\nimport { afterSetupIntegrations } from './integration';\nimport { setupIntegration, setupIntegrations } from './integration';\nimport { createMetricEnvelope } from './metrics/envelope';\nimport type { Scope } from './scope';\nimport { updateSession } from './session';\nimport { getDynamicSamplingContextFromClient } from './tracing/dynamicSamplingContext';\nimport { prepareEvent } from './utils/prepareEvent';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nexport abstract class BaseClient implements Client {\n /**\n * A reference to a metrics aggregator\n *\n * @experimental Note this is alpha API. It may experience breaking changes in the future.\n */\n public metricsAggregator?: MetricsAggregator;\n\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n protected readonly _dsn?: DsnComponents;\n\n protected readonly _transport?: Transport;\n\n /** Array of set up integrations. */\n protected _integrations: IntegrationIndex;\n\n /** Indicates whether this client's integrations have been set up. */\n protected _integrationsInitialized: boolean;\n\n /** Number of calls being processed */\n protected _numProcessing: number;\n\n protected _eventProcessors: EventProcessor[];\n\n /** Holds flushable */\n private _outcomes: { [key: string]: number };\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n private _hooks: Record;\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n protected constructor(options: O) {\n this._options = options;\n this._integrations = {};\n this._integrationsInitialized = false;\n this._numProcessing = 0;\n this._outcomes = {};\n this._hooks = {};\n this._eventProcessors = [];\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n DEBUG_BUILD && logger.warn('No DSN provided, client will not send events.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);\n this._transport = options.transport({\n tunnel: this._options.tunnel,\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this.eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n scope?: Scope,\n ): string | undefined {\n let eventId: string | undefined = hint && hint.event_id;\n\n const eventMessage = isParameterizedString(message) ? message : String(message);\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(eventMessage, level, hint)\n : this.eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanScope: Scope | undefined = sdkProcessingMetadata.capturedSpanScope;\n\n this._process(\n this._captureEvent(event, hint, capturedSpanScope || scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(session: Session): void {\n if (!(typeof session.release === 'string')) {\n DEBUG_BUILD && logger.warn('Discarded session because of missing or non-string release');\n } else {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n public getDsn(): DsnComponents | undefined {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n public getOptions(): O {\n return this._options;\n }\n\n /**\n * @see SdkMetadata in @sentry/types\n *\n * @return The metadata of the SDK\n */\n public getSdkMetadata(): SdkMetadata | undefined {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport | undefined {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n public flush(timeout?: number): PromiseLike {\n const transport = this._transport;\n if (transport) {\n if (this.metricsAggregator) {\n this.metricsAggregator.flush();\n }\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return resolvedSyncPromise(true);\n }\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n if (this.metricsAggregator) {\n this.metricsAggregator.close();\n }\n return result;\n });\n }\n\n /** Get all installed event processors. */\n public getEventProcessors(): EventProcessor[] {\n return this._eventProcessors;\n }\n\n /** @inheritDoc */\n public addEventProcessor(eventProcessor: EventProcessor): void {\n this._eventProcessors.push(eventProcessor);\n }\n\n /**\n * This is an internal function to setup all integrations that should run on the client.\n * @deprecated Use `client.init()` instead.\n */\n public setupIntegrations(forceInitialize?: boolean): void {\n if ((forceInitialize && !this._integrationsInitialized) || (this._isEnabled() && !this._integrationsInitialized)) {\n this._setupIntegrations();\n }\n }\n\n /** @inheritdoc */\n public init(): void {\n if (this._isEnabled()) {\n this._setupIntegrations();\n }\n }\n\n /**\n * Gets an installed integration by its `id`.\n *\n * @returns The installed integration or `undefined` if no integration with that `id` was installed.\n * @deprecated Use `getIntegrationByName()` instead.\n */\n public getIntegrationById(integrationId: string): Integration | undefined {\n return this.getIntegrationByName(integrationId);\n }\n\n /**\n * Gets an installed integration by its name.\n *\n * @returns The installed integration or `undefined` if no integration with that `name` was installed.\n */\n public getIntegrationByName(integrationName: string): T | undefined {\n return this._integrations[integrationName] as T | undefined;\n }\n\n /**\n * Returns the client's instance of the given integration class, it any.\n * @deprecated Use `getIntegrationByName()` instead.\n */\n public getIntegration(integration: IntegrationClass): T | null {\n try {\n return (this._integrations[integration.id] as T) || null;\n } catch (_oO) {\n DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public addIntegration(integration: Integration): void {\n const isAlreadyInstalled = this._integrations[integration.name];\n\n // This hook takes care of only installing if not already installed\n setupIntegration(this, integration, this._integrations);\n // Here we need to check manually to make sure to not run this multiple times\n if (!isAlreadyInstalled) {\n afterSetupIntegrations(this, [integration]);\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event, hint: EventHint = {}): void {\n this.emit('beforeSendEvent', event, hint);\n\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(\n env,\n createAttachmentEnvelopeItem(\n attachment,\n this._options.transportOptions && this._options.transportOptions.textEncoder,\n ),\n );\n }\n\n const promise = this._sendEnvelope(env);\n if (promise) {\n promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null);\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session | SessionAggregates): void {\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(env);\n }\n\n /**\n * @inheritDoc\n */\n public recordDroppedEvent(reason: EventDropReason, category: DataCategory, eventOrCount?: Event | number): void {\n if (this._options.sendClientReports) {\n // TODO v9: We do not need the `event` passed as third argument anymore, and can possibly remove this overload\n // If event is passed as third argument, we assume this is a count of 1\n const count = typeof eventOrCount === 'number' ? eventOrCount : 1;\n\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n DEBUG_BUILD && logger.log(`Recording outcome: \"${key}\"${count > 1 ? ` (${count} times)` : ''}`);\n this._outcomes[key] = (this._outcomes[key] || 0) + count;\n }\n }\n\n /**\n * @inheritDoc\n */\n public captureAggregateMetrics(metricBucketItems: Array): void {\n DEBUG_BUILD && logger.log(`Flushing aggregated metrics, number of metrics: ${metricBucketItems.length}`);\n const metricsEnvelope = createMetricEnvelope(\n metricBucketItems,\n this._dsn,\n this._options._metadata,\n this._options.tunnel,\n );\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(metricsEnvelope);\n }\n\n // Keep on() & emit() signatures in sync with types' client.ts interface\n /* eslint-disable @typescript-eslint/unified-signatures */\n\n /** @inheritdoc */\n public on(hook: 'startTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'finishTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeEnvelope', callback: (envelope: Envelope) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeSendEvent', callback: (event: Event, hint?: EventHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'preprocessEvent', callback: (event: Event, hint?: EventHint) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'afterSendEvent',\n callback: (event: Event, sendResponse: TransportMakeRequestResponse | void) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'otelSpanEnd', callback: (otelSpan: unknown, mutableOptions: { drop: boolean }) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'beforeSendFeedback',\n callback: (feedback: FeedbackEvent, options?: { includeReplay: boolean }) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'startPageLoadSpan', callback: (options: StartSpanOptions) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'startNavigationSpan', callback: (options: StartSpanOptions) => void): void;\n\n /** @inheritdoc */\n public on(hook: string, callback: unknown): void {\n if (!this._hooks[hook]) {\n this._hooks[hook] = [];\n }\n\n // @ts-expect-error We assue the types are correct\n this._hooks[hook].push(callback);\n }\n\n /** @inheritdoc */\n public emit(hook: 'startTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'finishTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeEnvelope', envelope: Envelope): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeSendEvent', event: Event, hint?: EventHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'preprocessEvent', event: Event, hint?: EventHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'afterSendEvent', event: Event, sendResponse: TransportMakeRequestResponse | void): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;\n\n /** @inheritdoc */\n public emit(hook: 'otelSpanEnd', otelSpan: unknown, mutableOptions: { drop: boolean }): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay: boolean }): void;\n\n /** @inheritdoc */\n public emit(hook: 'startPageLoadSpan', options: StartSpanOptions): void;\n\n /** @inheritdoc */\n public emit(hook: 'startNavigationSpan', options: StartSpanOptions): void;\n\n /** @inheritdoc */\n public emit(hook: string, ...rest: unknown[]): void {\n if (this._hooks[hook]) {\n this._hooks[hook].forEach(callback => callback(...rest));\n }\n }\n\n /* eslint-enable @typescript-eslint/unified-signatures */\n\n /** Setup integrations for this client. */\n protected _setupIntegrations(): void {\n const { integrations } = this._options;\n this._integrations = setupIntegrations(this, integrations);\n afterSetupIntegrations(this, integrations);\n\n // TODO v8: We don't need this flag anymore\n this._integrationsInitialized = true;\n }\n\n /** Updates existing session based on the provided event */\n protected _updateSessionFromEvent(session: Session, event: Event): void {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n protected _isClientDoneProcessing(timeout?: number): PromiseLike {\n return new SyncPromise(resolve => {\n let ticked: number = 0;\n const tick: number = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Determines whether this SDK is enabled and a transport is present. */\n protected _isEnabled(): boolean {\n return this.getOptions().enabled !== false && this._transport !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n protected _prepareEvent(\n event: Event,\n hint: EventHint,\n scope?: Scope,\n isolationScope = getIsolationScope(),\n ): PromiseLike {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n\n this.emit('preprocessEvent', event, hint);\n\n return prepareEvent(options, event, hint, scope, this, isolationScope).then(evt => {\n if (evt === null) {\n return evt;\n }\n\n const propagationContext = {\n ...isolationScope.getPropagationContext(),\n ...(scope ? scope.getPropagationContext() : undefined),\n };\n\n const trace = evt.contexts && evt.contexts.trace;\n if (!trace && propagationContext) {\n const { traceId: trace_id, spanId, parentSpanId, dsc } = propagationContext;\n evt.contexts = {\n trace: {\n trace_id,\n span_id: spanId,\n parent_span_id: parentSpanId,\n },\n ...evt.contexts,\n };\n\n const dynamicSamplingContext = dsc ? dsc : getDynamicSamplingContextFromClient(trace_id, this, scope);\n\n evt.sdkProcessingMetadata = {\n dynamicSamplingContext,\n ...evt.sdkProcessingMetadata,\n };\n }\n return evt;\n });\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n protected _captureEvent(event: Event, hint: EventHint = {}, scope?: Scope): PromiseLike {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if (DEBUG_BUILD) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n const sentryError = reason as SentryError;\n if (sentryError.logLevel === 'log') {\n logger.log(sentryError.message);\n } else {\n logger.warn(sentryError);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n protected _processEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n this.recordDroppedEvent('sample_rate', 'error', event);\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory: DataCategory = eventType === 'replay_event' ? 'replay' : eventType;\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanIsolationScope: Scope | undefined = sdkProcessingMetadata.capturedSpanIsolationScope;\n\n return this._prepareEvent(event, hint, scope, capturedSpanIsolationScope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\n throw new SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data as { __sentry__: boolean }).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory, event);\n if (isTransaction) {\n const spans = event.spans || [];\n // the transaction itself counts as one span, plus all the child spans that are added\n const spanCount = 1 + spans.length;\n this.recordDroppedEvent('before_send', 'span', spanCount);\n }\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = scope && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n if (isTransaction) {\n const spanCountBefore =\n (processedEvent.sdkProcessingMetadata && processedEvent.sdkProcessingMetadata.spanCountBeforeProcessing) ||\n 0;\n const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0;\n\n const droppedSpanCount = spanCountBefore - spanCountAfter;\n if (droppedSpanCount > 0) {\n this.recordDroppedEvent('before_send', 'span', droppedSpanCount);\n }\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n protected _process(promise: PromiseLike): void {\n this._numProcessing++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * @inheritdoc\n */\n protected _sendEnvelope(envelope: Envelope): PromiseLike | void {\n this.emit('beforeEnvelope', envelope);\n\n if (this._isEnabled() && this._transport) {\n return this._transport.send(envelope).then(null, reason => {\n DEBUG_BUILD && logger.error('Error while sending event:', reason);\n });\n } else {\n DEBUG_BUILD && logger.error('Transport disabled');\n }\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n protected _clearOutcomes(): Outcome[] {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.keys(outcomes).map(key => {\n const [reason, category] = key.split(':') as [EventDropReason, DataCategory];\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n });\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public abstract eventFromException(_exception: any, _hint?: EventHint): PromiseLike;\n\n /**\n * @inheritDoc\n */\n public abstract eventFromMessage(\n _message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n _level?: Severity | SeverityLevel,\n _hint?: EventHint,\n ): PromiseLike;\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult: PromiseLike | Event | null,\n beforeSendLabel: string,\n): PromiseLike | Event | null {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw new SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n): PromiseLike | Event | null {\n const { beforeSend, beforeSendTransaction } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event) && beforeSendTransaction) {\n if (event.spans) {\n // We store the # of spans before processing in SDK metadata,\n // so we can compare it afterwards to determine how many spans were dropped\n const spanCountBefore = event.spans.length;\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n spanCountBeforeProcessing: spanCountBefore,\n };\n }\n return beforeSendTransaction(event, hint);\n }\n\n return event;\n}\n\nfunction isErrorEvent(event: Event): event is ErrorEvent {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n\n/**\n * Add an event processor to the current client.\n * This event processor will run for all events processed by this client.\n */\nexport function addEventProcessor(callback: EventProcessor): void {\n const client = getClient();\n\n if (!client || !client.addEventProcessor) {\n return;\n }\n\n client.addEventProcessor(callback);\n}\n","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","import { getClient } from '@sentry/core';\nimport type {\n Event,\n EventHint,\n Exception,\n ParameterizedString,\n Severity,\n SeverityLevel,\n StackFrame,\n StackParser,\n} from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n extractExceptionKeysForMessage,\n isDOMError,\n isDOMException,\n isError,\n isErrorEvent,\n isEvent,\n isParameterizedString,\n isPlainObject,\n normalizeToSize,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n\n/**\n * This function creates an exception from a JavaScript Error\n */\nexport function exceptionFromError(stackParser: StackParser, ex: Error): Exception {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(stackParser, ex);\n\n const exception: Exception = {\n type: ex && ex.name,\n value: extractMessage(ex),\n };\n\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\n/**\n * @hidden\n */\nexport function eventFromPlainObject(\n stackParser: StackParser,\n exception: Record,\n syntheticException?: Error,\n isUnhandledRejection?: boolean,\n): Event {\n const client = getClient();\n const normalizeDepth = client && client.getOptions().normalizeDepth;\n\n const event: Event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }),\n },\n ],\n },\n extra: {\n __serialized__: normalizeToSize(exception, normalizeDepth),\n },\n };\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n (event.exception as { values: Exception[] }).values[0].stacktrace = { frames };\n }\n }\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromError(stackParser: StackParser, ex: Error): Event {\n return {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nexport function parseStackFrames(\n stackParser: StackParser,\n ex: Error & { framesToPop?: number; stacktrace?: string },\n): StackFrame[] {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const popSize = getPopSize(ex);\n\n try {\n return stackParser(stacktrace, popSize);\n } catch (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\nfunction getPopSize(ex: Error & { framesToPop?: number }): number {\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n if (reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n }\n\n return 0;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\nfunction extractMessage(ex: Error & { message: { error?: Error } }): string {\n const message = ex && ex.message;\n if (!message) {\n return 'No error message';\n }\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n return message;\n}\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nexport function eventFromException(\n stackParser: StackParser,\n exception: unknown,\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = 'error';\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nexport function eventFromMessage(\n stackParser: StackParser,\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nexport function eventFromUnknownInput(\n stackParser: StackParser,\n exception: unknown,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n isUnhandledRejection?: boolean,\n): Event {\n let event: Event;\n\n if (isErrorEvent(exception as ErrorEvent) && (exception as ErrorEvent).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception as ErrorEvent;\n return eventFromError(stackParser, errorEvent.error as Error);\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception) || isDOMException(exception as DOMException)) {\n const domException = exception as DOMException;\n\n if ('stack' in (exception as Error)) {\n event = eventFromError(stackParser, exception as Error);\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n // eslint-disable-next-line deprecation/deprecation\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception)) {\n // we have a real Error object, do nothing\n return eventFromError(stackParser, exception);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception as Record;\n event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(stackParser, exception as string, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromString(\n stackParser: StackParser,\n message: ParameterizedString,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n): Event {\n const event: Event = {};\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n event.exception = {\n values: [{ value: message, stacktrace: { frames } }],\n };\n }\n }\n\n if (isParameterizedString(message)) {\n const { __sentry_template_string__, __sentry_template_values__ } = message;\n\n event.logentry = {\n message: __sentry_template_string__,\n params: __sentry_template_values__,\n };\n return event;\n }\n\n event.message = message;\n return event;\n}\n\nfunction getNonErrorObjectExceptionValue(\n exception: Record,\n { isUnhandledRejection }: { isUnhandledRejection?: boolean },\n): string {\n const keys = extractExceptionKeysForMessage(exception);\n const captureType = isUnhandledRejection ? 'promise rejection' : 'exception';\n\n // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before\n // We still want to try to get a decent message for these cases\n if (isErrorEvent(exception)) {\n return `Event \\`ErrorEvent\\` captured as ${captureType} with message \\`${exception.message}\\``;\n }\n\n if (isEvent(exception)) {\n const className = getObjectClassName(exception);\n return `Event \\`${className}\\` (type=${exception.type}) captured as ${captureType}`;\n }\n\n return `Object captured as ${captureType} with keys: ${keys}`;\n}\n\nfunction getObjectClassName(obj: unknown): string | undefined | void {\n try {\n const prototype: Prototype | null = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : undefined;\n } catch (e) {\n // ignore errors here\n }\n}\n","import type { browserTracingIntegration } from '@sentry-internal/tracing';\nimport { BrowserTracing } from '@sentry-internal/tracing';\nimport { captureException, withScope } from '@sentry/core';\nimport type { DsnLike, Integration, Mechanism, WrappedFunction } from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n addExceptionMechanism,\n addExceptionTypeValue,\n addNonEnumerableProperty,\n getOriginalFunction,\n markFunctionWrapped,\n} from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nlet ignoreOnError: number = 0;\n\n/**\n * @hidden\n */\nexport function shouldIgnoreOnError(): boolean {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nexport function ignoreNextOnError(): void {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nexport function wrap(\n fn: WrappedFunction,\n options: {\n mechanism?: Mechanism;\n } = {},\n before?: WrappedFunction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n if (typeof fn !== 'function') {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = fn.__sentry_wrapped__;\n if (wrapper) {\n return wrapper;\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n /* eslint-disable prefer-rest-params */\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped: WrappedFunction = function (this: unknown): void {\n const args = Array.prototype.slice.call(arguments);\n\n try {\n if (before && typeof before === 'function') {\n before.apply(this, arguments);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n const wrappedArguments = args.map((arg: any) => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n captureException(ex);\n });\n\n throw ex;\n }\n };\n /* eslint-enable prefer-rest-params */\n\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property] = fn[property];\n }\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name') as PropertyDescriptor;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get(): string {\n return fn.name;\n },\n });\n }\n // eslint-disable-next-line no-empty\n } catch (_oO) {}\n\n return sentryWrapped;\n}\n\n/**\n * All properties the report dialog supports\n *\n * @deprecated This type will be removed in the next major version of the Sentry SDK. `showReportDialog` will still be around, however the `eventId` option will now be required.\n */\nexport interface ReportDialogOptions {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n eventId?: string;\n dsn?: DsnLike;\n user?: {\n email?: string;\n name?: string;\n };\n lang?: string;\n title?: string;\n subtitle?: string;\n subtitle2?: string;\n labelName?: string;\n labelEmail?: string;\n labelComments?: string;\n labelClose?: string;\n labelSubmit?: string;\n errorGeneric?: string;\n errorFormEntry?: string;\n successMessage?: string;\n /** Callback after reportDialog showed up */\n onLoad?(this: void): void;\n /** Callback after reportDialog closed */\n onClose?(this: void): void;\n}\n\n/**\n * This is a slim shim of `browserTracingIntegration` for the CDN bundles.\n * Since the actual functional integration uses a different code from `BrowserTracing`,\n * we want to avoid shipping both of them in the CDN bundles, as that would blow up the size.\n * Instead, we provide a functional integration with the same API, but the old implementation.\n * This means that it's not possible to register custom routing instrumentation, but that's OK for now.\n * We also don't expose the utilities for this anyhow in the CDN bundles.\n * For users that need custom routing in CDN bundles, they have to continue using `new BrowserTracing()` until v8.\n */\nexport function bundleBrowserTracingIntegration(\n options: Parameters[0] = {},\n): Integration {\n // Migrate some options from the old integration to the new one\n // eslint-disable-next-line deprecation/deprecation\n const opts: ConstructorParameters[0] = options;\n\n if (typeof options.markBackgroundSpan === 'boolean') {\n opts.markBackgroundTransactions = options.markBackgroundSpan;\n }\n\n if (typeof options.instrumentPageLoad === 'boolean') {\n opts.startTransactionOnPageLoad = options.instrumentPageLoad;\n }\n\n if (typeof options.instrumentNavigation === 'boolean') {\n opts.startTransactionOnLocationChange = options.instrumentNavigation;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return new BrowserTracing(opts);\n}\n","import type { Scope } from '@sentry/core';\nimport { applySdkMetadata } from '@sentry/core';\nimport { BaseClient } from '@sentry/core';\nimport type {\n BrowserClientProfilingOptions,\n BrowserClientReplayOptions,\n ClientOptions,\n Event,\n EventHint,\n Options,\n ParameterizedString,\n Severity,\n SeverityLevel,\n UserFeedback,\n} from '@sentry/types';\nimport { createClientReportEnvelope, dsnToString, getSDKSource, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { WINDOW } from './helpers';\nimport type { BrowserTransportOptions } from './transports/types';\nimport { createUserFeedbackEnvelope } from './userfeedback';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/types Options for more information.\n */\nexport type BrowserOptions = Options &\n BrowserClientReplayOptions &\n BrowserClientProfilingOptions;\n\n/**\n * Configuration options for the Sentry Browser SDK Client class\n * @see BrowserClient for more information.\n */\nexport type BrowserClientOptions = ClientOptions &\n BrowserClientReplayOptions &\n BrowserClientProfilingOptions;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class BrowserClient extends BaseClient {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n public constructor(options: BrowserClientOptions) {\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n applySdkMetadata(options, 'browser', ['browser'], sdkSource);\n\n super(options);\n\n if (options.sendClientReports && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * Sends user feedback to Sentry.\n */\n public captureUserFeedback(feedback: UserFeedback): void {\n if (!this._isEnabled()) {\n DEBUG_BUILD && logger.warn('SDK not enabled, will not capture user feedback.');\n return;\n }\n\n const envelope = createUserFeedbackEnvelope(feedback, {\n metadata: this.getSdkMetadata(),\n dsn: this.getDsn(),\n tunnel: this.getOptions().tunnel,\n });\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(envelope);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, hint, scope);\n }\n\n /**\n * Sends client reports as an envelope.\n */\n private _flushOutcomes(): void {\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n DEBUG_BUILD && logger.log('No outcomes to send');\n return;\n }\n\n // This is really the only place where we want to check for a DSN and only send outcomes then\n if (!this._dsn) {\n DEBUG_BUILD && logger.log('No dsn provided, will not send outcomes');\n return;\n }\n\n DEBUG_BUILD && logger.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(envelope);\n }\n}\n","import type { DsnComponents, EventEnvelope, SdkMetadata, UserFeedback, UserFeedbackItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\n\n/**\n * Creates an envelope from a user feedback.\n */\nexport function createUserFeedbackEnvelope(\n feedback: UserFeedback,\n {\n metadata,\n tunnel,\n dsn,\n }: {\n metadata: SdkMetadata | undefined;\n tunnel: string | undefined;\n dsn: DsnComponents | undefined;\n },\n): EventEnvelope {\n const headers: EventEnvelope[0] = {\n event_id: feedback.event_id,\n sent_at: new Date().toISOString(),\n ...(metadata &&\n metadata.sdk && {\n sdk: {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n },\n }),\n ...(!!tunnel && !!dsn && { dsn: dsnToString(dsn) }),\n };\n const item = createUserFeedbackEnvelopeItem(feedback);\n\n return createEnvelope(headers, [item]);\n}\n\nfunction createUserFeedbackEnvelopeItem(feedback: UserFeedback): UserFeedbackItem {\n const feedbackHeaders: UserFeedbackItem[0] = {\n type: 'user_report',\n };\n return [feedbackHeaders, feedback];\n}\n","import type { ClientReport, ClientReportEnvelope, ClientReportItem } from '@sentry/types';\n\nimport { createEnvelope } from './envelope';\nimport { dateTimestampInSeconds } from './time';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nexport function createClientReportEnvelope(\n discarded_events: ClientReport['discarded_events'],\n dsn?: string,\n timestamp?: number,\n): ClientReportEnvelope {\n const clientReportItem: ClientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { ConsoleLevel, HandlerDataConsole } from '@sentry/types';\n\nimport { CONSOLE_LEVELS, originalConsoleMethods } from '../logger';\nimport { fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\n/**\n * Add an instrumentation handler for when a console.xxx method is called.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addConsoleInstrumentationHandler(handler: (data: HandlerDataConsole) => void): void {\n const type = 'console';\n addHandler(type, handler);\n maybeInstrument(type, instrumentConsole);\n}\n\nfunction instrumentConsole(): void {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level: ConsoleLevel): void {\n if (!(level in GLOBAL_OBJ.console)) {\n return;\n }\n\n fill(GLOBAL_OBJ.console, level, function (originalConsoleMethod: () => any): Function {\n originalConsoleMethods[level] = originalConsoleMethod;\n\n return function (...args: any[]): void {\n const handlerData: HandlerDataConsole = { args, level };\n triggerHandlers('console', handlerData);\n\n const log = originalConsoleMethods[level];\n log && log.apply(GLOBAL_OBJ.console, args);\n };\n });\n });\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataDom } from '@sentry/types';\n\nimport { uuid4 } from '../misc';\nimport { addNonEnumerableProperty, fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\ntype SentryWrappedTarget = HTMLElement & { _sentryId?: string };\n\ntype AddEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n) => void;\ntype RemoveEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n) => void;\n\ntype InstrumentedElement = Element & {\n __sentry_instrumentation_handlers__?: {\n [key in 'click' | 'keypress']?: {\n handler?: Function;\n /** The number of custom listeners attached to this element */\n refCount: number;\n };\n };\n};\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\nconst DEBOUNCE_DURATION = 1000;\n\nlet debounceTimerID: number | undefined;\nlet lastCapturedEventType: string | undefined;\nlet lastCapturedEventTargetId: string | undefined;\n\n/**\n * Add an instrumentation handler for when a click or a keypress happens.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addClickKeypressInstrumentationHandler(handler: (data: HandlerDataDom) => void): void {\n const type = 'dom';\n addHandler(type, handler);\n maybeInstrument(type, instrumentDOM);\n}\n\n/** Exported for tests only. */\nexport function instrumentDOM(): void {\n if (!WINDOW.document) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (WINDOW as any)[target] && (WINDOW as any)[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener: AddEventListener): AddEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): AddEventListener {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener: RemoveEventListener): RemoveEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\n/**\n * Check whether the event is similar to the last captured one. For example, two click events on the same button.\n */\nfunction isSimilarToLastCapturedEvent(event: Event): boolean {\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (event.type !== lastCapturedEventType) {\n return false;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (!event.target || (event.target as SentryWrappedTarget)._sentryId !== lastCapturedEventTargetId) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return true;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(eventType: string, target: SentryWrappedTarget | null): boolean {\n // We are only interested in filtering `keypress` events for now.\n if (eventType !== 'keypress') {\n return false;\n }\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n */\nfunction makeDOMEventHandler(\n handler: (data: HandlerDataDom) => void,\n globalListener: boolean = false,\n): (event: Event) => void {\n return (event: Event & { _sentryCaptured?: true }): void => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || event['_sentryCaptured']) {\n return;\n }\n\n const target = getEventTarget(event);\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event.type, target)) {\n return;\n }\n\n // Mark event as \"seen\"\n addNonEnumerableProperty(event, '_sentryCaptured', true);\n\n if (target && !target._sentryId) {\n // Add UUID to event target so we can identify if\n addNonEnumerableProperty(target, '_sentryId', uuid4());\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no last captured event, it means that we can safely capture the new event and store it for future comparisons.\n // If there is a last captured event, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n if (!isSimilarToLastCapturedEvent(event)) {\n const handlerData: HandlerDataDom = { event, name, global: globalListener };\n handler(handlerData);\n lastCapturedEventType = event.type;\n lastCapturedEventTargetId = target ? target._sentryId : undefined;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n lastCapturedEventTargetId = undefined;\n lastCapturedEventType = undefined;\n }, DEBOUNCE_DURATION);\n };\n}\n\nfunction getEventTarget(event: Event): SentryWrappedTarget | null {\n try {\n return event.target as SentryWrappedTarget | null;\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n return null;\n }\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataXhr, SentryWrappedXMLHttpRequest, WrappedFunction } from '@sentry/types';\n\nimport { isString } from '../is';\nimport { fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nexport const SENTRY_XHR_DATA_KEY = '__sentry_xhr_v3__';\n\n/**\n * Add an instrumentation handler for when an XHR request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addXhrInstrumentationHandler(handler: (data: HandlerDataXhr) => void): void {\n const type = 'xhr';\n addHandler(type, handler);\n maybeInstrument(type, instrumentXHR);\n}\n\n/** Exported only for tests. */\nexport function instrumentXHR(): void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (!(WINDOW as any).XMLHttpRequest) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const startTimestamp = Date.now();\n\n // open() should always be called with two or more arguments\n // But to be on the safe side, we actually validate this and bail out if we don't have a method & url\n const method = isString(args[0]) ? args[0].toUpperCase() : undefined;\n const url = parseUrl(args[1]);\n\n if (!method || !url) {\n return originalOpen.apply(this, args);\n }\n\n this[SENTRY_XHR_DATA_KEY] = {\n method,\n url,\n request_headers: {},\n };\n\n // if Sentry key appears in URL, don't capture it as a request\n if (method === 'POST' && url.match(/sentry_key/)) {\n this.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler: () => void = () => {\n // For whatever reason, this is not the same instance here as from the outer method\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (this.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = this.status;\n } catch (e) {\n /* do nothing */\n }\n\n const handlerData: HandlerDataXhr = {\n args: [method, url],\n endTimestamp: Date.now(),\n startTimestamp,\n xhr: this,\n };\n triggerHandlers('xhr', handlerData);\n }\n };\n\n if ('onreadystatechange' in this && typeof this.onreadystatechange === 'function') {\n fill(this, 'onreadystatechange', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...readyStateArgs: any[]): void {\n onreadystatechangeHandler();\n return original.apply(this, readyStateArgs);\n };\n });\n } else {\n this.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n fill(this, 'setRequestHeader', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...setRequestHeaderArgs: unknown[]): void {\n const [header, value] = setRequestHeaderArgs;\n\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo && isString(header) && isString(value)) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return original.apply(this, setRequestHeaderArgs);\n };\n });\n\n return originalOpen.apply(this, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const sentryXhrData = this[SENTRY_XHR_DATA_KEY];\n\n if (!sentryXhrData) {\n return originalSend.apply(this, args);\n }\n\n if (args[0] !== undefined) {\n sentryXhrData.body = args[0];\n }\n\n const handlerData: HandlerDataXhr = {\n args: [sentryXhrData.method, sentryXhrData.url],\n startTimestamp: Date.now(),\n xhr: this,\n };\n triggerHandlers('xhr', handlerData);\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nfunction parseUrl(url: string | unknown): string | undefined {\n if (isString(url)) {\n return url;\n }\n\n try {\n // url can be a string or URL\n // but since URL is not available in IE11, we do not check for it,\n // but simply assume it is an URL and return `toString()` from it (which returns the full URL)\n // If that fails, we just return undefined\n return (url as URL).toString();\n } catch {} // eslint-disable-line no-empty\n\n return undefined;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataFetch } from '@sentry/types';\n\nimport { fill } from '../object';\nimport { supportsNativeFetch } from '../supports';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\ntype FetchResource = string | { toString(): string } | { url: string };\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addFetchInstrumentationHandler(handler: (data: HandlerDataFetch) => void): void {\n const type = 'fetch';\n addHandler(type, handler);\n maybeInstrument(type, instrumentFetch);\n}\n\nfunction instrumentFetch(): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(GLOBAL_OBJ, 'fetch', function (originalFetch: () => void): () => void {\n return function (...args: any[]): void {\n const { method, url } = parseFetchArgs(args);\n\n const handlerData: HandlerDataFetch = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(GLOBAL_OBJ, args).then(\n (response: Response) => {\n const finishedHandlerData: HandlerDataFetch = {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n };\n\n triggerHandlers('fetch', finishedHandlerData);\n return response;\n },\n (error: Error) => {\n const erroredHandlerData: HandlerDataFetch = {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n };\n\n triggerHandlers('fetch', erroredHandlerData);\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\nfunction hasProp(obj: unknown, prop: T): obj is Record {\n return !!obj && typeof obj === 'object' && !!(obj as Record)[prop];\n}\n\nfunction getUrlFromResource(resource: FetchResource): string {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request.\n * Exported for tests only.\n */\nexport function parseFetchArgs(fetchArgs: unknown[]): { method: string; url: string } {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [url, options] = fetchArgs as [FetchResource, object];\n\n return {\n url: getUrlFromResource(url),\n method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg as FetchResource),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n","/* eslint-disable deprecation/deprecation */\nimport type { Severity, SeverityLevel } from '@sentry/types';\n\n// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either\n//\n// a) moving `validSeverityLevels` to `@sentry/types`,\n// b) moving the`SeverityLevel` type here, or\n// c) importing `validSeverityLevels` from here into `@sentry/types`.\n//\n// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would\n// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the\n// type, reminding anyone who changes it to change this list also, will have to do.\n\nexport const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\n\n/**\n * Converts a string-based level into a member of the deprecated {@link Severity} enum.\n *\n * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead.\n *\n * @param level String representation of Severity\n * @returns Severity\n */\nexport function severityFromString(level: Severity | SeverityLevel | string): Severity {\n return severityLevelFromString(level) as Severity;\n}\n\n/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nexport function severityLevelFromString(level: SeverityLevel | string): SeverityLevel {\n return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') as SeverityLevel;\n}\n","type PartialURL = {\n host?: string;\n path?: string;\n protocol?: string;\n relative?: string;\n search?: string;\n hash?: string;\n};\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nexport function parseUrl(url: string): PartialURL {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n search: query,\n hash: fragment,\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nexport function stripUrlQueryAndFragment(urlPath: string): string {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Returns number of URL segments of a passed string URL.\n */\nexport function getNumberOfUrlSegments(url: string): number {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span description\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nexport function getSanitizedUrlString(url: PartialURL): string {\n const { protocol, host, path } = url;\n\n const filteredHost =\n (host &&\n host\n // Always filter out authority\n .replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n // TODO: Use new URL global if it exists\n .replace(/(:80)$/, '')\n .replace(/(:443)$/, '')) ||\n '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n","/* eslint-disable max-lines */\nimport { addBreadcrumb, convertIntegrationFnToClass, defineIntegration, getClient } from '@sentry/core';\nimport type {\n Client,\n Event as SentryEvent,\n HandlerDataConsole,\n HandlerDataDom,\n HandlerDataFetch,\n HandlerDataHistory,\n HandlerDataXhr,\n Integration,\n IntegrationClass,\n IntegrationFn,\n} from '@sentry/types';\nimport type {\n Breadcrumb,\n FetchBreadcrumbData,\n FetchBreadcrumbHint,\n XhrBreadcrumbData,\n XhrBreadcrumbHint,\n} from '@sentry/types/build/types/breadcrumb';\nimport {\n SENTRY_XHR_DATA_KEY,\n addClickKeypressInstrumentationHandler,\n addConsoleInstrumentationHandler,\n addFetchInstrumentationHandler,\n addHistoryInstrumentationHandler,\n addXhrInstrumentationHandler,\n getComponentName,\n getEventDescription,\n htmlTreeAsString,\n logger,\n parseUrl,\n safeJoin,\n severityLevelFromString,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\ninterface BreadcrumbsOptions {\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n}\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\nconst INTEGRATION_NAME = 'Breadcrumbs';\n\nconst _breadcrumbsIntegration = ((options: Partial = {}) => {\n const _options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n setup(client) {\n if (_options.console) {\n addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(client));\n }\n if (_options.dom) {\n addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom));\n }\n if (_options.xhr) {\n addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(client));\n }\n if (_options.fetch) {\n addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(client));\n }\n if (_options.history) {\n addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(client));\n }\n if (_options.sentry && client.on) {\n client.on('beforeSendEvent', _getSentryBreadcrumbHandler(client));\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration);\n\n/**\n * Default Breadcrumbs instrumentations\n *\n * @deprecated Use `breadcrumbsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const Breadcrumbs = convertIntegrationFnToClass(INTEGRATION_NAME, breadcrumbsIntegration) as IntegrationClass<\n Integration & { setup: (client: Client) => void }\n> & {\n new (\n options?: Partial<{\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n }>,\n ): Integration;\n};\n\n/**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\nfunction _getSentryBreadcrumbHandler(client: Client): (event: SentryEvent) => void {\n return function addSentryBreadcrumb(event: SentryEvent): void {\n if (getClient() !== client) {\n return;\n }\n\n addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n };\n}\n\n/**\n * A HOC that creaes a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\nfunction _getDomBreadcrumbHandler(\n client: Client,\n dom: BreadcrumbsOptions['dom'],\n): (handlerData: HandlerDataDom) => void {\n return function _innerDomBreadcrumb(handlerData: HandlerDataDom): void {\n if (getClient() !== client) {\n return;\n }\n\n let target;\n let componentName;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event as Event | Node;\n const element = _isEvent(event) ? event.target : event;\n\n target = htmlTreeAsString(element, { keyAttrs, maxStringLength });\n componentName = getComponentName(element);\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n const breadcrumb: Breadcrumb = {\n category: `ui.${handlerData.name}`,\n message: target,\n };\n\n if (componentName) {\n breadcrumb.data = { 'ui.component_name': componentName };\n }\n\n addBreadcrumb(breadcrumb, {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\nfunction _getConsoleBreadcrumbHandler(client: Client): (handlerData: HandlerDataConsole) => void {\n return function _consoleBreadcrumb(handlerData: HandlerDataConsole): void {\n if (getClient() !== client) {\n return;\n }\n\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityLevelFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _getXhrBreadcrumbHandler(client: Client): (handlerData: HandlerDataXhr) => void {\n return function _xhrBreadcrumb(handlerData: HandlerDataXhr): void {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];\n\n // We only capture complete, non-sentry requests\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return;\n }\n\n const { method, url, status_code, body } = sentryXhrData;\n\n const data: XhrBreadcrumbData = {\n method,\n url,\n status_code,\n };\n\n const hint: XhrBreadcrumbHint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n addBreadcrumb(\n {\n category: 'xhr',\n data,\n type: 'http',\n },\n hint,\n );\n };\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _getFetchBreadcrumbHandler(client: Client): (handlerData: HandlerDataFetch) => void {\n return function _fetchBreadcrumb(handlerData: HandlerDataFetch): void {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n const data: FetchBreadcrumbData = handlerData.fetchData;\n const hint: FetchBreadcrumbHint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n addBreadcrumb(\n {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n },\n hint,\n );\n } else {\n const response = handlerData.response as Response | undefined;\n const data: FetchBreadcrumbData = {\n ...handlerData.fetchData,\n status_code: response && response.status,\n };\n const hint: FetchBreadcrumbHint = {\n input: handlerData.args,\n response,\n startTimestamp,\n endTimestamp,\n };\n addBreadcrumb(\n {\n category: 'fetch',\n data,\n type: 'http',\n },\n hint,\n );\n }\n };\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _getHistoryBreadcrumbHandler(client: Client): (handlerData: HandlerDataHistory) => void {\n return function _historyBreadcrumb(handlerData: HandlerDataHistory): void {\n if (getClient() !== client) {\n return;\n }\n\n let from: string | undefined = handlerData.from;\n let to: string | undefined = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = from ? parseUrl(from) : undefined;\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom || !parsedFrom.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n };\n}\n\nfunction _isEvent(event: unknown): event is Event {\n return !!event && !!(event as Record).target;\n}\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Event, Exception, Integration, IntegrationClass, IntegrationFn, StackFrame } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst INTEGRATION_NAME = 'Dedupe';\n\nconst _dedupeIntegration = (() => {\n let previousEvent: Event | undefined;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(currentEvent) {\n // We want to ignore any non-error type events, e.g. transactions or replays\n // These should never be deduped, and also not be compared against as _previousEvent.\n if (currentEvent.type) {\n return currentEvent;\n }\n\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, previousEvent)) {\n DEBUG_BUILD && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n return (previousEvent = currentEvent);\n },\n };\n}) satisfies IntegrationFn;\n\nexport const dedupeIntegration = defineIntegration(_dedupeIntegration);\n\n/**\n * Deduplication filter.\n * @deprecated Use `dedupeIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const Dedupe = convertIntegrationFnToClass(INTEGRATION_NAME, dedupeIntegration) as IntegrationClass<\n Integration & { processEvent: (event: Event) => Event }\n>;\n\nfunction _shouldDropEvent(currentEvent: Event, previousEvent?: Event): boolean {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\nfunction _isSameMessageEvent(currentEvent: Event, previousEvent: Event): boolean {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameExceptionEvent(currentEvent: Event, previousEvent: Event): boolean {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameStacktrace(currentEvent: Event, previousEvent: Event): boolean {\n let currentFrames = _getFramesFromEvent(currentEvent);\n let previousFrames = _getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames as StackFrame[];\n previousFrames = previousFrames as StackFrame[];\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction _isSameFingerprint(currentEvent: Event, previousEvent: Event): boolean {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint as string[];\n previousFingerprint = previousFingerprint as string[];\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\nfunction _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\nfunction _getFramesFromEvent(event: Event): StackFrame[] | undefined {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-expect-error Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n","import type { HandlerDataError } from '@sentry/types';\n\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nlet _oldOnErrorHandler: (typeof GLOBAL_OBJ)['onerror'] | null = null;\n\n/**\n * Add an instrumentation handler for when an error is captured by the global error handler.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalErrorInstrumentationHandler(handler: (data: HandlerDataError) => void): void {\n const type = 'error';\n addHandler(type, handler);\n maybeInstrument(type, instrumentError);\n}\n\nfunction instrumentError(): void {\n _oldOnErrorHandler = GLOBAL_OBJ.onerror;\n\n GLOBAL_OBJ.onerror = function (\n msg: string | object,\n url?: string,\n line?: number,\n column?: number,\n error?: Error,\n ): boolean {\n const handlerData: HandlerDataError = {\n column,\n error,\n line,\n msg,\n url,\n };\n triggerHandlers('error', handlerData);\n\n if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { HandlerDataUnhandledRejection } from '@sentry/types';\n\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nlet _oldOnUnhandledRejectionHandler: (typeof GLOBAL_OBJ)['onunhandledrejection'] | null = null;\n\n/**\n * Add an instrumentation handler for when an unhandled promise rejection is captured.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalUnhandledRejectionInstrumentationHandler(\n handler: (data: HandlerDataUnhandledRejection) => void,\n): void {\n const type = 'unhandledrejection';\n addHandler(type, handler);\n maybeInstrument(type, instrumentUnhandledRejection);\n}\n\nfunction instrumentUnhandledRejection(): void {\n _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;\n\n GLOBAL_OBJ.onunhandledrejection = function (e: any): boolean {\n const handlerData: HandlerDataUnhandledRejection = e;\n triggerHandlers('unhandledrejection', handlerData);\n\n if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport { captureEvent, convertIntegrationFnToClass, defineIntegration, getClient } from '@sentry/core';\nimport type {\n Client,\n Event,\n Integration,\n IntegrationClass,\n IntegrationFn,\n Primitive,\n StackParser,\n} from '@sentry/types';\nimport {\n addGlobalErrorInstrumentationHandler,\n addGlobalUnhandledRejectionInstrumentationHandler,\n getLocationHref,\n isErrorEvent,\n isPrimitive,\n isString,\n logger,\n} from '@sentry/utils';\n\nimport type { BrowserClient } from '../client';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { shouldIgnoreOnError } from '../helpers';\n\ntype GlobalHandlersIntegrationsOptionKeys = 'onerror' | 'onunhandledrejection';\n\ntype GlobalHandlersIntegrations = Record;\n\nconst INTEGRATION_NAME = 'GlobalHandlers';\n\nconst _globalHandlersIntegration = ((options: Partial = {}) => {\n const _options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n Error.stackTraceLimit = 50;\n },\n setup(client) {\n if (_options.onerror) {\n _installGlobalOnErrorHandler(client);\n globalHandlerLog('onerror');\n }\n if (_options.onunhandledrejection) {\n _installGlobalOnUnhandledRejectionHandler(client);\n globalHandlerLog('onunhandledrejection');\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const globalHandlersIntegration = defineIntegration(_globalHandlersIntegration);\n\n/**\n * Global handlers.\n * @deprecated Use `globalHandlersIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const GlobalHandlers = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n globalHandlersIntegration,\n) as IntegrationClass void }> & {\n new (options?: Partial): Integration;\n};\n\nfunction _installGlobalOnErrorHandler(client: Client): void {\n addGlobalErrorInstrumentationHandler(data => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const { msg, url, line, column, error } = data;\n\n const event =\n error === undefined && isString(msg)\n ? _eventFromIncompleteOnError(msg, url, line, column)\n : _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'onerror',\n },\n });\n });\n}\n\nfunction _installGlobalOnUnhandledRejectionHandler(client: Client): void {\n addGlobalUnhandledRejectionInstrumentationHandler(e => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const error = _getUnhandledRejectionError(e as unknown);\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'onunhandledrejection',\n },\n });\n });\n}\n\nfunction _getUnhandledRejectionError(error: unknown): unknown {\n if (isPrimitive(error)) {\n return error;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const e = error as any;\n\n // dig the object of the rejection out of known event types\n try {\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in e) {\n return e.reason;\n }\n\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n else if ('detail' in e && 'reason' in e.detail) {\n return e.detail.reason;\n }\n } catch {} // eslint-disable-line no-empty\n\n return error;\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason: Primitive): Event {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\n/**\n * This function creates a stack from an old, error-less onerror handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _eventFromIncompleteOnError(msg: any, url: any, line: any, column: any): Event {\n const ERROR_TYPES_RE =\n /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\n\n // If 'message' is ErrorEvent, get real message from inside\n let message = isErrorEvent(msg) ? msg.message : msg;\n let name = 'Error';\n\n const groups = message.match(ERROR_TYPES_RE);\n if (groups) {\n name = groups[1];\n message = groups[2];\n }\n\n const event = {\n exception: {\n values: [\n {\n type: name,\n value: message,\n },\n ],\n },\n };\n\n return _enhanceEventWithInitialFrame(event, url, line, column);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column: any): Event {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = isNaN(parseInt(column, 10)) ? undefined : column;\n const lineno = isNaN(parseInt(line, 10)) ? undefined : line;\n const filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: '?',\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type: string): void {\n DEBUG_BUILD && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction getOptions(): { stackParser: StackParser; attachStacktrace?: boolean } {\n const client = getClient();\n const options = (client && client.getOptions()) || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return options;\n}\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Event, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\n\nimport { WINDOW } from '../helpers';\n\nconst INTEGRATION_NAME = 'HttpContext';\n\nconst _httpContextIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n preprocessEvent(event) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n // grab as much info as exists and add it to the event\n const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...event.request, ...(url && { url }), headers };\n\n event.request = request;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const httpContextIntegration = defineIntegration(_httpContextIntegration);\n\n/**\n * HttpContext integration collects information about HTTP request headers.\n * @deprecated Use `httpContextIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const HttpContext = convertIntegrationFnToClass(INTEGRATION_NAME, httpContextIntegration) as IntegrationClass<\n Integration & { preprocessEvent: (event: Event) => void }\n>;\n","import type { Event, EventHint, Exception, ExtendedError, StackParser } from '@sentry/types';\n\nimport { isInstanceOf } from './is';\nimport { truncate } from './string';\n\n/**\n * Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter.\n */\nexport function applyAggregateErrorsToEvent(\n exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) => Exception,\n parser: StackParser,\n maxValueLimit: number = 250,\n key: string,\n limit: number,\n event: Event,\n hint?: EventHint,\n): void {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return;\n }\n\n // Generally speaking the last item in `event.exception.values` is the exception originating from the original Error\n const originalException: Exception | undefined =\n event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : undefined;\n\n // We only create exception grouping if there is an exception in the event.\n if (originalException) {\n event.exception.values = truncateAggregateExceptions(\n aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n hint.originalException as ExtendedError,\n key,\n event.exception.values,\n originalException,\n 0,\n ),\n maxValueLimit,\n );\n }\n}\n\nfunction aggregateExceptionsFromError(\n exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) => Exception,\n parser: StackParser,\n limit: number,\n error: ExtendedError,\n key: string,\n prevExceptions: Exception[],\n exception: Exception,\n exceptionId: number,\n): Exception[] {\n if (prevExceptions.length >= limit + 1) {\n return prevExceptions;\n }\n\n let newExceptions = [...prevExceptions];\n\n // Recursively call this function in order to walk down a chain of errors\n if (isInstanceOf(error[key], Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, error[key]);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n error[key],\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n\n // This will create exception grouping for AggregateErrors\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError\n if (Array.isArray(error.errors)) {\n error.errors.forEach((childError, i) => {\n if (isInstanceOf(childError, Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, childError);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n childError,\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n });\n }\n\n return newExceptions;\n}\n\nfunction applyExceptionGroupFieldsForParentException(exception: Exception, exceptionId: number): void {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n ...(exception.type === 'AggregateError' && { is_exception_group: true }),\n exception_id: exceptionId,\n };\n}\n\nfunction applyExceptionGroupFieldsForChildException(\n exception: Exception,\n source: string,\n exceptionId: number,\n parentId: number | undefined,\n): void {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n type: 'chained',\n source,\n exception_id: exceptionId,\n parent_id: parentId,\n };\n}\n\n/**\n * Truncate the message (exception.value) of all exceptions in the event.\n * Because this event processor is ran after `applyClientOptions`,\n * we need to truncate the message of the added exceptions here.\n */\nfunction truncateAggregateExceptions(exceptions: Exception[], maxValueLength: number): Exception[] {\n return exceptions.map(exception => {\n if (exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n return exception;\n });\n}\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Client, Event, EventHint, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport { applyAggregateErrorsToEvent } from '@sentry/utils';\nimport { exceptionFromError } from '../eventbuilder';\n\ninterface LinkedErrorsOptions {\n key?: string;\n limit?: number;\n}\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\nconst INTEGRATION_NAME = 'LinkedErrors';\n\nconst _linkedErrorsIntegration = ((options: LinkedErrorsOptions = {}) => {\n const limit = options.limit || DEFAULT_LIMIT;\n const key = options.key || DEFAULT_KEY;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n preprocessEvent(event, hint, client) {\n const options = client.getOptions();\n\n applyAggregateErrorsToEvent(\n // This differs from the LinkedErrors integration in core by using a different exceptionFromError function\n exceptionFromError,\n options.stackParser,\n options.maxValueLength,\n key,\n limit,\n event,\n hint,\n );\n },\n };\n}) satisfies IntegrationFn;\n\nexport const linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);\n\n/**\n * Aggregrate linked errors in an event.\n * @deprecated Use `linkedErrorsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const LinkedErrors = convertIntegrationFnToClass(INTEGRATION_NAME, linkedErrorsIntegration) as IntegrationClass<\n Integration & { preprocessEvent: (event: Event, hint: EventHint, client: Client) => void }\n> & { new (options?: { key?: string; limit?: number }): Integration };\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Integration, IntegrationClass, IntegrationFn, WrappedFunction } from '@sentry/types';\nimport { fill, getFunctionName, getOriginalFunction } from '@sentry/utils';\n\nimport { WINDOW, wrap } from '../helpers';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'BroadcastChannel',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'SharedWorker',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\nconst INTEGRATION_NAME = 'TryCatch';\n\ntype XMLHttpRequestProp = 'onload' | 'onerror' | 'onprogress' | 'onreadystatechange';\n\ninterface TryCatchOptions {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n}\n\nconst _browserApiErrorsIntegration = ((options: Partial = {}) => {\n const _options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO: This currently only works for the first client this is setup\n // We may want to adjust this to check for client etc.\n setupOnce() {\n if (_options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (_options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (_options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (_options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = _options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const browserApiErrorsIntegration = defineIntegration(_browserApiErrorsIntegration);\n\n/**\n * Wrap timer functions and event targets to catch errors and provide better meta data.\n * @deprecated Use `browserApiErrorsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const TryCatch = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n browserApiErrorsIntegration,\n) as IntegrationClass & {\n new (options?: {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n }): Integration;\n};\n\nfunction _wrapTimeFunction(original: () => void): () => number {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, ...args: any[]): number {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: false,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _wrapRAF(original: any): (callback: () => void) => any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, callback: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n }),\n ]);\n };\n}\n\nfunction _wrapXHR(originalSend: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: XMLHttpRequest, ...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps: XMLHttpRequestProp[] = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(xhr, prop, function (original: WrappedFunction): () => any {\n const wrapOptions = {\n mechanism: {\n data: {\n function: prop,\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n };\n\n // If Instrument integration has been called before TryCatch, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\nfunction _wrapEventTarget(target: string): void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const globalObject = WINDOW as { [key: string]: any };\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = globalObject[target] && globalObject[target].prototype;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original: VoidFunction,): (\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ) => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): (eventName: string, fn: EventListenerObject, capture?: boolean, secure?: boolean) => void {\n try {\n if (typeof fn.handleEvent === 'function') {\n // ESlint disable explanation:\n // First, it is generally safe to call `wrap` with an unbound function. Furthermore, using `.bind()` would\n // introduce a bug here, because bind returns a new function that doesn't have our\n // flags(like __sentry_original__) attached. `wrap` checks for those flags to avoid unnecessary wrapping.\n // Without those flags, every call to addEventListener wraps the function again, causing a memory leak.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n fn.handleEvent = wrap(fn.handleEvent, {\n mechanism: {\n data: {\n function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n });\n }\n } catch (err) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wrap(fn as any as WrappedFunction, {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (\n originalRemoveEventListener: () => void,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): (this: any, eventName: string, fn: EventListenerObject, options?: boolean | EventListenerOptions) => () => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n const wrappedEventHandler = fn as unknown as WrappedFunction;\n try {\n const originalEventHandler = wrappedEventHandler && wrappedEventHandler.__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);\n };\n },\n );\n}\n","// This was originally forked from https://github.com/csnover/TraceKit, and was largely\n// re - written as part of raven - js.\n//\n// This code was later copied to the JavaScript mono - repo and further modified and\n// refactored over the years.\n\n// Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this\n// software and associated documentation files(the 'Software'), to deal in the Software\n// without restriction, including without limitation the rights to use, copy, modify,\n// merge, publish, distribute, sublicense, and / or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following\n// conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies\n// or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { StackFrame, StackLineParser, StackLineParserFn } from '@sentry/types';\nimport { createStackParser } from '@sentry/utils';\n\n// global reference to slice\nconst UNKNOWN_FUNCTION = '?';\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename: string, func: string, lineno?: number, colno?: number): StackFrame {\n const frame: StackFrame = {\n filename,\n function: func,\n in_app: true, // All browser frames are considered in_app\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\nconst chromeRegex =\n /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\n// We cannot call this variable `chrome` because it can conflict with global `chrome` variable in certain environments\n// See: https://github.com/getsentry/sentry-javascript/issues/6880\nconst chromeStackParserFn: StackLineParserFn = line => {\n const parts = chromeRegex.exec(line);\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nexport const chromeStackLineParser: StackLineParser = [CHROME_PRIORITY, chromeStackParserFn];\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nconst gecko: StackLineParserFn = line => {\n const parts = geckoREgex.exec(line);\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nexport const geckoStackLineParser: StackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:[-a-z]+):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs: StackLineParserFn = line => {\n const parts = winjsRegex.exec(line);\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nexport const winjsStackLineParser: StackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10: StackLineParserFn = line => {\n const parts = opera10Regex.exec(line);\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nexport const opera10StackLineParser: StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11: StackLineParserFn = line => {\n const parts = opera11Regex.exec(line);\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nexport const opera11StackLineParser: StackLineParser = [OPERA11_PRIORITY, opera11];\n\nexport const defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser, winjsStackLineParser];\n\nexport const defaultStackParser = createStackParser(...defaultStackLineParsers);\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func: string, filename: string): [string, string] => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n","import { SentryError } from './error';\nimport { SyncPromise, rejectedSyncPromise, resolvedSyncPromise } from './syncpromise';\n\nexport interface PromiseBuffer {\n // exposes the internal array so tests can assert on the state of it.\n // XXX: this really should not be public api.\n $: Array>;\n add(taskProducer: () => PromiseLike): PromiseLike;\n drain(timeout?: number): PromiseLike;\n}\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nexport function makePromiseBuffer(limit?: number): PromiseBuffer {\n const buffer: Array> = [];\n\n function isReady(): boolean {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task: PromiseLike): PromiseLike {\n return buffer.splice(buffer.indexOf(task), 1)[0];\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer: () => PromiseLike): PromiseLike {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise because buffer limit was reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout?: number): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n","import type { DataCategory, TransportMakeRequestResponse } from '@sentry/types';\n\n// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\nexport type RateLimits = Record;\n\nexport const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nexport function parseRetryAfterHeader(header: string, now: number = Date.now()): number {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nexport function disabledUntil(limits: RateLimits, dataCategory: DataCategory): number {\n return limits[dataCategory] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nexport function isRateLimited(limits: RateLimits, dataCategory: DataCategory, now: number = Date.now()): boolean {\n return disabledUntil(limits, dataCategory) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nexport function updateRateLimits(\n limits: RateLimits,\n { statusCode, headers }: TransportMakeRequestResponse,\n now: number = Date.now(),\n): RateLimits {\n const updatedRateLimits: RateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && headers['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n *
,
,..\n * where each
is of the form\n * : : : : \n * where\n * is a delay in seconds\n * is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * ;;...\n * is what's being limited (org, project, or key) - ignored by SDK\n * is an arbitrary string like \"org_quota\" - ignored by SDK\n * Semicolon-separated list of metric namespace identifiers. Defines which namespace(s) will be affected.\n * Only present if rate limit applies to the metric_bucket data category.\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories, , , namespaces] = limit.split(':', 5);\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n if (category === 'metric_bucket') {\n // namespaces will be present when category === 'metric_bucket'\n if (!namespaces || namespaces.split(';').includes('custom')) {\n updatedRateLimits[category] = now + delay;\n }\n } else {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n","import type {\n Envelope,\n EnvelopeItem,\n EnvelopeItemType,\n Event,\n EventDropReason,\n EventItem,\n InternalBaseTransportOptions,\n Transport,\n TransportMakeRequestResponse,\n TransportRequestExecutor,\n} from '@sentry/types';\nimport type { PromiseBuffer, RateLimits } from '@sentry/utils';\nimport {\n SentryError,\n createEnvelope,\n envelopeItemTypeToDataCategory,\n forEachEnvelopeItem,\n isRateLimited,\n logger,\n makePromiseBuffer,\n resolvedSyncPromise,\n serializeEnvelope,\n updateRateLimits,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\nexport const DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nexport function createTransport(\n options: InternalBaseTransportOptions,\n makeRequest: TransportRequestExecutor,\n buffer: PromiseBuffer = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n): Transport {\n let rateLimits: RateLimits = {};\n const flush = (timeout?: number): PromiseLike => buffer.drain(timeout);\n\n function send(envelope: Envelope): PromiseLike {\n const filteredEnvelopeItems: EnvelopeItem[] = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const dataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, dataCategory)) {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', dataCategory, event);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return resolvedSyncPromise();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const filteredEnvelope: Envelope = createEnvelope(envelope[0], filteredEnvelopeItems as any);\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason: EventDropReason): void => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = (): PromiseLike =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope, options.textEncoder) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n DEBUG_BUILD && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof SentryError) {\n DEBUG_BUILD && logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return resolvedSyncPromise();\n } else {\n throw error;\n }\n },\n );\n }\n\n // We use this to identifify if the transport is the base transport\n // TODO (v8): Remove this again as we'll no longer need it\n send.__sentry__baseTransport__ = true;\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item: Envelope[1][number], type: EnvelopeItemType): Event | undefined {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item as EventItem)[1] : undefined;\n}\n","import { isNativeFetch, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\nlet cachedFetchImpl: FetchImpl | undefined = undefined;\n\nexport type FetchImpl = typeof fetch;\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nexport function getNativeFetchImplementation(): FetchImpl {\n if (cachedFetchImpl) {\n return cachedFetchImpl;\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n\n // Fast path to avoid DOM I/O\n if (isNativeFetch(WINDOW.fetch)) {\n return (cachedFetchImpl = WINDOW.fetch.bind(WINDOW));\n }\n\n const document = WINDOW.document;\n let fetchImpl = WINDOW.fetch;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow.fetch) {\n fetchImpl = contentWindow.fetch;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n DEBUG_BUILD && logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\n }\n }\n\n return (cachedFetchImpl = fetchImpl.bind(WINDOW));\n /* eslint-enable @typescript-eslint/unbound-method */\n}\n\n/** Clears cached fetch impl */\nexport function clearCachedFetchImplementation(): void {\n cachedFetchImpl = undefined;\n}\n","import { createTransport } from '@sentry/core';\nimport type { Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/types';\nimport { rejectedSyncPromise } from '@sentry/utils';\n\nimport type { BrowserTransportOptions } from './types';\nimport type { FetchImpl } from './utils';\nimport { clearCachedFetchImplementation, getNativeFetchImplementation } from './utils';\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nexport function makeFetchTransport(\n options: BrowserTransportOptions,\n nativeFetch: FetchImpl = getNativeFetchImplementation(),\n): Transport {\n let pendingBodySize = 0;\n let pendingCount = 0;\n\n function makeRequest(request: TransportRequest): PromiseLike {\n const requestSize = request.body.length;\n pendingBodySize += requestSize;\n pendingCount++;\n\n const requestOptions: RequestInit = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'origin',\n headers: options.headers,\n // Outgoing requests are usually cancelled when navigating to a different page, causing a \"TypeError: Failed to\n // fetch\" error and sending a \"network_error\" client-outcome - in Chrome, the request status shows \"(cancelled)\".\n // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're\n // frequently sending events right before the user is switching pages (eg. whenfinishing navigation transactions).\n // Gotchas:\n // - `keepalive` isn't supported by Firefox\n // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch):\n // If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.\n // We will therefore only activate the flag when we're below that limit.\n // There is also a limit of requests that can be open at the same time, so we also limit this to 15\n // See https://github.com/getsentry/sentry-javascript/pull/7553 for details\n keepalive: pendingBodySize <= 60_000 && pendingCount < 15,\n ...options.fetchOptions,\n };\n\n try {\n return nativeFetch(options.url, requestOptions).then(response => {\n pendingBodySize -= requestSize;\n pendingCount--;\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n } catch (e) {\n clearCachedFetchImplementation();\n pendingBodySize -= requestSize;\n pendingCount--;\n return rejectedSyncPromise(e);\n }\n }\n\n return createTransport(options, makeRequest);\n}\n","import { createTransport } from '@sentry/core';\nimport type { Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/types';\nimport { SyncPromise } from '@sentry/utils';\n\nimport type { BrowserTransportOptions } from './types';\n\n/**\n * The DONE ready state for XmlHttpRequest\n *\n * Defining it here as a constant b/c XMLHttpRequest.DONE is not always defined\n * (e.g. during testing, it is `undefined`)\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState}\n */\nconst XHR_READYSTATE_DONE = 4;\n\n/**\n * Creates a Transport that uses the XMLHttpRequest API to send events to Sentry.\n */\nexport function makeXHRTransport(options: BrowserTransportOptions): Transport {\n function makeRequest(request: TransportRequest): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n\n xhr.onerror = reject;\n\n xhr.onreadystatechange = (): void => {\n if (xhr.readyState === XHR_READYSTATE_DONE) {\n resolve({\n statusCode: xhr.status,\n headers: {\n 'x-sentry-rate-limits': xhr.getResponseHeader('X-Sentry-Rate-Limits'),\n 'retry-after': xhr.getResponseHeader('Retry-After'),\n },\n });\n }\n };\n\n xhr.open('POST', options.url);\n\n for (const header in options.headers) {\n if (Object.prototype.hasOwnProperty.call(options.headers, header)) {\n xhr.setRequestHeader(header, options.headers[header]);\n }\n }\n\n xhr.send(request.body);\n });\n }\n\n return createTransport(options, makeRequest);\n}\n","import type { Hub } from '@sentry/core';\nimport { functionToStringIntegration, inboundFiltersIntegration } from '@sentry/core';\nimport {\n captureSession,\n getClient,\n getCurrentHub,\n getIntegrationsToSetup,\n getReportDialogEndpoint,\n initAndBind,\n startSession,\n} from '@sentry/core';\nimport type { Integration, Options, UserFeedback } from '@sentry/types';\nimport {\n addHistoryInstrumentationHandler,\n logger,\n stackParserFromStackParserOptions,\n supportsFetch,\n} from '@sentry/utils';\n\nimport type { BrowserClientOptions, BrowserOptions } from './client';\nimport { BrowserClient } from './client';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ReportDialogOptions } from './helpers';\nimport { WINDOW, wrap as internalWrap } from './helpers';\nimport { breadcrumbsIntegration } from './integrations/breadcrumbs';\nimport { dedupeIntegration } from './integrations/dedupe';\nimport { globalHandlersIntegration } from './integrations/globalhandlers';\nimport { httpContextIntegration } from './integrations/httpcontext';\nimport { linkedErrorsIntegration } from './integrations/linkederrors';\nimport { browserApiErrorsIntegration } from './integrations/trycatch';\nimport { defaultStackParser } from './stack-parsers';\nimport { makeFetchTransport, makeXHRTransport } from './transports';\n\n/** @deprecated Use `getDefaultIntegrations(options)` instead. */\nexport const defaultIntegrations = [\n inboundFiltersIntegration(),\n functionToStringIntegration(),\n browserApiErrorsIntegration(),\n breadcrumbsIntegration(),\n globalHandlersIntegration(),\n linkedErrorsIntegration(),\n dedupeIntegration(),\n httpContextIntegration(),\n];\n\n/** Get the default integrations for the browser SDK. */\nexport function getDefaultIntegrations(_options: Options): Integration[] {\n // We return a copy of the defaultIntegrations here to avoid mutating this\n return [\n // eslint-disable-next-line deprecation/deprecation\n ...defaultIntegrations,\n ];\n}\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\ndeclare const __SENTRY_RELEASE__: string | undefined;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { configureScope } from '@sentry/browser';\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nexport function init(options: BrowserOptions = {}): void {\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = getDefaultIntegrations(options);\n }\n if (options.release === undefined) {\n // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n if (typeof __SENTRY_RELEASE__ === 'string') {\n options.release = __SENTRY_RELEASE__;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id) {\n options.release = WINDOW.SENTRY_RELEASE.id;\n }\n }\n if (options.autoSessionTracking === undefined) {\n options.autoSessionTracking = true;\n }\n if (options.sendClientReports === undefined) {\n options.sendClientReports = true;\n }\n\n const clientOptions: BrowserClientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || (supportsFetch() ? makeFetchTransport : makeXHRTransport),\n };\n\n initAndBind(BrowserClient, clientOptions);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\ntype NewReportDialogOptions = ReportDialogOptions & { eventId: string }; // eslint-disable-line\n\ninterface ShowReportDialogFunction {\n /**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\n (options: NewReportDialogOptions): void;\n\n /**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n *\n * @deprecated Please always pass an `options` argument with `eventId`. The `hub` argument will not be used in the next version of the SDK.\n */\n // eslint-disable-next-line deprecation/deprecation\n (options?: ReportDialogOptions, hub?: Hub): void;\n}\n\nexport const showReportDialog: ShowReportDialogFunction = (\n // eslint-disable-next-line deprecation/deprecation\n options: ReportDialogOptions = {},\n // eslint-disable-next-line deprecation/deprecation\n hub: Hub = getCurrentHub(),\n) => {\n // doesn't work without a document (React Native)\n if (!WINDOW.document) {\n DEBUG_BUILD && logger.error('Global document not defined in showReportDialog call');\n return;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n const { client, scope } = hub.getStackTop();\n const dsn = options.dsn || (client && client.getDsn());\n if (!dsn) {\n DEBUG_BUILD && logger.error('DSN not configured for showReportDialog call');\n return;\n }\n\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n // eslint-disable-next-line deprecation/deprecation\n options.eventId = hub.lastEventId();\n }\n\n const script = WINDOW.document.createElement('script');\n script.async = true;\n script.crossOrigin = 'anonymous';\n script.src = getReportDialogEndpoint(dsn, options);\n\n if (options.onLoad) {\n script.onload = options.onLoad;\n }\n\n const { onClose } = options;\n if (onClose) {\n const reportDialogClosedMessageHandler = (event: MessageEvent): void => {\n if (event.data === '__sentry_reportdialog_closed__') {\n try {\n onClose();\n } finally {\n WINDOW.removeEventListener('message', reportDialogClosedMessageHandler);\n }\n }\n };\n WINDOW.addEventListener('message', reportDialogClosedMessageHandler);\n }\n\n const injectionPoint = WINDOW.document.head || WINDOW.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n } else {\n DEBUG_BUILD && logger.error('Not injecting report dialog. No injection point found in HTML');\n }\n};\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function forceLoad(): void {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function onLoad(callback: () => void): void {\n callback();\n}\n\n/**\n * Wrap code within a try/catch block so the SDK is able to capture errors.\n *\n * @deprecated This function will be removed in v8.\n * It is not part of Sentry's official API and it's easily replaceable by using a try/catch block\n * and calling Sentry.captureException.\n *\n * @param fn A function to wrap.\n *\n * @returns The result of wrapped function call.\n */\n// TODO(v8): Remove this function\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function wrap(fn: (...args: any) => any): any {\n return internalWrap(fn)();\n}\n\n/**\n * Enable automatic Session Tracking for the initial page load.\n */\nfunction startSessionTracking(): void {\n if (typeof WINDOW.document === 'undefined') {\n DEBUG_BUILD && logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSession({ ignoreDuration: true });\n captureSession();\n\n // We want to create a session for every navigation as well\n addHistoryInstrumentationHandler(({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (from !== undefined && from !== to) {\n startSession({ ignoreDuration: true });\n captureSession();\n }\n });\n}\n\n/**\n * Captures user feedback and sends it to Sentry.\n */\nexport function captureUserFeedback(feedback: UserFeedback): void {\n const client = getClient();\n if (client) {\n client.captureUserFeedback(feedback);\n }\n}\n","import type { MeasurementUnit, Span } from '@sentry/types';\nimport type { MetricSummary } from '@sentry/types';\nimport type { Primitive } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\nimport { getActiveSpan } from '../tracing';\nimport type { MetricType } from './types';\n\n/**\n * key: bucketKey\n * value: [exportKey, MetricSummary]\n */\ntype MetricSummaryStorage = Map;\n\nlet SPAN_METRIC_SUMMARY: WeakMap | undefined;\n\nfunction getMetricStorageForSpan(span: Span): MetricSummaryStorage | undefined {\n return SPAN_METRIC_SUMMARY ? SPAN_METRIC_SUMMARY.get(span) : undefined;\n}\n\n/**\n * Fetches the metric summary if it exists for the passed span\n */\nexport function getMetricSummaryJsonForSpan(span: Span): Record> | undefined {\n const storage = getMetricStorageForSpan(span);\n\n if (!storage) {\n return undefined;\n }\n const output: Record> = {};\n\n for (const [, [exportKey, summary]] of storage) {\n if (!output[exportKey]) {\n output[exportKey] = [];\n }\n\n output[exportKey].push(dropUndefinedKeys(summary));\n }\n\n return output;\n}\n\n/**\n * Updates the metric summary on the currently active span\n */\nexport function updateMetricSummaryOnActiveSpan(\n metricType: MetricType,\n sanitizedName: string,\n value: number,\n unit: MeasurementUnit,\n tags: Record,\n bucketKey: string,\n): void {\n const span = getActiveSpan();\n if (span) {\n const storage = getMetricStorageForSpan(span) || new Map();\n\n const exportKey = `${metricType}:${sanitizedName}@${unit}`;\n const bucketItem = storage.get(bucketKey);\n\n if (bucketItem) {\n const [, summary] = bucketItem;\n storage.set(bucketKey, [\n exportKey,\n {\n min: Math.min(summary.min, value),\n max: Math.max(summary.max, value),\n count: (summary.count += 1),\n sum: (summary.sum += value),\n tags: summary.tags,\n },\n ]);\n } else {\n storage.set(bucketKey, [\n exportKey,\n {\n min: value,\n max: value,\n count: 1,\n sum: value,\n tags,\n },\n ]);\n }\n\n if (!SPAN_METRIC_SUMMARY) {\n SPAN_METRIC_SUMMARY = new WeakMap();\n }\n\n SPAN_METRIC_SUMMARY.set(span, storage);\n }\n}\n","/**\n * Use this attribute to represent the source of a span.\n * Should be one of: custom, url, route, view, component, task, unknown\n *\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = 'sentry.source';\n\n/**\n * Use this attribute to represent the sample rate used for a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = 'sentry.sample_rate';\n\n/**\n * Use this attribute to represent the operation of a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_OP = 'sentry.op';\n\n/**\n * Use this attribute to represent the origin of a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin';\n\n/**\n * The id of the profile that this span occured in.\n */\nexport const SEMANTIC_ATTRIBUTE_PROFILE_ID = 'profile_id';\n","import type { Span } from '@sentry/types';\n\n/** The status of an Span.\n *\n * @deprecated Use string literals - if you require type casting, cast to SpanStatusType type\n */\nexport enum SpanStatus {\n /** The operation completed successfully. */\n Ok = 'ok',\n /** Deadline expired before operation could complete. */\n DeadlineExceeded = 'deadline_exceeded',\n /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */\n Unauthenticated = 'unauthenticated',\n /** 403 Forbidden */\n PermissionDenied = 'permission_denied',\n /** 404 Not Found. Some requested entity (file or directory) was not found. */\n NotFound = 'not_found',\n /** 429 Too Many Requests */\n ResourceExhausted = 'resource_exhausted',\n /** Client specified an invalid argument. 4xx. */\n InvalidArgument = 'invalid_argument',\n /** 501 Not Implemented */\n Unimplemented = 'unimplemented',\n /** 503 Service Unavailable */\n Unavailable = 'unavailable',\n /** Other/generic 5xx. */\n InternalError = 'internal_error',\n /** Unknown. Any non-standard HTTP status code. */\n UnknownError = 'unknown_error',\n /** The operation was cancelled (typically by the user). */\n Cancelled = 'cancelled',\n /** Already exists (409) */\n AlreadyExists = 'already_exists',\n /** Operation was rejected because the system is not in a state required for the operation's */\n FailedPrecondition = 'failed_precondition',\n /** The operation was aborted, typically due to a concurrency issue. */\n Aborted = 'aborted',\n /** Operation was attempted past the valid range. */\n OutOfRange = 'out_of_range',\n /** Unrecoverable data loss or corruption */\n DataLoss = 'data_loss',\n}\n\nexport type SpanStatusType =\n /** The operation completed successfully. */\n | 'ok'\n /** Deadline expired before operation could complete. */\n | 'deadline_exceeded'\n /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */\n | 'unauthenticated'\n /** 403 Forbidden */\n | 'permission_denied'\n /** 404 Not Found. Some requested entity (file or directory) was not found. */\n | 'not_found'\n /** 429 Too Many Requests */\n | 'resource_exhausted'\n /** Client specified an invalid argument. 4xx. */\n | 'invalid_argument'\n /** 501 Not Implemented */\n | 'unimplemented'\n /** 503 Service Unavailable */\n | 'unavailable'\n /** Other/generic 5xx. */\n | 'internal_error'\n /** Unknown. Any non-standard HTTP status code. */\n | 'unknown_error'\n /** The operation was cancelled (typically by the user). */\n | 'cancelled'\n /** Already exists (409) */\n | 'already_exists'\n /** Operation was rejected because the system is not in a state required for the operation's */\n | 'failed_precondition'\n /** The operation was aborted, typically due to a concurrency issue. */\n | 'aborted'\n /** Operation was attempted past the valid range. */\n | 'out_of_range'\n /** Unrecoverable data loss or corruption */\n | 'data_loss';\n\n/**\n * Converts a HTTP status code into a {@link SpanStatusType}.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\nexport function getSpanStatusFromHttpCode(httpStatus: number): SpanStatusType {\n if (httpStatus < 400 && httpStatus >= 100) {\n return 'ok';\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return 'unauthenticated';\n case 403:\n return 'permission_denied';\n case 404:\n return 'not_found';\n case 409:\n return 'already_exists';\n case 413:\n return 'failed_precondition';\n case 429:\n return 'resource_exhausted';\n default:\n return 'invalid_argument';\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return 'unimplemented';\n case 503:\n return 'unavailable';\n case 504:\n return 'deadline_exceeded';\n default:\n return 'internal_error';\n }\n }\n\n return 'unknown_error';\n}\n\n/**\n * Converts a HTTP status code into a {@link SpanStatusType}.\n *\n * @deprecated Use {@link spanStatusFromHttpCode} instead.\n * This export will be removed in v8 as the signature contains a typo.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\nexport const spanStatusfromHttpCode = getSpanStatusFromHttpCode;\n\n/**\n * Sets the Http status attributes on the current span based on the http code.\n * Additionally, the span's status is updated, depending on the http code.\n */\nexport function setHttpStatus(span: Span, httpStatus: number): void {\n // TODO (v8): Remove these calls\n // Relay does not require us to send the status code as a tag\n // For now, just because users might expect it to land as a tag we keep sending it.\n // Same with data.\n // In v8, we replace both, simply with\n // span.setAttribute('http.response.status_code', httpStatus);\n\n // eslint-disable-next-line deprecation/deprecation\n span.setTag('http.status_code', String(httpStatus));\n // eslint-disable-next-line deprecation/deprecation\n span.setData('http.response.status_code', httpStatus);\n\n const spanStatus = getSpanStatusFromHttpCode(httpStatus);\n if (spanStatus !== 'unknown_error') {\n span.setStatus(spanStatus);\n }\n}\n","/* eslint-disable max-lines */\nimport type {\n Instrumenter,\n Measurements,\n Primitive,\n Span as SpanInterface,\n SpanAttributeValue,\n SpanAttributes,\n SpanContext,\n SpanContextData,\n SpanJSON,\n SpanOrigin,\n SpanTimeInput,\n TraceContext,\n Transaction,\n} from '@sentry/types';\nimport { dropUndefinedKeys, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { getMetricSummaryJsonForSpan } from '../metrics/metric-summary';\nimport {\n SEMANTIC_ATTRIBUTE_PROFILE_ID,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n} from '../semanticAttributes';\nimport { getRootSpan } from '../utils/getRootSpan';\nimport {\n TRACE_FLAG_NONE,\n TRACE_FLAG_SAMPLED,\n spanTimeInputToSeconds,\n spanToJSON,\n spanToTraceContext,\n spanToTraceHeader,\n} from '../utils/spanUtils';\nimport type { SpanStatusType } from './spanstatus';\nimport { setHttpStatus } from './spanstatus';\n\n/**\n * Keeps track of finished spans for a given transaction\n * @internal\n * @hideconstructor\n * @hidden\n */\nexport class SpanRecorder {\n public spans: Span[];\n\n private readonly _maxlen: number;\n\n public constructor(maxlen: number = 1000) {\n this._maxlen = maxlen;\n this.spans = [];\n }\n\n /**\n * This is just so that we don't run out of memory while recording a lot\n * of spans. At some point we just stop and flush out the start of the\n * trace tree (i.e.the first n spans with the smallest\n * start_timestamp).\n */\n public add(span: Span): void {\n if (this.spans.length > this._maxlen) {\n // eslint-disable-next-line deprecation/deprecation\n span.spanRecorder = undefined;\n } else {\n this.spans.push(span);\n }\n }\n}\n\n/**\n * Span contains all data about a span\n */\nexport class Span implements SpanInterface {\n /**\n * Tags for the span.\n * @deprecated Use `spanToJSON(span).atttributes` instead.\n */\n public tags: { [key: string]: Primitive };\n\n /**\n * Data for the span.\n * @deprecated Use `spanToJSON(span).atttributes` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public data: { [key: string]: any };\n\n /**\n * List of spans that were finalized\n *\n * @deprecated This property will no longer be public. Span recording will be handled internally.\n */\n public spanRecorder?: SpanRecorder;\n\n /**\n * @inheritDoc\n * @deprecated Use top level `Sentry.getRootSpan()` instead\n */\n public transaction?: Transaction;\n\n /**\n * The instrumenter that created this span.\n *\n * TODO (v8): This can probably be replaced by an `instanceOf` check of the span class.\n * the instrumenter can only be sentry or otel so we can check the span instance\n * to verify which one it is and remove this field entirely.\n *\n * @deprecated This field will be removed.\n */\n public instrumenter: Instrumenter;\n\n protected _traceId: string;\n protected _spanId: string;\n protected _parentSpanId?: string | undefined;\n protected _sampled: boolean | undefined;\n protected _name?: string | undefined;\n protected _attributes: SpanAttributes;\n /** Epoch timestamp in seconds when the span started. */\n protected _startTime: number;\n /** Epoch timestamp in seconds when the span ended. */\n protected _endTime?: number | undefined;\n /** Internal keeper of the status */\n protected _status?: SpanStatusType | string | undefined;\n protected _exclusiveTime?: number;\n\n protected _measurements: Measurements;\n\n private _logMessage?: string;\n\n /**\n * You should never call the constructor manually, always use `Sentry.startTransaction()`\n * or call `startChild()` on an existing span.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(spanContext: SpanContext = {}) {\n this._traceId = spanContext.traceId || uuid4();\n this._spanId = spanContext.spanId || uuid4().substring(16);\n this._startTime = spanContext.startTimestamp || timestampInSeconds();\n // eslint-disable-next-line deprecation/deprecation\n this.tags = spanContext.tags ? { ...spanContext.tags } : {};\n // eslint-disable-next-line deprecation/deprecation\n this.data = spanContext.data ? { ...spanContext.data } : {};\n // eslint-disable-next-line deprecation/deprecation\n this.instrumenter = spanContext.instrumenter || 'sentry';\n\n this._attributes = {};\n this.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanContext.origin || 'manual',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op,\n ...spanContext.attributes,\n });\n\n // eslint-disable-next-line deprecation/deprecation\n this._name = spanContext.name || spanContext.description;\n\n if (spanContext.parentSpanId) {\n this._parentSpanId = spanContext.parentSpanId;\n }\n // We want to include booleans as well here\n if ('sampled' in spanContext) {\n this._sampled = spanContext.sampled;\n }\n if (spanContext.status) {\n this._status = spanContext.status;\n }\n if (spanContext.endTimestamp) {\n this._endTime = spanContext.endTimestamp;\n }\n if (spanContext.exclusiveTime !== undefined) {\n this._exclusiveTime = spanContext.exclusiveTime;\n }\n this._measurements = spanContext.measurements ? { ...spanContext.measurements } : {};\n }\n\n // This rule conflicts with another eslint rule :(\n /* eslint-disable @typescript-eslint/member-ordering */\n\n /**\n * An alias for `description` of the Span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public get name(): string {\n return this._name || '';\n }\n\n /**\n * Update the name of the span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public set name(name: string) {\n this.updateName(name);\n }\n\n /**\n * Get the description of the Span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public get description(): string | undefined {\n return this._name;\n }\n\n /**\n * Get the description of the Span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public set description(description: string | undefined) {\n this._name = description;\n }\n\n /**\n * The ID of the trace.\n * @deprecated Use `spanContext().traceId` instead.\n */\n public get traceId(): string {\n return this._traceId;\n }\n\n /**\n * The ID of the trace.\n * @deprecated You cannot update the traceId of a span after span creation.\n */\n public set traceId(traceId: string) {\n this._traceId = traceId;\n }\n\n /**\n * The ID of the span.\n * @deprecated Use `spanContext().spanId` instead.\n */\n public get spanId(): string {\n return this._spanId;\n }\n\n /**\n * The ID of the span.\n * @deprecated You cannot update the spanId of a span after span creation.\n */\n public set spanId(spanId: string) {\n this._spanId = spanId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `startSpan` functions instead.\n */\n public set parentSpanId(string) {\n this._parentSpanId = string;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToJSON(span).parent_span_id` instead.\n */\n public get parentSpanId(): string | undefined {\n return this._parentSpanId;\n }\n\n /**\n * Was this span chosen to be sent as part of the sample?\n * @deprecated Use `isRecording()` instead.\n */\n public get sampled(): boolean | undefined {\n return this._sampled;\n }\n\n /**\n * Was this span chosen to be sent as part of the sample?\n * @deprecated You cannot update the sampling decision of a span after span creation.\n */\n public set sampled(sampled: boolean | undefined) {\n this._sampled = sampled;\n }\n\n /**\n * Attributes for the span.\n * @deprecated Use `spanToJSON(span).atttributes` instead.\n */\n public get attributes(): SpanAttributes {\n return this._attributes;\n }\n\n /**\n * Attributes for the span.\n * @deprecated Use `setAttributes()` instead.\n */\n public set attributes(attributes: SpanAttributes) {\n this._attributes = attributes;\n }\n\n /**\n * Timestamp in seconds (epoch time) indicating when the span started.\n * @deprecated Use `spanToJSON()` instead.\n */\n public get startTimestamp(): number {\n return this._startTime;\n }\n\n /**\n * Timestamp in seconds (epoch time) indicating when the span started.\n * @deprecated In v8, you will not be able to update the span start time after creation.\n */\n public set startTimestamp(startTime: number) {\n this._startTime = startTime;\n }\n\n /**\n * Timestamp in seconds when the span ended.\n * @deprecated Use `spanToJSON()` instead.\n */\n public get endTimestamp(): number | undefined {\n return this._endTime;\n }\n\n /**\n * Timestamp in seconds when the span ended.\n * @deprecated Set the end time via `span.end()` instead.\n */\n public set endTimestamp(endTime: number | undefined) {\n this._endTime = endTime;\n }\n\n /**\n * The status of the span.\n *\n * @deprecated Use `spanToJSON().status` instead to get the status.\n */\n public get status(): SpanStatusType | string | undefined {\n return this._status;\n }\n\n /**\n * The status of the span.\n *\n * @deprecated Use `.setStatus()` instead to set or update the status.\n */\n public set status(status: SpanStatusType | string | undefined) {\n this._status = status;\n }\n\n /**\n * Operation of the span\n *\n * @deprecated Use `spanToJSON().op` to read the op instead.\n */\n public get op(): string | undefined {\n return this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] as string | undefined;\n }\n\n /**\n * Operation of the span\n *\n * @deprecated Use `startSpan()` functions to set or `span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'op')\n * to update the span instead.\n */\n public set op(op: string | undefined) {\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, op);\n }\n\n /**\n * The origin of the span, giving context about what created the span.\n *\n * @deprecated Use `spanToJSON().origin` to read the origin instead.\n */\n public get origin(): SpanOrigin | undefined {\n return this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] as SpanOrigin | undefined;\n }\n\n /**\n * The origin of the span, giving context about what created the span.\n *\n * @deprecated Use `startSpan()` functions to set the origin instead.\n */\n public set origin(origin: SpanOrigin | undefined) {\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, origin);\n }\n\n /* eslint-enable @typescript-eslint/member-ordering */\n\n /** @inheritdoc */\n public spanContext(): SpanContextData {\n const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this;\n return {\n spanId,\n traceId,\n traceFlags: sampled ? TRACE_FLAG_SAMPLED : TRACE_FLAG_NONE,\n };\n }\n\n /**\n * Creates a new `Span` while setting the current `Span.id` as `parentSpanId`.\n * Also the `sampled` decision will be inherited.\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\n public startChild(\n spanContext?: Pick>,\n ): SpanInterface {\n const childSpan = new Span({\n ...spanContext,\n parentSpanId: this._spanId,\n sampled: this._sampled,\n traceId: this._traceId,\n });\n\n // eslint-disable-next-line deprecation/deprecation\n childSpan.spanRecorder = this.spanRecorder;\n // eslint-disable-next-line deprecation/deprecation\n if (childSpan.spanRecorder) {\n // eslint-disable-next-line deprecation/deprecation\n childSpan.spanRecorder.add(childSpan);\n }\n\n const rootSpan = getRootSpan(this);\n // TODO: still set span.transaction here until we have a more permanent solution\n // Probably similarly to the weakmap we hold in node-experimental\n // eslint-disable-next-line deprecation/deprecation\n childSpan.transaction = rootSpan as Transaction;\n\n if (DEBUG_BUILD && rootSpan) {\n const opStr = (spanContext && spanContext.op) || '< unknown op >';\n const nameStr = spanToJSON(childSpan).description || '< unknown name >';\n const idStr = rootSpan.spanContext().spanId;\n\n const logMessage = `[Tracing] Starting '${opStr}' span on transaction '${nameStr}' (${idStr}).`;\n logger.log(logMessage);\n this._logMessage = logMessage;\n }\n\n return childSpan;\n }\n\n /**\n * Sets the tag attribute on the current span.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key Tag key\n * @param value Tag value\n * @deprecated Use `setAttribute()` instead.\n */\n public setTag(key: string, value: Primitive): this {\n // eslint-disable-next-line deprecation/deprecation\n this.tags = { ...this.tags, [key]: value };\n return this;\n }\n\n /**\n * Sets the data attribute on the current span\n * @param key Data key\n * @param value Data value\n * @deprecated Use `setAttribute()` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setData(key: string, value: any): this {\n // eslint-disable-next-line deprecation/deprecation\n this.data = { ...this.data, [key]: value };\n return this;\n }\n\n /** @inheritdoc */\n public setAttribute(key: string, value: SpanAttributeValue | undefined): void {\n if (value === undefined) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._attributes[key];\n } else {\n this._attributes[key] = value;\n }\n }\n\n /** @inheritdoc */\n public setAttributes(attributes: SpanAttributes): void {\n Object.keys(attributes).forEach(key => this.setAttribute(key, attributes[key]));\n }\n\n /**\n * @inheritDoc\n */\n public setStatus(value: SpanStatusType): this {\n this._status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top-level `setHttpStatus()` instead.\n */\n public setHttpStatus(httpStatus: number): this {\n setHttpStatus(this, httpStatus);\n return this;\n }\n\n /**\n * @inheritdoc\n *\n * @deprecated Use `.updateName()` instead.\n */\n public setName(name: string): void {\n this.updateName(name);\n }\n\n /**\n * @inheritDoc\n */\n public updateName(name: string): this {\n this._name = name;\n return this;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToJSON(span).status === 'ok'` instead.\n */\n public isSuccess(): boolean {\n return this._status === 'ok';\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `.end()` instead.\n */\n public finish(endTimestamp?: number): void {\n return this.end(endTimestamp);\n }\n\n /** @inheritdoc */\n public end(endTimestamp?: SpanTimeInput): void {\n // If already ended, skip\n if (this._endTime) {\n return;\n }\n const rootSpan = getRootSpan(this);\n if (\n DEBUG_BUILD &&\n // Don't call this for transactions\n rootSpan &&\n rootSpan.spanContext().spanId !== this._spanId\n ) {\n const logMessage = this._logMessage;\n if (logMessage) {\n logger.log((logMessage as string).replace('Starting', 'Finishing'));\n }\n }\n\n this._endTime = spanTimeInputToSeconds(endTimestamp);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToTraceHeader()` instead.\n */\n public toTraceparent(): string {\n return spanToTraceHeader(this);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToJSON()` or access the fields directly instead.\n */\n public toContext(): SpanContext {\n return dropUndefinedKeys({\n data: this._getData(),\n description: this._name,\n endTimestamp: this._endTime,\n // eslint-disable-next-line deprecation/deprecation\n op: this.op,\n parentSpanId: this._parentSpanId,\n sampled: this._sampled,\n spanId: this._spanId,\n startTimestamp: this._startTime,\n status: this._status,\n // eslint-disable-next-line deprecation/deprecation\n tags: this.tags,\n traceId: this._traceId,\n });\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Update the fields directly instead.\n */\n public updateWithContext(spanContext: SpanContext): this {\n // eslint-disable-next-line deprecation/deprecation\n this.data = spanContext.data || {};\n // eslint-disable-next-line deprecation/deprecation\n this._name = spanContext.name || spanContext.description;\n this._endTime = spanContext.endTimestamp;\n // eslint-disable-next-line deprecation/deprecation\n this.op = spanContext.op;\n this._parentSpanId = spanContext.parentSpanId;\n this._sampled = spanContext.sampled;\n this._spanId = spanContext.spanId || this._spanId;\n this._startTime = spanContext.startTimestamp || this._startTime;\n this._status = spanContext.status;\n // eslint-disable-next-line deprecation/deprecation\n this.tags = spanContext.tags || {};\n this._traceId = spanContext.traceId || this._traceId;\n\n return this;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToTraceContext()` util function instead.\n */\n public getTraceContext(): TraceContext {\n return spanToTraceContext(this);\n }\n\n /**\n * Get JSON representation of this span.\n *\n * @hidden\n * @internal This method is purely for internal purposes and should not be used outside\n * of SDK code. If you need to get a JSON representation of a span,\n * use `spanToJSON(span)` instead.\n */\n public getSpanJSON(): SpanJSON {\n return dropUndefinedKeys({\n data: this._getData(),\n description: this._name,\n op: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] as string | undefined,\n parent_span_id: this._parentSpanId,\n span_id: this._spanId,\n start_timestamp: this._startTime,\n status: this._status,\n // eslint-disable-next-line deprecation/deprecation\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n timestamp: this._endTime,\n trace_id: this._traceId,\n origin: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] as SpanOrigin | undefined,\n _metrics_summary: getMetricSummaryJsonForSpan(this),\n profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID] as string | undefined,\n exclusive_time: this._exclusiveTime,\n measurements: Object.keys(this._measurements).length > 0 ? this._measurements : undefined,\n });\n }\n\n /** @inheritdoc */\n public isRecording(): boolean {\n return !this._endTime && !!this._sampled;\n }\n\n /**\n * Convert the object to JSON.\n * @deprecated Use `spanToJSON(span)` instead.\n */\n public toJSON(): SpanJSON {\n return this.getSpanJSON();\n }\n\n /**\n * Get the merged data for this span.\n * For now, this combines `data` and `attributes` together,\n * until eventually we can ingest `attributes` directly.\n */\n private _getData():\n | {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n }\n | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const { data, _attributes: attributes } = this;\n\n const hasData = Object.keys(data).length > 0;\n const hasAttributes = Object.keys(attributes).length > 0;\n\n if (!hasData && !hasAttributes) {\n return undefined;\n }\n\n if (hasData && hasAttributes) {\n return {\n ...data,\n ...attributes,\n };\n }\n\n return hasData ? data : attributes;\n }\n}\n","import type { Options } from '@sentry/types';\n\nimport { getClient } from '../exports';\n\n// Treeshakable guard to remove all code related to tracing\ndeclare const __SENTRY_TRACING__: boolean | undefined;\n\n/**\n * Determines if tracing is currently enabled.\n *\n * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config.\n */\nexport function hasTracingEnabled(\n maybeOptions?: Pick | undefined,\n): boolean {\n if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) {\n return false;\n }\n\n const client = getClient();\n const options = maybeOptions || (client && client.getOptions());\n return !!options && (options.enableTracing || 'tracesSampleRate' in options || 'tracesSampler' in options);\n}\n","import type { Scope, Span, SpanTimeInput, StartSpanOptions, TransactionContext } from '@sentry/types';\n\nimport { addNonEnumerableProperty, dropUndefinedKeys, logger, tracingContextFromHeaders } from '@sentry/utils';\nimport { getDynamicSamplingContextFromSpan } from '.';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { getCurrentScope, withScope } from '../exports';\nimport type { Hub } from '../hub';\nimport { runWithAsyncContext } from '../hub';\nimport { getIsolationScope } from '../hub';\nimport { getCurrentHub } from '../hub';\nimport type { Scope as ScopeClass } from '../scope';\nimport { handleCallbackErrors } from '../utils/handleCallbackErrors';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled';\nimport { spanIsSampled, spanTimeInputToSeconds, spanToJSON } from '../utils/spanUtils';\n\n/**\n * Wraps a function with a transaction/span and finishes the span after the function is done.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n *\n * This function is meant to be used internally and may break at any time. Use at your own risk.\n *\n * @internal\n * @private\n *\n * @deprecated Use `startSpan` instead.\n */\nexport function trace(\n context: TransactionContext,\n callback: (span?: Span) => T,\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n onError: (error: unknown, span?: Span) => void = () => {},\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n afterFinish: () => void = () => {},\n): T {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n const scope = getCurrentScope();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const spanContext = normalizeContext(context);\n const activeSpan = createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: false,\n scope,\n });\n\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(activeSpan);\n\n return handleCallbackErrors(\n () => callback(activeSpan),\n error => {\n activeSpan && activeSpan.setStatus('internal_error');\n onError(error, activeSpan);\n },\n () => {\n activeSpan && activeSpan.end();\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(parentSpan);\n afterFinish();\n },\n );\n}\n\n/**\n * Wraps a function with a transaction/span and finishes the span after the function is done.\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getSpan()`, as long as the function is executed while the scope is active.\n *\n * If you want to create a span that is not set as active, use {@link startInactiveSpan}.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n */\nexport function startSpan(context: StartSpanOptions, callback: (span: Span | undefined) => T): T {\n const spanContext = normalizeContext(context);\n\n return runWithAsyncContext(() => {\n return withScope(context.scope, scope => {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const shouldSkipSpan = context.onlyIfParent && !parentSpan;\n const activeSpan = shouldSkipSpan\n ? undefined\n : createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: context.forceTransaction,\n scope,\n });\n\n return handleCallbackErrors(\n () => callback(activeSpan),\n () => {\n // Only update the span status if it hasn't been changed yet\n if (activeSpan) {\n const { status } = spanToJSON(activeSpan);\n if (!status || status === 'ok') {\n activeSpan.setStatus('internal_error');\n }\n }\n },\n () => activeSpan && activeSpan.end(),\n );\n });\n });\n}\n\n/**\n * @deprecated Use {@link startSpan} instead.\n */\nexport const startActiveSpan = startSpan;\n\n/**\n * Similar to `Sentry.startSpan`. Wraps a function with a transaction/span, but does not finish the span\n * after the function is done automatically. You'll have to call `span.end()` manually.\n *\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n */\nexport function startSpanManual(\n context: StartSpanOptions,\n callback: (span: Span | undefined, finish: () => void) => T,\n): T {\n const spanContext = normalizeContext(context);\n\n return runWithAsyncContext(() => {\n return withScope(context.scope, scope => {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const shouldSkipSpan = context.onlyIfParent && !parentSpan;\n const activeSpan = shouldSkipSpan\n ? undefined\n : createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: context.forceTransaction,\n scope,\n });\n\n function finishAndSetSpan(): void {\n activeSpan && activeSpan.end();\n }\n\n return handleCallbackErrors(\n () => callback(activeSpan, finishAndSetSpan),\n () => {\n // Only update the span status if it hasn't been changed yet, and the span is not yet finished\n if (activeSpan && activeSpan.isRecording()) {\n const { status } = spanToJSON(activeSpan);\n if (!status || status === 'ok') {\n activeSpan.setStatus('internal_error');\n }\n }\n },\n );\n });\n });\n}\n\n/**\n * Creates a span. This span is not set as active, so will not get automatic instrumentation spans\n * as children or be able to be accessed via `Sentry.getSpan()`.\n *\n * If you want to create a span that is set as active, use {@link startSpan}.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate` or `tracesSampler`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n */\nexport function startInactiveSpan(context: StartSpanOptions): Span | undefined {\n if (!hasTracingEnabled()) {\n return undefined;\n }\n\n const spanContext = normalizeContext(context);\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n const parentSpan = context.scope\n ? // eslint-disable-next-line deprecation/deprecation\n context.scope.getSpan()\n : getActiveSpan();\n\n const shouldSkipSpan = context.onlyIfParent && !parentSpan;\n\n if (shouldSkipSpan) {\n return undefined;\n }\n\n const scope = context.scope || getCurrentScope();\n\n // Even though we don't actually want to make this span active on the current scope,\n // we need to make it active on a temporary scope that we use for event processing\n // as otherwise, it won't pick the correct span for the event when processing it\n const temporaryScope = (scope as ScopeClass).clone();\n\n return createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: context.forceTransaction,\n scope: temporaryScope,\n });\n}\n\n/**\n * Returns the currently active span.\n */\nexport function getActiveSpan(): Span | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentScope().getSpan();\n}\n\ninterface ContinueTrace {\n /**\n * Continue a trace from `sentry-trace` and `baggage` values.\n * These values can be obtained from incoming request headers,\n * or in the browser from `` and `` HTML tags.\n *\n * @deprecated Use the version of this function taking a callback as second parameter instead:\n *\n * ```\n * Sentry.continueTrace(sentryTrace: '...', baggage: '...' }, () => {\n * // ...\n * })\n * ```\n *\n */\n ({\n sentryTrace,\n baggage,\n }: {\n // eslint-disable-next-line deprecation/deprecation\n sentryTrace: Parameters[0];\n // eslint-disable-next-line deprecation/deprecation\n baggage: Parameters[1];\n }): Partial;\n\n /**\n * Continue a trace from `sentry-trace` and `baggage` values.\n * These values can be obtained from incoming request headers, or in the browser from ``\n * and `` HTML tags.\n *\n * Spans started with `startSpan`, `startSpanManual` and `startInactiveSpan`, within the callback will automatically\n * be attached to the incoming trace.\n *\n * Deprecation notice: In the next major version of the SDK the provided callback will not receive a transaction\n * context argument.\n */\n (\n {\n sentryTrace,\n baggage,\n }: {\n // eslint-disable-next-line deprecation/deprecation\n sentryTrace: Parameters[0];\n // eslint-disable-next-line deprecation/deprecation\n baggage: Parameters[1];\n },\n // TODO(v8): Remove parameter from this callback.\n callback: (transactionContext: Partial) => V,\n ): V;\n}\n\nexport const continueTrace: ContinueTrace = (\n {\n sentryTrace,\n baggage,\n }: {\n // eslint-disable-next-line deprecation/deprecation\n sentryTrace: Parameters[0];\n // eslint-disable-next-line deprecation/deprecation\n baggage: Parameters[1];\n },\n callback?: (transactionContext: Partial) => V,\n): V | Partial => {\n // TODO(v8): Change this function so it doesn't do anything besides setting the propagation context on the current scope:\n /*\n return withScope((scope) => {\n const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);\n scope.setPropagationContext(propagationContext);\n return callback();\n })\n */\n\n const currentScope = getCurrentScope();\n\n // eslint-disable-next-line deprecation/deprecation\n const { traceparentData, dynamicSamplingContext, propagationContext } = tracingContextFromHeaders(\n sentryTrace,\n baggage,\n );\n\n currentScope.setPropagationContext(propagationContext);\n\n if (DEBUG_BUILD && traceparentData) {\n logger.log(`[Tracing] Continuing trace ${traceparentData.traceId}.`);\n }\n\n const transactionContext: Partial = {\n ...traceparentData,\n metadata: dropUndefinedKeys({\n dynamicSamplingContext,\n }),\n };\n\n if (!callback) {\n return transactionContext;\n }\n\n return runWithAsyncContext(() => {\n return callback(transactionContext);\n });\n};\n\nfunction createChildSpanOrTransaction(\n // eslint-disable-next-line deprecation/deprecation\n hub: Hub,\n {\n parentSpan,\n spanContext,\n forceTransaction,\n scope,\n }: {\n parentSpan: Span | undefined;\n spanContext: TransactionContext;\n forceTransaction?: boolean;\n scope: Scope;\n },\n): Span | undefined {\n if (!hasTracingEnabled()) {\n return undefined;\n }\n\n const isolationScope = getIsolationScope();\n\n let span: Span | undefined;\n if (parentSpan && !forceTransaction) {\n // eslint-disable-next-line deprecation/deprecation\n span = parentSpan.startChild(spanContext);\n } else if (parentSpan) {\n // If we forced a transaction but have a parent span, make sure to continue from the parent span, not the scope\n const dsc = getDynamicSamplingContextFromSpan(parentSpan);\n const { traceId, spanId: parentSpanId } = parentSpan.spanContext();\n const sampled = spanIsSampled(parentSpan);\n\n // eslint-disable-next-line deprecation/deprecation\n span = hub.startTransaction({\n traceId,\n parentSpanId,\n parentSampled: sampled,\n ...spanContext,\n metadata: {\n dynamicSamplingContext: dsc,\n // eslint-disable-next-line deprecation/deprecation\n ...spanContext.metadata,\n },\n });\n } else {\n const { traceId, dsc, parentSpanId, sampled } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n // eslint-disable-next-line deprecation/deprecation\n span = hub.startTransaction({\n traceId,\n parentSpanId,\n parentSampled: sampled,\n ...spanContext,\n metadata: {\n dynamicSamplingContext: dsc,\n // eslint-disable-next-line deprecation/deprecation\n ...spanContext.metadata,\n },\n });\n }\n\n // We always set this as active span on the scope\n // In the case of this being an inactive span, we ensure to pass a detached scope in here in the first place\n // But by having this here, we can ensure that the lookup through `getCapturedScopesOnSpan` results in the correct scope & span combo\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(span);\n\n setCapturedScopesOnSpan(span, scope, isolationScope);\n\n return span;\n}\n\n/**\n * This converts StartSpanOptions to TransactionContext.\n * For the most part (for now) we accept the same options,\n * but some of them need to be transformed.\n *\n * Eventually the StartSpanOptions will be more aligned with OpenTelemetry.\n */\nfunction normalizeContext(context: StartSpanOptions): TransactionContext {\n if (context.startTime) {\n const ctx: TransactionContext & { startTime?: SpanTimeInput } = { ...context };\n ctx.startTimestamp = spanTimeInputToSeconds(context.startTime);\n delete ctx.startTime;\n return ctx;\n }\n\n return context;\n}\n\nconst SCOPE_ON_START_SPAN_FIELD = '_sentryScope';\nconst ISOLATION_SCOPE_ON_START_SPAN_FIELD = '_sentryIsolationScope';\n\ntype SpanWithScopes = Span & {\n [SCOPE_ON_START_SPAN_FIELD]?: Scope;\n [ISOLATION_SCOPE_ON_START_SPAN_FIELD]?: Scope;\n};\n\nfunction setCapturedScopesOnSpan(span: Span | undefined, scope: Scope, isolationScope: Scope): void {\n if (span) {\n addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, isolationScope);\n addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope);\n }\n}\n\n/**\n * Grabs the scope and isolation scope off a span that were active when the span was started.\n */\nexport function getCapturedScopesOnSpan(span: Span): { scope?: Scope; isolationScope?: Scope } {\n return {\n scope: (span as SpanWithScopes)[SCOPE_ON_START_SPAN_FIELD],\n isolationScope: (span as SpanWithScopes)[ISOLATION_SCOPE_ON_START_SPAN_FIELD],\n };\n}\n","import type {\n Context,\n Contexts,\n DynamicSamplingContext,\n MeasurementUnit,\n SpanTimeInput,\n Transaction as TransactionInterface,\n TransactionContext,\n TransactionEvent,\n TransactionMetadata,\n} from '@sentry/types';\nimport { dropUndefinedKeys, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Hub } from '../hub';\nimport { getCurrentHub } from '../hub';\nimport { getMetricSummaryJsonForSpan } from '../metrics/metric-summary';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '../semanticAttributes';\nimport { spanTimeInputToSeconds, spanToJSON, spanToTraceContext } from '../utils/spanUtils';\nimport { getDynamicSamplingContextFromSpan } from './dynamicSamplingContext';\nimport { Span as SpanClass, SpanRecorder } from './span';\nimport { getCapturedScopesOnSpan } from './trace';\n\n/** JSDoc */\nexport class Transaction extends SpanClass implements TransactionInterface {\n /**\n * The reference to the current hub.\n */\n // eslint-disable-next-line deprecation/deprecation\n public _hub: Hub;\n\n protected _name: string;\n\n private _contexts: Contexts;\n\n private _trimEnd?: boolean | undefined;\n\n // DO NOT yet remove this property, it is used in a hack for v7 backwards compatibility.\n private _frozenDynamicSamplingContext: Readonly> | undefined;\n\n private _metadata: Partial;\n\n /**\n * This constructor should never be called manually. Those instrumenting tracing should use\n * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.\n * @internal\n * @hideconstructor\n * @hidden\n *\n * @deprecated Transactions will be removed in v8. Use spans instead.\n */\n // eslint-disable-next-line deprecation/deprecation\n public constructor(transactionContext: TransactionContext, hub?: Hub) {\n super(transactionContext);\n this._contexts = {};\n\n // eslint-disable-next-line deprecation/deprecation\n this._hub = hub || getCurrentHub();\n\n this._name = transactionContext.name || '';\n\n this._metadata = {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.metadata,\n };\n\n this._trimEnd = transactionContext.trimEnd;\n\n // this is because transactions are also spans, and spans have a transaction pointer\n // TODO (v8): Replace this with another way to set the root span\n // eslint-disable-next-line deprecation/deprecation\n this.transaction = this;\n\n // If Dynamic Sampling Context is provided during the creation of the transaction, we freeze it as it usually means\n // there is incoming Dynamic Sampling Context. (Either through an incoming request, a baggage meta-tag, or other means)\n const incomingDynamicSamplingContext = this._metadata.dynamicSamplingContext;\n if (incomingDynamicSamplingContext) {\n // We shallow copy this in case anything writes to the original reference of the passed in `dynamicSamplingContext`\n this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext };\n }\n }\n\n // This sadly conflicts with the getter/setter ordering :(\n /* eslint-disable @typescript-eslint/member-ordering */\n\n /**\n * Getter for `name` property.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public get name(): string {\n return this._name;\n }\n\n /**\n * Setter for `name` property, which also sets `source` as custom.\n * @deprecated Use `updateName()` and `setMetadata()` instead.\n */\n public set name(newName: string) {\n // eslint-disable-next-line deprecation/deprecation\n this.setName(newName);\n }\n\n /**\n * Get the metadata for this transaction.\n * @deprecated Use `spanGetMetadata(transaction)` instead.\n */\n public get metadata(): TransactionMetadata {\n // We merge attributes in for backwards compatibility\n return {\n // Defaults\n // eslint-disable-next-line deprecation/deprecation\n source: 'custom',\n spanMetadata: {},\n\n // Legacy metadata\n ...this._metadata,\n\n // From attributes\n ...(this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] && {\n source: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] as TransactionMetadata['source'],\n }),\n ...(this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] && {\n sampleRate: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] as TransactionMetadata['sampleRate'],\n }),\n };\n }\n\n /**\n * Update the metadata for this transaction.\n * @deprecated Use `spanGetMetadata(transaction)` instead.\n */\n public set metadata(metadata: TransactionMetadata) {\n this._metadata = metadata;\n }\n\n /* eslint-enable @typescript-eslint/member-ordering */\n\n /**\n * Setter for `name` property, which also sets `source` on the metadata.\n *\n * @deprecated Use `.updateName()` and `.setAttribute()` instead.\n */\n public setName(name: string, source: TransactionMetadata['source'] = 'custom'): void {\n this._name = name;\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source);\n }\n\n /** @inheritdoc */\n public updateName(name: string): this {\n this._name = name;\n return this;\n }\n\n /**\n * Attaches SpanRecorder to the span itself\n * @param maxlen maximum number of spans that can be recorded\n */\n public initSpanRecorder(maxlen: number = 1000): void {\n // eslint-disable-next-line deprecation/deprecation\n if (!this.spanRecorder) {\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder = new SpanRecorder(maxlen);\n }\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.add(this);\n }\n\n /**\n * Set the context of a transaction event.\n * @deprecated Use either `.setAttribute()`, or set the context on the scope before creating the transaction.\n */\n public setContext(key: string, context: Context | null): void {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use top-level `setMeasurement()` instead.\n */\n public setMeasurement(name: string, value: number, unit: MeasurementUnit = ''): void {\n this._measurements[name] = { value, unit };\n }\n\n /**\n * Store metadata on this transaction.\n * @deprecated Use attributes or store data on the scope instead.\n */\n public setMetadata(newMetadata: Partial): void {\n this._metadata = { ...this._metadata, ...newMetadata };\n }\n\n /**\n * @inheritDoc\n */\n public end(endTimestamp?: SpanTimeInput): string | undefined {\n const timestampInS = spanTimeInputToSeconds(endTimestamp);\n const transaction = this._finishTransaction(timestampInS);\n if (!transaction) {\n return undefined;\n }\n // eslint-disable-next-line deprecation/deprecation\n return this._hub.captureEvent(transaction);\n }\n\n /**\n * @inheritDoc\n */\n public toContext(): TransactionContext {\n // eslint-disable-next-line deprecation/deprecation\n const spanContext = super.toContext();\n\n return dropUndefinedKeys({\n ...spanContext,\n name: this._name,\n trimEnd: this._trimEnd,\n });\n }\n\n /**\n * @inheritDoc\n */\n public updateWithContext(transactionContext: TransactionContext): this {\n // eslint-disable-next-line deprecation/deprecation\n super.updateWithContext(transactionContext);\n\n this._name = transactionContext.name || '';\n this._trimEnd = transactionContext.trimEnd;\n\n return this;\n }\n\n /**\n * @inheritdoc\n *\n * @experimental\n *\n * @deprecated Use top-level `getDynamicSamplingContextFromSpan` instead.\n */\n public getDynamicSamplingContext(): Readonly> {\n return getDynamicSamplingContextFromSpan(this);\n }\n\n /**\n * Override the current hub with a new one.\n * Used if you want another hub to finish the transaction.\n *\n * @internal\n */\n // eslint-disable-next-line deprecation/deprecation\n public setHub(hub: Hub): void {\n this._hub = hub;\n }\n\n /**\n * Get the profile id of the transaction.\n */\n public getProfileId(): string | undefined {\n if (this._contexts !== undefined && this._contexts['profile'] !== undefined) {\n return this._contexts['profile'].profile_id as string;\n }\n return undefined;\n }\n\n /**\n * Finish the transaction & prepare the event to send to Sentry.\n */\n protected _finishTransaction(endTimestamp?: number): TransactionEvent | undefined {\n // This transaction is already finished, so we should not flush it again.\n if (this._endTime !== undefined) {\n return undefined;\n }\n\n if (!this._name) {\n DEBUG_BUILD && logger.warn('Transaction has no name, falling back to ``.');\n this._name = '';\n }\n\n // just sets the end timestamp\n super.end(endTimestamp);\n\n // eslint-disable-next-line deprecation/deprecation\n const client = this._hub.getClient();\n if (client && client.emit) {\n client.emit('finishTransaction', this);\n }\n\n if (this._sampled !== true) {\n // At this point if `sampled !== true` we want to discard the transaction.\n DEBUG_BUILD && logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');\n\n if (client) {\n client.recordDroppedEvent('sample_rate', 'transaction');\n }\n\n return undefined;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n const finishedSpans = this.spanRecorder\n ? // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.spans.filter(span => span !== this && spanToJSON(span).timestamp)\n : [];\n\n if (this._trimEnd && finishedSpans.length > 0) {\n const endTimes = finishedSpans.map(span => spanToJSON(span).timestamp).filter(Boolean) as number[];\n this._endTime = endTimes.reduce((prev, current) => {\n return prev > current ? prev : current;\n });\n }\n\n const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this);\n\n // eslint-disable-next-line deprecation/deprecation\n const { metadata } = this;\n // eslint-disable-next-line deprecation/deprecation\n const { source } = metadata;\n\n const transaction: TransactionEvent = {\n contexts: {\n ...this._contexts,\n // We don't want to override trace context\n trace: spanToTraceContext(this),\n },\n // TODO: Pass spans serialized via `spanToJSON()` here instead in v8.\n spans: finishedSpans,\n start_timestamp: this._startTime,\n // eslint-disable-next-line deprecation/deprecation\n tags: this.tags,\n timestamp: this._endTime,\n transaction: this._name,\n type: 'transaction',\n sdkProcessingMetadata: {\n ...metadata,\n capturedSpanScope,\n capturedSpanIsolationScope,\n ...dropUndefinedKeys({\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(this),\n }),\n },\n _metrics_summary: getMetricSummaryJsonForSpan(this),\n ...(source && {\n transaction_info: {\n source,\n },\n }),\n };\n\n const hasMeasurements = Object.keys(this._measurements).length > 0;\n\n if (hasMeasurements) {\n DEBUG_BUILD &&\n logger.log(\n '[Measurements] Adding measurements to transaction',\n JSON.stringify(this._measurements, undefined, 2),\n );\n transaction.measurements = this._measurements;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n DEBUG_BUILD && logger.log(`[Tracing] Finishing ${this.op} transaction: ${this._name}.`);\n\n return transaction;\n }\n}\n","/* eslint-disable max-lines */\nimport type { SpanTimeInput, TransactionContext } from '@sentry/types';\nimport { logger, timestampInSeconds } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Hub } from '../hub';\nimport { spanTimeInputToSeconds, spanToJSON } from '../utils/spanUtils';\nimport type { Span } from './span';\nimport { SpanRecorder } from './span';\nimport { Transaction } from './transaction';\n\nexport const TRACING_DEFAULTS = {\n idleTimeout: 1000,\n finalTimeout: 30000,\n heartbeatInterval: 5000,\n};\n\nconst FINISH_REASON_TAG = 'finishReason';\n\nconst IDLE_TRANSACTION_FINISH_REASONS = [\n 'heartbeatFailed',\n 'idleTimeout',\n 'documentHidden',\n 'finalTimeout',\n 'externalFinish',\n 'cancelled',\n];\n\n/**\n * @inheritDoc\n */\nexport class IdleTransactionSpanRecorder extends SpanRecorder {\n public constructor(\n private readonly _pushActivity: (id: string) => void,\n private readonly _popActivity: (id: string) => void,\n public transactionSpanId: string,\n maxlen?: number,\n ) {\n super(maxlen);\n }\n\n /**\n * @inheritDoc\n */\n public add(span: Span): void {\n // We should make sure we do not push and pop activities for\n // the transaction that this span recorder belongs to.\n if (span.spanContext().spanId !== this.transactionSpanId) {\n // We patch span.end() to pop an activity after setting an endTimestamp.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalEnd = span.end;\n span.end = (...rest: unknown[]) => {\n this._popActivity(span.spanContext().spanId);\n return originalEnd.apply(span, rest);\n };\n\n // We should only push new activities if the span does not have an end timestamp.\n if (spanToJSON(span).timestamp === undefined) {\n this._pushActivity(span.spanContext().spanId);\n }\n }\n\n super.add(span);\n }\n}\n\nexport type BeforeFinishCallback = (transactionSpan: IdleTransaction, endTimestamp: number) => void;\n\n/**\n * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.\n * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will\n * put itself on the scope on creation.\n */\nexport class IdleTransaction extends Transaction {\n // Activities store a list of active spans\n public activities: Record;\n // Track state of activities in previous heartbeat\n private _prevHeartbeatString: string | undefined;\n\n // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.\n private _heartbeatCounter: number;\n\n // We should not use heartbeat if we finished a transaction\n private _finished: boolean;\n\n // Idle timeout was canceled and we should finish the transaction with the last span end.\n private _idleTimeoutCanceledPermanently: boolean;\n\n private readonly _beforeFinishCallbacks: BeforeFinishCallback[];\n\n /**\n * Timer that tracks Transaction idleTimeout\n */\n private _idleTimeoutID: ReturnType | undefined;\n\n private _finishReason: (typeof IDLE_TRANSACTION_FINISH_REASONS)[number];\n\n private _autoFinishAllowed: boolean;\n\n /**\n * @deprecated Transactions will be removed in v8. Use spans instead.\n */\n public constructor(\n transactionContext: TransactionContext,\n // eslint-disable-next-line deprecation/deprecation\n private readonly _idleHub: Hub,\n /**\n * The time to wait in ms until the idle transaction will be finished. This timer is started each time\n * there are no active spans on this transaction.\n */\n private readonly _idleTimeout: number = TRACING_DEFAULTS.idleTimeout,\n /**\n * The final value in ms that a transaction cannot exceed\n */\n private readonly _finalTimeout: number = TRACING_DEFAULTS.finalTimeout,\n private readonly _heartbeatInterval: number = TRACING_DEFAULTS.heartbeatInterval,\n // Whether or not the transaction should put itself on the scope when it starts and pop itself off when it ends\n private readonly _onScope: boolean = false,\n /**\n * When set to `true`, will disable the idle timeout (`_idleTimeout` option) and heartbeat mechanisms (`_heartbeatInterval`\n * option) until the `sendAutoFinishSignal()` method is called. The final timeout mechanism (`_finalTimeout` option)\n * will not be affected by this option, meaning the transaction will definitely be finished when the final timeout is\n * reached, no matter what this option is configured to.\n *\n * Defaults to `false`.\n */\n delayAutoFinishUntilSignal: boolean = false,\n ) {\n super(transactionContext, _idleHub);\n\n this.activities = {};\n this._heartbeatCounter = 0;\n this._finished = false;\n this._idleTimeoutCanceledPermanently = false;\n this._beforeFinishCallbacks = [];\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[4];\n this._autoFinishAllowed = !delayAutoFinishUntilSignal;\n\n if (_onScope) {\n // We set the transaction here on the scope so error events pick up the trace\n // context and attach it to the error.\n DEBUG_BUILD && logger.log(`Setting idle transaction on scope. Span ID: ${this.spanContext().spanId}`);\n // eslint-disable-next-line deprecation/deprecation\n _idleHub.getScope().setSpan(this);\n }\n\n if (!delayAutoFinishUntilSignal) {\n this._restartIdleTimeout();\n }\n\n setTimeout(() => {\n if (!this._finished) {\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[3];\n this.end();\n }\n }, this._finalTimeout);\n }\n\n /** {@inheritDoc} */\n public end(endTimestamp?: SpanTimeInput): string | undefined {\n const endTimestampInS = spanTimeInputToSeconds(endTimestamp);\n\n this._finished = true;\n this.activities = {};\n\n // eslint-disable-next-line deprecation/deprecation\n if (this.op === 'ui.action.click') {\n this.setAttribute(FINISH_REASON_TAG, this._finishReason);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n if (this.spanRecorder) {\n DEBUG_BUILD &&\n // eslint-disable-next-line deprecation/deprecation\n logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestampInS * 1000).toISOString(), this.op);\n\n for (const callback of this._beforeFinishCallbacks) {\n callback(this, endTimestampInS);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.spans = this.spanRecorder.spans.filter((span: Span) => {\n // If we are dealing with the transaction itself, we just return it\n if (span.spanContext().spanId === this.spanContext().spanId) {\n return true;\n }\n\n // We cancel all pending spans with status \"cancelled\" to indicate the idle transaction was finished early\n if (!spanToJSON(span).timestamp) {\n span.setStatus('cancelled');\n span.end(endTimestampInS);\n DEBUG_BUILD &&\n logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));\n }\n\n const { start_timestamp: startTime, timestamp: endTime } = spanToJSON(span);\n const spanStartedBeforeTransactionFinish = startTime && startTime < endTimestampInS;\n\n // Add a delta with idle timeout so that we prevent false positives\n const timeoutWithMarginOfError = (this._finalTimeout + this._idleTimeout) / 1000;\n const spanEndedBeforeFinalTimeout = endTime && startTime && endTime - startTime < timeoutWithMarginOfError;\n\n if (DEBUG_BUILD) {\n const stringifiedSpan = JSON.stringify(span, undefined, 2);\n if (!spanStartedBeforeTransactionFinish) {\n logger.log('[Tracing] discarding Span since it happened after Transaction was finished', stringifiedSpan);\n } else if (!spanEndedBeforeFinalTimeout) {\n logger.log('[Tracing] discarding Span since it finished after Transaction final timeout', stringifiedSpan);\n }\n }\n\n return spanStartedBeforeTransactionFinish && spanEndedBeforeFinalTimeout;\n });\n\n DEBUG_BUILD && logger.log('[Tracing] flushing IdleTransaction');\n } else {\n DEBUG_BUILD && logger.log('[Tracing] No active IdleTransaction');\n }\n\n // if `this._onScope` is `true`, the transaction put itself on the scope when it started\n if (this._onScope) {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this._idleHub.getScope();\n // eslint-disable-next-line deprecation/deprecation\n if (scope.getTransaction() === this) {\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(undefined);\n }\n }\n\n return super.end(endTimestamp);\n }\n\n /**\n * Register a callback function that gets executed before the transaction finishes.\n * Useful for cleanup or if you want to add any additional spans based on current context.\n *\n * This is exposed because users have no other way of running something before an idle transaction\n * finishes.\n */\n public registerBeforeFinishCallback(callback: BeforeFinishCallback): void {\n this._beforeFinishCallbacks.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public initSpanRecorder(maxlen?: number): void {\n // eslint-disable-next-line deprecation/deprecation\n if (!this.spanRecorder) {\n const pushActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._pushActivity(id);\n };\n const popActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._popActivity(id);\n };\n\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanContext().spanId, maxlen);\n\n // Start heartbeat so that transactions do not run forever.\n DEBUG_BUILD && logger.log('Starting heartbeat');\n this._pingHeartbeat();\n }\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.add(this);\n }\n\n /**\n * Cancels the existing idle timeout, if there is one.\n * @param restartOnChildSpanChange Default is `true`.\n * If set to false the transaction will end\n * with the last child span.\n */\n public cancelIdleTimeout(\n endTimestamp?: Parameters[0],\n {\n restartOnChildSpanChange,\n }: {\n restartOnChildSpanChange?: boolean;\n } = {\n restartOnChildSpanChange: true,\n },\n ): void {\n this._idleTimeoutCanceledPermanently = restartOnChildSpanChange === false;\n if (this._idleTimeoutID) {\n clearTimeout(this._idleTimeoutID);\n this._idleTimeoutID = undefined;\n\n if (Object.keys(this.activities).length === 0 && this._idleTimeoutCanceledPermanently) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.end(endTimestamp);\n }\n }\n }\n\n /**\n * Temporary method used to externally set the transaction's `finishReason`\n *\n * ** WARNING**\n * This is for the purpose of experimentation only and will be removed in the near future, do not use!\n *\n * @internal\n *\n */\n public setFinishReason(reason: string): void {\n this._finishReason = reason;\n }\n\n /**\n * Permits the IdleTransaction to automatically end itself via the idle timeout and heartbeat mechanisms when the `delayAutoFinishUntilSignal` option was set to `true`.\n */\n public sendAutoFinishSignal(): void {\n if (!this._autoFinishAllowed) {\n DEBUG_BUILD && logger.log('[Tracing] Received finish signal for idle transaction.');\n this._restartIdleTimeout();\n this._autoFinishAllowed = true;\n }\n }\n\n /**\n * Restarts idle timeout, if there is no running idle timeout it will start one.\n */\n private _restartIdleTimeout(endTimestamp?: Parameters[0]): void {\n this.cancelIdleTimeout();\n this._idleTimeoutID = setTimeout(() => {\n if (!this._finished && Object.keys(this.activities).length === 0) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[1];\n this.end(endTimestamp);\n }\n }, this._idleTimeout);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n private _pushActivity(spanId: string): void {\n this.cancelIdleTimeout(undefined, { restartOnChildSpanChange: !this._idleTimeoutCanceledPermanently });\n DEBUG_BUILD && logger.log(`[Tracing] pushActivity: ${spanId}`);\n this.activities[spanId] = true;\n DEBUG_BUILD && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n private _popActivity(spanId: string): void {\n if (this.activities[spanId]) {\n DEBUG_BUILD && logger.log(`[Tracing] popActivity ${spanId}`);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this.activities[spanId];\n DEBUG_BUILD && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n if (Object.keys(this.activities).length === 0) {\n const endTimestamp = timestampInSeconds();\n if (this._idleTimeoutCanceledPermanently) {\n if (this._autoFinishAllowed) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.end(endTimestamp);\n }\n } else {\n // We need to add the timeout here to have the real endtimestamp of the transaction\n // Remember timestampInSeconds is in seconds, timeout is in ms\n this._restartIdleTimeout(endTimestamp + this._idleTimeout / 1000);\n }\n }\n }\n\n /**\n * Checks when entries of this.activities are not changing for 3 beats.\n * If this occurs we finish the transaction.\n */\n private _beat(): void {\n // We should not be running heartbeat if the idle transaction is finished.\n if (this._finished) {\n return;\n }\n\n const heartbeatString = Object.keys(this.activities).join('');\n\n if (heartbeatString === this._prevHeartbeatString) {\n this._heartbeatCounter++;\n } else {\n this._heartbeatCounter = 1;\n }\n\n this._prevHeartbeatString = heartbeatString;\n\n if (this._heartbeatCounter >= 3) {\n if (this._autoFinishAllowed) {\n DEBUG_BUILD && logger.log('[Tracing] Transaction finished because of no change for 3 heart beats');\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[0];\n this.end();\n }\n } else {\n this._pingHeartbeat();\n }\n }\n\n /**\n * Pings the heartbeat\n */\n private _pingHeartbeat(): void {\n DEBUG_BUILD && logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);\n setTimeout(() => {\n this._beat();\n }, this._heartbeatInterval);\n }\n}\n","import type { Transaction } from '@sentry/types';\nimport { extractTraceparentData as _extractTraceparentData } from '@sentry/utils';\n\nimport type { Hub } from '../hub';\nimport { getCurrentHub } from '../hub';\n\n/**\n * Grabs active transaction off scope.\n *\n * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getActiveTransaction(maybeHub?: Hub): T | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const hub = maybeHub || getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const scope = hub.getScope();\n // eslint-disable-next-line deprecation/deprecation\n return scope.getTransaction() as T | undefined;\n}\n\n// so it can be used in manual instrumentation without necessitating a hard dependency on @sentry/utils\nexport { stripUrlQueryAndFragment } from '@sentry/utils';\n\n/**\n * The `extractTraceparentData` function and `TRACEPARENT_REGEXP` constant used\n * to be declared in this file. It was later moved into `@sentry/utils` as part of a\n * move to remove `@sentry/tracing` dependencies from `@sentry/node` (`extractTraceparentData`\n * is the only tracing function used by `@sentry/node`).\n *\n * These exports are kept here for backwards compatability's sake.\n *\n * See https://github.com/getsentry/sentry-javascript/issues/4642 for more details.\n *\n * @deprecated Import this function from `@sentry/utils` instead\n */\nexport const extractTraceparentData = _extractTraceparentData;\n","import {\n addGlobalErrorInstrumentationHandler,\n addGlobalUnhandledRejectionInstrumentationHandler,\n logger,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { SpanStatusType } from './spanstatus';\nimport { getActiveTransaction } from './utils';\n\nlet errorsInstrumented = false;\n\n/**\n * Configures global error listeners\n */\nexport function registerErrorInstrumentation(): void {\n if (errorsInstrumented) {\n return;\n }\n\n errorsInstrumented = true;\n addGlobalErrorInstrumentationHandler(errorCallback);\n addGlobalUnhandledRejectionInstrumentationHandler(errorCallback);\n}\n\n/**\n * If an error or unhandled promise occurs, we mark the active transaction as failed\n */\nfunction errorCallback(): void {\n // eslint-disable-next-line deprecation/deprecation\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n const status: SpanStatusType = 'internal_error';\n DEBUG_BUILD && logger.log(`[Tracing] Transaction: ${status} -> Global error occured`);\n activeTransaction.setStatus(status);\n }\n}\n\n// The function name will be lost when bundling but we need to be able to identify this listener later to maintain the\n// node.js default exit behaviour\nerrorCallback.tag = 'sentry_tracingErrorCallback';\n","import type { Options, SamplingContext } from '@sentry/types';\nimport { isNaN, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE } from '../semanticAttributes';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled';\nimport { spanToJSON } from '../utils/spanUtils';\nimport type { Transaction } from './transaction';\n\n/**\n * Makes a sampling decision for the given transaction and stores it on the transaction.\n *\n * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n *\n * This method muttes the given `transaction` and will set the `sampled` value on it.\n * It returns the same transaction, for convenience.\n */\nexport function sampleTransaction(\n transaction: T,\n options: Pick,\n samplingContext: SamplingContext,\n): T {\n // nothing to do if tracing is not enabled\n if (!hasTracingEnabled(options)) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = false;\n return transaction;\n }\n\n // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that\n // eslint-disable-next-line deprecation/deprecation\n if (transaction.sampled !== undefined) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(transaction.sampled));\n return transaction;\n }\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` nor `enableTracing` were defined, so one of these should\n // work; prefer the hook if so\n let sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler(samplingContext);\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(sampleRate));\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(sampleRate));\n } else {\n // When `enableTracing === true`, we use a sample rate of 100%\n sampleRate = 1;\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, sampleRate);\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(sampleRate)) {\n DEBUG_BUILD && logger.warn('[Tracing] Discarding transaction because of invalid sample rate.');\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = false;\n return transaction;\n }\n\n // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n if (!sampleRate) {\n DEBUG_BUILD &&\n logger.log(\n `[Tracing] Discarding transaction because ${\n typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n }`,\n );\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = false;\n return transaction;\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = Math.random() < (sampleRate as number | boolean);\n\n // if we're not going to keep it, we're done\n // eslint-disable-next-line deprecation/deprecation\n if (!transaction.sampled) {\n DEBUG_BUILD &&\n logger.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n return transaction;\n }\n\n DEBUG_BUILD &&\n // eslint-disable-next-line deprecation/deprecation\n logger.log(`[Tracing] starting ${transaction.op} transaction - ${spanToJSON(transaction).description}`);\n return transaction;\n}\n\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nexport function isValidSampleRate(rate: unknown): boolean {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {\n DEBUG_BUILD &&\n logger.warn(\n `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n rate,\n )} of type ${JSON.stringify(typeof rate)}.`,\n );\n return false;\n }\n\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n DEBUG_BUILD &&\n logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);\n return false;\n }\n return true;\n}\n","import type { ClientOptions, CustomSamplingContext, TransactionContext } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Hub } from '../hub';\nimport { getMainCarrier } from '../hub';\nimport { spanToTraceHeader } from '../utils/spanUtils';\nimport { registerErrorInstrumentation } from './errors';\nimport { IdleTransaction } from './idletransaction';\nimport { sampleTransaction } from './sampling';\nimport { Transaction } from './transaction';\n\n/** Returns all trace headers that are currently on the top scope. */\n// eslint-disable-next-line deprecation/deprecation\nfunction traceHeaders(this: Hub): { [key: string]: string } {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.getScope();\n // eslint-disable-next-line deprecation/deprecation\n const span = scope.getSpan();\n\n return span\n ? {\n 'sentry-trace': spanToTraceHeader(span),\n }\n : {};\n}\n\n/**\n * Creates a new transaction and adds a sampling decision if it doesn't yet have one.\n *\n * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if\n * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an\n * \"extension method.\"\n *\n * @param this: The Hub starting the transaction\n * @param transactionContext: Data used to configure the transaction\n * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any)\n *\n * @returns The new transaction\n *\n * @see {@link Hub.startTransaction}\n */\nfunction _startTransaction(\n // eslint-disable-next-line deprecation/deprecation\n this: Hub,\n transactionContext: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): Transaction {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n const options: Partial = (client && client.getOptions()) || {};\n\n const configInstrumenter = options.instrumenter || 'sentry';\n const transactionInstrumenter = transactionContext.instrumenter || 'sentry';\n\n if (configInstrumenter !== transactionInstrumenter) {\n DEBUG_BUILD &&\n logger.error(\n `A transaction was started with instrumenter=\\`${transactionInstrumenter}\\`, but the SDK is configured with the \\`${configInstrumenter}\\` instrumenter.\nThe transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`,\n );\n\n // eslint-disable-next-line deprecation/deprecation\n transactionContext.sampled = false;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n let transaction = new Transaction(transactionContext, this);\n transaction = sampleTransaction(transaction, options, {\n name: transactionContext.name,\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n attributes: {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.data,\n ...transactionContext.attributes,\n },\n ...customSamplingContext,\n });\n if (transaction.isRecording()) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Create new idle transaction.\n */\nexport function startIdleTransaction(\n // eslint-disable-next-line deprecation/deprecation\n hub: Hub,\n transactionContext: TransactionContext,\n idleTimeout: number,\n finalTimeout: number,\n onScope?: boolean,\n customSamplingContext?: CustomSamplingContext,\n heartbeatInterval?: number,\n delayAutoFinishUntilSignal: boolean = false,\n): IdleTransaction {\n // eslint-disable-next-line deprecation/deprecation\n const client = hub.getClient();\n const options: Partial = (client && client.getOptions()) || {};\n\n // eslint-disable-next-line deprecation/deprecation\n let transaction = new IdleTransaction(\n transactionContext,\n hub,\n idleTimeout,\n finalTimeout,\n heartbeatInterval,\n onScope,\n delayAutoFinishUntilSignal,\n );\n transaction = sampleTransaction(transaction, options, {\n name: transactionContext.name,\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n attributes: {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.data,\n ...transactionContext.attributes,\n },\n ...customSamplingContext,\n });\n if (transaction.isRecording()) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Adds tracing extensions to the global hub.\n */\nexport function addTracingExtensions(): void {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n if (!carrier.__SENTRY__.extensions.startTransaction) {\n carrier.__SENTRY__.extensions.startTransaction = _startTransaction;\n }\n if (!carrier.__SENTRY__.extensions.traceHeaders) {\n carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;\n }\n\n registerErrorInstrumentation();\n}\n","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","import { GLOBAL_OBJ } from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ &\n // document is not available in all browser environments (webworkers). We make it optional so you have to explicitly check for it\n Omit &\n Partial>;\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Metric, ReportCallback } from '../types';\n\nexport const bindReporter = (\n callback: ReportCallback,\n metric: Metric,\n reportAllChanges?: boolean,\n): ((forceReport?: boolean) => void) => {\n let prevValue: number;\n let delta: number;\n return (forceReport?: boolean) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n delta = metric.value - (prevValue || 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (delta || prevValue === undefined) {\n prevValue = metric.value;\n metric.delta = delta;\n callback(metric);\n }\n }\n }\n };\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Metric } from '../../types';\nimport { observe } from '../observe';\n\ndeclare global {\n interface Performance {\n interactionCount: number;\n }\n}\n\nlet interactionCountEstimate = 0;\nlet minKnownInteractionId = Infinity;\nlet maxKnownInteractionId = 0;\n\nconst updateEstimate = (entries: Metric['entries']): void => {\n (entries as PerformanceEventTiming[]).forEach(e => {\n if (e.interactionId) {\n minKnownInteractionId = Math.min(minKnownInteractionId, e.interactionId);\n maxKnownInteractionId = Math.max(maxKnownInteractionId, e.interactionId);\n\n interactionCountEstimate = maxKnownInteractionId ? (maxKnownInteractionId - minKnownInteractionId) / 7 + 1 : 0;\n }\n });\n};\n\nlet po: PerformanceObserver | undefined;\n\n/**\n * Returns the `interactionCount` value using the native API (if available)\n * or the polyfill estimate in this module.\n */\nexport const getInteractionCount = (): number => {\n return po ? interactionCountEstimate : performance.interactionCount || 0;\n};\n\n/**\n * Feature detects native support or initializes the polyfill if needed.\n */\nexport const initInteractionCountPolyfill = (): void => {\n if ('interactionCount' in performance || po) return;\n\n po = observe('event', updateEstimate, {\n type: 'event',\n buffered: true,\n durationThreshold: 0,\n } as PerformanceObserverInit);\n};\n","import { getFunctionName, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { onCLS } from './web-vitals/getCLS';\nimport { onFID } from './web-vitals/getFID';\nimport { onINP } from './web-vitals/getINP';\nimport { onLCP } from './web-vitals/getLCP';\nimport { observe } from './web-vitals/lib/observe';\nimport { onTTFB } from './web-vitals/onTTFB';\n\ntype InstrumentHandlerTypePerformanceObserver =\n | 'longtask'\n | 'event'\n | 'navigation'\n | 'paint'\n | 'resource'\n | 'first-input';\n\ntype InstrumentHandlerTypeMetric = 'cls' | 'lcp' | 'fid' | 'ttfb' | 'inp';\n\n// We provide this here manually instead of relying on a global, as this is not available in non-browser environements\n// And we do not want to expose such types\ninterface PerformanceEntry {\n readonly duration: number;\n readonly entryType: string;\n readonly name: string;\n readonly startTime: number;\n toJSON(): Record;\n}\ninterface PerformanceEventTiming extends PerformanceEntry {\n processingStart: number;\n processingEnd: number;\n duration: number;\n cancelable?: boolean;\n target?: unknown | null;\n interactionId?: number;\n}\n\ninterface Metric {\n /**\n * The name of the metric (in acronym form).\n */\n name: 'CLS' | 'FCP' | 'FID' | 'INP' | 'LCP' | 'TTFB';\n\n /**\n * The current value of the metric.\n */\n value: number;\n\n /**\n * The rating as to whether the metric value is within the \"good\",\n * \"needs improvement\", or \"poor\" thresholds of the metric.\n */\n rating: 'good' | 'needs-improvement' | 'poor';\n\n /**\n * The delta between the current value and the last-reported value.\n * On the first report, `delta` and `value` will always be the same.\n */\n delta: number;\n\n /**\n * A unique ID representing this particular metric instance. This ID can\n * be used by an analytics tool to dedupe multiple values sent for the same\n * metric instance, or to group multiple deltas together and calculate a\n * total. It can also be used to differentiate multiple different metric\n * instances sent from the same page, which can happen if the page is\n * restored from the back/forward cache (in that case new metrics object\n * get created).\n */\n id: string;\n\n /**\n * Any performance entries relevant to the metric value calculation.\n * The array may also be empty if the metric value was not based on any\n * entries (e.g. a CLS value of 0 given no layout shifts).\n */\n entries: PerformanceEntry[];\n\n /**\n * The type of navigation\n *\n * Navigation Timing API (or `undefined` if the browser doesn't\n * support that API). For pages that are restored from the bfcache, this\n * value will be 'back-forward-cache'.\n */\n navigationType: 'navigate' | 'reload' | 'back-forward' | 'back-forward-cache' | 'prerender';\n}\n\ntype InstrumentHandlerType = InstrumentHandlerTypeMetric | InstrumentHandlerTypePerformanceObserver;\n\ntype StopListening = undefined | void | (() => void);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InstrumentHandlerCallback = (data: any) => void;\n\ntype CleanupHandlerCallback = () => void;\n\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\nlet _previousCls: Metric | undefined;\nlet _previousFid: Metric | undefined;\nlet _previousLcp: Metric | undefined;\nlet _previousTtfb: Metric | undefined;\nlet _previousInp: Metric | undefined;\n\n/**\n * Add a callback that will be triggered when a CLS metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n *\n * Pass `stopOnCallback = true` to stop listening for CLS when the cleanup callback is called.\n * This will lead to the CLS being finalized and frozen.\n */\nexport function addClsInstrumentationHandler(\n callback: (data: { metric: Metric }) => void,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n return addMetricObserver('cls', callback, instrumentCls, _previousCls, stopOnCallback);\n}\n\n/**\n * Add a callback that will be triggered when a LCP metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n *\n * Pass `stopOnCallback = true` to stop listening for LCP when the cleanup callback is called.\n * This will lead to the LCP being finalized and frozen.\n */\nexport function addLcpInstrumentationHandler(\n callback: (data: { metric: Metric }) => void,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n return addMetricObserver('lcp', callback, instrumentLcp, _previousLcp, stopOnCallback);\n}\n\n/**\n * Add a callback that will be triggered when a FID metric is available.\n */\nexport function addTtfbInstrumentationHandler(callback: (data: { metric: Metric }) => void): CleanupHandlerCallback {\n return addMetricObserver('ttfb', callback, instrumentTtfb, _previousTtfb);\n}\n\n/**\n * Add a callback that will be triggered when a FID metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addFidInstrumentationHandler(callback: (data: { metric: Metric }) => void): CleanupHandlerCallback {\n return addMetricObserver('fid', callback, instrumentFid, _previousFid);\n}\n\n/**\n * Add a callback that will be triggered when a INP metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addInpInstrumentationHandler(\n callback: (data: { metric: Omit & { entries: PerformanceEventTiming[] } }) => void,\n): CleanupHandlerCallback {\n return addMetricObserver('inp', callback, instrumentInp, _previousInp);\n}\n\nexport function addPerformanceInstrumentationHandler(\n type: 'event' | 'first-input',\n callback: (data: { entries: ((PerformanceEntry & { target?: unknown | null }) | PerformanceEventTiming)[] }) => void,\n): CleanupHandlerCallback;\nexport function addPerformanceInstrumentationHandler(\n type: InstrumentHandlerTypePerformanceObserver,\n callback: (data: { entries: PerformanceEntry[] }) => void,\n): CleanupHandlerCallback;\n\n/**\n * Add a callback that will be triggered when a performance observer is triggered,\n * and receives the entries of the observer.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addPerformanceInstrumentationHandler(\n type: InstrumentHandlerTypePerformanceObserver,\n callback: (data: { entries: PerformanceEntry[] }) => void,\n): CleanupHandlerCallback {\n addHandler(type, callback);\n\n if (!instrumented[type]) {\n instrumentPerformanceObserver(type);\n instrumented[type] = true;\n }\n\n return getCleanupCallback(type, callback);\n}\n\n/** Trigger all handlers of a given type. */\nfunction triggerHandlers(type: InstrumentHandlerType, data: unknown): void {\n const typeHandlers = handlers[type];\n\n if (!typeHandlers || !typeHandlers.length) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\nfunction instrumentCls(): StopListening {\n return onCLS(\n metric => {\n triggerHandlers('cls', {\n metric,\n });\n _previousCls = metric;\n },\n { reportAllChanges: true },\n );\n}\n\nfunction instrumentFid(): void {\n return onFID(metric => {\n triggerHandlers('fid', {\n metric,\n });\n _previousFid = metric;\n });\n}\n\nfunction instrumentLcp(): StopListening {\n return onLCP(metric => {\n triggerHandlers('lcp', {\n metric,\n });\n _previousLcp = metric;\n });\n}\n\nfunction instrumentTtfb(): StopListening {\n return onTTFB(metric => {\n triggerHandlers('ttfb', {\n metric,\n });\n _previousTtfb = metric;\n });\n}\n\nfunction instrumentInp(): void {\n return onINP(metric => {\n triggerHandlers('inp', {\n metric,\n });\n _previousInp = metric;\n });\n}\n\nfunction addMetricObserver(\n type: InstrumentHandlerTypeMetric,\n callback: InstrumentHandlerCallback,\n instrumentFn: () => StopListening,\n previousValue: Metric | undefined,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n addHandler(type, callback);\n\n let stopListening: StopListening | undefined;\n\n if (!instrumented[type]) {\n stopListening = instrumentFn();\n instrumented[type] = true;\n }\n\n if (previousValue) {\n callback({ metric: previousValue });\n }\n\n return getCleanupCallback(type, callback, stopOnCallback ? stopListening : undefined);\n}\n\nfunction instrumentPerformanceObserver(type: InstrumentHandlerTypePerformanceObserver): void {\n const options: PerformanceObserverInit = {};\n\n // Special per-type options we want to use\n if (type === 'event') {\n options.durationThreshold = 0;\n }\n\n observe(\n type,\n entries => {\n triggerHandlers(type, { entries });\n },\n options,\n );\n}\n\nfunction addHandler(type: InstrumentHandlerType, handler: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(handler);\n}\n\n// Get a callback which can be called to remove the instrumentation handler\nfunction getCleanupCallback(\n type: InstrumentHandlerType,\n callback: InstrumentHandlerCallback,\n stopListening: StopListening,\n): CleanupHandlerCallback {\n return () => {\n if (stopListening) {\n stopListening();\n }\n\n const typeHandlers = handlers[type];\n\n if (!typeHandlers) {\n return;\n }\n\n const index = typeHandlers.indexOf(callback);\n if (index !== -1) {\n typeHandlers.splice(index, 1);\n }\n };\n}\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { NavigationTimingPolyfillEntry } from '../types';\n\nconst getNavigationEntryFromPerformanceTiming = (): NavigationTimingPolyfillEntry => {\n // eslint-disable-next-line deprecation/deprecation\n const timing = WINDOW.performance.timing;\n // eslint-disable-next-line deprecation/deprecation\n const type = WINDOW.performance.navigation.type;\n\n const navigationEntry: { [key: string]: number | string } = {\n entryType: 'navigation',\n startTime: 0,\n type: type == 2 ? 'back_forward' : type === 1 ? 'reload' : 'navigate',\n };\n\n for (const key in timing) {\n if (key !== 'navigationStart' && key !== 'toJSON') {\n // eslint-disable-next-line deprecation/deprecation\n navigationEntry[key] = Math.max((timing[key as keyof PerformanceTiming] as number) - timing.navigationStart, 0);\n }\n }\n return navigationEntry as unknown as NavigationTimingPolyfillEntry;\n};\n\nexport const getNavigationEntry = (): PerformanceNavigationTiming | NavigationTimingPolyfillEntry | undefined => {\n if (WINDOW.__WEB_VITALS_POLYFILL__) {\n return (\n WINDOW.performance &&\n ((performance.getEntriesByType && performance.getEntriesByType('navigation')[0]) ||\n getNavigationEntryFromPerformanceTiming())\n );\n } else {\n return WINDOW.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0];\n }\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const getActivationStart = (): number => {\n const navEntry = getNavigationEntry();\n return (navEntry && navEntry.activationStart) || 0;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { Metric } from '../types';\nimport { generateUniqueID } from './generateUniqueID';\nimport { getActivationStart } from './getActivationStart';\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const initMetric = (name: Metric['name'], value?: number): Metric => {\n const navEntry = getNavigationEntry();\n let navigationType: Metric['navigationType'] = 'navigate';\n\n if (navEntry) {\n if ((WINDOW.document && WINDOW.document.prerendering) || getActivationStart() > 0) {\n navigationType = 'prerender';\n } else {\n navigationType = navEntry.type.replace(/_/g, '-') as Metric['navigationType'];\n }\n }\n\n return {\n name,\n value: typeof value === 'undefined' ? -1 : value,\n rating: 'good', // Will be updated if the value changes.\n delta: 0,\n entries: [],\n id: generateUniqueID(),\n navigationType,\n };\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nexport const generateUniqueID = (): string => {\n return `v3-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FirstInputPolyfillEntry, NavigationTimingPolyfillEntry, PerformancePaintTiming } from '../types';\n\nexport interface PerformanceEntryHandler {\n (entry: PerformanceEntry): void;\n}\n\ninterface PerformanceEntryMap {\n event: PerformanceEventTiming[];\n paint: PerformancePaintTiming[];\n 'layout-shift': LayoutShift[];\n 'largest-contentful-paint': LargestContentfulPaint[];\n 'first-input': PerformanceEventTiming[] | FirstInputPolyfillEntry[];\n navigation: PerformanceNavigationTiming[] | NavigationTimingPolyfillEntry[];\n resource: PerformanceResourceTiming[];\n longtask: PerformanceEntry[];\n}\n\n/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nexport const observe = (\n type: K,\n callback: (entries: PerformanceEntryMap[K]) => void,\n opts?: PerformanceObserverInit,\n): PerformanceObserver | undefined => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n const po = new PerformanceObserver(list => {\n callback(list.getEntries() as PerformanceEntryMap[K]);\n });\n po.observe(\n Object.assign(\n {\n type,\n buffered: true,\n },\n opts || {},\n ) as PerformanceObserverInit,\n );\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\n\nexport interface OnHiddenCallback {\n (event: Event): void;\n}\n\nexport const onHidden = (cb: OnHiddenCallback, once?: boolean): void => {\n const onHiddenOrPageHide = (event: Event): void => {\n if (event.type === 'pagehide' || WINDOW.document!.visibilityState === 'hidden') {\n cb(event);\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\n\n if (WINDOW.document) {\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n }\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { CLSMetric, ReportCallback, StopListening } from './types';\n\n/**\n * Calculates the [CLS](https://web.dev/cls/) value for the current page and\n * calls the `callback` function once the value is ready to be reported, along\n * with all `layout-shift` performance entries that were used in the metric\n * value calculation. The reported value is a `double` (corresponding to a\n * [layout shift score](https://web.dev/cls/#layout-shift-score)).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** CLS should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nexport const onCLS = (\n onReport: ReportCallback,\n options: { reportAllChanges?: boolean } = {},\n): StopListening | undefined => {\n const metric = initMetric('CLS', 0);\n let report: ReturnType;\n\n let sessionValue = 0;\n let sessionEntries: PerformanceEntry[] = [];\n\n // const handleEntries = (entries: Metric['entries']) => {\n const handleEntries = (entries: LayoutShift[]): void => {\n entries.forEach(entry => {\n // Only count layout shifts without recent user input.\n if (!entry.hadRecentInput) {\n const firstSessionEntry = sessionEntries[0];\n const lastSessionEntry = sessionEntries[sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry and\n // less than 5 seconds after the first entry in the session, include the\n // entry in the current session. Otherwise, start a new session.\n if (\n sessionValue &&\n sessionEntries.length !== 0 &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n }\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n if (report) {\n report();\n }\n }\n }\n });\n };\n\n const po = observe('layout-shift', handleEntries);\n if (po) {\n report = bindReporter(onReport, metric, options.reportAllChanges);\n\n const stopListening = (): void => {\n handleEntries(po.takeRecords() as CLSMetric['entries']);\n report(true);\n };\n\n onHidden(stopListening);\n\n return stopListening;\n }\n\n return;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport { onHidden } from './onHidden';\n\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = (): void => {\n // If the document is hidden and not prerendering, assume it was always\n // hidden and the page was loaded in the background.\n if (WINDOW.document && WINDOW.document.visibilityState) {\n firstHiddenTime = WINDOW.document.visibilityState === 'hidden' && !WINDOW.document.prerendering ? 0 : Infinity;\n }\n};\n\nconst trackChanges = (): void => {\n // Update the time if/when the document becomes hidden.\n onHidden(({ timeStamp }) => {\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nexport const getVisibilityWatcher = (): {\n readonly firstHiddenTime: number;\n} => {\n if (firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n initHiddenTime();\n trackChanges();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { FIDMetric, PerformanceEventTiming, ReportCallback } from './types';\n\n/**\n * Calculates the [FID](https://web.dev/fid/) value for the current page and\n * calls the `callback` function once the value is ready, along with the\n * relevant `first-input` performance entry used to determine the value. The\n * reported value is a `DOMHighResTimeStamp`.\n *\n * _**Important:** since FID is only reported after the user interacts with the\n * page, it's possible that it will not be reported for some page loads._\n */\nexport const onFID = (onReport: ReportCallback): void => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FID');\n // eslint-disable-next-line prefer-const\n let report: ReturnType;\n\n const handleEntry = (entry: PerformanceEventTiming): void => {\n // Only report if the page wasn't hidden prior to the first input.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n const handleEntries = (entries: FIDMetric['entries']): void => {\n (entries as PerformanceEventTiming[]).forEach(handleEntry);\n };\n\n const po = observe('first-input', handleEntries);\n report = bindReporter(onReport, metric);\n\n if (po) {\n onHidden(() => {\n handleEntries(po.takeRecords() as FIDMetric['entries']);\n po.disconnect();\n }, true);\n }\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport { getInteractionCount, initInteractionCountPolyfill } from './lib/polyfills/interactionCountPolyfill';\nimport type { ReportCallback, ReportOpts } from './types';\nimport type { INPMetric } from './types/inp';\n\ninterface Interaction {\n id: number;\n latency: number;\n entries: PerformanceEventTiming[];\n}\n\n/**\n * Returns the interaction count since the last bfcache restore (or for the\n * full page lifecycle if there were no bfcache restores).\n */\nconst getInteractionCountForNavigation = (): number => {\n return getInteractionCount();\n};\n\n// To prevent unnecessary memory usage on pages with lots of interactions,\n// store at most 10 of the longest interactions to consider as INP candidates.\nconst MAX_INTERACTIONS_TO_CONSIDER = 10;\n\n// A list of longest interactions on the page (by latency) sorted so the\n// longest one is first. The list is as most MAX_INTERACTIONS_TO_CONSIDER long.\nconst longestInteractionList: Interaction[] = [];\n\n// A mapping of longest interactions by their interaction ID.\n// This is used for faster lookup.\nconst longestInteractionMap: { [interactionId: string]: Interaction } = {};\n\n/**\n * Takes a performance entry and adds it to the list of worst interactions\n * if its duration is long enough to make it among the worst. If the\n * entry is part of an existing interaction, it is merged and the latency\n * and entries list is updated as needed.\n */\nconst processEntry = (entry: PerformanceEventTiming): void => {\n // The least-long of the 10 longest interactions.\n const minLongestInteraction = longestInteractionList[longestInteractionList.length - 1];\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const existingInteraction = longestInteractionMap[entry.interactionId!];\n\n // Only process the entry if it's possibly one of the ten longest,\n // or if it's part of an existing interaction.\n if (\n existingInteraction ||\n longestInteractionList.length < MAX_INTERACTIONS_TO_CONSIDER ||\n entry.duration > minLongestInteraction.latency\n ) {\n // If the interaction already exists, update it. Otherwise create one.\n if (existingInteraction) {\n existingInteraction.entries.push(entry);\n existingInteraction.latency = Math.max(existingInteraction.latency, entry.duration);\n } else {\n const interaction = {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n id: entry.interactionId!,\n latency: entry.duration,\n entries: [entry],\n };\n longestInteractionMap[interaction.id] = interaction;\n longestInteractionList.push(interaction);\n }\n\n // Sort the entries by latency (descending) and keep only the top ten.\n longestInteractionList.sort((a, b) => b.latency - a.latency);\n longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER).forEach(i => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete longestInteractionMap[i.id];\n });\n }\n};\n\n/**\n * Returns the estimated p98 longest interaction based on the stored\n * interaction candidates and the interaction count for the current page.\n */\nconst estimateP98LongestInteraction = (): Interaction => {\n const candidateInteractionIndex = Math.min(\n longestInteractionList.length - 1,\n Math.floor(getInteractionCountForNavigation() / 50),\n );\n\n return longestInteractionList[candidateInteractionIndex];\n};\n\n/**\n * Calculates the [INP](https://web.dev/responsiveness/) value for the current\n * page and calls the `callback` function once the value is ready, along with\n * the `event` performance entries reported for that interaction. The reported\n * value is a `DOMHighResTimeStamp`.\n *\n * A custom `durationThreshold` configuration option can optionally be passed to\n * control what `event-timing` entries are considered for INP reporting. The\n * default threshold is `40`, which means INP scores of less than 40 are\n * reported as 0. Note that this will not affect your 75th percentile INP value\n * unless that value is also less than 40 (well below the recommended\n * [good](https://web.dev/inp/#what-is-a-good-inp-score) threshold).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** INP should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nexport const onINP = (onReport: ReportCallback, opts?: ReportOpts): void => {\n // Set defaults\n // eslint-disable-next-line no-param-reassign\n opts = opts || {};\n\n // https://web.dev/inp/#what's-a-%22good%22-inp-value\n // const thresholds = [200, 500];\n\n // TODO(philipwalton): remove once the polyfill is no longer needed.\n initInteractionCountPolyfill();\n\n const metric = initMetric('INP');\n // eslint-disable-next-line prefer-const\n let report: ReturnType;\n\n const handleEntries = (entries: INPMetric['entries']): void => {\n entries.forEach(entry => {\n if (entry.interactionId) {\n processEntry(entry);\n }\n\n // Entries of type `first-input` don't currently have an `interactionId`,\n // so to consider them in INP we have to first check that an existing\n // entry doesn't match the `duration` and `startTime`.\n // Note that this logic assumes that `event` entries are dispatched\n // before `first-input` entries. This is true in Chrome but it is not\n // true in Firefox; however, Firefox doesn't support interactionId, so\n // it's not an issue at the moment.\n // TODO(philipwalton): remove once crbug.com/1325826 is fixed.\n if (entry.entryType === 'first-input') {\n const noMatchingEntry = !longestInteractionList.some(interaction => {\n return interaction.entries.some(prevEntry => {\n return entry.duration === prevEntry.duration && entry.startTime === prevEntry.startTime;\n });\n });\n if (noMatchingEntry) {\n processEntry(entry);\n }\n }\n });\n\n const inp = estimateP98LongestInteraction();\n\n if (inp && inp.latency !== metric.value) {\n metric.value = inp.latency;\n metric.entries = inp.entries;\n report();\n }\n };\n\n const po = observe('event', handleEntries, {\n // Event Timing entries have their durations rounded to the nearest 8ms,\n // so a duration of 40ms would be any event that spans 2.5 or more frames\n // at 60Hz. This threshold is chosen to strike a balance between usefulness\n // and performance. Running this callback for any interaction that spans\n // just one or two frames is likely not worth the insight that could be\n // gained.\n durationThreshold: opts.durationThreshold || 40,\n } as PerformanceObserverInit);\n\n report = bindReporter(onReport, metric, opts.reportAllChanges);\n\n if (po) {\n // Also observe entries of type `first-input`. This is useful in cases\n // where the first interaction is less than the `durationThreshold`.\n po.observe({ type: 'first-input', buffered: true });\n\n onHidden(() => {\n handleEntries(po.takeRecords() as INPMetric['entries']);\n\n // If the interaction count shows that there were interactions but\n // none were captured by the PerformanceObserver, report a latency of 0.\n if (metric.value < 0 && getInteractionCountForNavigation() > 0) {\n metric.value = 0;\n metric.entries = [];\n }\n\n report(true);\n });\n }\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../types';\nimport { bindReporter } from './lib/bindReporter';\nimport { getActivationStart } from './lib/getActivationStart';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { LCPMetric, ReportCallback, StopListening } from './types';\n\nconst reportedMetricIDs: Record = {};\n\n/**\n * Calculates the [LCP](https://web.dev/lcp/) value for the current page and\n * calls the `callback` function once the value is ready (along with the\n * relevant `largest-contentful-paint` performance entry used to determine the\n * value). The reported value is a `DOMHighResTimeStamp`.\n */\nexport const onLCP = (onReport: ReportCallback): StopListening | undefined => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report: ReturnType;\n\n const handleEntries = (entries: LCPMetric['entries']): void => {\n const lastEntry = entries[entries.length - 1] as LargestContentfulPaint;\n if (lastEntry) {\n // The startTime attribute returns the value of the renderTime if it is\n // not 0, and the value of the loadTime otherwise. The activationStart\n // reference is used because LCP should be relative to page activation\n // rather than navigation start if the page was prerendered.\n const value = Math.max(lastEntry.startTime - getActivationStart(), 0);\n\n // Only report if the page wasn't hidden prior to LCP.\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries = [lastEntry];\n report();\n }\n }\n };\n\n const po = observe('largest-contentful-paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = (): void => {\n if (!reportedMetricIDs[metric.id]) {\n handleEntries(po.takeRecords() as LCPMetric['entries']);\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n };\n\n // Stop listening after input. Note: while scrolling is an input that\n // stop LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n if (WINDOW.document) {\n addEventListener(type, stopListening, { once: true, capture: true });\n }\n });\n\n onHidden(stopListening, true);\n\n return stopListening;\n }\n\n return;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../types';\nimport { bindReporter } from './lib/bindReporter';\nimport { getActivationStart } from './lib/getActivationStart';\nimport { getNavigationEntry } from './lib/getNavigationEntry';\nimport { initMetric } from './lib/initMetric';\nimport type { ReportCallback, ReportOpts } from './types';\nimport type { TTFBMetric } from './types/ttfb';\n\n/**\n * Runs in the next task after the page is done loading and/or prerendering.\n * @param callback\n */\nconst whenReady = (callback: () => void): void => {\n if (!WINDOW.document) {\n return;\n }\n\n if (WINDOW.document.prerendering) {\n addEventListener('prerenderingchange', () => whenReady(callback), true);\n } else if (WINDOW.document.readyState !== 'complete') {\n addEventListener('load', () => whenReady(callback), true);\n } else {\n // Queue a task so the callback runs after `loadEventEnd`.\n setTimeout(callback, 0);\n }\n};\n\n/**\n * Calculates the [TTFB](https://web.dev/time-to-first-byte/) value for the\n * current page and calls the `callback` function once the page has loaded,\n * along with the relevant `navigation` performance entry used to determine the\n * value. The reported value is a `DOMHighResTimeStamp`.\n *\n * Note, this function waits until after the page is loaded to call `callback`\n * in order to ensure all properties of the `navigation` entry are populated.\n * This is useful if you want to report on other metrics exposed by the\n * [Navigation Timing API](https://w3c.github.io/navigation-timing/). For\n * example, the TTFB metric starts from the page's [time\n * origin](https://www.w3.org/TR/hr-time-2/#sec-time-origin), which means it\n * includes time spent on DNS lookup, connection negotiation, network latency,\n * and server processing time.\n */\nexport const onTTFB = (onReport: ReportCallback, opts?: ReportOpts): void => {\n // Set defaults\n // eslint-disable-next-line no-param-reassign\n opts = opts || {};\n\n // https://web.dev/ttfb/#what-is-a-good-ttfb-score\n // const thresholds = [800, 1800];\n\n const metric = initMetric('TTFB');\n const report = bindReporter(onReport, metric, opts.reportAllChanges);\n\n whenReady(() => {\n const navEntry = getNavigationEntry() as TTFBMetric['entries'][number];\n\n if (navEntry) {\n // The activationStart reference is used because TTFB should be\n // relative to page activation rather than navigation start if the\n // page was prerendered. But in cases where `activationStart` occurs\n // after the first byte is received, this time should be clamped at 0.\n metric.value = Math.max(navEntry.responseStart - getActivationStart(), 0);\n\n // In some cases the value reported is negative or is larger\n // than the current page time. Ignore these cases:\n // https://github.com/GoogleChrome/web-vitals/issues/137\n // https://github.com/GoogleChrome/web-vitals/issues/162\n if (metric.value < 0 || metric.value > performance.now()) return;\n\n metric.entries = [navEntry];\n\n report(true);\n }\n });\n};\n","import type { DsnComponents, SpanEnvelope, SpanItem } from '@sentry/types';\nimport type { Span } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\n\n/**\n * Create envelope from Span item.\n */\nexport function createSpanEnvelope(spans: Span[], dsn?: DsnComponents): SpanEnvelope {\n const headers: SpanEnvelope[0] = {\n sent_at: new Date().toISOString(),\n };\n\n if (dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n const items = spans.map(createSpanItem);\n return createEnvelope(headers, items);\n}\n\nfunction createSpanItem(span: Span): SpanItem {\n const spanHeaders: SpanItem[0] = {\n type: 'span',\n };\n return [spanHeaders, span];\n}\n","import objectWithoutPropertiesLoose from \"./objectWithoutPropertiesLoose.js\";\nexport default function _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n var target = objectWithoutPropertiesLoose(source, excluded);\n var key, i;\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n return target;\n}","export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n return target;\n}","import type { Transaction } from '@sentry/core';\nimport type { Span, SpanContext } from '@sentry/types';\n\n/**\n * Checks if a given value is a valid measurement value.\n */\nexport function isMeasurementValue(value: unknown): value is number {\n return typeof value === 'number' && isFinite(value);\n}\n\n/**\n * Helper function to start child on transactions. This function will make sure that the transaction will\n * use the start timestamp of the created child span if it is earlier than the transactions actual\n * start timestamp.\n *\n * Note: this will not be possible anymore in v8,\n * unless we do some special handling for browser here...\n */\nexport function _startChild(transaction: Transaction, { startTimestamp, ...ctx }: SpanContext): Span {\n // eslint-disable-next-line deprecation/deprecation\n if (startTimestamp && transaction.startTimestamp > startTimestamp) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.startTimestamp = startTimestamp;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return transaction.startChild({\n startTimestamp,\n ...ctx,\n });\n}\n","/* eslint-disable max-lines */\nimport type { IdleTransaction, Transaction } from '@sentry/core';\nimport {\n Span,\n getActiveTransaction,\n getClient,\n hasTracingEnabled,\n isValidSampleRate,\n setMeasurement,\n} from '@sentry/core';\nimport type { ClientOptions, Measurements, SpanContext, TransactionContext } from '@sentry/types';\nimport { browserPerformanceTimeOrigin, getComponentName, htmlTreeAsString, logger, parseUrl } from '@sentry/utils';\n\nimport { spanToJSON } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport {\n addClsInstrumentationHandler,\n addFidInstrumentationHandler,\n addInpInstrumentationHandler,\n addLcpInstrumentationHandler,\n addPerformanceInstrumentationHandler,\n addTtfbInstrumentationHandler,\n} from '../instrument';\nimport { WINDOW } from '../types';\nimport { getVisibilityWatcher } from '../web-vitals/lib/getVisibilityWatcher';\nimport type {\n InteractionRouteNameMapping,\n NavigatorDeviceMemory,\n NavigatorNetworkInformation,\n} from '../web-vitals/types';\nimport { _startChild, isMeasurementValue } from './utils';\n\nimport { createSpanEnvelope } from '@sentry/core';\nimport { getNavigationEntry } from '../web-vitals/lib/getNavigationEntry';\n\nconst MAX_INT_AS_BYTES = 2147483647;\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nfunction msToSec(time: number): number {\n return time / 1000;\n}\n\nfunction getBrowserPerformanceAPI(): Performance | undefined {\n // @ts-expect-error we want to make sure all of these are available, even if TS is sure they are\n return WINDOW && WINDOW.addEventListener && WINDOW.performance;\n}\n\nlet _performanceCursor: number = 0;\n\nlet _measurements: Measurements = {};\nlet _lcpEntry: LargestContentfulPaint | undefined;\nlet _clsEntry: LayoutShift | undefined;\n\n/**\n * Start tracking web vitals.\n * The callback returned by this function can be used to stop tracking & ensure all measurements are final & captured.\n *\n * @returns A function that forces web vitals collection\n */\nexport function startTrackingWebVitals(): () => void {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin) {\n // @ts-expect-error we want to make sure all of these are available, even if TS is sure they are\n if (performance.mark) {\n WINDOW.performance.mark('sentry-tracing-init');\n }\n const fidCallback = _trackFID();\n const clsCallback = _trackCLS();\n const lcpCallback = _trackLCP();\n const ttfbCallback = _trackTtfb();\n\n return (): void => {\n fidCallback();\n clsCallback();\n lcpCallback();\n ttfbCallback();\n };\n }\n\n return () => undefined;\n}\n\n/**\n * Start tracking long tasks.\n */\nexport function startTrackingLongTasks(): void {\n addPerformanceInstrumentationHandler('longtask', ({ entries }) => {\n for (const entry of entries) {\n // eslint-disable-next-line deprecation/deprecation\n const transaction = getActiveTransaction() as IdleTransaction | undefined;\n if (!transaction) {\n return;\n }\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n // eslint-disable-next-line deprecation/deprecation\n transaction.startChild({\n description: 'Main UI thread blocked',\n op: 'ui.long-task',\n origin: 'auto.ui.browser.metrics',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n });\n}\n\n/**\n * Start tracking interaction events.\n */\nexport function startTrackingInteractions(): void {\n addPerformanceInstrumentationHandler('event', ({ entries }) => {\n for (const entry of entries) {\n // eslint-disable-next-line deprecation/deprecation\n const transaction = getActiveTransaction() as IdleTransaction | undefined;\n if (!transaction) {\n return;\n }\n\n if (entry.name === 'click') {\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n const span: SpanContext = {\n description: htmlTreeAsString(entry.target),\n op: `ui.interaction.${entry.name}`,\n origin: 'auto.ui.browser.metrics',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n };\n\n const componentName = getComponentName(entry.target);\n if (componentName) {\n span.attributes = { 'ui.component_name': componentName };\n }\n\n // eslint-disable-next-line deprecation/deprecation\n transaction.startChild(span);\n }\n }\n });\n}\n\n/**\n * Start tracking INP webvital events.\n */\nexport function startTrackingINP(\n interactionIdtoRouteNameMapping: InteractionRouteNameMapping,\n interactionsSampleRate: number,\n): () => void {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin) {\n const inpCallback = _trackINP(interactionIdtoRouteNameMapping, interactionsSampleRate);\n\n return (): void => {\n inpCallback();\n };\n }\n\n return () => undefined;\n}\n\n/** Starts tracking the Cumulative Layout Shift on the current page. */\nfunction _trackCLS(): () => void {\n return addClsInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n DEBUG_BUILD && logger.log('[Measurements] Adding CLS');\n _measurements['cls'] = { value: metric.value, unit: '' };\n _clsEntry = entry as LayoutShift;\n }, true);\n}\n\n/** Starts tracking the Largest Contentful Paint on the current page. */\nfunction _trackLCP(): () => void {\n return addLcpInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n DEBUG_BUILD && logger.log('[Measurements] Adding LCP');\n _measurements['lcp'] = { value: metric.value, unit: 'millisecond' };\n _lcpEntry = entry as LargestContentfulPaint;\n }, true);\n}\n\n/** Starts tracking the First Input Delay on the current page. */\nfunction _trackFID(): () => void {\n return addFidInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);\n const startTime = msToSec(entry.startTime);\n DEBUG_BUILD && logger.log('[Measurements] Adding FID');\n _measurements['fid'] = { value: metric.value, unit: 'millisecond' };\n _measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' };\n });\n}\n\nfunction _trackTtfb(): () => void {\n return addTtfbInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n DEBUG_BUILD && logger.log('[Measurements] Adding TTFB');\n _measurements['ttfb'] = { value: metric.value, unit: 'millisecond' };\n });\n}\n\nconst INP_ENTRY_MAP: Record = {\n click: 'click',\n pointerdown: 'click',\n pointerup: 'click',\n mousedown: 'click',\n mouseup: 'click',\n touchstart: 'click',\n touchend: 'click',\n mouseover: 'hover',\n mouseout: 'hover',\n mouseenter: 'hover',\n mouseleave: 'hover',\n pointerover: 'hover',\n pointerout: 'hover',\n pointerenter: 'hover',\n pointerleave: 'hover',\n dragstart: 'drag',\n dragend: 'drag',\n drag: 'drag',\n dragenter: 'drag',\n dragleave: 'drag',\n dragover: 'drag',\n drop: 'drag',\n keydown: 'press',\n keyup: 'press',\n keypress: 'press',\n input: 'press',\n};\n\n/** Starts tracking the Interaction to Next Paint on the current page. */\nfunction _trackINP(\n interactionIdToRouteNameMapping: InteractionRouteNameMapping,\n interactionsSampleRate: number,\n): () => void {\n return addInpInstrumentationHandler(({ metric }) => {\n if (metric.value === undefined) {\n return;\n }\n const entry = metric.entries.find(\n entry => entry.duration === metric.value && INP_ENTRY_MAP[entry.name] !== undefined,\n );\n const client = getClient();\n if (!entry || !client) {\n return;\n }\n const interactionType = INP_ENTRY_MAP[entry.name];\n const options = client.getOptions();\n /** Build the INP span, create an envelope from the span, and then send the envelope */\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(metric.value);\n const interaction =\n entry.interactionId !== undefined ? interactionIdToRouteNameMapping[entry.interactionId] : undefined;\n if (interaction === undefined) {\n return;\n }\n const { routeName, parentContext, activeTransaction, user, replayId } = interaction;\n const userDisplay = user !== undefined ? user.email || user.id || user.ip_address : undefined;\n // eslint-disable-next-line deprecation/deprecation\n const profileId = activeTransaction !== undefined ? activeTransaction.getProfileId() : undefined;\n const span = new Span({\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n op: `ui.interaction.${interactionType}`,\n name: htmlTreeAsString(entry.target),\n attributes: {\n release: options.release,\n environment: options.environment,\n transaction: routeName,\n ...(userDisplay !== undefined && userDisplay !== '' ? { user: userDisplay } : {}),\n ...(profileId !== undefined ? { profile_id: profileId } : {}),\n ...(replayId !== undefined ? { replay_id: replayId } : {}),\n },\n exclusiveTime: metric.value,\n measurements: {\n inp: { value: metric.value, unit: 'millisecond' },\n },\n });\n\n /** Check to see if the span should be sampled */\n const sampleRate = getSampleRate(parentContext, options, interactionsSampleRate);\n\n if (!sampleRate) {\n return;\n }\n\n if (Math.random() < (sampleRate as number | boolean)) {\n const envelope = span ? createSpanEnvelope([span], client.getDsn()) : undefined;\n const transport = client && client.getTransport();\n if (transport && envelope) {\n transport.send(envelope).then(null, reason => {\n DEBUG_BUILD && logger.error('Error while sending interaction:', reason);\n });\n }\n return;\n }\n });\n}\n\n/** Add performance related spans to a transaction */\nexport function addPerformanceEntries(transaction: Transaction): void {\n const performance = getBrowserPerformanceAPI();\n if (!performance || !WINDOW.performance.getEntries || !browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n DEBUG_BUILD && logger.log('[Tracing] Adding & adjusting spans using Performance API');\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n\n const performanceEntries = performance.getEntries();\n\n const { op, start_timestamp: transactionStartTime } = spanToJSON(transaction);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n performanceEntries.slice(_performanceCursor).forEach((entry: Record) => {\n const startTime = msToSec(entry.startTime);\n const duration = msToSec(entry.duration);\n\n // eslint-disable-next-line deprecation/deprecation\n if (transaction.op === 'navigation' && transactionStartTime && timeOrigin + startTime < transactionStartTime) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n _addNavigationSpans(transaction, entry, timeOrigin);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n _addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);\n\n // capture web vitals\n const firstHidden = getVisibilityWatcher();\n // Only report if the page wasn't hidden prior to the web vital.\n const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n DEBUG_BUILD && logger.log('[Measurements] Adding FP');\n _measurements['fp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n DEBUG_BUILD && logger.log('[Measurements] Adding FCP');\n _measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n break;\n }\n case 'resource': {\n _addResourceSpans(transaction, entry, entry.name as string, startTime, duration, timeOrigin);\n break;\n }\n default:\n // Ignore other entry types.\n }\n });\n\n _performanceCursor = Math.max(performanceEntries.length - 1, 0);\n\n _trackNavigator(transaction);\n\n // Measurements are only available for pageload transactions\n if (op === 'pageload') {\n _addTtfbRequestTimeToMeasurements(_measurements);\n\n ['fcp', 'fp', 'lcp'].forEach(name => {\n if (!_measurements[name] || !transactionStartTime || timeOrigin >= transactionStartTime) {\n return;\n }\n // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.\n // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need\n // to be adjusted to be relative to transaction.startTimestamp.\n const oldValue = _measurements[name].value;\n const measurementTimestamp = timeOrigin + msToSec(oldValue);\n\n // normalizedValue should be in milliseconds\n const normalizedValue = Math.abs((measurementTimestamp - transactionStartTime) * 1000);\n const delta = normalizedValue - oldValue;\n\n DEBUG_BUILD && logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);\n _measurements[name].value = normalizedValue;\n });\n\n const fidMark = _measurements['mark.fid'];\n if (fidMark && _measurements['fid']) {\n // create span for FID\n _startChild(transaction, {\n description: 'first input delay',\n endTimestamp: fidMark.value + msToSec(_measurements['fid'].value),\n op: 'ui.action',\n origin: 'auto.ui.browser.metrics',\n startTimestamp: fidMark.value,\n });\n\n // Delete mark.fid as we don't want it to be part of final payload\n delete _measurements['mark.fid'];\n }\n\n // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n if (!('fcp' in _measurements)) {\n delete _measurements.cls;\n }\n\n Object.keys(_measurements).forEach(measurementName => {\n setMeasurement(measurementName, _measurements[measurementName].value, _measurements[measurementName].unit);\n });\n\n _tagMetricInfo(transaction);\n }\n\n _lcpEntry = undefined;\n _clsEntry = undefined;\n _measurements = {};\n}\n\n/** Create measure related spans */\nexport function _addMeasureSpans(\n transaction: Transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry: Record,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): number {\n const measureStartTimestamp = timeOrigin + startTime;\n const measureEndTimestamp = measureStartTimestamp + duration;\n\n _startChild(transaction, {\n description: entry.name as string,\n endTimestamp: measureEndTimestamp,\n op: entry.entryType as string,\n origin: 'auto.resource.browser.metrics',\n startTimestamp: measureStartTimestamp,\n });\n\n return measureStartTimestamp;\n}\n\n/** Instrument navigation entries */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addNavigationSpans(transaction: Transaction, entry: Record, timeOrigin: number): void {\n ['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'].forEach(event => {\n _addPerformanceNavigationTiming(transaction, entry, event, timeOrigin);\n });\n _addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'TLS/SSL', 'connectEnd');\n _addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'cache', 'domainLookupStart');\n _addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin, 'DNS');\n _addRequest(transaction, entry, timeOrigin);\n}\n\n/** Create performance navigation related spans */\nfunction _addPerformanceNavigationTiming(\n transaction: Transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry: Record,\n event: string,\n timeOrigin: number,\n description?: string,\n eventEnd?: string,\n): void {\n const end = eventEnd ? (entry[eventEnd] as number | undefined) : (entry[`${event}End`] as number | undefined);\n const start = entry[`${event}Start`] as number | undefined;\n if (!start || !end) {\n return;\n }\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: description || event,\n startTimestamp: timeOrigin + msToSec(start),\n endTimestamp: timeOrigin + msToSec(end),\n });\n}\n\n/** Create request and response related spans */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addRequest(transaction: Transaction, entry: Record, timeOrigin: number): void {\n if (entry.responseEnd) {\n // It is possible that we are collecting these metrics when the page hasn't finished loading yet, for example when the HTML slowly streams in.\n // In this case, ie. when the document request hasn't finished yet, `entry.responseEnd` will be 0.\n // In order not to produce faulty spans, where the end timestamp is before the start timestamp, we will only collect\n // these spans when the responseEnd value is available. The backend (Relay) would drop the entire transaction if it contained faulty spans.\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: 'request',\n startTimestamp: timeOrigin + msToSec(entry.requestStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: 'response',\n startTimestamp: timeOrigin + msToSec(entry.responseStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n }\n}\n\nexport interface ResourceEntry extends Record {\n initiatorType?: string;\n transferSize?: number;\n encodedBodySize?: number;\n decodedBodySize?: number;\n renderBlockingStatus?: string;\n}\n\n/** Create resource-related spans */\nexport function _addResourceSpans(\n transaction: Transaction,\n entry: ResourceEntry,\n resourceUrl: string,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): void {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return;\n }\n\n const parsedUrl = parseUrl(resourceUrl);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const data: Record = {};\n setResourceEntrySizeData(data, entry, 'transferSize', 'http.response_transfer_size');\n setResourceEntrySizeData(data, entry, 'encodedBodySize', 'http.response_content_length');\n setResourceEntrySizeData(data, entry, 'decodedBodySize', 'http.decoded_response_content_length');\n\n if ('renderBlockingStatus' in entry) {\n data['resource.render_blocking_status'] = entry.renderBlockingStatus;\n }\n if (parsedUrl.protocol) {\n data['url.scheme'] = parsedUrl.protocol.split(':').pop(); // the protocol returned by parseUrl includes a :, but OTEL spec does not, so we remove it.\n }\n\n if (parsedUrl.host) {\n data['server.address'] = parsedUrl.host;\n }\n\n data['url.same_origin'] = resourceUrl.includes(WINDOW.location.origin);\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n _startChild(transaction, {\n description: resourceUrl.replace(WINDOW.location.origin, ''),\n endTimestamp,\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other',\n origin: 'auto.resource.browser.metrics',\n startTimestamp,\n data,\n });\n}\n\n/**\n * Capture the information of the user agent.\n */\nfunction _trackNavigator(transaction: Transaction): void {\n const navigator = WINDOW.navigator as null | (Navigator & NavigatorNetworkInformation & NavigatorDeviceMemory);\n if (!navigator) {\n return;\n }\n\n // track network connectivity\n const connection = navigator.connection;\n if (connection) {\n if (connection.effectiveType) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('connectionType', connection.type);\n }\n\n if (isMeasurementValue(connection.rtt)) {\n _measurements['connection.rtt'] = { value: connection.rtt, unit: 'millisecond' };\n }\n }\n\n if (isMeasurementValue(navigator.deviceMemory)) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('deviceMemory', `${navigator.deviceMemory} GB`);\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n}\n\n/** Add LCP / CLS data to transaction to allow debugging */\nfunction _tagMetricInfo(transaction: Transaction): void {\n if (_lcpEntry) {\n DEBUG_BUILD && logger.log('[Measurements] Adding LCP Data');\n\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (_lcpEntry.element) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.element', htmlTreeAsString(_lcpEntry.element));\n }\n\n if (_lcpEntry.id) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.id', _lcpEntry.id);\n }\n\n if (_lcpEntry.url) {\n // Trim URL to the first 200 characters.\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.url', _lcpEntry.url.trim().slice(0, 200));\n }\n\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.size', _lcpEntry.size);\n }\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (_clsEntry && _clsEntry.sources) {\n DEBUG_BUILD && logger.log('[Measurements] Adding CLS Data');\n _clsEntry.sources.forEach((source, index) =>\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n}\n\nfunction setResourceEntrySizeData(\n data: Record,\n entry: ResourceEntry,\n key: keyof Pick,\n dataKey: 'http.response_transfer_size' | 'http.response_content_length' | 'http.decoded_response_content_length',\n): void {\n const entryVal = entry[key];\n if (entryVal != null && entryVal < MAX_INT_AS_BYTES) {\n data[dataKey] = entryVal;\n }\n}\n\n/**\n * Add ttfb request time information to measurements.\n *\n * ttfb information is added via vendored web vitals library.\n */\nfunction _addTtfbRequestTimeToMeasurements(_measurements: Measurements): void {\n const navEntry = getNavigationEntry();\n if (!navEntry) {\n return;\n }\n\n const { responseStart, requestStart } = navEntry;\n\n if (requestStart <= responseStart) {\n DEBUG_BUILD && logger.log('[Measurements] Adding TTFB Request Time');\n _measurements['ttfb.requestTime'] = {\n value: responseStart - requestStart,\n unit: 'millisecond',\n };\n }\n}\n\n/** Taken from @sentry/core sampling.ts */\nfunction getSampleRate(\n transactionContext: TransactionContext | undefined,\n options: ClientOptions,\n interactionsSampleRate: number,\n): number | boolean {\n if (!hasTracingEnabled(options)) {\n return false;\n }\n let sampleRate;\n if (transactionContext !== undefined && typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler({\n transactionContext,\n name: transactionContext.name,\n parentSampled: transactionContext.parentSampled,\n attributes: {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.data,\n ...transactionContext.attributes,\n },\n location: WINDOW.location,\n });\n } else if (transactionContext !== undefined && transactionContext.sampled !== undefined) {\n sampleRate = transactionContext.sampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n } else {\n sampleRate = 1;\n }\n if (!isValidSampleRate(sampleRate)) {\n DEBUG_BUILD && logger.warn('[Tracing] Discarding interaction span because of invalid sample rate.');\n return false;\n }\n if (sampleRate === true) {\n return interactionsSampleRate;\n } else if (sampleRate === false) {\n return 0;\n }\n return sampleRate * interactionsSampleRate;\n}\n","import type { MeasurementUnit } from '@sentry/types';\n\nimport { getActiveTransaction } from './utils';\n\n/**\n * Adds a measurement to the current active transaction.\n */\nexport function setMeasurement(name: string, value: number, unit: MeasurementUnit): void {\n // eslint-disable-next-line deprecation/deprecation\n const transaction = getActiveTransaction();\n if (transaction) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.setMeasurement(name, value, unit);\n }\n}\n","import {\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n getClient,\n getCurrentScope,\n getDynamicSamplingContextFromClient,\n getDynamicSamplingContextFromSpan,\n getIsolationScope,\n hasTracingEnabled,\n setHttpStatus,\n spanToTraceHeader,\n startInactiveSpan,\n} from '@sentry/core';\nimport type { Client, HandlerDataFetch, Scope, Span, SpanOrigin } from '@sentry/types';\nimport {\n BAGGAGE_HEADER_NAME,\n dynamicSamplingContextToSentryBaggageHeader,\n generateSentryTraceHeader,\n isInstanceOf,\n parseUrl,\n} from '@sentry/utils';\n\ntype PolymorphicRequestHeaders =\n | Record\n | Array<[string, string]>\n // the below is not preicsely the Header type used in Request, but it'll pass duck-typing\n | {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n append: (key: string, value: string) => void;\n get: (key: string) => string | null | undefined;\n };\n\n/**\n * Create and track fetch request spans for usage in combination with `addInstrumentationHandler`.\n *\n * @returns Span if a span was created, otherwise void.\n */\nexport function instrumentFetchRequest(\n handlerData: HandlerDataFetch,\n shouldCreateSpan: (url: string) => boolean,\n shouldAttachHeaders: (url: string) => boolean,\n spans: Record,\n spanOrigin: SpanOrigin = 'auto.http.browser',\n): Span | undefined {\n if (!hasTracingEnabled() || !handlerData.fetchData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = shouldCreateSpan(handlerData.fetchData.url);\n\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = handlerData.fetchData.__span;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n endSpan(span, handlerData);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const scope = getCurrentScope();\n const client = getClient();\n\n const { method, url } = handlerData.fetchData;\n\n const fullUrl = getFullURL(url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n\n const span = shouldCreateSpanResult\n ? startInactiveSpan({\n name: `${method} ${url}`,\n onlyIfParent: true,\n attributes: {\n url,\n type: 'fetch',\n 'http.method': method,\n 'http.url': fullUrl,\n 'server.address': host,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,\n },\n op: 'http.client',\n })\n : undefined;\n\n if (span) {\n handlerData.fetchData.__span = span.spanContext().spanId;\n spans[span.spanContext().spanId] = span;\n }\n\n if (shouldAttachHeaders(handlerData.fetchData.url) && client) {\n const request: string | Request = handlerData.args[0];\n\n // In case the user hasn't set the second argument of a fetch call we default it to `{}`.\n handlerData.args[1] = handlerData.args[1] || {};\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const options: { [key: string]: any } = handlerData.args[1];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n options.headers = addTracingHeadersToFetchRequest(request, client, scope, options, span);\n }\n\n return span;\n}\n\n/**\n * Adds sentry-trace and baggage headers to the various forms of fetch headers\n */\nexport function addTracingHeadersToFetchRequest(\n request: string | unknown, // unknown is actually type Request but we can't export DOM types from this package,\n client: Client,\n scope: Scope,\n options: {\n headers?:\n | {\n [key: string]: string[] | string | undefined;\n }\n | PolymorphicRequestHeaders;\n },\n requestSpan?: Span,\n): PolymorphicRequestHeaders | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const span = requestSpan || scope.getSpan();\n\n const isolationScope = getIsolationScope();\n\n const { traceId, spanId, sampled, dsc } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n const sentryTraceHeader = span ? spanToTraceHeader(span) : generateSentryTraceHeader(traceId, spanId, sampled);\n\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(\n dsc ||\n (span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromClient(traceId, client, scope)),\n );\n\n const headers =\n options.headers ||\n (typeof Request !== 'undefined' && isInstanceOf(request, Request) ? (request as Request).headers : undefined);\n\n if (!headers) {\n return { 'sentry-trace': sentryTraceHeader, baggage: sentryBaggageHeader };\n } else if (typeof Headers !== 'undefined' && isInstanceOf(headers, Headers)) {\n const newHeaders = new Headers(headers as Headers);\n\n newHeaders.append('sentry-trace', sentryTraceHeader);\n\n if (sentryBaggageHeader) {\n // If the same header is appended multiple times the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.append(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n\n return newHeaders as PolymorphicRequestHeaders;\n } else if (Array.isArray(headers)) {\n const newHeaders = [...headers, ['sentry-trace', sentryTraceHeader]];\n\n if (sentryBaggageHeader) {\n // If there are multiple entries with the same key, the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.push([BAGGAGE_HEADER_NAME, sentryBaggageHeader]);\n }\n\n return newHeaders as PolymorphicRequestHeaders;\n } else {\n const existingBaggageHeader = 'baggage' in headers ? headers.baggage : undefined;\n const newBaggageHeaders: string[] = [];\n\n if (Array.isArray(existingBaggageHeader)) {\n newBaggageHeaders.push(...existingBaggageHeader);\n } else if (existingBaggageHeader) {\n newBaggageHeaders.push(existingBaggageHeader);\n }\n\n if (sentryBaggageHeader) {\n newBaggageHeaders.push(sentryBaggageHeader);\n }\n\n return {\n ...(headers as Exclude),\n 'sentry-trace': sentryTraceHeader,\n baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,\n };\n }\n}\n\nfunction getFullURL(url: string): string | undefined {\n try {\n const parsed = new URL(url);\n return parsed.href;\n } catch {\n return undefined;\n }\n}\n\nfunction endSpan(span: Span, handlerData: HandlerDataFetch): void {\n if (handlerData.response) {\n setHttpStatus(span, handlerData.response.status);\n\n const contentLength =\n handlerData.response && handlerData.response.headers && handlerData.response.headers.get('content-length');\n\n if (contentLength) {\n const contentLengthNum = parseInt(contentLength);\n if (contentLengthNum > 0) {\n span.setAttribute('http.response_content_length', contentLengthNum);\n }\n }\n } else if (handlerData.error) {\n span.setStatus('internal_error');\n }\n span.end();\n}\n","/* eslint-disable max-lines */\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n getClient,\n getCurrentScope,\n getDynamicSamplingContextFromClient,\n getDynamicSamplingContextFromSpan,\n getIsolationScope,\n hasTracingEnabled,\n setHttpStatus,\n spanToJSON,\n spanToTraceHeader,\n startInactiveSpan,\n} from '@sentry/core';\nimport type { HandlerDataXhr, SentryWrappedXMLHttpRequest, Span } from '@sentry/types';\nimport {\n BAGGAGE_HEADER_NAME,\n SENTRY_XHR_DATA_KEY,\n addFetchInstrumentationHandler,\n addXhrInstrumentationHandler,\n browserPerformanceTimeOrigin,\n dynamicSamplingContextToSentryBaggageHeader,\n generateSentryTraceHeader,\n parseUrl,\n stringMatchesSomePattern,\n} from '@sentry/utils';\n\nimport { instrumentFetchRequest } from '../common/fetch';\nimport { addPerformanceInstrumentationHandler } from './instrument';\nimport { WINDOW } from './types';\n\nexport const DEFAULT_TRACE_PROPAGATION_TARGETS = ['localhost', /^\\/(?!\\/)/];\n\n/** Options for Request Instrumentation */\nexport interface RequestInstrumentationOptions {\n /**\n * @deprecated Will be removed in v8.\n * Use `shouldCreateSpanForRequest` to control span creation and `tracePropagationTargets` to control\n * trace header attachment.\n */\n tracingOrigins: Array;\n\n /**\n * List of strings and/or regexes used to determine which outgoing requests will have `sentry-trace` and `baggage`\n * headers attached.\n *\n * @deprecated Use the top-level `tracePropagationTargets` option in `Sentry.init` instead.\n * This option will be removed in v8.\n *\n * Default: ['localhost', /^\\//] @see {DEFAULT_TRACE_PROPAGATION_TARGETS}\n */\n tracePropagationTargets: Array;\n\n /**\n * Flag to disable patching all together for fetch requests.\n *\n * Default: true\n */\n traceFetch: boolean;\n\n /**\n * Flag to disable patching all together for xhr requests.\n *\n * Default: true\n */\n traceXHR: boolean;\n\n /**\n * If true, Sentry will capture http timings and add them to the corresponding http spans.\n *\n * Default: true\n */\n enableHTTPTimings: boolean;\n\n /**\n * This function will be called before creating a span for a request with the given url.\n * Return false if you don't want a span for the given url.\n *\n * Default: (url: string) => true\n */\n shouldCreateSpanForRequest?(this: void, url: string): boolean;\n}\n\nexport const defaultRequestInstrumentationOptions: RequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n enableHTTPTimings: true,\n // TODO (v8): Remove this property\n tracingOrigins: DEFAULT_TRACE_PROPAGATION_TARGETS,\n tracePropagationTargets: DEFAULT_TRACE_PROPAGATION_TARGETS,\n};\n\n/** Registers span creators for xhr and fetch requests */\nexport function instrumentOutgoingRequests(_options?: Partial): void {\n const {\n traceFetch,\n traceXHR,\n // eslint-disable-next-line deprecation/deprecation\n tracePropagationTargets,\n // eslint-disable-next-line deprecation/deprecation\n tracingOrigins,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n } = {\n traceFetch: defaultRequestInstrumentationOptions.traceFetch,\n traceXHR: defaultRequestInstrumentationOptions.traceXHR,\n ..._options,\n };\n\n const shouldCreateSpan =\n typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_: string) => true;\n\n // TODO(v8) Remove tracingOrigins here\n // The only reason we're passing it in here is because this instrumentOutgoingRequests function is publicly exported\n // and we don't want to break the API. We can remove it in v8.\n const shouldAttachHeadersWithTargets = (url: string): boolean =>\n shouldAttachHeaders(url, tracePropagationTargets || tracingOrigins);\n\n const spans: Record = {};\n\n if (traceFetch) {\n addFetchInstrumentationHandler(handlerData => {\n const createdSpan = instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n // We cannot use `window.location` in the generic fetch instrumentation,\n // but we need it for reliable `server.address` attribute.\n // so we extend this in here\n if (createdSpan) {\n const fullUrl = getFullURL(handlerData.fetchData.url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n createdSpan.setAttributes({\n 'http.url': fullUrl,\n 'server.address': host,\n });\n }\n\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n\n if (traceXHR) {\n addXhrInstrumentationHandler(handlerData => {\n const createdSpan = xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n}\n\nfunction isPerformanceResourceTiming(entry: PerformanceEntry): entry is PerformanceResourceTiming {\n return (\n entry.entryType === 'resource' &&\n 'initiatorType' in entry &&\n typeof (entry as PerformanceResourceTiming).nextHopProtocol === 'string' &&\n (entry.initiatorType === 'fetch' || entry.initiatorType === 'xmlhttprequest')\n );\n}\n\n/**\n * Creates a temporary observer to listen to the next fetch/xhr resourcing timings,\n * so that when timings hit their per-browser limit they don't need to be removed.\n *\n * @param span A span that has yet to be finished, must contain `url` on data.\n */\nfunction addHTTPTimings(span: Span): void {\n const { url } = spanToJSON(span).data || {};\n\n if (!url || typeof url !== 'string') {\n return;\n }\n\n const cleanup = addPerformanceInstrumentationHandler('resource', ({ entries }) => {\n entries.forEach(entry => {\n if (isPerformanceResourceTiming(entry) && entry.name.endsWith(url)) {\n const spanData = resourceTimingEntryToSpanData(entry);\n spanData.forEach(data => span.setAttribute(...data));\n // In the next tick, clean this handler up\n // We have to wait here because otherwise this cleans itself up before it is fully done\n setTimeout(cleanup);\n }\n });\n });\n}\n\n/**\n * Converts ALPN protocol ids to name and version.\n *\n * (https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids)\n * @param nextHopProtocol PerformanceResourceTiming.nextHopProtocol\n */\nexport function extractNetworkProtocol(nextHopProtocol: string): { name: string; version: string } {\n let name = 'unknown';\n let version = 'unknown';\n let _name = '';\n for (const char of nextHopProtocol) {\n // http/1.1 etc.\n if (char === '/') {\n [name, version] = nextHopProtocol.split('/');\n break;\n }\n // h2, h3 etc.\n if (!isNaN(Number(char))) {\n name = _name === 'h' ? 'http' : _name;\n version = nextHopProtocol.split(_name)[1];\n break;\n }\n _name += char;\n }\n if (_name === nextHopProtocol) {\n // webrtc, ftp, etc.\n name = _name;\n }\n return { name, version };\n}\n\nfunction getAbsoluteTime(time: number = 0): number {\n return ((browserPerformanceTimeOrigin || performance.timeOrigin) + time) / 1000;\n}\n\nfunction resourceTimingEntryToSpanData(resourceTiming: PerformanceResourceTiming): [string, string | number][] {\n const { name, version } = extractNetworkProtocol(resourceTiming.nextHopProtocol);\n\n const timingSpanData: [string, string | number][] = [];\n\n timingSpanData.push(['network.protocol.version', version], ['network.protocol.name', name]);\n\n if (!browserPerformanceTimeOrigin) {\n return timingSpanData;\n }\n return [\n ...timingSpanData,\n ['http.request.redirect_start', getAbsoluteTime(resourceTiming.redirectStart)],\n ['http.request.fetch_start', getAbsoluteTime(resourceTiming.fetchStart)],\n ['http.request.domain_lookup_start', getAbsoluteTime(resourceTiming.domainLookupStart)],\n ['http.request.domain_lookup_end', getAbsoluteTime(resourceTiming.domainLookupEnd)],\n ['http.request.connect_start', getAbsoluteTime(resourceTiming.connectStart)],\n ['http.request.secure_connection_start', getAbsoluteTime(resourceTiming.secureConnectionStart)],\n ['http.request.connection_end', getAbsoluteTime(resourceTiming.connectEnd)],\n ['http.request.request_start', getAbsoluteTime(resourceTiming.requestStart)],\n ['http.request.response_start', getAbsoluteTime(resourceTiming.responseStart)],\n ['http.request.response_end', getAbsoluteTime(resourceTiming.responseEnd)],\n ];\n}\n\n/**\n * A function that determines whether to attach tracing headers to a request.\n * This was extracted from `instrumentOutgoingRequests` to make it easier to test shouldAttachHeaders.\n * We only export this fuction for testing purposes.\n */\nexport function shouldAttachHeaders(url: string, tracePropagationTargets: (string | RegExp)[] | undefined): boolean {\n return stringMatchesSomePattern(url, tracePropagationTargets || DEFAULT_TRACE_PROPAGATION_TARGETS);\n}\n\n/**\n * Create and track xhr request spans\n *\n * @returns Span if a span was created, otherwise void.\n */\n// eslint-disable-next-line complexity\nexport function xhrCallback(\n handlerData: HandlerDataXhr,\n shouldCreateSpan: (url: string) => boolean,\n shouldAttachHeaders: (url: string) => boolean,\n spans: Record,\n): Span | undefined {\n const xhr = handlerData.xhr;\n const sentryXhrData = xhr && xhr[SENTRY_XHR_DATA_KEY];\n\n if (!hasTracingEnabled() || !xhr || xhr.__sentry_own_request__ || !sentryXhrData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = shouldCreateSpan(sentryXhrData.url);\n\n // check first if the request has finished and is tracked by an existing span which should now end\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = xhr.__sentry_xhr_span_id__;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span && sentryXhrData.status_code !== undefined) {\n setHttpStatus(span, sentryXhrData.status_code);\n span.end();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const scope = getCurrentScope();\n const isolationScope = getIsolationScope();\n\n const fullUrl = getFullURL(sentryXhrData.url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n\n const span = shouldCreateSpanResult\n ? startInactiveSpan({\n name: `${sentryXhrData.method} ${sentryXhrData.url}`,\n onlyIfParent: true,\n attributes: {\n type: 'xhr',\n 'http.method': sentryXhrData.method,\n 'http.url': fullUrl,\n url: sentryXhrData.url,\n 'server.address': host,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser',\n },\n op: 'http.client',\n })\n : undefined;\n\n if (span) {\n xhr.__sentry_xhr_span_id__ = span.spanContext().spanId;\n spans[xhr.__sentry_xhr_span_id__] = span;\n }\n\n const client = getClient();\n\n if (xhr.setRequestHeader && shouldAttachHeaders(sentryXhrData.url) && client) {\n const { traceId, spanId, sampled, dsc } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n const sentryTraceHeader = span ? spanToTraceHeader(span) : generateSentryTraceHeader(traceId, spanId, sampled);\n\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(\n dsc ||\n (span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromClient(traceId, client, scope)),\n );\n\n setHeaderOnXhr(xhr, sentryTraceHeader, sentryBaggageHeader);\n }\n\n return span;\n}\n\nfunction setHeaderOnXhr(\n xhr: SentryWrappedXMLHttpRequest,\n sentryTraceHeader: string,\n sentryBaggageHeader: string | undefined,\n): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader!('sentry-trace', sentryTraceHeader);\n if (sentryBaggageHeader) {\n // From MDN: \"If this method is called several times with the same header, the values are merged into one single request header.\"\n // We can therefore simply set a baggage header without checking what was there before\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader!(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n}\n\nfunction getFullURL(url: string): string | undefined {\n try {\n // By adding a base URL to new URL(), this will also work for relative urls\n // If `url` is a full URL, the base URL is ignored anyhow\n const parsed = new URL(url, WINDOW.location.origin);\n return parsed.href;\n } catch {\n return undefined;\n }\n}\n","/* eslint-disable max-lines */\nimport type { IdleTransaction } from '@sentry/core';\nimport { getActiveSpan, getClient, getCurrentScope } from '@sentry/core';\nimport { getCurrentHub } from '@sentry/core';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n TRACING_DEFAULTS,\n addTracingExtensions,\n getActiveTransaction,\n spanToJSON,\n startIdleTransaction,\n} from '@sentry/core';\nimport type {\n Client,\n Integration,\n IntegrationFn,\n StartSpanOptions,\n Transaction,\n TransactionContext,\n TransactionSource,\n} from '@sentry/types';\nimport type { Span } from '@sentry/types';\nimport {\n addHistoryInstrumentationHandler,\n browserPerformanceTimeOrigin,\n getDomElement,\n logger,\n propagationContextFromHeaders,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { registerBackgroundTabDetection } from './backgroundtab';\nimport { addPerformanceInstrumentationHandler } from './instrument';\nimport {\n addPerformanceEntries,\n startTrackingINP,\n startTrackingInteractions,\n startTrackingLongTasks,\n startTrackingWebVitals,\n} from './metrics';\nimport type { RequestInstrumentationOptions } from './request';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';\nimport { WINDOW } from './types';\nimport type { InteractionRouteNameMapping } from './web-vitals/types';\n\nexport const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\n/** Options for Browser Tracing integration */\nexport interface BrowserTracingOptions extends RequestInstrumentationOptions {\n /**\n * The time to wait in ms until the transaction will be finished during an idle state. An idle state is defined\n * by a moment where there are no in-progress spans.\n *\n * The transaction will use the end timestamp of the last finished span as the endtime for the transaction.\n * If there are still active spans when this the `idleTimeout` is set, the `idleTimeout` will get reset.\n * Time is in ms.\n *\n * Default: 1000\n */\n idleTimeout: number;\n\n /**\n * The max duration for a transaction. If a transaction duration hits the `finalTimeout` value, it\n * will be finished.\n * Time is in ms.\n *\n * Default: 30000\n */\n finalTimeout: number;\n\n /**\n * The heartbeat interval. If no new spans are started or open spans are finished within 3 heartbeats,\n * the transaction will be finished.\n * Time is in ms.\n *\n * Default: 5000\n */\n heartbeatInterval: number;\n\n /**\n * If a span should be created on page load.\n * If this is set to `false`, this integration will not start the default page load span.\n * Default: true\n */\n instrumentPageLoad: boolean;\n\n /**\n * If a span should be created on navigation (history change).\n * If this is set to `false`, this integration will not start the default navigation spans.\n * Default: true\n */\n instrumentNavigation: boolean;\n\n /**\n * Flag spans where tabs moved to background with \"cancelled\". Browser background tab timing is\n * not suited towards doing precise measurements of operations. By default, we recommend that this option\n * be enabled as background transactions can mess up your statistics in nondeterministic ways.\n *\n * Default: true\n */\n markBackgroundSpan: boolean;\n\n /**\n * If true, Sentry will capture long tasks and add them to the corresponding transaction.\n *\n * Default: true\n */\n enableLongTask: boolean;\n\n /**\n * If true, Sentry will capture INP web vitals as standalone spans .\n *\n * Default: false\n */\n enableInp: boolean;\n\n /**\n * Sample rate to determine interaction span sampling.\n * interactionsSampleRate is applied on top of the global tracesSampleRate.\n * ie a tracesSampleRate of 0.1 and interactionsSampleRate of 0.5 will result in a 0.05 sample rate for interactions.\n *\n * Default: 1\n */\n interactionsSampleRate: number;\n\n /**\n * _metricOptions allows the user to send options to change how metrics are collected.\n *\n * _metricOptions is currently experimental.\n *\n * Default: undefined\n */\n _metricOptions?: Partial<{\n /**\n * @deprecated This property no longer has any effect and will be removed in v8.\n */\n _reportAllChanges: boolean;\n }>;\n\n /**\n * _experiments allows the user to send options to define how this integration works.\n * Note that the `enableLongTask` options is deprecated in favor of the option at the top level, and will be removed in v8.\n *\n * TODO (v8): Remove enableLongTask\n *\n * Default: undefined\n */\n _experiments: Partial<{\n enableInteractions: boolean;\n }>;\n\n /**\n * A callback which is called before a span for a pageload or navigation is started.\n * It receives the options passed to `startSpan`, and expects to return an updated options object.\n */\n beforeStartSpan?: (options: StartSpanOptions) => StartSpanOptions;\n}\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingOptions = {\n ...TRACING_DEFAULTS,\n instrumentNavigation: true,\n instrumentPageLoad: true,\n markBackgroundSpan: true,\n enableLongTask: true,\n enableInp: false,\n interactionsSampleRate: 1,\n _experiments: {},\n ...defaultRequestInstrumentationOptions,\n};\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n *\n * We explicitly export the proper type here, as this has to be extended in some cases.\n */\nexport const browserTracingIntegration = ((_options: Partial = {}) => {\n const _hasSetTracePropagationTargets = DEBUG_BUILD\n ? !!(\n // eslint-disable-next-line deprecation/deprecation\n (_options.tracePropagationTargets || _options.tracingOrigins)\n )\n : false;\n\n addTracingExtensions();\n\n // TODO (v8): remove this block after tracingOrigins is removed\n // Set tracePropagationTargets to tracingOrigins if specified by the user\n // In case both are specified, tracePropagationTargets takes precedence\n // eslint-disable-next-line deprecation/deprecation\n if (!_options.tracePropagationTargets && _options.tracingOrigins) {\n // eslint-disable-next-line deprecation/deprecation\n _options.tracePropagationTargets = _options.tracingOrigins;\n }\n\n const options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n };\n\n const _collectWebVitals = startTrackingWebVitals();\n\n /** Stores a mapping of interactionIds from PerformanceEventTimings to the origin interaction path */\n const interactionIdToRouteNameMapping: InteractionRouteNameMapping = {};\n if (options.enableInp) {\n startTrackingINP(interactionIdToRouteNameMapping, options.interactionsSampleRate);\n }\n\n if (options.enableLongTask) {\n startTrackingLongTasks();\n }\n if (options._experiments.enableInteractions) {\n startTrackingInteractions();\n }\n\n const latestRoute: {\n name: string | undefined;\n context: TransactionContext | undefined;\n } = {\n name: undefined,\n context: undefined,\n };\n\n /** Create routing idle transaction. */\n function _createRouteTransaction(context: TransactionContext): Transaction | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n\n const { beforeStartSpan, idleTimeout, finalTimeout, heartbeatInterval } = options;\n\n const isPageloadTransaction = context.op === 'pageload';\n\n let expandedContext: TransactionContext;\n if (isPageloadTransaction) {\n const sentryTrace = isPageloadTransaction ? getMetaContent('sentry-trace') : '';\n const baggage = isPageloadTransaction ? getMetaContent('baggage') : undefined;\n const { traceId, dsc, parentSpanId, sampled } = propagationContextFromHeaders(sentryTrace, baggage);\n expandedContext = {\n traceId,\n parentSpanId,\n parentSampled: sampled,\n ...context,\n metadata: {\n // eslint-disable-next-line deprecation/deprecation\n ...context.metadata,\n dynamicSamplingContext: dsc,\n },\n trimEnd: true,\n };\n } else {\n expandedContext = {\n trimEnd: true,\n ...context,\n };\n }\n\n const finalContext = beforeStartSpan ? beforeStartSpan(expandedContext) : expandedContext;\n\n // If `beforeStartSpan` set a custom name, record that fact\n // eslint-disable-next-line deprecation/deprecation\n finalContext.metadata =\n finalContext.name !== expandedContext.name\n ? // eslint-disable-next-line deprecation/deprecation\n { ...finalContext.metadata, source: 'custom' }\n : // eslint-disable-next-line deprecation/deprecation\n finalContext.metadata;\n\n latestRoute.name = finalContext.name;\n latestRoute.context = finalContext;\n\n if (finalContext.sampled === false) {\n DEBUG_BUILD && logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n DEBUG_BUILD && logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const { location } = WINDOW;\n\n const idleTransaction = startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n isPageloadTransaction, // should wait for finish signal if it's a pageload transaction\n );\n\n if (isPageloadTransaction && WINDOW.document) {\n WINDOW.document.addEventListener('readystatechange', () => {\n if (['interactive', 'complete'].includes(WINDOW.document!.readyState)) {\n idleTransaction.sendAutoFinishSignal();\n }\n });\n\n if (['interactive', 'complete'].includes(WINDOW.document.readyState)) {\n idleTransaction.sendAutoFinishSignal();\n }\n }\n\n idleTransaction.registerBeforeFinishCallback(transaction => {\n _collectWebVitals();\n addPerformanceEntries(transaction);\n });\n\n return idleTransaction as Transaction;\n }\n\n return {\n name: BROWSER_TRACING_INTEGRATION_ID,\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n setupOnce: () => {},\n afterAllSetup(client) {\n const clientOptions = client.getOptions();\n\n const { markBackgroundSpan, traceFetch, traceXHR, shouldCreateSpanForRequest, enableHTTPTimings, _experiments } =\n options;\n\n const clientOptionsTracePropagationTargets = clientOptions && clientOptions.tracePropagationTargets;\n // There are three ways to configure tracePropagationTargets:\n // 1. via top level client option `tracePropagationTargets`\n // 2. via BrowserTracing option `tracePropagationTargets`\n // 3. via BrowserTracing option `tracingOrigins` (deprecated)\n //\n // To avoid confusion, favour top level client option `tracePropagationTargets`, and fallback to\n // BrowserTracing option `tracePropagationTargets` and then `tracingOrigins` (deprecated).\n // This is done as it minimizes bundle size (we don't have to have undefined checks).\n //\n // If both 1 and either one of 2 or 3 are set (from above), we log out a warning.\n // eslint-disable-next-line deprecation/deprecation\n const tracePropagationTargets = clientOptionsTracePropagationTargets || options.tracePropagationTargets;\n if (DEBUG_BUILD && _hasSetTracePropagationTargets && clientOptionsTracePropagationTargets) {\n logger.warn(\n '[Tracing] The `tracePropagationTargets` option was set in the BrowserTracing integration and top level `Sentry.init`. The top level `Sentry.init` value is being used.',\n );\n }\n\n let activeSpan: Span | undefined;\n let startingUrl: string | undefined = WINDOW.location && WINDOW.location.href;\n\n if (client.on) {\n client.on('startNavigationSpan', (context: StartSpanOptions) => {\n if (activeSpan) {\n DEBUG_BUILD && logger.log(`[Tracing] Finishing current transaction with op: ${spanToJSON(activeSpan).op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeSpan.end();\n }\n activeSpan = _createRouteTransaction({\n op: 'navigation',\n ...context,\n });\n });\n\n client.on('startPageLoadSpan', (context: StartSpanOptions) => {\n if (activeSpan) {\n DEBUG_BUILD && logger.log(`[Tracing] Finishing current transaction with op: ${spanToJSON(activeSpan).op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeSpan.end();\n }\n activeSpan = _createRouteTransaction({\n op: 'pageload',\n ...context,\n });\n });\n }\n\n if (options.instrumentPageLoad && client.emit && WINDOW.location) {\n const context: StartSpanOptions = {\n name: WINDOW.location.pathname,\n // pageload should always start at timeOrigin (and needs to be in s, not ms)\n startTimestamp: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 1000 : undefined,\n origin: 'auto.pageload.browser',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n },\n };\n startBrowserTracingPageLoadSpan(client, context);\n }\n\n if (options.instrumentNavigation && client.emit && WINDOW.location) {\n addHistoryInstrumentationHandler(({ to, from }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n const context: StartSpanOptions = {\n name: WINDOW.location.pathname,\n origin: 'auto.navigation.browser',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n },\n };\n\n startBrowserTracingNavigationSpan(client, context);\n }\n });\n }\n\n if (markBackgroundSpan) {\n registerBackgroundTabDetection();\n }\n\n if (_experiments.enableInteractions) {\n registerInteractionListener(options, latestRoute);\n }\n\n if (options.enableInp) {\n registerInpInteractionListener(interactionIdToRouteNameMapping, latestRoute);\n }\n\n instrumentOutgoingRequests({\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n });\n },\n // TODO v8: Remove this again\n // This is private API that we use to fix converted BrowserTracing integrations in Next.js & SvelteKit\n options,\n };\n}) satisfies IntegrationFn;\n\n/**\n * Manually start a page load span.\n * This will only do something if the BrowserTracing integration has been setup.\n */\nexport function startBrowserTracingPageLoadSpan(client: Client, spanOptions: StartSpanOptions): Span | undefined {\n if (!client.emit) {\n return;\n }\n\n client.emit('startPageLoadSpan', spanOptions);\n\n const span = getActiveSpan();\n const op = span && spanToJSON(span).op;\n return op === 'pageload' ? span : undefined;\n}\n\n/**\n * Manually start a navigation span.\n * This will only do something if the BrowserTracing integration has been setup.\n */\nexport function startBrowserTracingNavigationSpan(client: Client, spanOptions: StartSpanOptions): Span | undefined {\n if (!client.emit) {\n return;\n }\n\n client.emit('startNavigationSpan', spanOptions);\n\n const span = getActiveSpan();\n const op = span && spanToJSON(span).op;\n return op === 'navigation' ? span : undefined;\n}\n\n/** Returns the value of a meta tag */\nexport function getMetaContent(metaName: string): string | undefined {\n // Can't specify generic to `getDomElement` because tracing can be used\n // in a variety of environments, have to disable `no-unsafe-member-access`\n // as a result.\n const metaTag = getDomElement(`meta[name=${metaName}]`);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return metaTag ? metaTag.getAttribute('content') : undefined;\n}\n\n/** Start listener for interaction transactions */\nfunction registerInteractionListener(\n options: BrowserTracingOptions,\n latestRoute: {\n name: string | undefined;\n context: TransactionContext | undefined;\n },\n): void {\n let inflightInteractionTransaction: IdleTransaction | undefined;\n const registerInteractionTransaction = (): void => {\n const { idleTimeout, finalTimeout, heartbeatInterval } = options;\n const op = 'ui.action.click';\n\n // eslint-disable-next-line deprecation/deprecation\n const currentTransaction = getActiveTransaction();\n if (currentTransaction && currentTransaction.op && ['navigation', 'pageload'].includes(currentTransaction.op)) {\n DEBUG_BUILD &&\n logger.warn(\n `[Tracing] Did not create ${op} transaction because a pageload or navigation transaction is in progress.`,\n );\n return undefined;\n }\n\n if (inflightInteractionTransaction) {\n inflightInteractionTransaction.setFinishReason('interactionInterrupted');\n inflightInteractionTransaction.end();\n inflightInteractionTransaction = undefined;\n }\n\n if (!latestRoute.name) {\n DEBUG_BUILD && logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);\n return undefined;\n }\n\n const { location } = WINDOW;\n\n const context: TransactionContext = {\n name: latestRoute.name,\n op,\n trimEnd: true,\n data: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: latestRoute.context ? getSource(latestRoute.context) : undefined || 'url',\n },\n };\n\n inflightInteractionTransaction = startIdleTransaction(\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub(),\n context,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n };\n\n ['click'].forEach(type => {\n if (WINDOW.document) {\n addEventListener(type, registerInteractionTransaction, { once: false, capture: true });\n }\n });\n}\n\nfunction isPerformanceEventTiming(entry: PerformanceEntry): entry is PerformanceEventTiming {\n return 'duration' in entry;\n}\n\n/** We store up to 10 interaction candidates max to cap memory usage. This is the same cap as getINP from web-vitals */\nconst MAX_INTERACTIONS = 10;\n\n/** Creates a listener on interaction entries, and maps interactionIds to the origin path of the interaction */\nfunction registerInpInteractionListener(\n interactionIdToRouteNameMapping: InteractionRouteNameMapping,\n latestRoute: {\n name: string | undefined;\n context: TransactionContext | undefined;\n },\n): void {\n const handleEntries = ({ entries }: { entries: PerformanceEntry[] }): void => {\n const client = getClient();\n // We need to get the replay, user, and activeTransaction from the current scope\n // so that we can associate replay id, profile id, and a user display to the span\n const replay =\n client !== undefined && client.getIntegrationByName !== undefined\n ? (client.getIntegrationByName('Replay') as Integration & { getReplayId: () => string })\n : undefined;\n const replayId = replay !== undefined ? replay.getReplayId() : undefined;\n // eslint-disable-next-line deprecation/deprecation\n const activeTransaction = getActiveTransaction();\n const currentScope = getCurrentScope();\n const user = currentScope !== undefined ? currentScope.getUser() : undefined;\n entries.forEach(entry => {\n if (isPerformanceEventTiming(entry)) {\n const interactionId = entry.interactionId;\n if (interactionId === undefined) {\n return;\n }\n const existingInteraction = interactionIdToRouteNameMapping[interactionId];\n const duration = entry.duration;\n const startTime = entry.startTime;\n const keys = Object.keys(interactionIdToRouteNameMapping);\n const minInteractionId =\n keys.length > 0\n ? keys.reduce((a, b) => {\n return interactionIdToRouteNameMapping[a].duration < interactionIdToRouteNameMapping[b].duration\n ? a\n : b;\n })\n : undefined;\n // For a first input event to be considered, we must check that an interaction event does not already exist with the same duration and start time.\n // This is also checked in the web-vitals library.\n if (entry.entryType === 'first-input') {\n const matchingEntry = keys\n .map(key => interactionIdToRouteNameMapping[key])\n .some(interaction => {\n return interaction.duration === duration && interaction.startTime === startTime;\n });\n if (matchingEntry) {\n return;\n }\n }\n // Interactions with an id of 0 and are not first-input are not valid.\n if (!interactionId) {\n return;\n }\n // If the interaction already exists, we want to use the duration of the longest entry, since that is what the INP metric uses.\n if (existingInteraction) {\n existingInteraction.duration = Math.max(existingInteraction.duration, duration);\n } else if (\n keys.length < MAX_INTERACTIONS ||\n minInteractionId === undefined ||\n duration > interactionIdToRouteNameMapping[minInteractionId].duration\n ) {\n // If the interaction does not exist, we want to add it to the mapping if there is space, or if the duration is longer than the shortest entry.\n const routeName = latestRoute.name;\n const parentContext = latestRoute.context;\n if (routeName && parentContext) {\n if (minInteractionId && Object.keys(interactionIdToRouteNameMapping).length >= MAX_INTERACTIONS) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete interactionIdToRouteNameMapping[minInteractionId];\n }\n interactionIdToRouteNameMapping[interactionId] = {\n routeName,\n duration,\n parentContext,\n user,\n activeTransaction,\n replayId,\n startTime,\n };\n }\n }\n }\n });\n };\n addPerformanceInstrumentationHandler('event', handleEntries);\n addPerformanceInstrumentationHandler('first-input', handleEntries);\n}\n\nfunction getSource(context: TransactionContext): TransactionSource | undefined {\n const sourceFromAttributes = context.attributes && context.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n // eslint-disable-next-line deprecation/deprecation\n const sourceFromData = context.data && context.data[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n // eslint-disable-next-line deprecation/deprecation\n const sourceFromMetadata = context.metadata && context.metadata.source;\n\n return sourceFromAttributes || sourceFromData || sourceFromMetadata;\n}\n","import type { IdleTransaction, SpanStatusType } from '@sentry/core';\nimport { getActiveTransaction, spanToJSON } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { WINDOW } from './types';\n\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\nexport function registerBackgroundTabDetection(): void {\n if (WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n // eslint-disable-next-line deprecation/deprecation\n const activeTransaction = getActiveTransaction() as IdleTransaction;\n if (WINDOW.document!.hidden && activeTransaction) {\n const statusType: SpanStatusType = 'cancelled';\n\n const { op, status } = spanToJSON(activeTransaction);\n\n DEBUG_BUILD &&\n logger.log(`[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${op}`);\n // We should not set status if it is already set, this prevent important statuses like\n // error or data loss from being overwritten on transaction.\n if (!status) {\n activeTransaction.setStatus(statusType);\n }\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n activeTransaction.setTag('visibilitychange', 'document.hidden');\n activeTransaction.end();\n }\n });\n } else {\n DEBUG_BUILD && logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n","/* eslint-disable max-lines */\n// Inspired from Donnie McNeal's solution:\n// https://gist.github.com/wontondon/e8c4bdf2888875e4c755712e99279536\n\nimport {\n WINDOW,\n browserTracingIntegration,\n startBrowserTracingNavigationSpan,\n startBrowserTracingPageLoadSpan,\n} from '@sentry/browser';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n getActiveSpan,\n getRootSpan,\n spanToJSON,\n} from '@sentry/core';\nimport type {\n Integration,\n Span,\n StartSpanOptions,\n Transaction,\n TransactionContext,\n TransactionSource,\n} from '@sentry/types';\nimport { getNumberOfUrlSegments, logger } from '@sentry/utils';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\nimport * as React from 'react';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport type {\n Action,\n AgnosticDataRouteMatch,\n CreateRouterFunction,\n CreateRoutesFromChildren,\n Location,\n MatchRoutes,\n RouteMatch,\n RouteObject,\n Router,\n RouterState,\n UseEffect,\n UseLocation,\n UseNavigationType,\n UseRoutes,\n} from './types';\n\nlet activeTransaction: Transaction | undefined;\n\nlet _useEffect: UseEffect;\nlet _useLocation: UseLocation;\nlet _useNavigationType: UseNavigationType;\nlet _createRoutesFromChildren: CreateRoutesFromChildren;\nlet _matchRoutes: MatchRoutes;\nlet _customStartTransaction: (context: TransactionContext) => Transaction | undefined;\nlet _startTransactionOnLocationChange: boolean;\nlet _stripBasename: boolean = false;\n\ninterface ReactRouterOptions {\n useEffect: UseEffect;\n useLocation: UseLocation;\n useNavigationType: UseNavigationType;\n createRoutesFromChildren: CreateRoutesFromChildren;\n matchRoutes: MatchRoutes;\n stripBasename?: boolean;\n}\n\n/**\n * A browser tracing integration that uses React Router v3 to instrument navigations.\n * Expects `history` (and optionally `routes` and `matchPath`) to be passed as options.\n */\nexport function reactRouterV6BrowserTracingIntegration(\n options: Parameters[0] & ReactRouterOptions,\n): Integration {\n const integration = browserTracingIntegration({\n ...options,\n instrumentPageLoad: false,\n instrumentNavigation: false,\n });\n\n const {\n useEffect,\n useLocation,\n useNavigationType,\n createRoutesFromChildren,\n matchRoutes,\n stripBasename,\n instrumentPageLoad = true,\n instrumentNavigation = true,\n } = options;\n\n return {\n ...integration,\n afterAllSetup(client) {\n integration.afterAllSetup(client);\n\n const startNavigationCallback = (startSpanOptions: StartSpanOptions): undefined => {\n startBrowserTracingNavigationSpan(client, startSpanOptions);\n return undefined;\n };\n\n const initPathName = WINDOW && WINDOW.location && WINDOW.location.pathname;\n if (instrumentPageLoad && initPathName) {\n startBrowserTracingPageLoadSpan(client, {\n name: initPathName,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'pageload',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.pageload.react.reactrouter_v6',\n },\n });\n }\n\n _useEffect = useEffect;\n _useLocation = useLocation;\n _useNavigationType = useNavigationType;\n _matchRoutes = matchRoutes;\n _createRoutesFromChildren = createRoutesFromChildren;\n _stripBasename = stripBasename || false;\n\n _customStartTransaction = startNavigationCallback;\n _startTransactionOnLocationChange = instrumentNavigation;\n },\n };\n}\n\n/**\n * @deprecated Use `reactRouterV6BrowserTracingIntegration()` instead.\n */\nexport function reactRouterV6Instrumentation(\n useEffect: UseEffect,\n useLocation: UseLocation,\n useNavigationType: UseNavigationType,\n createRoutesFromChildren: CreateRoutesFromChildren,\n matchRoutes: MatchRoutes,\n stripBasename?: boolean,\n) {\n return (\n customStartTransaction: (context: TransactionContext) => Transaction | undefined,\n startTransactionOnPageLoad = true,\n startTransactionOnLocationChange = true,\n ): void => {\n const initPathName = WINDOW && WINDOW.location && WINDOW.location.pathname;\n if (startTransactionOnPageLoad && initPathName) {\n activeTransaction = customStartTransaction({\n name: initPathName,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'pageload',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.pageload.react.reactrouter_v6',\n },\n });\n }\n\n _useEffect = useEffect;\n _useLocation = useLocation;\n _useNavigationType = useNavigationType;\n _matchRoutes = matchRoutes;\n _createRoutesFromChildren = createRoutesFromChildren;\n _stripBasename = stripBasename || false;\n\n _customStartTransaction = customStartTransaction;\n _startTransactionOnLocationChange = startTransactionOnLocationChange;\n };\n}\n\n/**\n * Strip the basename from a pathname if exists.\n *\n * Vendored and modified from `react-router`\n * https://github.com/remix-run/react-router/blob/462bb712156a3f739d6139a0f14810b76b002df6/packages/router/utils.ts#L1038\n */\nfunction stripBasenameFromPathname(pathname: string, basename: string): string {\n if (!basename || basename === '/') {\n return pathname;\n }\n\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return pathname;\n }\n\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n const startIndex = basename.endsWith('/') ? basename.length - 1 : basename.length;\n const nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== '/') {\n // pathname does not start with basename/\n return pathname;\n }\n\n return pathname.slice(startIndex) || '/';\n}\n\nfunction getNormalizedName(\n routes: RouteObject[],\n location: Location,\n branches: RouteMatch[],\n basename: string = '',\n): [string, TransactionSource] {\n if (!routes || routes.length === 0) {\n return [_stripBasename ? stripBasenameFromPathname(location.pathname, basename) : location.pathname, 'url'];\n }\n\n let pathBuilder = '';\n if (branches) {\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let x = 0; x < branches.length; x++) {\n const branch = branches[x];\n const route = branch.route;\n if (route) {\n // Early return if index route\n if (route.index) {\n return [_stripBasename ? stripBasenameFromPathname(branch.pathname, basename) : branch.pathname, 'route'];\n }\n\n const path = route.path;\n if (path) {\n const newPath = path[0] === '/' || pathBuilder[pathBuilder.length - 1] === '/' ? path : `/${path}`;\n pathBuilder += newPath;\n\n if (basename + branch.pathname === location.pathname) {\n if (\n // If the route defined on the element is something like\n // Product} />\n // We should check against the branch.pathname for the number of / seperators\n getNumberOfUrlSegments(pathBuilder) !== getNumberOfUrlSegments(branch.pathname) &&\n // We should not count wildcard operators in the url segments calculation\n pathBuilder.slice(-2) !== '/*'\n ) {\n return [(_stripBasename ? '' : basename) + newPath, 'route'];\n }\n return [(_stripBasename ? '' : basename) + pathBuilder, 'route'];\n }\n }\n }\n }\n }\n\n return [_stripBasename ? stripBasenameFromPathname(location.pathname, basename) : location.pathname, 'url'];\n}\n\nfunction updatePageloadTransaction(\n activeRootSpan: Span | undefined,\n location: Location,\n routes: RouteObject[],\n matches?: AgnosticDataRouteMatch,\n basename?: string,\n): void {\n const branches = Array.isArray(matches)\n ? matches\n : (_matchRoutes(routes, location, basename) as unknown as RouteMatch[]);\n\n if (activeRootSpan && branches) {\n const [name, source] = getNormalizedName(routes, location, branches, basename);\n activeRootSpan.updateName(name);\n activeRootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source);\n }\n}\n\nfunction handleNavigation(\n location: Location,\n routes: RouteObject[],\n navigationType: Action,\n matches?: AgnosticDataRouteMatch,\n basename?: string,\n): void {\n const branches = Array.isArray(matches) ? matches : _matchRoutes(routes, location, basename);\n\n if (_startTransactionOnLocationChange && (navigationType === 'PUSH' || navigationType === 'POP') && branches) {\n if (activeTransaction) {\n activeTransaction.end();\n }\n\n const [name, source] = getNormalizedName(routes, location, branches, basename);\n activeTransaction = _customStartTransaction({\n name,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source,\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'navigation',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.navigation.react.reactrouter_v6',\n },\n });\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function withSentryReactRouterV6Routing

, R extends React.FC

>(Routes: R): R {\n if (\n !_useEffect ||\n !_useLocation ||\n !_useNavigationType ||\n !_createRoutesFromChildren ||\n !_matchRoutes ||\n !_customStartTransaction\n ) {\n DEBUG_BUILD &&\n logger.warn(`reactRouterV6Instrumentation was unable to wrap Routes because of one or more missing parameters.\n useEffect: ${_useEffect}. useLocation: ${_useLocation}. useNavigationType: ${_useNavigationType}.\n createRoutesFromChildren: ${_createRoutesFromChildren}. matchRoutes: ${_matchRoutes}. customStartTransaction: ${_customStartTransaction}.`);\n\n return Routes;\n }\n\n let isMountRenderPass: boolean = true;\n\n const SentryRoutes: React.FC

= (props: P) => {\n const location = _useLocation();\n const navigationType = _useNavigationType();\n\n _useEffect(\n () => {\n const routes = _createRoutesFromChildren(props.children) as RouteObject[];\n\n if (isMountRenderPass) {\n updatePageloadTransaction(getActiveRootSpan(), location, routes);\n isMountRenderPass = false;\n } else {\n handleNavigation(location, routes, navigationType);\n }\n },\n // `props.children` is purpusely not included in the dependency array, because we do not want to re-run this effect\n // when the children change. We only want to start transactions when the location or navigation type change.\n [location, navigationType],\n );\n\n // @ts-expect-error Setting more specific React Component typing for `R` generic above\n // will break advanced type inference done by react router params\n return ;\n };\n\n hoistNonReactStatics(SentryRoutes, Routes);\n\n // @ts-expect-error Setting more specific React Component typing for `R` generic above\n // will break advanced type inference done by react router params\n return SentryRoutes;\n}\n\nexport function wrapUseRoutes(origUseRoutes: UseRoutes): UseRoutes {\n if (!_useEffect || !_useLocation || !_useNavigationType || !_matchRoutes || !_customStartTransaction) {\n DEBUG_BUILD &&\n logger.warn(\n 'reactRouterV6Instrumentation was unable to wrap `useRoutes` because of one or more missing parameters.',\n );\n\n return origUseRoutes;\n }\n\n let isMountRenderPass: boolean = true;\n\n const SentryRoutes: React.FC<{\n children?: React.ReactNode;\n routes: RouteObject[];\n locationArg?: Partial | string;\n }> = (props: { children?: React.ReactNode; routes: RouteObject[]; locationArg?: Partial | string }) => {\n const { routes, locationArg } = props;\n\n const Routes = origUseRoutes(routes, locationArg);\n\n const location = _useLocation();\n const navigationType = _useNavigationType();\n\n // A value with stable identity to either pick `locationArg` if available or `location` if not\n const stableLocationParam =\n typeof locationArg === 'string' || (locationArg && locationArg.pathname)\n ? (locationArg as { pathname: string })\n : location;\n\n _useEffect(() => {\n const normalizedLocation =\n typeof stableLocationParam === 'string' ? { pathname: stableLocationParam } : stableLocationParam;\n\n if (isMountRenderPass) {\n updatePageloadTransaction(getActiveRootSpan(), normalizedLocation, routes);\n isMountRenderPass = false;\n } else {\n handleNavigation(normalizedLocation, routes, navigationType);\n }\n }, [navigationType, stableLocationParam]);\n\n return Routes;\n };\n\n // eslint-disable-next-line react/display-name\n return (routes: RouteObject[], locationArg?: Partial | string): React.ReactElement | null => {\n return ;\n };\n}\n\nexport function wrapCreateBrowserRouter<\n TState extends RouterState = RouterState,\n TRouter extends Router = Router,\n>(createRouterFunction: CreateRouterFunction): CreateRouterFunction {\n // `opts` for createBrowserHistory and createMemoryHistory are different, but also not relevant for us at the moment.\n // `basename` is the only option that is relevant for us, and it is the same for all.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (routes: RouteObject[], opts?: Record & { basename?: string }): TRouter {\n const router = createRouterFunction(routes, opts);\n const basename = opts && opts.basename;\n\n const activeRootSpan = getActiveRootSpan();\n\n // The initial load ends when `createBrowserRouter` is called.\n // This is the earliest convenient time to update the transaction name.\n // Callbacks to `router.subscribe` are not called for the initial load.\n if (router.state.historyAction === 'POP' && activeRootSpan) {\n updatePageloadTransaction(activeRootSpan, router.state.location, routes, undefined, basename);\n }\n\n router.subscribe((state: RouterState) => {\n const location = state.location;\n if (_startTransactionOnLocationChange && (state.historyAction === 'PUSH' || state.historyAction === 'POP')) {\n handleNavigation(location, routes, state.historyAction, undefined, basename);\n }\n });\n\n return router;\n };\n}\n\nfunction getActiveRootSpan(): Span | undefined {\n // Legacy behavior for \"old\" react router instrumentation\n if (activeTransaction) {\n return activeTransaction;\n }\n\n const span = getActiveSpan();\n const rootSpan = span ? getRootSpan(span) : undefined;\n\n if (!rootSpan) {\n return undefined;\n }\n\n const op = spanToJSON(rootSpan).op;\n\n // Only use this root span if it is a pageload or navigation span\n return op === 'navigation' || op === 'pageload' ? rootSpan : undefined;\n}\n","import _typeof from \"./typeof.js\";\nexport default function _regeneratorRuntime() {\n \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */\n _regeneratorRuntime = function _regeneratorRuntime() {\n return exports;\n };\n var exports = {},\n Op = Object.prototype,\n hasOwn = Op.hasOwnProperty,\n defineProperty = Object.defineProperty || function (obj, key, desc) {\n obj[key] = desc.value;\n },\n $Symbol = \"function\" == typeof Symbol ? Symbol : {},\n iteratorSymbol = $Symbol.iterator || \"@@iterator\",\n asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\",\n toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n function define(obj, key, value) {\n return Object.defineProperty(obj, key, {\n value: value,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }), obj[key];\n }\n try {\n define({}, \"\");\n } catch (err) {\n define = function define(obj, key, value) {\n return obj[key] = value;\n };\n }\n function wrap(innerFn, outerFn, self, tryLocsList) {\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,\n generator = Object.create(protoGenerator.prototype),\n context = new Context(tryLocsList || []);\n return defineProperty(generator, \"_invoke\", {\n value: makeInvokeMethod(innerFn, self, context)\n }), generator;\n }\n function tryCatch(fn, obj, arg) {\n try {\n return {\n type: \"normal\",\n arg: fn.call(obj, arg)\n };\n } catch (err) {\n return {\n type: \"throw\",\n arg: err\n };\n }\n }\n exports.wrap = wrap;\n var ContinueSentinel = {};\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n var IteratorPrototype = {};\n define(IteratorPrototype, iteratorSymbol, function () {\n return this;\n });\n var getProto = Object.getPrototypeOf,\n NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);\n var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function (method) {\n define(prototype, method, function (arg) {\n return this._invoke(method, arg);\n });\n });\n }\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (\"throw\" !== record.type) {\n var result = record.arg,\n value = result.value;\n return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) {\n invoke(\"next\", value, resolve, reject);\n }, function (err) {\n invoke(\"throw\", err, resolve, reject);\n }) : PromiseImpl.resolve(value).then(function (unwrapped) {\n result.value = unwrapped, resolve(result);\n }, function (error) {\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n reject(record.arg);\n }\n var previousPromise;\n defineProperty(this, \"_invoke\", {\n value: function value(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function (resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();\n }\n });\n }\n function makeInvokeMethod(innerFn, self, context) {\n var state = \"suspendedStart\";\n return function (method, arg) {\n if (\"executing\" === state) throw new Error(\"Generator is already running\");\n if (\"completed\" === state) {\n if (\"throw\" === method) throw arg;\n return doneResult();\n }\n for (context.method = method, context.arg = arg;;) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) {\n if (\"suspendedStart\" === state) throw state = \"completed\", context.arg;\n context.dispatchException(context.arg);\n } else \"return\" === context.method && context.abrupt(\"return\", context.arg);\n state = \"executing\";\n var record = tryCatch(innerFn, self, context);\n if (\"normal\" === record.type) {\n if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue;\n return {\n value: record.arg,\n done: context.done\n };\n }\n \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg);\n }\n };\n }\n function maybeInvokeDelegate(delegate, context) {\n var methodName = context.method,\n method = delegate.iterator[methodName];\n if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel;\n var record = tryCatch(method, delegate.iterator, context.arg);\n if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel;\n var info = record.arg;\n return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel);\n }\n function pushTryEntry(locs) {\n var entry = {\n tryLoc: locs[0]\n };\n 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);\n }\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\", delete record.arg, entry.completion = record;\n }\n function Context(tryLocsList) {\n this.tryEntries = [{\n tryLoc: \"root\"\n }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);\n }\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) return iteratorMethod.call(iterable);\n if (\"function\" == typeof iterable.next) return iterable;\n if (!isNaN(iterable.length)) {\n var i = -1,\n next = function next() {\n for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;\n return next.value = undefined, next.done = !0, next;\n };\n return next.next = next;\n }\n }\n return {\n next: doneResult\n };\n }\n function doneResult() {\n return {\n value: undefined,\n done: !0\n };\n }\n return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", {\n value: GeneratorFunctionPrototype,\n configurable: !0\n }), defineProperty(GeneratorFunctionPrototype, \"constructor\", {\n value: GeneratorFunction,\n configurable: !0\n }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) {\n var ctor = \"function\" == typeof genFun && genFun.constructor;\n return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name));\n }, exports.mark = function (genFun) {\n return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun;\n }, exports.awrap = function (arg) {\n return {\n __await: arg\n };\n }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {\n return this;\n }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n void 0 === PromiseImpl && (PromiseImpl = Promise);\n var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);\n return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {\n return result.done ? result.value : iter.next();\n });\n }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () {\n return this;\n }), define(Gp, \"toString\", function () {\n return \"[object Generator]\";\n }), exports.keys = function (val) {\n var object = Object(val),\n keys = [];\n for (var key in object) keys.push(key);\n return keys.reverse(), function next() {\n for (; keys.length;) {\n var key = keys.pop();\n if (key in object) return next.value = key, next.done = !1, next;\n }\n return next.done = !0, next;\n };\n }, exports.values = values, Context.prototype = {\n constructor: Context,\n reset: function reset(skipTempReset) {\n if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);\n },\n stop: function stop() {\n this.done = !0;\n var rootRecord = this.tryEntries[0].completion;\n if (\"throw\" === rootRecord.type) throw rootRecord.arg;\n return this.rval;\n },\n dispatchException: function dispatchException(exception) {\n if (this.done) throw exception;\n var context = this;\n function handle(loc, caught) {\n return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught;\n }\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i],\n record = entry.completion;\n if (\"root\" === entry.tryLoc) return handle(\"end\");\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\"),\n hasFinally = hasOwn.call(entry, \"finallyLoc\");\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n } else {\n if (!hasFinally) throw new Error(\"try statement without catch or finally\");\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n }\n }\n }\n },\n abrupt: function abrupt(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev && hasOwn.call(entry, \"finallyLoc\") && this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);\n var record = finallyEntry ? finallyEntry.completion : {};\n return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);\n },\n complete: function complete(record, afterLoc) {\n if (\"throw\" === record.type) throw record.arg;\n return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;\n },\n finish: function finish(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;\n }\n },\n \"catch\": function _catch(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (\"throw\" === record.type) {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n throw new Error(\"illegal catch attempt\");\n },\n delegateYield: function delegateYield(iterable, resultName, nextLoc) {\n return this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel;\n }\n }, exports;\n}","function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\nexport default function _asyncToGenerator(fn) {\n return function () {\n var self = this,\n args = arguments;\n return new Promise(function (resolve, reject) {\n var gen = fn.apply(self, args);\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n _next(undefined);\n });\n };\n}","// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2012-2018 various contributors (see AUTHORS)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport type { GenericFunction } from './types';\n\n/**\n * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values,\n * descriptors, and functions.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n * See https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15\n *\n * @param ops Array result of expression conversion\n * @returns The value of the expression\n */\nexport function _optionalChain(ops: unknown[]): unknown {\n let lastAccessLHS: unknown = undefined;\n let value = ops[0];\n let i = 1;\n while (i < ops.length) {\n const op = ops[i] as string;\n const fn = ops[i + 1] as (intermediateValue: unknown) => unknown;\n i += 2;\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it\n return;\n }\n if (op === 'access' || op === 'optionalAccess') {\n lastAccessLHS = value;\n value = fn(value);\n } else if (op === 'call' || op === 'optionalCall') {\n value = fn((...args: unknown[]) => (value as GenericFunction).call(lastAccessLHS, ...args));\n lastAccessLHS = undefined;\n }\n }\n return value;\n}\n\n// Sucrase version\n// function _optionalChain(ops) {\n// let lastAccessLHS = undefined;\n// let value = ops[0];\n// let i = 1;\n// while (i < ops.length) {\n// const op = ops[i];\n// const fn = ops[i + 1];\n// i += 2;\n// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n// return undefined;\n// }\n// if (op === 'access' || op === 'optionalAccess') {\n// lastAccessLHS = value;\n// value = fn(value);\n// } else if (op === 'call' || op === 'optionalCall') {\n// value = fn((...args) => value.call(lastAccessLHS, ...args));\n// lastAccessLHS = undefined;\n// }\n// }\n// return value;\n// }\n","import type { Client, DsnComponents, Hub } from '@sentry/types';\n\n/**\n * Checks whether given url points to Sentry server\n * @param url url to verify\n *\n * TODO(v8): Remove Hub fallback type\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function isSentryRequestUrl(url: string, hubOrClient: Hub | Client | undefined): boolean {\n const client =\n hubOrClient && isHub(hubOrClient)\n ? // eslint-disable-next-line deprecation/deprecation\n hubOrClient.getClient()\n : hubOrClient;\n const dsn = client && client.getDsn();\n const tunnel = client && client.getOptions().tunnel;\n\n return checkDsn(url, dsn) || checkTunnel(url, tunnel);\n}\n\nfunction checkTunnel(url: string, tunnel: string | undefined): boolean {\n if (!tunnel) {\n return false;\n }\n\n return removeTrailingSlash(url) === removeTrailingSlash(tunnel);\n}\n\nfunction checkDsn(url: string, dsn: DsnComponents | undefined): boolean {\n return dsn ? url.includes(dsn.host) : false;\n}\n\nfunction removeTrailingSlash(str: string): string {\n return str[str.length - 1] === '/' ? str.slice(0, -1) : str;\n}\n\n// eslint-disable-next-line deprecation/deprecation\nfunction isHub(hubOrClient: Hub | Client | undefined): hubOrClient is Hub {\n // eslint-disable-next-line deprecation/deprecation\n return (hubOrClient as Hub).getClient !== undefined;\n}\n","import { isNodeEnv } from './node';\nimport { GLOBAL_OBJ } from './worldwide';\n\n/**\n * Returns true if we are in the browser.\n */\nexport function isBrowser(): boolean {\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' && (!isNodeEnv() || isElectronNodeRenderer());\n}\n\ntype ElectronProcess = { type?: string };\n\n// Electron renderers with nodeIntegration enabled are detected as Node.js so we specifically test for them\nfunction isElectronNodeRenderer(): boolean {\n return (\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (GLOBAL_OBJ as any).process !== undefined && ((GLOBAL_OBJ as any).process as ElectronProcess).type === 'renderer'\n );\n}\n","import { GLOBAL_OBJ } from '@sentry/utils';\n\n// exporting a separate copy of `WINDOW` rather than exporting the one from `@sentry/browser`\n// prevents the browser package from being bundled in the CDN bundle, and avoids a\n// circular dependency between the browser and replay packages should `@sentry/browser` import\n// from `@sentry/replay` in the future\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nexport const REPLAY_SESSION_KEY = 'sentryReplaySession';\nexport const REPLAY_EVENT_NAME = 'replay_event';\nexport const RECORDING_EVENT_NAME = 'replay_recording';\nexport const UNABLE_TO_SEND_REPLAY = 'Unable to send Replay';\n\n// The idle limit for a session after which recording is paused.\nexport const SESSION_IDLE_PAUSE_DURATION = 300_000; // 5 minutes in ms\n\n// The idle limit for a session after which the session expires.\nexport const SESSION_IDLE_EXPIRE_DURATION = 900_000; // 15 minutes in ms\n\n/** Default flush delays */\nexport const DEFAULT_FLUSH_MIN_DELAY = 5_000;\n// XXX: Temp fix for our debounce logic where `maxWait` would never occur if it\n// was the same as `wait`\nexport const DEFAULT_FLUSH_MAX_DELAY = 5_500;\n\n/* How long to wait for error checkouts */\nexport const BUFFER_CHECKOUT_TIME = 60_000;\n\nexport const RETRY_BASE_INTERVAL = 5000;\nexport const RETRY_MAX_COUNT = 3;\n\n/* The max (uncompressed) size in bytes of a network body. Any body larger than this will be truncated. */\nexport const NETWORK_BODY_MAX_SIZE = 150_000;\n\n/* The max size of a single console arg that is captured. Any arg larger than this will be truncated. */\nexport const CONSOLE_ARG_MAX_SIZE = 5_000;\n\n/* Min. time to wait before we consider something a slow click. */\nexport const SLOW_CLICK_THRESHOLD = 3_000;\n/* For scroll actions after a click, we only look for a very short time period to detect programmatic scrolling. */\nexport const SLOW_CLICK_SCROLL_TIMEOUT = 300;\n\n/** When encountering a total segment size exceeding this size, stop the replay (as we cannot properly ingest it). */\nexport const REPLAY_MAX_EVENT_BUFFER_SIZE = 20_000_000; // ~20MB\n\n/** Replays must be min. 5s long before we send them. */\nexport const MIN_REPLAY_DURATION = 4_999;\n/* The max. allowed value that the minReplayDuration can be set to. */\nexport const MIN_REPLAY_DURATION_LIMIT = 15_000;\n\n/** The max. length of a replay. */\nexport const MAX_REPLAY_DURATION = 3_600_000; // 60 minutes in ms;\n\n/** Default attributes to be ignored when `maskAllText` is enabled */\nexport const DEFAULT_IGNORED_ATTRIBUTES = ['title', 'placeholder'];\n","var NodeType;\r\n(function (NodeType) {\r\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\r\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\r\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\r\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\r\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\r\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\r\n})(NodeType || (NodeType = {}));\n\nfunction isElement(n) {\r\n return n.nodeType === n.ELEMENT_NODE;\r\n}\r\nfunction isShadowRoot(n) {\r\n const host = n?.host;\r\n return Boolean(host?.shadowRoot === n);\r\n}\r\nfunction isNativeShadowDom(shadowRoot) {\r\n return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';\r\n}\r\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\r\n if (cssText.includes(' background-clip: text;') &&\r\n !cssText.includes(' -webkit-background-clip: text;')) {\r\n cssText = cssText.replace(' background-clip: text;', ' -webkit-background-clip: text; background-clip: text;');\r\n }\r\n return cssText;\r\n}\r\nfunction escapeImportStatement(rule) {\r\n const { cssText } = rule;\r\n if (cssText.split('\"').length < 3)\r\n return cssText;\r\n const statement = ['@import', `url(${JSON.stringify(rule.href)})`];\r\n if (rule.layerName === '') {\r\n statement.push(`layer`);\r\n }\r\n else if (rule.layerName) {\r\n statement.push(`layer(${rule.layerName})`);\r\n }\r\n if (rule.supportsText) {\r\n statement.push(`supports(${rule.supportsText})`);\r\n }\r\n if (rule.media.length) {\r\n statement.push(rule.media.mediaText);\r\n }\r\n return statement.join(' ') + ';';\r\n}\r\nfunction stringifyStylesheet(s) {\r\n try {\r\n const rules = s.rules || s.cssRules;\r\n return rules\r\n ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules, stringifyRule).join(''))\r\n : null;\r\n }\r\n catch (error) {\r\n return null;\r\n }\r\n}\r\nfunction stringifyRule(rule) {\r\n let importStringified;\r\n if (isCSSImportRule(rule)) {\r\n try {\r\n importStringified =\r\n stringifyStylesheet(rule.styleSheet) ||\r\n escapeImportStatement(rule);\r\n }\r\n catch (error) {\r\n }\r\n }\r\n else if (isCSSStyleRule(rule) && rule.selectorText.includes(':')) {\r\n return fixSafariColons(rule.cssText);\r\n }\r\n return importStringified || rule.cssText;\r\n}\r\nfunction fixSafariColons(cssStringified) {\r\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\r\n return cssStringified.replace(regex, '$1\\\\$2');\r\n}\r\nfunction isCSSImportRule(rule) {\r\n return 'styleSheet' in rule;\r\n}\r\nfunction isCSSStyleRule(rule) {\r\n return 'selectorText' in rule;\r\n}\r\nclass Mirror {\r\n constructor() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n getId(n) {\r\n if (!n)\r\n return -1;\r\n const id = this.getMeta(n)?.id;\r\n return id ?? -1;\r\n }\r\n getNode(id) {\r\n return this.idNodeMap.get(id) || null;\r\n }\r\n getIds() {\r\n return Array.from(this.idNodeMap.keys());\r\n }\r\n getMeta(n) {\r\n return this.nodeMetaMap.get(n) || null;\r\n }\r\n removeNodeFromMap(n) {\r\n const id = this.getId(n);\r\n this.idNodeMap.delete(id);\r\n if (n.childNodes) {\r\n n.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode));\r\n }\r\n }\r\n has(id) {\r\n return this.idNodeMap.has(id);\r\n }\r\n hasNode(node) {\r\n return this.nodeMetaMap.has(node);\r\n }\r\n add(n, meta) {\r\n const id = meta.id;\r\n this.idNodeMap.set(id, n);\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n replace(id, n) {\r\n const oldNode = this.getNode(id);\r\n if (oldNode) {\r\n const meta = this.nodeMetaMap.get(oldNode);\r\n if (meta)\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n this.idNodeMap.set(id, n);\r\n }\r\n reset() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n}\r\nfunction createMirror() {\r\n return new Mirror();\r\n}\r\nfunction shouldMaskInput({ maskInputOptions, tagName, type, }) {\r\n if (tagName === 'OPTION') {\r\n tagName = 'SELECT';\r\n }\r\n return Boolean(maskInputOptions[tagName.toLowerCase()] ||\r\n (type && maskInputOptions[type]) ||\r\n type === 'password' ||\r\n (tagName === 'INPUT' && !type && maskInputOptions['text']));\r\n}\r\nfunction maskInputValue({ isMasked, element, value, maskInputFn, }) {\r\n let text = value || '';\r\n if (!isMasked) {\r\n return text;\r\n }\r\n if (maskInputFn) {\r\n text = maskInputFn(text, element);\r\n }\r\n return '*'.repeat(text.length);\r\n}\r\nfunction toLowerCase(str) {\r\n return str.toLowerCase();\r\n}\r\nfunction toUpperCase(str) {\r\n return str.toUpperCase();\r\n}\r\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\r\nfunction is2DCanvasBlank(canvas) {\r\n const ctx = canvas.getContext('2d');\r\n if (!ctx)\r\n return true;\r\n const chunkSize = 50;\r\n for (let x = 0; x < canvas.width; x += chunkSize) {\r\n for (let y = 0; y < canvas.height; y += chunkSize) {\r\n const getImageData = ctx.getImageData;\r\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\r\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\r\n : getImageData;\r\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\r\n if (pixelBuffer.some((pixel) => pixel !== 0))\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isNodeMetaEqual(a, b) {\r\n if (!a || !b || a.type !== b.type)\r\n return false;\r\n if (a.type === NodeType.Document)\r\n return a.compatMode === b.compatMode;\r\n else if (a.type === NodeType.DocumentType)\r\n return (a.name === b.name &&\r\n a.publicId === b.publicId &&\r\n a.systemId === b.systemId);\r\n else if (a.type === NodeType.Comment ||\r\n a.type === NodeType.Text ||\r\n a.type === NodeType.CDATA)\r\n return a.textContent === b.textContent;\r\n else if (a.type === NodeType.Element)\r\n return (a.tagName === b.tagName &&\r\n JSON.stringify(a.attributes) ===\r\n JSON.stringify(b.attributes) &&\r\n a.isSVG === b.isSVG &&\r\n a.needBlock === b.needBlock);\r\n return false;\r\n}\r\nfunction getInputType(element) {\r\n const type = element.type;\r\n return element.hasAttribute('data-rr-is-password')\r\n ? 'password'\r\n : type\r\n ?\r\n toLowerCase(type)\r\n : null;\r\n}\r\nfunction getInputValue(el, tagName, type) {\r\n if (tagName === 'INPUT' && (type === 'radio' || type === 'checkbox')) {\r\n return el.getAttribute('value') || '';\r\n }\r\n return el.value;\r\n}\n\nlet _id = 1;\r\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\r\nconst IGNORED_NODE = -2;\r\nfunction genId() {\r\n return _id++;\r\n}\r\nfunction getValidTagName(element) {\r\n if (element instanceof HTMLFormElement) {\r\n return 'form';\r\n }\r\n const processedTagName = toLowerCase(element.tagName);\r\n if (tagNameRegex.test(processedTagName)) {\r\n return 'div';\r\n }\r\n return processedTagName;\r\n}\r\nfunction extractOrigin(url) {\r\n let origin = '';\r\n if (url.indexOf('//') > -1) {\r\n origin = url.split('/').slice(0, 3).join('/');\r\n }\r\n else {\r\n origin = url.split('/')[0];\r\n }\r\n origin = origin.split('?')[0];\r\n return origin;\r\n}\r\nlet canvasService;\r\nlet canvasCtx;\r\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\r\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\r\nconst URL_WWW_MATCH = /^www\\..*/i;\r\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\r\nfunction absoluteToStylesheet(cssText, href) {\r\n return (cssText || '').replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => {\r\n const filePath = path1 || path2 || path3;\r\n const maybeQuote = quote1 || quote2 || '';\r\n if (!filePath) {\r\n return origin;\r\n }\r\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (DATA_URI.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (filePath[0] === '/') {\r\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\r\n }\r\n const stack = href.split('/');\r\n const parts = filePath.split('/');\r\n stack.pop();\r\n for (const part of parts) {\r\n if (part === '.') {\r\n continue;\r\n }\r\n else if (part === '..') {\r\n stack.pop();\r\n }\r\n else {\r\n stack.push(part);\r\n }\r\n }\r\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\r\n });\r\n}\r\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\r\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\r\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\r\n if (attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n let pos = 0;\r\n function collectCharacters(regEx) {\r\n let chars;\r\n const match = regEx.exec(attributeValue.substring(pos));\r\n if (match) {\r\n chars = match[0];\r\n pos += chars.length;\r\n return chars;\r\n }\r\n return '';\r\n }\r\n const output = [];\r\n while (true) {\r\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\r\n if (pos >= attributeValue.length) {\r\n break;\r\n }\r\n let url = collectCharacters(SRCSET_NOT_SPACES);\r\n if (url.slice(-1) === ',') {\r\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\r\n output.push(url);\r\n }\r\n else {\r\n let descriptorsStr = '';\r\n url = absoluteToDoc(doc, url);\r\n let inParens = false;\r\n while (true) {\r\n const c = attributeValue.charAt(pos);\r\n if (c === '') {\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (!inParens) {\r\n if (c === ',') {\r\n pos += 1;\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (c === '(') {\r\n inParens = true;\r\n }\r\n }\r\n else {\r\n if (c === ')') {\r\n inParens = false;\r\n }\r\n }\r\n descriptorsStr += c;\r\n pos += 1;\r\n }\r\n }\r\n }\r\n return output.join(', ');\r\n}\r\nfunction absoluteToDoc(doc, attributeValue) {\r\n if (!attributeValue || attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n const a = doc.createElement('a');\r\n a.href = attributeValue;\r\n return a.href;\r\n}\r\nfunction isSVGElement(el) {\r\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\r\n}\r\nfunction getHref() {\r\n const a = document.createElement('a');\r\n a.href = '';\r\n return a.href;\r\n}\r\nfunction transformAttribute(doc, tagName, name, value, element, maskAttributeFn) {\r\n if (!value) {\r\n return value;\r\n }\r\n if (name === 'src' ||\r\n (name === 'href' && !(tagName === 'use' && value[0] === '#'))) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'xlink:href' && value[0] !== '#') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'background' &&\r\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'srcset') {\r\n return getAbsoluteSrcsetString(doc, value);\r\n }\r\n else if (name === 'style') {\r\n return absoluteToStylesheet(value, getHref());\r\n }\r\n else if (tagName === 'object' && name === 'data') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n if (typeof maskAttributeFn === 'function') {\r\n return maskAttributeFn(name, value, element);\r\n }\r\n return value;\r\n}\r\nfunction ignoreAttribute(tagName, name, _value) {\r\n return (tagName === 'video' || tagName === 'audio') && name === 'autoplay';\r\n}\r\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\r\n try {\r\n if (unblockSelector && element.matches(unblockSelector)) {\r\n return false;\r\n }\r\n if (typeof blockClass === 'string') {\r\n if (element.classList.contains(blockClass)) {\r\n return true;\r\n }\r\n }\r\n else {\r\n for (let eIndex = element.classList.length; eIndex--;) {\r\n const className = element.classList[eIndex];\r\n if (blockClass.test(className)) {\r\n return true;\r\n }\r\n }\r\n }\r\n if (blockSelector) {\r\n return element.matches(blockSelector);\r\n }\r\n }\r\n catch (e) {\r\n }\r\n return false;\r\n}\r\nfunction elementClassMatchesRegex(el, regex) {\r\n for (let eIndex = el.classList.length; eIndex--;) {\r\n const className = el.classList[eIndex];\r\n if (regex.test(className)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction distanceToMatch(node, matchPredicate, limit = Infinity, distance = 0) {\r\n if (!node)\r\n return -1;\r\n if (node.nodeType !== node.ELEMENT_NODE)\r\n return -1;\r\n if (distance > limit)\r\n return -1;\r\n if (matchPredicate(node))\r\n return distance;\r\n return distanceToMatch(node.parentNode, matchPredicate, limit, distance + 1);\r\n}\r\nfunction createMatchPredicate(className, selector) {\r\n return (node) => {\r\n const el = node;\r\n if (el === null)\r\n return false;\r\n try {\r\n if (className) {\r\n if (typeof className === 'string') {\r\n if (el.matches(`.${className}`))\r\n return true;\r\n }\r\n else if (elementClassMatchesRegex(el, className)) {\r\n return true;\r\n }\r\n }\r\n if (selector && el.matches(selector))\r\n return true;\r\n return false;\r\n }\r\n catch {\r\n return false;\r\n }\r\n };\r\n}\r\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText) {\r\n try {\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n if (el === null)\r\n return false;\r\n if (el.tagName === 'INPUT') {\r\n const autocomplete = el.getAttribute('autocomplete');\r\n const disallowedAutocompleteValues = [\r\n 'current-password',\r\n 'new-password',\r\n 'cc-number',\r\n 'cc-exp',\r\n 'cc-exp-month',\r\n 'cc-exp-year',\r\n 'cc-csc',\r\n ];\r\n if (disallowedAutocompleteValues.includes(autocomplete)) {\r\n return true;\r\n }\r\n }\r\n let maskDistance = -1;\r\n let unmaskDistance = -1;\r\n if (maskAllText) {\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector));\r\n if (unmaskDistance < 0) {\r\n return true;\r\n }\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector), unmaskDistance >= 0 ? unmaskDistance : Infinity);\r\n }\r\n else {\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector));\r\n if (maskDistance < 0) {\r\n return false;\r\n }\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector), maskDistance >= 0 ? maskDistance : Infinity);\r\n }\r\n return maskDistance >= 0\r\n ? unmaskDistance >= 0\r\n ? maskDistance <= unmaskDistance\r\n : true\r\n : unmaskDistance >= 0\r\n ? false\r\n : !!maskAllText;\r\n }\r\n catch (e) {\r\n }\r\n return !!maskAllText;\r\n}\r\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\r\n const win = iframeEl.contentWindow;\r\n if (!win) {\r\n return;\r\n }\r\n let fired = false;\r\n let readyState;\r\n try {\r\n readyState = win.document.readyState;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (readyState !== 'complete') {\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, iframeLoadTimeout);\r\n iframeEl.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n return;\r\n }\r\n const blankUrl = 'about:blank';\r\n if (win.location.href !== blankUrl ||\r\n iframeEl.src === blankUrl ||\r\n iframeEl.src === '') {\r\n setTimeout(listener, 0);\r\n return iframeEl.addEventListener('load', listener);\r\n }\r\n iframeEl.addEventListener('load', listener);\r\n}\r\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\r\n let fired = false;\r\n let styleSheetLoaded;\r\n try {\r\n styleSheetLoaded = link.sheet;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (styleSheetLoaded)\r\n return;\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, styleSheetLoadTimeout);\r\n link.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n}\r\nfunction serializeNode(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskAttributeFn, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, } = options;\r\n const rootId = getRootId(doc, mirror);\r\n switch (n.nodeType) {\r\n case n.DOCUMENT_NODE:\r\n if (n.compatMode !== 'CSS1Compat') {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n compatMode: n.compatMode,\r\n };\r\n }\r\n else {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n };\r\n }\r\n case n.DOCUMENT_TYPE_NODE:\r\n return {\r\n type: NodeType.DocumentType,\r\n name: n.name,\r\n publicId: n.publicId,\r\n systemId: n.systemId,\r\n rootId,\r\n };\r\n case n.ELEMENT_NODE:\r\n return serializeElementNode(n, {\r\n doc,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n inlineStylesheet,\r\n maskAttributeFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n rootId,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n });\r\n case n.TEXT_NODE:\r\n return serializeTextNode(n, {\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n maskTextFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n rootId,\r\n });\r\n case n.CDATA_SECTION_NODE:\r\n return {\r\n type: NodeType.CDATA,\r\n textContent: '',\r\n rootId,\r\n };\r\n case n.COMMENT_NODE:\r\n return {\r\n type: NodeType.Comment,\r\n textContent: n.textContent || '',\r\n rootId,\r\n };\r\n default:\r\n return false;\r\n }\r\n}\r\nfunction getRootId(doc, mirror) {\r\n if (!mirror.hasNode(doc))\r\n return undefined;\r\n const docId = mirror.getId(doc);\r\n return docId === 1 ? undefined : docId;\r\n}\r\nfunction serializeTextNode(n, options) {\r\n const { maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, maskTextFn, maskInputOptions, maskInputFn, rootId, } = options;\r\n const parentTagName = n.parentNode && n.parentNode.tagName;\r\n let textContent = n.textContent;\r\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\r\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\r\n const isTextarea = parentTagName === 'TEXTAREA' ? true : undefined;\r\n if (isStyle && textContent) {\r\n try {\r\n if (n.nextSibling || n.previousSibling) {\r\n }\r\n else if (n.parentNode.sheet?.cssRules) {\r\n textContent = stringifyStylesheet(n.parentNode.sheet);\r\n }\r\n }\r\n catch (err) {\r\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\r\n }\r\n textContent = absoluteToStylesheet(textContent, getHref());\r\n }\r\n if (isScript) {\r\n textContent = 'SCRIPT_PLACEHOLDER';\r\n }\r\n const forceMask = needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText);\r\n if (!isStyle && !isScript && !isTextarea && textContent && forceMask) {\r\n textContent = maskTextFn\r\n ? maskTextFn(textContent, n.parentElement)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (isTextarea && textContent && (maskInputOptions.textarea || forceMask)) {\r\n textContent = maskInputFn\r\n ? maskInputFn(textContent, n.parentNode)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (parentTagName === 'OPTION' && textContent) {\r\n const isInputMasked = shouldMaskInput({\r\n type: null,\r\n tagName: parentTagName,\r\n maskInputOptions,\r\n });\r\n textContent = maskInputValue({\r\n isMasked: needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked),\r\n element: n,\r\n value: textContent,\r\n maskInputFn,\r\n });\r\n }\r\n return {\r\n type: NodeType.Text,\r\n textContent: textContent || '',\r\n isStyle,\r\n rootId,\r\n };\r\n}\r\nfunction serializeElementNode(n, options) {\r\n const { doc, blockClass, blockSelector, unblockSelector, inlineStylesheet, maskInputOptions = {}, maskAttributeFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, rootId, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, } = options;\r\n const needBlock = _isBlockedElement(n, blockClass, blockSelector, unblockSelector);\r\n const tagName = getValidTagName(n);\r\n let attributes = {};\r\n const len = n.attributes.length;\r\n for (let i = 0; i < len; i++) {\r\n const attr = n.attributes[i];\r\n if (attr.name && !ignoreAttribute(tagName, attr.name, attr.value)) {\r\n attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value, n, maskAttributeFn);\r\n }\r\n }\r\n if (tagName === 'link' && inlineStylesheet) {\r\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\r\n return s.href === n.href;\r\n });\r\n let cssText = null;\r\n if (stylesheet) {\r\n cssText = stringifyStylesheet(stylesheet);\r\n }\r\n if (cssText) {\r\n delete attributes.rel;\r\n delete attributes.href;\r\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\r\n }\r\n }\r\n if (tagName === 'style' &&\r\n n.sheet &&\r\n !(n.innerText || n.textContent || '').trim().length) {\r\n const cssText = stringifyStylesheet(n.sheet);\r\n if (cssText) {\r\n attributes._cssText = absoluteToStylesheet(cssText, getHref());\r\n }\r\n }\r\n if (tagName === 'input' ||\r\n tagName === 'textarea' ||\r\n tagName === 'select' ||\r\n tagName === 'option') {\r\n const el = n;\r\n const type = getInputType(el);\r\n const value = getInputValue(el, toUpperCase(tagName), type);\r\n const checked = el.checked;\r\n if (type !== 'submit' && type !== 'button' && value) {\r\n const forceMask = needMaskingText(el, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, shouldMaskInput({\r\n type,\r\n tagName: toUpperCase(tagName),\r\n maskInputOptions,\r\n }));\r\n attributes.value = maskInputValue({\r\n isMasked: forceMask,\r\n element: el,\r\n value,\r\n maskInputFn,\r\n });\r\n }\r\n if (checked) {\r\n attributes.checked = checked;\r\n }\r\n }\r\n if (tagName === 'option') {\r\n if (n.selected && !maskInputOptions['select']) {\r\n attributes.selected = true;\r\n }\r\n else {\r\n delete attributes.selected;\r\n }\r\n }\r\n if (tagName === 'canvas' && recordCanvas) {\r\n if (n.__context === '2d') {\r\n if (!is2DCanvasBlank(n)) {\r\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n }\r\n else if (!('__context' in n)) {\r\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n const blankCanvas = document.createElement('canvas');\r\n blankCanvas.width = n.width;\r\n blankCanvas.height = n.height;\r\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n if (canvasDataURL !== blankCanvasDataURL) {\r\n attributes.rr_dataURL = canvasDataURL;\r\n }\r\n }\r\n }\r\n if (tagName === 'img' && inlineImages) {\r\n if (!canvasService) {\r\n canvasService = doc.createElement('canvas');\r\n canvasCtx = canvasService.getContext('2d');\r\n }\r\n const image = n;\r\n const oldValue = image.crossOrigin;\r\n image.crossOrigin = 'anonymous';\r\n const recordInlineImage = () => {\r\n image.removeEventListener('load', recordInlineImage);\r\n try {\r\n canvasService.width = image.naturalWidth;\r\n canvasService.height = image.naturalHeight;\r\n canvasCtx.drawImage(image, 0, 0);\r\n attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n catch (err) {\r\n console.warn(`Cannot inline img src=${image.currentSrc}! Error: ${err}`);\r\n }\r\n oldValue\r\n ? (attributes.crossOrigin = oldValue)\r\n : image.removeAttribute('crossorigin');\r\n };\r\n if (image.complete && image.naturalWidth !== 0)\r\n recordInlineImage();\r\n else\r\n image.addEventListener('load', recordInlineImage);\r\n }\r\n if (tagName === 'audio' || tagName === 'video') {\r\n attributes.rr_mediaState = n.paused\r\n ? 'paused'\r\n : 'played';\r\n attributes.rr_mediaCurrentTime = n.currentTime;\r\n }\r\n if (!newlyAddedElement) {\r\n if (n.scrollLeft) {\r\n attributes.rr_scrollLeft = n.scrollLeft;\r\n }\r\n if (n.scrollTop) {\r\n attributes.rr_scrollTop = n.scrollTop;\r\n }\r\n }\r\n if (needBlock) {\r\n const { width, height } = n.getBoundingClientRect();\r\n attributes = {\r\n class: attributes.class,\r\n rr_width: `${width}px`,\r\n rr_height: `${height}px`,\r\n };\r\n }\r\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\r\n if (!n.contentDocument) {\r\n attributes.rr_src = attributes.src;\r\n }\r\n delete attributes.src;\r\n }\r\n let isCustomElement;\r\n try {\r\n if (customElements.get(tagName))\r\n isCustomElement = true;\r\n }\r\n catch (e) {\r\n }\r\n return {\r\n type: NodeType.Element,\r\n tagName,\r\n attributes,\r\n childNodes: [],\r\n isSVG: isSVGElement(n) || undefined,\r\n needBlock,\r\n rootId,\r\n isCustom: isCustomElement,\r\n };\r\n}\r\nfunction lowerIfExists(maybeAttr) {\r\n if (maybeAttr === undefined || maybeAttr === null) {\r\n return '';\r\n }\r\n else {\r\n return maybeAttr.toLowerCase();\r\n }\r\n}\r\nfunction slimDOMExcluded(sn, slimDOMOptions) {\r\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\r\n return true;\r\n }\r\n else if (sn.type === NodeType.Element) {\r\n if (slimDOMOptions.script &&\r\n (sn.tagName === 'script' ||\r\n (sn.tagName === 'link' &&\r\n (sn.attributes.rel === 'preload' ||\r\n sn.attributes.rel === 'modulepreload') &&\r\n sn.attributes.as === 'script') ||\r\n (sn.tagName === 'link' &&\r\n sn.attributes.rel === 'prefetch' &&\r\n typeof sn.attributes.href === 'string' &&\r\n sn.attributes.href.endsWith('.js')))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headFavicon &&\r\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\r\n (sn.tagName === 'meta' &&\r\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\r\n lowerIfExists(sn.attributes.name) === 'application-name' ||\r\n lowerIfExists(sn.attributes.rel) === 'icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\r\n return true;\r\n }\r\n else if (sn.tagName === 'meta') {\r\n if (slimDOMOptions.headMetaDescKeywords &&\r\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaSocial &&\r\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\r\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\r\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaRobots &&\r\n (lowerIfExists(sn.attributes.name) === 'robots' ||\r\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\r\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaHttpEquiv &&\r\n sn.attributes['http-equiv'] !== undefined) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaAuthorship &&\r\n (lowerIfExists(sn.attributes.name) === 'author' ||\r\n lowerIfExists(sn.attributes.name) === 'generator' ||\r\n lowerIfExists(sn.attributes.name) === 'framework' ||\r\n lowerIfExists(sn.attributes.name) === 'publisher' ||\r\n lowerIfExists(sn.attributes.name) === 'progid' ||\r\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\r\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaVerification &&\r\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\r\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\r\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\r\n lowerIfExists(sn.attributes.name) === 'verification' ||\r\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n}\r\nfunction serializeNodeWithId(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputOptions = {}, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, onStylesheetLoad, stylesheetLoadTimeout = 5000, keepIframeSrcFn = () => false, newlyAddedElement = false, } = options;\r\n let { preserveWhiteSpace = true } = options;\r\n const _serializedNode = serializeNode(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n });\r\n if (!_serializedNode) {\r\n console.warn(n, 'not serialized');\r\n return null;\r\n }\r\n let id;\r\n if (mirror.hasNode(n)) {\r\n id = mirror.getId(n);\r\n }\r\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\r\n (!preserveWhiteSpace &&\r\n _serializedNode.type === NodeType.Text &&\r\n !_serializedNode.isStyle &&\r\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\r\n id = IGNORED_NODE;\r\n }\r\n else {\r\n id = genId();\r\n }\r\n const serializedNode = Object.assign(_serializedNode, { id });\r\n mirror.add(n, serializedNode);\r\n if (id === IGNORED_NODE) {\r\n return null;\r\n }\r\n if (onSerialize) {\r\n onSerialize(n);\r\n }\r\n let recordChild = !skipChild;\r\n if (serializedNode.type === NodeType.Element) {\r\n recordChild = recordChild && !serializedNode.needBlock;\r\n delete serializedNode.needBlock;\r\n const shadowRoot = n.shadowRoot;\r\n if (shadowRoot && isNativeShadowDom(shadowRoot))\r\n serializedNode.isShadowHost = true;\r\n }\r\n if ((serializedNode.type === NodeType.Document ||\r\n serializedNode.type === NodeType.Element) &&\r\n recordChild) {\r\n if (slimDOMOptions.headWhitespace &&\r\n serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'head') {\r\n preserveWhiteSpace = false;\r\n }\r\n const bypassOptions = {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n };\r\n for (const childN of Array.from(n.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n if (isElement(n) && n.shadowRoot) {\r\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n isNativeShadowDom(n.shadowRoot) &&\r\n (serializedChildNode.isShadow = true);\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n }\r\n }\r\n if (n.parentNode &&\r\n isShadowRoot(n.parentNode) &&\r\n isNativeShadowDom(n.parentNode)) {\r\n serializedNode.isShadow = true;\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'iframe') {\r\n onceIframeLoaded(n, () => {\r\n const iframeDoc = n.contentDocument;\r\n if (iframeDoc && onIframeLoad) {\r\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\r\n doc: iframeDoc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedIframeNode) {\r\n onIframeLoad(n, serializedIframeNode);\r\n }\r\n }\r\n }, iframeLoadTimeout);\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'link' &&\r\n serializedNode.attributes.rel === 'stylesheet') {\r\n onceStylesheetLoaded(n, () => {\r\n if (onStylesheetLoad) {\r\n const serializedLinkNode = serializeNodeWithId(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedLinkNode) {\r\n onStylesheetLoad(n, serializedLinkNode);\r\n }\r\n }\r\n }, stylesheetLoadTimeout);\r\n }\r\n return serializedNode;\r\n}\r\nfunction snapshot(n, options) {\r\n const { mirror = new Mirror(), blockClass = 'rr-block', blockSelector = null, unblockSelector = null, maskAllText = false, maskTextClass = 'rr-mask', unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskAllInputs = false, maskAttributeFn, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn = () => false, } = options || {};\r\n const maskInputOptions = maskAllInputs === true\r\n ? {\r\n color: true,\r\n date: true,\r\n 'datetime-local': true,\r\n email: true,\r\n month: true,\r\n number: true,\r\n range: true,\r\n search: true,\r\n tel: true,\r\n text: true,\r\n time: true,\r\n url: true,\r\n week: true,\r\n textarea: true,\r\n select: true,\r\n }\r\n : maskAllInputs === false\r\n ? {}\r\n : maskAllInputs;\r\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\r\n ?\r\n {\r\n script: true,\r\n comment: true,\r\n headFavicon: true,\r\n headWhitespace: true,\r\n headMetaDescKeywords: slimDOM === 'all',\r\n headMetaSocial: true,\r\n headMetaRobots: true,\r\n headMetaHttpEquiv: true,\r\n headMetaAuthorship: true,\r\n headMetaVerification: true,\r\n }\r\n : slimDOM === false\r\n ? {}\r\n : slimDOM;\r\n return serializeNodeWithId(n, {\r\n doc: n,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n newlyAddedElement: false,\r\n });\r\n}\r\n\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\r\nfunction parse(css, options = {}) {\r\n let lineno = 1;\r\n let column = 1;\r\n function updatePosition(str) {\r\n const lines = str.match(/\\n/g);\r\n if (lines) {\r\n lineno += lines.length;\r\n }\r\n const i = str.lastIndexOf('\\n');\r\n column = i === -1 ? column + str.length : str.length - i;\r\n }\r\n function position() {\r\n const start = { line: lineno, column };\r\n return (node) => {\r\n node.position = new Position(start);\r\n whitespace();\r\n return node;\r\n };\r\n }\r\n class Position {\r\n constructor(start) {\r\n this.start = start;\r\n this.end = { line: lineno, column };\r\n this.source = options.source;\r\n }\r\n }\r\n Position.prototype.content = css;\r\n const errorsList = [];\r\n function error(msg) {\r\n const err = new Error(`${options.source || ''}:${lineno}:${column}: ${msg}`);\r\n err.reason = msg;\r\n err.filename = options.source;\r\n err.line = lineno;\r\n err.column = column;\r\n err.source = css;\r\n if (options.silent) {\r\n errorsList.push(err);\r\n }\r\n else {\r\n throw err;\r\n }\r\n }\r\n function stylesheet() {\r\n const rulesList = rules();\r\n return {\r\n type: 'stylesheet',\r\n stylesheet: {\r\n source: options.source,\r\n rules: rulesList,\r\n parsingErrors: errorsList,\r\n },\r\n };\r\n }\r\n function open() {\r\n return match(/^{\\s*/);\r\n }\r\n function close() {\r\n return match(/^}/);\r\n }\r\n function rules() {\r\n let node;\r\n const rules = [];\r\n whitespace();\r\n comments(rules);\r\n while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {\r\n if (node) {\r\n rules.push(node);\r\n comments(rules);\r\n }\r\n }\r\n return rules;\r\n }\r\n function match(re) {\r\n const m = re.exec(css);\r\n if (!m) {\r\n return;\r\n }\r\n const str = m[0];\r\n updatePosition(str);\r\n css = css.slice(str.length);\r\n return m;\r\n }\r\n function whitespace() {\r\n match(/^\\s*/);\r\n }\r\n function comments(rules = []) {\r\n let c;\r\n while ((c = comment())) {\r\n if (c) {\r\n rules.push(c);\r\n }\r\n c = comment();\r\n }\r\n return rules;\r\n }\r\n function comment() {\r\n const pos = position();\r\n if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {\r\n return;\r\n }\r\n let i = 2;\r\n while ('' !== css.charAt(i) &&\r\n ('*' !== css.charAt(i) || '/' !== css.charAt(i + 1))) {\r\n ++i;\r\n }\r\n i += 2;\r\n if ('' === css.charAt(i - 1)) {\r\n return error('End of comment missing');\r\n }\r\n const str = css.slice(2, i - 2);\r\n column += 2;\r\n updatePosition(str);\r\n css = css.slice(i);\r\n column += 2;\r\n return pos({\r\n type: 'comment',\r\n comment: str,\r\n });\r\n }\r\n function selector() {\r\n whitespace();\r\n while (css[0] == '}') {\r\n error('extra closing bracket');\r\n css = css.slice(1);\r\n whitespace();\r\n }\r\n const m = match(/^((\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'|[^{])+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const cleanedInput = m[0]\r\n .trim()\r\n .replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/g, '')\r\n .replace(/\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'/g, (m) => {\r\n return m.replace(/,/g, '\\u200C');\r\n });\r\n return customSplit(cleanedInput).map((s) => s.replace(/\\u200C/g, ',').trim());\r\n }\r\n function customSplit(input) {\r\n const result = [];\r\n let currentSegment = '';\r\n let depthParentheses = 0;\r\n let depthBrackets = 0;\r\n let currentStringChar = null;\r\n for (const char of input) {\r\n const hasStringEscape = currentSegment.endsWith('\\\\');\r\n if (currentStringChar) {\r\n if (currentStringChar === char && !hasStringEscape) {\r\n currentStringChar = null;\r\n }\r\n }\r\n else if (char === '(') {\r\n depthParentheses++;\r\n }\r\n else if (char === ')') {\r\n depthParentheses--;\r\n }\r\n else if (char === '[') {\r\n depthBrackets++;\r\n }\r\n else if (char === ']') {\r\n depthBrackets--;\r\n }\r\n else if ('\\'\"'.includes(char)) {\r\n currentStringChar = char;\r\n }\r\n if (char === ',' && depthParentheses === 0 && depthBrackets === 0) {\r\n result.push(currentSegment);\r\n currentSegment = '';\r\n }\r\n else {\r\n currentSegment += char;\r\n }\r\n }\r\n if (currentSegment) {\r\n result.push(currentSegment);\r\n }\r\n return result;\r\n }\r\n function declaration() {\r\n const pos = position();\r\n const propMatch = match(/^(\\*?[-#\\/\\*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\r\n if (!propMatch) {\r\n return;\r\n }\r\n const prop = trim(propMatch[0]);\r\n if (!match(/^:\\s*/)) {\r\n return error(`property missing ':'`);\r\n }\r\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^\\)]*?\\)|[^};])+)/);\r\n const ret = pos({\r\n type: 'declaration',\r\n property: prop.replace(commentre, ''),\r\n value: val ? trim(val[0]).replace(commentre, '') : '',\r\n });\r\n match(/^[;\\s]*/);\r\n return ret;\r\n }\r\n function declarations() {\r\n const decls = [];\r\n if (!open()) {\r\n return error(`missing '{'`);\r\n }\r\n comments(decls);\r\n let decl;\r\n while ((decl = declaration())) {\r\n if (decl !== false) {\r\n decls.push(decl);\r\n comments(decls);\r\n }\r\n decl = declaration();\r\n }\r\n if (!close()) {\r\n return error(`missing '}'`);\r\n }\r\n return decls;\r\n }\r\n function keyframe() {\r\n let m;\r\n const vals = [];\r\n const pos = position();\r\n while ((m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/))) {\r\n vals.push(m[1]);\r\n match(/^,\\s*/);\r\n }\r\n if (!vals.length) {\r\n return;\r\n }\r\n return pos({\r\n type: 'keyframe',\r\n values: vals,\r\n declarations: declarations(),\r\n });\r\n }\r\n function atkeyframes() {\r\n const pos = position();\r\n let m = match(/^@([-\\w]+)?keyframes\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = m[1];\r\n m = match(/^([-\\w]+)\\s*/);\r\n if (!m) {\r\n return error('@keyframes missing name');\r\n }\r\n const name = m[1];\r\n if (!open()) {\r\n return error(`@keyframes missing '{'`);\r\n }\r\n let frame;\r\n let frames = comments();\r\n while ((frame = keyframe())) {\r\n frames.push(frame);\r\n frames = frames.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@keyframes missing '}'`);\r\n }\r\n return pos({\r\n type: 'keyframes',\r\n name,\r\n vendor,\r\n keyframes: frames,\r\n });\r\n }\r\n function atsupports() {\r\n const pos = position();\r\n const m = match(/^@supports *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const supports = trim(m[1]);\r\n if (!open()) {\r\n return error(`@supports missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@supports missing '}'`);\r\n }\r\n return pos({\r\n type: 'supports',\r\n supports,\r\n rules: style,\r\n });\r\n }\r\n function athost() {\r\n const pos = position();\r\n const m = match(/^@host\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@host missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@host missing '}'`);\r\n }\r\n return pos({\r\n type: 'host',\r\n rules: style,\r\n });\r\n }\r\n function atmedia() {\r\n const pos = position();\r\n const m = match(/^@media *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const media = trim(m[1]);\r\n if (!open()) {\r\n return error(`@media missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@media missing '}'`);\r\n }\r\n return pos({\r\n type: 'media',\r\n media,\r\n rules: style,\r\n });\r\n }\r\n function atcustommedia() {\r\n const pos = position();\r\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\r\n if (!m) {\r\n return;\r\n }\r\n return pos({\r\n type: 'custom-media',\r\n name: trim(m[1]),\r\n media: trim(m[2]),\r\n });\r\n }\r\n function atpage() {\r\n const pos = position();\r\n const m = match(/^@page */);\r\n if (!m) {\r\n return;\r\n }\r\n const sel = selector() || [];\r\n if (!open()) {\r\n return error(`@page missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@page missing '}'`);\r\n }\r\n return pos({\r\n type: 'page',\r\n selectors: sel,\r\n declarations: decls,\r\n });\r\n }\r\n function atdocument() {\r\n const pos = position();\r\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = trim(m[1]);\r\n const doc = trim(m[2]);\r\n if (!open()) {\r\n return error(`@document missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@document missing '}'`);\r\n }\r\n return pos({\r\n type: 'document',\r\n document: doc,\r\n vendor,\r\n rules: style,\r\n });\r\n }\r\n function atfontface() {\r\n const pos = position();\r\n const m = match(/^@font-face\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@font-face missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@font-face missing '}'`);\r\n }\r\n return pos({\r\n type: 'font-face',\r\n declarations: decls,\r\n });\r\n }\r\n const atimport = _compileAtrule('import');\r\n const atcharset = _compileAtrule('charset');\r\n const atnamespace = _compileAtrule('namespace');\r\n function _compileAtrule(name) {\r\n const re = new RegExp('^@' + name + '\\\\s*([^;]+);');\r\n return () => {\r\n const pos = position();\r\n const m = match(re);\r\n if (!m) {\r\n return;\r\n }\r\n const ret = { type: name };\r\n ret[name] = m[1].trim();\r\n return pos(ret);\r\n };\r\n }\r\n function atrule() {\r\n if (css[0] !== '@') {\r\n return;\r\n }\r\n return (atkeyframes() ||\r\n atmedia() ||\r\n atcustommedia() ||\r\n atsupports() ||\r\n atimport() ||\r\n atcharset() ||\r\n atnamespace() ||\r\n atdocument() ||\r\n atpage() ||\r\n athost() ||\r\n atfontface());\r\n }\r\n function rule() {\r\n const pos = position();\r\n const sel = selector();\r\n if (!sel) {\r\n return error('selector missing');\r\n }\r\n comments();\r\n return pos({\r\n type: 'rule',\r\n selectors: sel,\r\n declarations: declarations(),\r\n });\r\n }\r\n return addParent(stylesheet());\r\n}\r\nfunction trim(str) {\r\n return str ? str.replace(/^\\s+|\\s+$/g, '') : '';\r\n}\r\nfunction addParent(obj, parent) {\r\n const isNode = obj && typeof obj.type === 'string';\r\n const childParent = isNode ? obj : parent;\r\n for (const k of Object.keys(obj)) {\r\n const value = obj[k];\r\n if (Array.isArray(value)) {\r\n value.forEach((v) => {\r\n addParent(v, childParent);\r\n });\r\n }\r\n else if (value && typeof value === 'object') {\r\n addParent(value, childParent);\r\n }\r\n }\r\n if (isNode) {\r\n Object.defineProperty(obj, 'parent', {\r\n configurable: true,\r\n writable: true,\r\n enumerable: false,\r\n value: parent || null,\r\n });\r\n }\r\n return obj;\r\n}\n\nconst tagMap = {\r\n script: 'noscript',\r\n altglyph: 'altGlyph',\r\n altglyphdef: 'altGlyphDef',\r\n altglyphitem: 'altGlyphItem',\r\n animatecolor: 'animateColor',\r\n animatemotion: 'animateMotion',\r\n animatetransform: 'animateTransform',\r\n clippath: 'clipPath',\r\n feblend: 'feBlend',\r\n fecolormatrix: 'feColorMatrix',\r\n fecomponenttransfer: 'feComponentTransfer',\r\n fecomposite: 'feComposite',\r\n feconvolvematrix: 'feConvolveMatrix',\r\n fediffuselighting: 'feDiffuseLighting',\r\n fedisplacementmap: 'feDisplacementMap',\r\n fedistantlight: 'feDistantLight',\r\n fedropshadow: 'feDropShadow',\r\n feflood: 'feFlood',\r\n fefunca: 'feFuncA',\r\n fefuncb: 'feFuncB',\r\n fefuncg: 'feFuncG',\r\n fefuncr: 'feFuncR',\r\n fegaussianblur: 'feGaussianBlur',\r\n feimage: 'feImage',\r\n femerge: 'feMerge',\r\n femergenode: 'feMergeNode',\r\n femorphology: 'feMorphology',\r\n feoffset: 'feOffset',\r\n fepointlight: 'fePointLight',\r\n fespecularlighting: 'feSpecularLighting',\r\n fespotlight: 'feSpotLight',\r\n fetile: 'feTile',\r\n feturbulence: 'feTurbulence',\r\n foreignobject: 'foreignObject',\r\n glyphref: 'glyphRef',\r\n lineargradient: 'linearGradient',\r\n radialgradient: 'radialGradient',\r\n};\r\nfunction getTagName(n) {\r\n let tagName = tagMap[n.tagName] ? tagMap[n.tagName] : n.tagName;\r\n if (tagName === 'link' && n.attributes._cssText) {\r\n tagName = 'style';\r\n }\r\n return tagName;\r\n}\r\nfunction escapeRegExp(str) {\r\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\nconst HOVER_SELECTOR = /([^\\\\]):hover/;\r\nconst HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, 'g');\r\nfunction addHoverClass(cssText, cache) {\r\n const cachedStyle = cache?.stylesWithHoverClass.get(cssText);\r\n if (cachedStyle)\r\n return cachedStyle;\r\n if (cssText.length >= 1000000) {\r\n return cssText;\r\n }\r\n const ast = parse(cssText, {\r\n silent: true,\r\n });\r\n if (!ast.stylesheet) {\r\n return cssText;\r\n }\r\n const selectors = [];\r\n ast.stylesheet.rules.forEach((rule) => {\r\n if ('selectors' in rule) {\r\n (rule.selectors || []).forEach((selector) => {\r\n if (HOVER_SELECTOR.test(selector)) {\r\n selectors.push(selector);\r\n }\r\n });\r\n }\r\n });\r\n if (selectors.length === 0) {\r\n return cssText;\r\n }\r\n const selectorMatcher = new RegExp(selectors\r\n .filter((selector, index) => selectors.indexOf(selector) === index)\r\n .sort((a, b) => b.length - a.length)\r\n .map((selector) => {\r\n return escapeRegExp(selector);\r\n })\r\n .join('|'), 'g');\r\n const result = cssText.replace(selectorMatcher, (selector) => {\r\n const newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, '$1.\\\\:hover');\r\n return `${selector}, ${newSelector}`;\r\n });\r\n cache?.stylesWithHoverClass.set(cssText, result);\r\n return result;\r\n}\r\nfunction createCache() {\r\n const stylesWithHoverClass = new Map();\r\n return {\r\n stylesWithHoverClass,\r\n };\r\n}\r\nfunction buildNode(n, options) {\r\n const { doc, hackCss, cache } = options;\r\n switch (n.type) {\r\n case NodeType.Document:\r\n return doc.implementation.createDocument(null, '', null);\r\n case NodeType.DocumentType:\r\n return doc.implementation.createDocumentType(n.name || 'html', n.publicId, n.systemId);\r\n case NodeType.Element: {\r\n const tagName = getTagName(n);\r\n let node;\r\n if (n.isSVG) {\r\n node = doc.createElementNS('http://www.w3.org/2000/svg', tagName);\r\n }\r\n else {\r\n if (n.isCustom &&\r\n doc.defaultView?.customElements &&\r\n !doc.defaultView.customElements.get(n.tagName))\r\n doc.defaultView.customElements.define(n.tagName, class extends doc.defaultView.HTMLElement {\r\n });\r\n node = doc.createElement(tagName);\r\n }\r\n const specialAttributes = {};\r\n for (const name in n.attributes) {\r\n if (!Object.prototype.hasOwnProperty.call(n.attributes, name)) {\r\n continue;\r\n }\r\n let value = n.attributes[name];\r\n if (tagName === 'option' &&\r\n name === 'selected' &&\r\n value === false) {\r\n continue;\r\n }\r\n if (value === null) {\r\n continue;\r\n }\r\n if (value === true)\r\n value = '';\r\n if (name.startsWith('rr_')) {\r\n specialAttributes[name] = value;\r\n continue;\r\n }\r\n const isTextarea = tagName === 'textarea' && name === 'value';\r\n const isRemoteOrDynamicCss = tagName === 'style' && name === '_cssText';\r\n if (isRemoteOrDynamicCss && hackCss && typeof value === 'string') {\r\n value = addHoverClass(value, cache);\r\n }\r\n if ((isTextarea || isRemoteOrDynamicCss) && typeof value === 'string') {\r\n const child = doc.createTextNode(value);\r\n for (const c of Array.from(node.childNodes)) {\r\n if (c.nodeType === node.TEXT_NODE) {\r\n node.removeChild(c);\r\n }\r\n }\r\n node.appendChild(child);\r\n continue;\r\n }\r\n try {\r\n if (n.isSVG && name === 'xlink:href') {\r\n node.setAttributeNS('http://www.w3.org/1999/xlink', name, value.toString());\r\n }\r\n else if (name === 'onload' ||\r\n name === 'onclick' ||\r\n name.substring(0, 7) === 'onmouse') {\r\n node.setAttribute('_' + name, value.toString());\r\n }\r\n else if (tagName === 'meta' &&\r\n n.attributes['http-equiv'] === 'Content-Security-Policy' &&\r\n name === 'content') {\r\n node.setAttribute('csp-content', value.toString());\r\n continue;\r\n }\r\n else if (tagName === 'link' &&\r\n (n.attributes.rel === 'preload' ||\r\n n.attributes.rel === 'modulepreload') &&\r\n n.attributes.as === 'script') {\r\n }\r\n else if (tagName === 'link' &&\r\n n.attributes.rel === 'prefetch' &&\r\n typeof n.attributes.href === 'string' &&\r\n n.attributes.href.endsWith('.js')) {\r\n }\r\n else if (tagName === 'img' &&\r\n n.attributes.srcset &&\r\n n.attributes.rr_dataURL) {\r\n node.setAttribute('rrweb-original-srcset', n.attributes.srcset);\r\n }\r\n else {\r\n node.setAttribute(name, value.toString());\r\n }\r\n }\r\n catch (error) {\r\n }\r\n }\r\n for (const name in specialAttributes) {\r\n const value = specialAttributes[name];\r\n if (tagName === 'canvas' && name === 'rr_dataURL') {\r\n const image = document.createElement('img');\r\n image.onload = () => {\r\n const ctx = node.getContext('2d');\r\n if (ctx) {\r\n ctx.drawImage(image, 0, 0, image.width, image.height);\r\n }\r\n };\r\n image.src = value.toString();\r\n if (node.RRNodeType)\r\n node.rr_dataURL = value.toString();\r\n }\r\n else if (tagName === 'img' && name === 'rr_dataURL') {\r\n const image = node;\r\n if (!image.currentSrc.startsWith('data:')) {\r\n image.setAttribute('rrweb-original-src', n.attributes.src);\r\n image.src = value.toString();\r\n }\r\n }\r\n if (name === 'rr_width') {\r\n node.style.setProperty('width', value.toString());\r\n }\r\n else if (name === 'rr_height') {\r\n node.style.setProperty('height', value.toString());\r\n }\r\n else if (name === 'rr_mediaCurrentTime' &&\r\n typeof value === 'number') {\r\n node.currentTime = value;\r\n }\r\n else if (name === 'rr_mediaState') {\r\n switch (value) {\r\n case 'played':\r\n node\r\n .play()\r\n .catch((e) => console.warn('media playback error', e));\r\n break;\r\n case 'paused':\r\n node.pause();\r\n break;\r\n }\r\n }\r\n }\r\n if (n.isShadowHost) {\r\n if (!node.shadowRoot) {\r\n node.attachShadow({ mode: 'open' });\r\n }\r\n else {\r\n while (node.shadowRoot.firstChild) {\r\n node.shadowRoot.removeChild(node.shadowRoot.firstChild);\r\n }\r\n }\r\n }\r\n return node;\r\n }\r\n case NodeType.Text:\r\n return doc.createTextNode(n.isStyle && hackCss\r\n ? addHoverClass(n.textContent, cache)\r\n : n.textContent);\r\n case NodeType.CDATA:\r\n return doc.createCDATASection(n.textContent);\r\n case NodeType.Comment:\r\n return doc.createComment(n.textContent);\r\n default:\r\n return null;\r\n }\r\n}\r\nfunction buildNodeWithSN(n, options) {\r\n const { doc, mirror, skipChild = false, hackCss = true, afterAppend, cache, } = options;\r\n if (mirror.has(n.id)) {\r\n const nodeInMirror = mirror.getNode(n.id);\r\n const meta = mirror.getMeta(nodeInMirror);\r\n if (isNodeMetaEqual(meta, n))\r\n return mirror.getNode(n.id);\r\n }\r\n let node = buildNode(n, { doc, hackCss, cache });\r\n if (!node) {\r\n return null;\r\n }\r\n if (n.rootId && mirror.getNode(n.rootId) !== doc) {\r\n mirror.replace(n.rootId, doc);\r\n }\r\n if (n.type === NodeType.Document) {\r\n doc.close();\r\n doc.open();\r\n if (n.compatMode === 'BackCompat' &&\r\n n.childNodes &&\r\n n.childNodes[0].type !== NodeType.DocumentType) {\r\n if (n.childNodes[0].type === NodeType.Element &&\r\n 'xmlns' in n.childNodes[0].attributes &&\r\n n.childNodes[0].attributes.xmlns === 'http://www.w3.org/1999/xhtml') {\r\n doc.write('');\r\n }\r\n else {\r\n doc.write('');\r\n }\r\n }\r\n node = doc;\r\n }\r\n mirror.add(node, n);\r\n if ((n.type === NodeType.Document || n.type === NodeType.Element) &&\r\n !skipChild) {\r\n for (const childN of n.childNodes) {\r\n const childNode = buildNodeWithSN(childN, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n if (!childNode) {\r\n console.warn('Failed to rebuild', childN);\r\n continue;\r\n }\r\n if (childN.isShadow && isElement(node) && node.shadowRoot) {\r\n node.shadowRoot.appendChild(childNode);\r\n }\r\n else if (n.type === NodeType.Document &&\r\n childN.type == NodeType.Element) {\r\n const htmlElement = childNode;\r\n let body = null;\r\n htmlElement.childNodes.forEach((child) => {\r\n if (child.nodeName === 'BODY')\r\n body = child;\r\n });\r\n if (body) {\r\n htmlElement.removeChild(body);\r\n node.appendChild(childNode);\r\n htmlElement.appendChild(body);\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n if (afterAppend) {\r\n afterAppend(childNode, childN.id);\r\n }\r\n }\r\n }\r\n return node;\r\n}\r\nfunction visit(mirror, onVisit) {\r\n function walk(node) {\r\n onVisit(node);\r\n }\r\n for (const id of mirror.getIds()) {\r\n if (mirror.has(id)) {\r\n walk(mirror.getNode(id));\r\n }\r\n }\r\n}\r\nfunction handleScroll(node, mirror) {\r\n const n = mirror.getMeta(node);\r\n if (n?.type !== NodeType.Element) {\r\n return;\r\n }\r\n const el = node;\r\n for (const name in n.attributes) {\r\n if (!(Object.prototype.hasOwnProperty.call(n.attributes, name) &&\r\n name.startsWith('rr_'))) {\r\n continue;\r\n }\r\n const value = n.attributes[name];\r\n if (name === 'rr_scrollLeft') {\r\n el.scrollLeft = value;\r\n }\r\n if (name === 'rr_scrollTop') {\r\n el.scrollTop = value;\r\n }\r\n }\r\n}\r\nfunction rebuild(n, options) {\r\n const { doc, onVisit, hackCss = true, afterAppend, cache, mirror = new Mirror(), } = options;\r\n const node = buildNodeWithSN(n, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n visit(mirror, (visitedNode) => {\r\n if (onVisit) {\r\n onVisit(visitedNode);\r\n }\r\n handleScroll(visitedNode, mirror);\r\n });\r\n return node;\r\n}\n\nexport { IGNORED_NODE, Mirror, NodeType, addHoverClass, buildNodeWithSN, createCache, createMatchPredicate, createMirror, distanceToMatch, escapeImportStatement, fixSafariColons, genId, getInputType, getInputValue, ignoreAttribute, is2DCanvasBlank, isCSSImportRule, isCSSStyleRule, isElement, isNativeShadowDom, isNodeMetaEqual, isShadowRoot, maskInputValue, needMaskingText, rebuild, serializeNodeWithId, shouldMaskInput, snapshot, stringifyRule, stringifyStylesheet, toLowerCase, toUpperCase, transformAttribute };\n","import { distanceToMatch, IGNORED_NODE, isShadowRoot, createMatchPredicate } from '../../rrweb-snapshot/es/rrweb-snapshot.js';\n\nfunction on(type, fn, target = document) {\r\n const options = { capture: true, passive: true };\r\n target.addEventListener(type, fn, options);\r\n return () => target.removeEventListener(type, fn, options);\r\n}\r\nconst DEPARTED_MIRROR_ACCESS_WARNING = 'Please stop import mirror directly. Instead of that,' +\r\n '\\r\\n' +\r\n 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +\r\n '\\r\\n' +\r\n 'or you can use record.mirror to access the mirror instance during recording.';\r\nlet _mirror = {\r\n map: {},\r\n getId() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return -1;\r\n },\r\n getNode() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return null;\r\n },\r\n removeNodeFromMap() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n },\r\n has() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return false;\r\n },\r\n reset() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n },\r\n};\r\nif (typeof window !== 'undefined' && window.Proxy && window.Reflect) {\r\n _mirror = new Proxy(_mirror, {\r\n get(target, prop, receiver) {\r\n if (prop === 'map') {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n }\r\n return Reflect.get(target, prop, receiver);\r\n },\r\n });\r\n}\r\nfunction throttle(func, wait, options = {}) {\r\n let timeout = null;\r\n let previous = 0;\r\n return function (...args) {\r\n const now = Date.now();\r\n if (!previous && options.leading === false) {\r\n previous = now;\r\n }\r\n const remaining = wait - (now - previous);\r\n const context = this;\r\n if (remaining <= 0 || remaining > wait) {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n }\r\n previous = now;\r\n func.apply(context, args);\r\n }\r\n else if (!timeout && options.trailing !== false) {\r\n timeout = setTimeout(() => {\r\n previous = options.leading === false ? 0 : Date.now();\r\n timeout = null;\r\n func.apply(context, args);\r\n }, remaining);\r\n }\r\n };\r\n}\r\nfunction hookSetter(target, key, d, isRevoked, win = window) {\r\n const original = win.Object.getOwnPropertyDescriptor(target, key);\r\n win.Object.defineProperty(target, key, isRevoked\r\n ? d\r\n : {\r\n set(value) {\r\n setTimeout(() => {\r\n d.set.call(this, value);\r\n }, 0);\r\n if (original && original.set) {\r\n original.set.call(this, value);\r\n }\r\n },\r\n });\r\n return () => hookSetter(target, key, original || {}, true);\r\n}\r\nfunction patch(source, name, replacement) {\r\n try {\r\n if (!(name in source)) {\r\n return () => {\r\n };\r\n }\r\n const original = source[name];\r\n const wrapped = replacement(original);\r\n if (typeof wrapped === 'function') {\r\n wrapped.prototype = wrapped.prototype || {};\r\n Object.defineProperties(wrapped, {\r\n __rrweb_original__: {\r\n enumerable: false,\r\n value: original,\r\n },\r\n });\r\n }\r\n source[name] = wrapped;\r\n return () => {\r\n source[name] = original;\r\n };\r\n }\r\n catch {\r\n return () => {\r\n };\r\n }\r\n}\r\nlet nowTimestamp = Date.now;\r\nif (!(/[1-9][0-9]{12}/.test(Date.now().toString()))) {\r\n nowTimestamp = () => new Date().getTime();\r\n}\r\nfunction getWindowScroll(win) {\r\n const doc = win.document;\r\n return {\r\n left: doc.scrollingElement\r\n ? doc.scrollingElement.scrollLeft\r\n : win.pageXOffset !== undefined\r\n ? win.pageXOffset\r\n : doc?.documentElement.scrollLeft ||\r\n doc?.body?.parentElement?.scrollLeft ||\r\n doc?.body?.scrollLeft ||\r\n 0,\r\n top: doc.scrollingElement\r\n ? doc.scrollingElement.scrollTop\r\n : win.pageYOffset !== undefined\r\n ? win.pageYOffset\r\n : doc?.documentElement.scrollTop ||\r\n doc?.body?.parentElement?.scrollTop ||\r\n doc?.body?.scrollTop ||\r\n 0,\r\n };\r\n}\r\nfunction getWindowHeight() {\r\n return (window.innerHeight ||\r\n (document.documentElement && document.documentElement.clientHeight) ||\r\n (document.body && document.body.clientHeight));\r\n}\r\nfunction getWindowWidth() {\r\n return (window.innerWidth ||\r\n (document.documentElement && document.documentElement.clientWidth) ||\r\n (document.body && document.body.clientWidth));\r\n}\r\nfunction closestElementOfNode(node) {\r\n if (!node) {\r\n return null;\r\n }\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n return el;\r\n}\r\nfunction isBlocked(node, blockClass, blockSelector, unblockSelector, checkAncestors) {\r\n if (!node) {\r\n return false;\r\n }\r\n const el = closestElementOfNode(node);\r\n if (!el) {\r\n return false;\r\n }\r\n const blockedPredicate = createMatchPredicate(blockClass, blockSelector);\r\n if (!checkAncestors) {\r\n const isUnblocked = unblockSelector && el.matches(unblockSelector);\r\n return blockedPredicate(el) && !isUnblocked;\r\n }\r\n const blockDistance = distanceToMatch(el, blockedPredicate);\r\n let unblockDistance = -1;\r\n if (blockDistance < 0) {\r\n return false;\r\n }\r\n if (unblockSelector) {\r\n unblockDistance = distanceToMatch(el, createMatchPredicate(null, unblockSelector));\r\n }\r\n if (blockDistance > -1 && unblockDistance < 0) {\r\n return true;\r\n }\r\n return blockDistance < unblockDistance;\r\n}\r\nfunction isSerialized(n, mirror) {\r\n return mirror.getId(n) !== -1;\r\n}\r\nfunction isIgnored(n, mirror) {\r\n return mirror.getId(n) === IGNORED_NODE;\r\n}\r\nfunction isAncestorRemoved(target, mirror) {\r\n if (isShadowRoot(target)) {\r\n return false;\r\n }\r\n const id = mirror.getId(target);\r\n if (!mirror.has(id)) {\r\n return true;\r\n }\r\n if (target.parentNode &&\r\n target.parentNode.nodeType === target.DOCUMENT_NODE) {\r\n return false;\r\n }\r\n if (!target.parentNode) {\r\n return true;\r\n }\r\n return isAncestorRemoved(target.parentNode, mirror);\r\n}\r\nfunction legacy_isTouchEvent(event) {\r\n return Boolean(event.changedTouches);\r\n}\r\nfunction polyfill(win = window) {\r\n if ('NodeList' in win && !win.NodeList.prototype.forEach) {\r\n win.NodeList.prototype.forEach = Array.prototype\r\n .forEach;\r\n }\r\n if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {\r\n win.DOMTokenList.prototype.forEach = Array.prototype\r\n .forEach;\r\n }\r\n if (!Node.prototype.contains) {\r\n Node.prototype.contains = (...args) => {\r\n let node = args[0];\r\n if (!(0 in args)) {\r\n throw new TypeError('1 argument is required');\r\n }\r\n do {\r\n if (this === node) {\r\n return true;\r\n }\r\n } while ((node = node && node.parentNode));\r\n return false;\r\n };\r\n }\r\n}\r\nfunction queueToResolveTrees(queue) {\r\n const queueNodeMap = {};\r\n const putIntoMap = (m, parent) => {\r\n const nodeInTree = {\r\n value: m,\r\n parent,\r\n children: [],\r\n };\r\n queueNodeMap[m.node.id] = nodeInTree;\r\n return nodeInTree;\r\n };\r\n const queueNodeTrees = [];\r\n for (const mutation of queue) {\r\n const { nextId, parentId } = mutation;\r\n if (nextId && nextId in queueNodeMap) {\r\n const nextInTree = queueNodeMap[nextId];\r\n if (nextInTree.parent) {\r\n const idx = nextInTree.parent.children.indexOf(nextInTree);\r\n nextInTree.parent.children.splice(idx, 0, putIntoMap(mutation, nextInTree.parent));\r\n }\r\n else {\r\n const idx = queueNodeTrees.indexOf(nextInTree);\r\n queueNodeTrees.splice(idx, 0, putIntoMap(mutation, null));\r\n }\r\n continue;\r\n }\r\n if (parentId in queueNodeMap) {\r\n const parentInTree = queueNodeMap[parentId];\r\n parentInTree.children.push(putIntoMap(mutation, parentInTree));\r\n continue;\r\n }\r\n queueNodeTrees.push(putIntoMap(mutation, null));\r\n }\r\n return queueNodeTrees;\r\n}\r\nfunction iterateResolveTree(tree, cb) {\r\n cb(tree.value);\r\n for (let i = tree.children.length - 1; i >= 0; i--) {\r\n iterateResolveTree(tree.children[i], cb);\r\n }\r\n}\r\nfunction isSerializedIframe(n, mirror) {\r\n return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));\r\n}\r\nfunction isSerializedStylesheet(n, mirror) {\r\n return Boolean(n.nodeName === 'LINK' &&\r\n n.nodeType === n.ELEMENT_NODE &&\r\n n.getAttribute &&\r\n n.getAttribute('rel') === 'stylesheet' &&\r\n mirror.getMeta(n));\r\n}\r\nfunction getBaseDimension(node, rootIframe) {\r\n const frameElement = node.ownerDocument?.defaultView?.frameElement;\r\n if (!frameElement || frameElement === rootIframe) {\r\n return {\r\n x: 0,\r\n y: 0,\r\n relativeScale: 1,\r\n absoluteScale: 1,\r\n };\r\n }\r\n const frameDimension = frameElement.getBoundingClientRect();\r\n const frameBaseDimension = getBaseDimension(frameElement, rootIframe);\r\n const relativeScale = frameDimension.height / frameElement.clientHeight;\r\n return {\r\n x: frameDimension.x * frameBaseDimension.relativeScale +\r\n frameBaseDimension.x,\r\n y: frameDimension.y * frameBaseDimension.relativeScale +\r\n frameBaseDimension.y,\r\n relativeScale,\r\n absoluteScale: frameBaseDimension.absoluteScale * relativeScale,\r\n };\r\n}\r\nfunction hasShadowRoot(n) {\r\n return Boolean(n?.shadowRoot);\r\n}\r\nfunction getNestedRule(rules, position) {\r\n const rule = rules[position[0]];\r\n if (position.length === 1) {\r\n return rule;\r\n }\r\n else {\r\n return getNestedRule(rule.cssRules[position[1]].cssRules, position.slice(2));\r\n }\r\n}\r\nfunction getPositionsAndIndex(nestedIndex) {\r\n const positions = [...nestedIndex];\r\n const index = positions.pop();\r\n return { positions, index };\r\n}\r\nfunction uniqueTextMutations(mutations) {\r\n const idSet = new Set();\r\n const uniqueMutations = [];\r\n for (let i = mutations.length; i--;) {\r\n const mutation = mutations[i];\r\n if (!idSet.has(mutation.id)) {\r\n uniqueMutations.push(mutation);\r\n idSet.add(mutation.id);\r\n }\r\n }\r\n return uniqueMutations;\r\n}\r\nclass StyleSheetMirror {\r\n constructor() {\r\n this.id = 1;\r\n this.styleIDMap = new WeakMap();\r\n this.idStyleMap = new Map();\r\n }\r\n getId(stylesheet) {\r\n return this.styleIDMap.get(stylesheet) ?? -1;\r\n }\r\n has(stylesheet) {\r\n return this.styleIDMap.has(stylesheet);\r\n }\r\n add(stylesheet, id) {\r\n if (this.has(stylesheet))\r\n return this.getId(stylesheet);\r\n let newId;\r\n if (id === undefined) {\r\n newId = this.id++;\r\n }\r\n else\r\n newId = id;\r\n this.styleIDMap.set(stylesheet, newId);\r\n this.idStyleMap.set(newId, stylesheet);\r\n return newId;\r\n }\r\n getStyle(id) {\r\n return this.idStyleMap.get(id) || null;\r\n }\r\n reset() {\r\n this.styleIDMap = new WeakMap();\r\n this.idStyleMap = new Map();\r\n this.id = 1;\r\n }\r\n generateId() {\r\n return this.id++;\r\n }\r\n}\r\nfunction getShadowHost(n) {\r\n let shadowHost = null;\r\n if (n.getRootNode?.()?.nodeType === Node.DOCUMENT_FRAGMENT_NODE &&\r\n n.getRootNode().host)\r\n shadowHost = n.getRootNode().host;\r\n return shadowHost;\r\n}\r\nfunction getRootShadowHost(n) {\r\n let rootShadowHost = n;\r\n let shadowHost;\r\n while ((shadowHost = getShadowHost(rootShadowHost)))\r\n rootShadowHost = shadowHost;\r\n return rootShadowHost;\r\n}\r\nfunction shadowHostInDom(n) {\r\n const doc = n.ownerDocument;\r\n if (!doc)\r\n return false;\r\n const shadowHost = getRootShadowHost(n);\r\n return doc.contains(shadowHost);\r\n}\r\nfunction inDom(n) {\r\n const doc = n.ownerDocument;\r\n if (!doc)\r\n return false;\r\n return doc.contains(n) || shadowHostInDom(n);\r\n}\r\nconst cachedImplementations = {};\r\nfunction getImplementation(name) {\r\n const cached = cachedImplementations[name];\r\n if (cached) {\r\n return cached;\r\n }\r\n const document = window.document;\r\n let impl = window[name];\r\n if (document && typeof document.createElement === 'function') {\r\n try {\r\n const sandbox = document.createElement('iframe');\r\n sandbox.hidden = true;\r\n document.head.appendChild(sandbox);\r\n const contentWindow = sandbox.contentWindow;\r\n if (contentWindow && contentWindow[name]) {\r\n impl =\r\n contentWindow[name];\r\n }\r\n document.head.removeChild(sandbox);\r\n }\r\n catch (e) {\r\n }\r\n }\r\n return (cachedImplementations[name] = impl.bind(window));\r\n}\r\nfunction onRequestAnimationFrame(...rest) {\r\n return getImplementation('requestAnimationFrame')(...rest);\r\n}\r\nfunction setTimeout(...rest) {\r\n return getImplementation('setTimeout')(...rest);\r\n}\r\nfunction clearTimeout(...rest) {\r\n return getImplementation('clearTimeout')(...rest);\r\n}\n\nexport { StyleSheetMirror, _mirror, clearTimeout, closestElementOfNode, getBaseDimension, getNestedRule, getPositionsAndIndex, getRootShadowHost, getShadowHost, getWindowHeight, getWindowScroll, getWindowWidth, hasShadowRoot, hookSetter, inDom, isAncestorRemoved, isBlocked, isIgnored, isSerialized, isSerializedIframe, isSerializedStylesheet, iterateResolveTree, legacy_isTouchEvent, nowTimestamp, on, onRequestAnimationFrame, patch, polyfill, queueToResolveTrees, setTimeout, shadowHostInDom, throttle, uniqueTextMutations };\n","// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2012-2018 various contributors (see AUTHORS)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Polyfill for the nullish coalescing operator (`??`).\n *\n * Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the\n * LHS evaluates to a nullish value, to mimic the operator's short-circuiting behavior.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n *\n * @param lhs The value of the expression to the left of the `??`\n * @param rhsFn A function returning the value of the expression to the right of the `??`\n * @returns The LHS value, unless it's `null` or `undefined`, in which case, the RHS value\n */\nexport function _nullishCoalesce(lhs: unknown, rhsFn: () => unknown): unknown {\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n return lhs != null ? lhs : rhsFn();\n}\n\n// Sucrase version:\n// function _nullishCoalesce(lhs, rhsFn) {\n// if (lhs != null) {\n// return lhs;\n// } else {\n// return rhsFn();\n// }\n// }\n","var EventType = /* @__PURE__ */ ((EventType2) => {\n EventType2[EventType2[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n EventType2[EventType2[\"Load\"] = 1] = \"Load\";\n EventType2[EventType2[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n EventType2[EventType2[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n EventType2[EventType2[\"Meta\"] = 4] = \"Meta\";\n EventType2[EventType2[\"Custom\"] = 5] = \"Custom\";\n EventType2[EventType2[\"Plugin\"] = 6] = \"Plugin\";\n return EventType2;\n})(EventType || {});\nvar IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {\n IncrementalSource2[IncrementalSource2[\"Mutation\"] = 0] = \"Mutation\";\n IncrementalSource2[IncrementalSource2[\"MouseMove\"] = 1] = \"MouseMove\";\n IncrementalSource2[IncrementalSource2[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n IncrementalSource2[IncrementalSource2[\"Scroll\"] = 3] = \"Scroll\";\n IncrementalSource2[IncrementalSource2[\"ViewportResize\"] = 4] = \"ViewportResize\";\n IncrementalSource2[IncrementalSource2[\"Input\"] = 5] = \"Input\";\n IncrementalSource2[IncrementalSource2[\"TouchMove\"] = 6] = \"TouchMove\";\n IncrementalSource2[IncrementalSource2[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n IncrementalSource2[IncrementalSource2[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n IncrementalSource2[IncrementalSource2[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n IncrementalSource2[IncrementalSource2[\"Font\"] = 10] = \"Font\";\n IncrementalSource2[IncrementalSource2[\"Log\"] = 11] = \"Log\";\n IncrementalSource2[IncrementalSource2[\"Drag\"] = 12] = \"Drag\";\n IncrementalSource2[IncrementalSource2[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n IncrementalSource2[IncrementalSource2[\"Selection\"] = 14] = \"Selection\";\n IncrementalSource2[IncrementalSource2[\"AdoptedStyleSheet\"] = 15] = \"AdoptedStyleSheet\";\n IncrementalSource2[IncrementalSource2[\"CustomElement\"] = 16] = \"CustomElement\";\n return IncrementalSource2;\n})(IncrementalSource || {});\nvar MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {\n MouseInteractions2[MouseInteractions2[\"MouseUp\"] = 0] = \"MouseUp\";\n MouseInteractions2[MouseInteractions2[\"MouseDown\"] = 1] = \"MouseDown\";\n MouseInteractions2[MouseInteractions2[\"Click\"] = 2] = \"Click\";\n MouseInteractions2[MouseInteractions2[\"ContextMenu\"] = 3] = \"ContextMenu\";\n MouseInteractions2[MouseInteractions2[\"DblClick\"] = 4] = \"DblClick\";\n MouseInteractions2[MouseInteractions2[\"Focus\"] = 5] = \"Focus\";\n MouseInteractions2[MouseInteractions2[\"Blur\"] = 6] = \"Blur\";\n MouseInteractions2[MouseInteractions2[\"TouchStart\"] = 7] = \"TouchStart\";\n MouseInteractions2[MouseInteractions2[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n MouseInteractions2[MouseInteractions2[\"TouchEnd\"] = 9] = \"TouchEnd\";\n MouseInteractions2[MouseInteractions2[\"TouchCancel\"] = 10] = \"TouchCancel\";\n return MouseInteractions2;\n})(MouseInteractions || {});\nvar PointerTypes = /* @__PURE__ */ ((PointerTypes2) => {\n PointerTypes2[PointerTypes2[\"Mouse\"] = 0] = \"Mouse\";\n PointerTypes2[PointerTypes2[\"Pen\"] = 1] = \"Pen\";\n PointerTypes2[PointerTypes2[\"Touch\"] = 2] = \"Touch\";\n return PointerTypes2;\n})(PointerTypes || {});\nvar CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {\n CanvasContext2[CanvasContext2[\"2D\"] = 0] = \"2D\";\n CanvasContext2[CanvasContext2[\"WebGL\"] = 1] = \"WebGL\";\n CanvasContext2[CanvasContext2[\"WebGL2\"] = 2] = \"WebGL2\";\n return CanvasContext2;\n})(CanvasContext || {});\nvar ReplayerEvents = /* @__PURE__ */ ((ReplayerEvents2) => {\n ReplayerEvents2[\"Start\"] = \"start\";\n ReplayerEvents2[\"Pause\"] = \"pause\";\n ReplayerEvents2[\"Resume\"] = \"resume\";\n ReplayerEvents2[\"Resize\"] = \"resize\";\n ReplayerEvents2[\"Finish\"] = \"finish\";\n ReplayerEvents2[\"FullsnapshotRebuilded\"] = \"fullsnapshot-rebuilded\";\n ReplayerEvents2[\"LoadStylesheetStart\"] = \"load-stylesheet-start\";\n ReplayerEvents2[\"LoadStylesheetEnd\"] = \"load-stylesheet-end\";\n ReplayerEvents2[\"SkipStart\"] = \"skip-start\";\n ReplayerEvents2[\"SkipEnd\"] = \"skip-end\";\n ReplayerEvents2[\"MouseInteraction\"] = \"mouse-interaction\";\n ReplayerEvents2[\"EventCast\"] = \"event-cast\";\n ReplayerEvents2[\"CustomEvent\"] = \"custom-event\";\n ReplayerEvents2[\"Flush\"] = \"flush\";\n ReplayerEvents2[\"StateChange\"] = \"state-change\";\n ReplayerEvents2[\"PlayBack\"] = \"play-back\";\n ReplayerEvents2[\"Destroy\"] = \"destroy\";\n return ReplayerEvents2;\n})(ReplayerEvents || {});\n\nexport { CanvasContext, EventType, IncrementalSource, MouseInteractions, PointerTypes, ReplayerEvents };\n","import { isShadowRoot, isNativeShadowDom, getInputType, getInputValue, shouldMaskInput, needMaskingText, maskInputValue, ignoreAttribute, transformAttribute, toLowerCase, IGNORED_NODE, serializeNodeWithId } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { isIgnored, isBlocked, isSerialized, isAncestorRemoved, closestElementOfNode, hasShadowRoot, inDom, getShadowHost, isSerializedIframe, isSerializedStylesheet } from '../utils.js';\n\nfunction isNodeInLinkedList(n) {\r\n return '__ln' in n;\r\n}\r\nclass DoubleLinkedList {\r\n constructor() {\r\n this.length = 0;\r\n this.head = null;\r\n this.tail = null;\r\n }\r\n get(position) {\r\n if (position >= this.length) {\r\n throw new Error('Position outside of list range');\r\n }\r\n let current = this.head;\r\n for (let index = 0; index < position; index++) {\r\n current = current?.next || null;\r\n }\r\n return current;\r\n }\r\n addNode(n) {\r\n const node = {\r\n value: n,\r\n previous: null,\r\n next: null,\r\n };\r\n n.__ln = node;\r\n if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {\r\n const current = n.previousSibling.__ln.next;\r\n node.next = current;\r\n node.previous = n.previousSibling.__ln;\r\n n.previousSibling.__ln.next = node;\r\n if (current) {\r\n current.previous = node;\r\n }\r\n }\r\n else if (n.nextSibling &&\r\n isNodeInLinkedList(n.nextSibling) &&\r\n n.nextSibling.__ln.previous) {\r\n const current = n.nextSibling.__ln.previous;\r\n node.previous = current;\r\n node.next = n.nextSibling.__ln;\r\n n.nextSibling.__ln.previous = node;\r\n if (current) {\r\n current.next = node;\r\n }\r\n }\r\n else {\r\n if (this.head) {\r\n this.head.previous = node;\r\n }\r\n node.next = this.head;\r\n this.head = node;\r\n }\r\n if (node.next === null) {\r\n this.tail = node;\r\n }\r\n this.length++;\r\n }\r\n removeNode(n) {\r\n const current = n.__ln;\r\n if (!this.head) {\r\n return;\r\n }\r\n if (!current.previous) {\r\n this.head = current.next;\r\n if (this.head) {\r\n this.head.previous = null;\r\n }\r\n else {\r\n this.tail = null;\r\n }\r\n }\r\n else {\r\n current.previous.next = current.next;\r\n if (current.next) {\r\n current.next.previous = current.previous;\r\n }\r\n else {\r\n this.tail = current.previous;\r\n }\r\n }\r\n if (n.__ln) {\r\n delete n.__ln;\r\n }\r\n this.length--;\r\n }\r\n}\r\nconst moveKey = (id, parentId) => `${id}@${parentId}`;\r\nclass MutationBuffer {\r\n constructor() {\r\n this.frozen = false;\r\n this.locked = false;\r\n this.texts = [];\r\n this.attributes = [];\r\n this.attributeMap = new WeakMap();\r\n this.removes = [];\r\n this.mapRemoves = [];\r\n this.movedMap = {};\r\n this.addedSet = new Set();\r\n this.movedSet = new Set();\r\n this.droppedSet = new Set();\r\n this.processMutations = (mutations) => {\r\n mutations.forEach(this.processMutation);\r\n this.emit();\r\n };\r\n this.emit = () => {\r\n if (this.frozen || this.locked) {\r\n return;\r\n }\r\n const adds = [];\r\n const addedIds = new Set();\r\n const addList = new DoubleLinkedList();\r\n const getNextId = (n) => {\r\n let ns = n;\r\n let nextId = IGNORED_NODE;\r\n while (nextId === IGNORED_NODE) {\r\n ns = ns && ns.nextSibling;\r\n nextId = ns && this.mirror.getId(ns);\r\n }\r\n return nextId;\r\n };\r\n const pushAdd = (n) => {\r\n if (!n.parentNode || !inDom(n)) {\r\n return;\r\n }\r\n const parentId = isShadowRoot(n.parentNode)\r\n ? this.mirror.getId(getShadowHost(n))\r\n : this.mirror.getId(n.parentNode);\r\n const nextId = getNextId(n);\r\n if (parentId === -1 || nextId === -1) {\r\n return addList.addNode(n);\r\n }\r\n const sn = serializeNodeWithId(n, {\r\n doc: this.doc,\r\n mirror: this.mirror,\r\n blockClass: this.blockClass,\r\n blockSelector: this.blockSelector,\r\n maskAllText: this.maskAllText,\r\n unblockSelector: this.unblockSelector,\r\n maskTextClass: this.maskTextClass,\r\n unmaskTextClass: this.unmaskTextClass,\r\n maskTextSelector: this.maskTextSelector,\r\n unmaskTextSelector: this.unmaskTextSelector,\r\n skipChild: true,\r\n newlyAddedElement: true,\r\n inlineStylesheet: this.inlineStylesheet,\r\n maskInputOptions: this.maskInputOptions,\r\n maskAttributeFn: this.maskAttributeFn,\r\n maskTextFn: this.maskTextFn,\r\n maskInputFn: this.maskInputFn,\r\n slimDOMOptions: this.slimDOMOptions,\r\n dataURLOptions: this.dataURLOptions,\r\n recordCanvas: this.recordCanvas,\r\n inlineImages: this.inlineImages,\r\n onSerialize: (currentN) => {\r\n if (isSerializedIframe(currentN, this.mirror)) {\r\n this.iframeManager.addIframe(currentN);\r\n }\r\n if (isSerializedStylesheet(currentN, this.mirror)) {\r\n this.stylesheetManager.trackLinkElement(currentN);\r\n }\r\n if (hasShadowRoot(n)) {\r\n this.shadowDomManager.addShadowRoot(n.shadowRoot, this.doc);\r\n }\r\n },\r\n onIframeLoad: (iframe, childSn) => {\r\n this.iframeManager.attachIframe(iframe, childSn);\r\n this.shadowDomManager.observeAttachShadow(iframe);\r\n },\r\n onStylesheetLoad: (link, childSn) => {\r\n this.stylesheetManager.attachLinkElement(link, childSn);\r\n },\r\n });\r\n if (sn) {\r\n adds.push({\r\n parentId,\r\n nextId,\r\n node: sn,\r\n });\r\n addedIds.add(sn.id);\r\n }\r\n };\r\n while (this.mapRemoves.length) {\r\n this.mirror.removeNodeFromMap(this.mapRemoves.shift());\r\n }\r\n for (const n of this.movedSet) {\r\n if (isParentRemoved(this.removes, n, this.mirror) &&\r\n !this.movedSet.has(n.parentNode)) {\r\n continue;\r\n }\r\n pushAdd(n);\r\n }\r\n for (const n of this.addedSet) {\r\n if (!isAncestorInSet(this.droppedSet, n) &&\r\n !isParentRemoved(this.removes, n, this.mirror)) {\r\n pushAdd(n);\r\n }\r\n else if (isAncestorInSet(this.movedSet, n)) {\r\n pushAdd(n);\r\n }\r\n else {\r\n this.droppedSet.add(n);\r\n }\r\n }\r\n let candidate = null;\r\n while (addList.length) {\r\n let node = null;\r\n if (candidate) {\r\n const parentId = this.mirror.getId(candidate.value.parentNode);\r\n const nextId = getNextId(candidate.value);\r\n if (parentId !== -1 && nextId !== -1) {\r\n node = candidate;\r\n }\r\n }\r\n if (!node) {\r\n let tailNode = addList.tail;\r\n while (tailNode) {\r\n const _node = tailNode;\r\n tailNode = tailNode.previous;\r\n if (_node) {\r\n const parentId = this.mirror.getId(_node.value.parentNode);\r\n const nextId = getNextId(_node.value);\r\n if (nextId === -1)\r\n continue;\r\n else if (parentId !== -1) {\r\n node = _node;\r\n break;\r\n }\r\n else {\r\n const unhandledNode = _node.value;\r\n if (unhandledNode.parentNode &&\r\n unhandledNode.parentNode.nodeType ===\r\n Node.DOCUMENT_FRAGMENT_NODE) {\r\n const shadowHost = unhandledNode.parentNode\r\n .host;\r\n const parentId = this.mirror.getId(shadowHost);\r\n if (parentId !== -1) {\r\n node = _node;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (!node) {\r\n while (addList.head) {\r\n addList.removeNode(addList.head.value);\r\n }\r\n break;\r\n }\r\n candidate = node.previous;\r\n addList.removeNode(node.value);\r\n pushAdd(node.value);\r\n }\r\n const payload = {\r\n texts: this.texts\r\n .map((text) => ({\r\n id: this.mirror.getId(text.node),\r\n value: text.value,\r\n }))\r\n .filter((text) => !addedIds.has(text.id))\r\n .filter((text) => this.mirror.has(text.id)),\r\n attributes: this.attributes\r\n .map((attribute) => {\r\n const { attributes } = attribute;\r\n if (typeof attributes.style === 'string') {\r\n const diffAsStr = JSON.stringify(attribute.styleDiff);\r\n const unchangedAsStr = JSON.stringify(attribute._unchangedStyles);\r\n if (diffAsStr.length < attributes.style.length) {\r\n if ((diffAsStr + unchangedAsStr).split('var(').length ===\r\n attributes.style.split('var(').length) {\r\n attributes.style = attribute.styleDiff;\r\n }\r\n }\r\n }\r\n return {\r\n id: this.mirror.getId(attribute.node),\r\n attributes: attributes,\r\n };\r\n })\r\n .filter((attribute) => !addedIds.has(attribute.id))\r\n .filter((attribute) => this.mirror.has(attribute.id)),\r\n removes: this.removes,\r\n adds,\r\n };\r\n if (!payload.texts.length &&\r\n !payload.attributes.length &&\r\n !payload.removes.length &&\r\n !payload.adds.length) {\r\n return;\r\n }\r\n this.texts = [];\r\n this.attributes = [];\r\n this.attributeMap = new WeakMap();\r\n this.removes = [];\r\n this.addedSet = new Set();\r\n this.movedSet = new Set();\r\n this.droppedSet = new Set();\r\n this.movedMap = {};\r\n this.mutationCb(payload);\r\n };\r\n this.processMutation = (m) => {\r\n if (isIgnored(m.target, this.mirror)) {\r\n return;\r\n }\r\n switch (m.type) {\r\n case 'characterData': {\r\n const value = m.target.textContent;\r\n if (!isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) &&\r\n value !== m.oldValue) {\r\n this.texts.push({\r\n value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, this.maskAllText) && value\r\n ? this.maskTextFn\r\n ? this.maskTextFn(value, closestElementOfNode(m.target))\r\n : value.replace(/[\\S]/g, '*')\r\n : value,\r\n node: m.target,\r\n });\r\n }\r\n break;\r\n }\r\n case 'attributes': {\r\n const target = m.target;\r\n let attributeName = m.attributeName;\r\n let value = m.target.getAttribute(attributeName);\r\n if (attributeName === 'value') {\r\n const type = getInputType(target);\r\n const tagName = target.tagName;\r\n value = getInputValue(target, tagName, type);\r\n const isInputMasked = shouldMaskInput({\r\n maskInputOptions: this.maskInputOptions,\r\n tagName,\r\n type,\r\n });\r\n const forceMask = needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, isInputMasked);\r\n value = maskInputValue({\r\n isMasked: forceMask,\r\n element: target,\r\n value,\r\n maskInputFn: this.maskInputFn,\r\n });\r\n }\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) ||\r\n value === m.oldValue) {\r\n return;\r\n }\r\n let item = this.attributeMap.get(m.target);\r\n if (target.tagName === 'IFRAME' &&\r\n attributeName === 'src' &&\r\n !this.keepIframeSrcFn(value)) {\r\n if (!target.contentDocument) {\r\n attributeName = 'rr_src';\r\n }\r\n else {\r\n return;\r\n }\r\n }\r\n if (!item) {\r\n item = {\r\n node: m.target,\r\n attributes: {},\r\n styleDiff: {},\r\n _unchangedStyles: {},\r\n };\r\n this.attributes.push(item);\r\n this.attributeMap.set(m.target, item);\r\n }\r\n if (attributeName === 'type' &&\r\n target.tagName === 'INPUT' &&\r\n (m.oldValue || '').toLowerCase() === 'password') {\r\n target.setAttribute('data-rr-is-password', 'true');\r\n }\r\n if (!ignoreAttribute(target.tagName, attributeName)) {\r\n item.attributes[attributeName] = transformAttribute(this.doc, toLowerCase(target.tagName), toLowerCase(attributeName), value, target, this.maskAttributeFn);\r\n if (attributeName === 'style') {\r\n if (!this.unattachedDoc) {\r\n try {\r\n this.unattachedDoc =\r\n document.implementation.createHTMLDocument();\r\n }\r\n catch (e) {\r\n this.unattachedDoc = this.doc;\r\n }\r\n }\r\n const old = this.unattachedDoc.createElement('span');\r\n if (m.oldValue) {\r\n old.setAttribute('style', m.oldValue);\r\n }\r\n for (const pname of Array.from(target.style)) {\r\n const newValue = target.style.getPropertyValue(pname);\r\n const newPriority = target.style.getPropertyPriority(pname);\r\n if (newValue !== old.style.getPropertyValue(pname) ||\r\n newPriority !== old.style.getPropertyPriority(pname)) {\r\n if (newPriority === '') {\r\n item.styleDiff[pname] = newValue;\r\n }\r\n else {\r\n item.styleDiff[pname] = [newValue, newPriority];\r\n }\r\n }\r\n else {\r\n item._unchangedStyles[pname] = [newValue, newPriority];\r\n }\r\n }\r\n for (const pname of Array.from(old.style)) {\r\n if (target.style.getPropertyValue(pname) === '') {\r\n item.styleDiff[pname] = false;\r\n }\r\n }\r\n }\r\n }\r\n break;\r\n }\r\n case 'childList': {\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, true)) {\r\n return;\r\n }\r\n m.addedNodes.forEach((n) => this.genAdds(n, m.target));\r\n m.removedNodes.forEach((n) => {\r\n const nodeId = this.mirror.getId(n);\r\n const parentId = isShadowRoot(m.target)\r\n ? this.mirror.getId(m.target.host)\r\n : this.mirror.getId(m.target);\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) ||\r\n isIgnored(n, this.mirror) ||\r\n !isSerialized(n, this.mirror)) {\r\n return;\r\n }\r\n if (this.addedSet.has(n)) {\r\n deepDelete(this.addedSet, n);\r\n this.droppedSet.add(n);\r\n }\r\n else if (this.addedSet.has(m.target) && nodeId === -1) ;\r\n else if (isAncestorRemoved(m.target, this.mirror)) ;\r\n else if (this.movedSet.has(n) &&\r\n this.movedMap[moveKey(nodeId, parentId)]) {\r\n deepDelete(this.movedSet, n);\r\n }\r\n else {\r\n this.removes.push({\r\n parentId,\r\n id: nodeId,\r\n isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target)\r\n ? true\r\n : undefined,\r\n });\r\n }\r\n this.mapRemoves.push(n);\r\n });\r\n break;\r\n }\r\n }\r\n };\r\n this.genAdds = (n, target) => {\r\n if (this.processedNodeManager.inOtherBuffer(n, this))\r\n return;\r\n if (this.addedSet.has(n) || this.movedSet.has(n))\r\n return;\r\n if (this.mirror.hasNode(n)) {\r\n if (isIgnored(n, this.mirror)) {\r\n return;\r\n }\r\n this.movedSet.add(n);\r\n let targetId = null;\r\n if (target && this.mirror.hasNode(target)) {\r\n targetId = this.mirror.getId(target);\r\n }\r\n if (targetId && targetId !== -1) {\r\n this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;\r\n }\r\n }\r\n else {\r\n this.addedSet.add(n);\r\n this.droppedSet.delete(n);\r\n }\r\n if (!isBlocked(n, this.blockClass, this.blockSelector, this.unblockSelector, false)) {\r\n n.childNodes.forEach((childN) => this.genAdds(childN));\r\n if (hasShadowRoot(n)) {\r\n n.shadowRoot.childNodes.forEach((childN) => {\r\n this.processedNodeManager.add(childN, this);\r\n this.genAdds(childN, n);\r\n });\r\n }\r\n }\r\n };\r\n }\r\n init(options) {\r\n [\r\n 'mutationCb',\r\n 'blockClass',\r\n 'blockSelector',\r\n 'unblockSelector',\r\n 'maskAllText',\r\n 'maskTextClass',\r\n 'unmaskTextClass',\r\n 'maskTextSelector',\r\n 'unmaskTextSelector',\r\n 'inlineStylesheet',\r\n 'maskInputOptions',\r\n 'maskAttributeFn',\r\n 'maskTextFn',\r\n 'maskInputFn',\r\n 'keepIframeSrcFn',\r\n 'recordCanvas',\r\n 'inlineImages',\r\n 'slimDOMOptions',\r\n 'dataURLOptions',\r\n 'doc',\r\n 'mirror',\r\n 'iframeManager',\r\n 'stylesheetManager',\r\n 'shadowDomManager',\r\n 'canvasManager',\r\n 'processedNodeManager',\r\n ].forEach((key) => {\r\n this[key] = options[key];\r\n });\r\n }\r\n freeze() {\r\n this.frozen = true;\r\n this.canvasManager.freeze();\r\n }\r\n unfreeze() {\r\n this.frozen = false;\r\n this.canvasManager.unfreeze();\r\n this.emit();\r\n }\r\n isFrozen() {\r\n return this.frozen;\r\n }\r\n lock() {\r\n this.locked = true;\r\n this.canvasManager.lock();\r\n }\r\n unlock() {\r\n this.locked = false;\r\n this.canvasManager.unlock();\r\n this.emit();\r\n }\r\n reset() {\r\n this.shadowDomManager.reset();\r\n this.canvasManager.reset();\r\n }\r\n}\r\nfunction deepDelete(addsSet, n) {\r\n addsSet.delete(n);\r\n n.childNodes.forEach((childN) => deepDelete(addsSet, childN));\r\n}\r\nfunction isParentRemoved(removes, n, mirror) {\r\n if (removes.length === 0)\r\n return false;\r\n return _isParentRemoved(removes, n, mirror);\r\n}\r\nfunction _isParentRemoved(removes, n, mirror) {\r\n const { parentNode } = n;\r\n if (!parentNode) {\r\n return false;\r\n }\r\n const parentId = mirror.getId(parentNode);\r\n if (removes.some((r) => r.id === parentId)) {\r\n return true;\r\n }\r\n return _isParentRemoved(removes, parentNode, mirror);\r\n}\r\nfunction isAncestorInSet(set, n) {\r\n if (set.size === 0)\r\n return false;\r\n return _isAncestorInSet(set, n);\r\n}\r\nfunction _isAncestorInSet(set, n) {\r\n const { parentNode } = n;\r\n if (!parentNode) {\r\n return false;\r\n }\r\n if (set.has(parentNode)) {\r\n return true;\r\n }\r\n return _isAncestorInSet(set, parentNode);\r\n}\n\nexport { MutationBuffer as default };\n","let errorHandler;\r\nfunction registerErrorHandler(handler) {\r\n errorHandler = handler;\r\n}\r\nfunction unregisterErrorHandler() {\r\n errorHandler = undefined;\r\n}\r\nconst callbackWrapper = (cb) => {\r\n if (!errorHandler) {\r\n return cb;\r\n }\r\n const rrwebWrapped = ((...rest) => {\r\n try {\r\n return cb(...rest);\r\n }\r\n catch (error) {\r\n if (errorHandler && errorHandler(error) === true) {\r\n return () => {\r\n };\r\n }\r\n throw error;\r\n }\r\n });\r\n return rrwebWrapped;\r\n};\n\nexport { callbackWrapper, registerErrorHandler, unregisterErrorHandler };\n","import { toLowerCase, toUpperCase, getInputType, getInputValue, shouldMaskInput, needMaskingText, maskInputValue } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { on, throttle, isBlocked, getWindowScroll, hookSetter, patch, setTimeout, legacy_isTouchEvent, nowTimestamp, getWindowHeight, getWindowWidth } from '../utils.js';\nimport { MouseInteractions, IncrementalSource, PointerTypes } from '../../../types/dist/rrweb-types.js';\nimport MutationBuffer from './mutation.js';\nimport { callbackWrapper } from './error-handler.js';\n\nconst mutationBuffers = [];\r\nfunction getEventTarget(event) {\r\n try {\r\n if ('composedPath' in event) {\r\n const path = event.composedPath();\r\n if (path.length) {\r\n return path[0];\r\n }\r\n }\r\n else if ('path' in event && event.path.length) {\r\n return event.path[0];\r\n }\r\n }\r\n catch {\r\n }\r\n return event && event.target;\r\n}\r\nfunction initMutationObserver(options, rootEl) {\r\n const mutationBuffer = new MutationBuffer();\r\n mutationBuffers.push(mutationBuffer);\r\n mutationBuffer.init(options);\r\n let mutationObserverCtor = window.MutationObserver ||\r\n window.__rrMutationObserver;\r\n const angularZoneSymbol = window?.Zone?.__symbol__?.('MutationObserver');\r\n if (angularZoneSymbol &&\r\n window[angularZoneSymbol]) {\r\n mutationObserverCtor = window[angularZoneSymbol];\r\n }\r\n const observer = new mutationObserverCtor(callbackWrapper((mutations) => {\r\n if (options.onMutation && options.onMutation(mutations) === false) {\r\n return;\r\n }\r\n mutationBuffer.processMutations.bind(mutationBuffer)(mutations);\r\n }));\r\n observer.observe(rootEl, {\r\n attributes: true,\r\n attributeOldValue: true,\r\n characterData: true,\r\n characterDataOldValue: true,\r\n childList: true,\r\n subtree: true,\r\n });\r\n return observer;\r\n}\r\nfunction initMoveObserver({ mousemoveCb, sampling, doc, mirror, }) {\r\n if (sampling.mousemove === false) {\r\n return () => {\r\n };\r\n }\r\n const threshold = typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;\r\n const callbackThreshold = typeof sampling.mousemoveCallback === 'number'\r\n ? sampling.mousemoveCallback\r\n : 500;\r\n let positions = [];\r\n let timeBaseline;\r\n const wrappedCb = throttle(callbackWrapper((source) => {\r\n const totalOffset = Date.now() - timeBaseline;\r\n mousemoveCb(positions.map((p) => {\r\n p.timeOffset -= totalOffset;\r\n return p;\r\n }), source);\r\n positions = [];\r\n timeBaseline = null;\r\n }), callbackThreshold);\r\n const updatePosition = callbackWrapper(throttle(callbackWrapper((evt) => {\r\n const target = getEventTarget(evt);\r\n const { clientX, clientY } = legacy_isTouchEvent(evt)\r\n ? evt.changedTouches[0]\r\n : evt;\r\n if (!timeBaseline) {\r\n timeBaseline = nowTimestamp();\r\n }\r\n positions.push({\r\n x: clientX,\r\n y: clientY,\r\n id: mirror.getId(target),\r\n timeOffset: nowTimestamp() - timeBaseline,\r\n });\r\n wrappedCb(typeof DragEvent !== 'undefined' && evt instanceof DragEvent\r\n ? IncrementalSource.Drag\r\n : evt instanceof MouseEvent\r\n ? IncrementalSource.MouseMove\r\n : IncrementalSource.TouchMove);\r\n }), threshold, {\r\n trailing: false,\r\n }));\r\n const handlers = [\r\n on('mousemove', updatePosition, doc),\r\n on('touchmove', updatePosition, doc),\r\n on('drag', updatePosition, doc),\r\n ];\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initMouseInteractionObserver({ mouseInteractionCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\r\n if (sampling.mouseInteraction === false) {\r\n return () => {\r\n };\r\n }\r\n const disableMap = sampling.mouseInteraction === true ||\r\n sampling.mouseInteraction === undefined\r\n ? {}\r\n : sampling.mouseInteraction;\r\n const handlers = [];\r\n let currentPointerType = null;\r\n const getHandler = (eventKey) => {\r\n return (event) => {\r\n const target = getEventTarget(event);\r\n if (isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\r\n return;\r\n }\r\n let pointerType = null;\r\n let thisEventKey = eventKey;\r\n if ('pointerType' in event) {\r\n switch (event.pointerType) {\r\n case 'mouse':\r\n pointerType = PointerTypes.Mouse;\r\n break;\r\n case 'touch':\r\n pointerType = PointerTypes.Touch;\r\n break;\r\n case 'pen':\r\n pointerType = PointerTypes.Pen;\r\n break;\r\n }\r\n if (pointerType === PointerTypes.Touch) {\r\n if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {\r\n thisEventKey = 'TouchStart';\r\n }\r\n else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {\r\n thisEventKey = 'TouchEnd';\r\n }\r\n }\r\n else if (pointerType === PointerTypes.Pen) ;\r\n }\r\n else if (legacy_isTouchEvent(event)) {\r\n pointerType = PointerTypes.Touch;\r\n }\r\n if (pointerType !== null) {\r\n currentPointerType = pointerType;\r\n if ((thisEventKey.startsWith('Touch') &&\r\n pointerType === PointerTypes.Touch) ||\r\n (thisEventKey.startsWith('Mouse') &&\r\n pointerType === PointerTypes.Mouse)) {\r\n pointerType = null;\r\n }\r\n }\r\n else if (MouseInteractions[eventKey] === MouseInteractions.Click) {\r\n pointerType = currentPointerType;\r\n currentPointerType = null;\r\n }\r\n const e = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;\r\n if (!e) {\r\n return;\r\n }\r\n const id = mirror.getId(target);\r\n const { clientX, clientY } = e;\r\n callbackWrapper(mouseInteractionCb)({\r\n type: MouseInteractions[thisEventKey],\r\n id,\r\n x: clientX,\r\n y: clientY,\r\n ...(pointerType !== null && { pointerType }),\r\n });\r\n };\r\n };\r\n Object.keys(MouseInteractions)\r\n .filter((key) => Number.isNaN(Number(key)) &&\r\n !key.endsWith('_Departed') &&\r\n disableMap[key] !== false)\r\n .forEach((eventKey) => {\r\n let eventName = toLowerCase(eventKey);\r\n const handler = getHandler(eventKey);\r\n if (window.PointerEvent) {\r\n switch (MouseInteractions[eventKey]) {\r\n case MouseInteractions.MouseDown:\r\n case MouseInteractions.MouseUp:\r\n eventName = eventName.replace('mouse', 'pointer');\r\n break;\r\n case MouseInteractions.TouchStart:\r\n case MouseInteractions.TouchEnd:\r\n return;\r\n }\r\n }\r\n handlers.push(on(eventName, handler, doc));\r\n });\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initScrollObserver({ scrollCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\r\n const updatePosition = callbackWrapper(throttle(callbackWrapper((evt) => {\r\n const target = getEventTarget(evt);\r\n if (!target ||\r\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\r\n return;\r\n }\r\n const id = mirror.getId(target);\r\n if (target === doc && doc.defaultView) {\r\n const scrollLeftTop = getWindowScroll(doc.defaultView);\r\n scrollCb({\r\n id,\r\n x: scrollLeftTop.left,\r\n y: scrollLeftTop.top,\r\n });\r\n }\r\n else {\r\n scrollCb({\r\n id,\r\n x: target.scrollLeft,\r\n y: target.scrollTop,\r\n });\r\n }\r\n }), sampling.scroll || 100));\r\n return on('scroll', updatePosition, doc);\r\n}\r\nfunction initViewportResizeObserver({ viewportResizeCb }, { win }) {\r\n let lastH = -1;\r\n let lastW = -1;\r\n const updateDimension = callbackWrapper(throttle(callbackWrapper(() => {\r\n const height = getWindowHeight();\r\n const width = getWindowWidth();\r\n if (lastH !== height || lastW !== width) {\r\n viewportResizeCb({\r\n width: Number(width),\r\n height: Number(height),\r\n });\r\n lastH = height;\r\n lastW = width;\r\n }\r\n }), 200));\r\n return on('resize', updateDimension, win);\r\n}\r\nconst INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];\r\nconst lastInputValueMap = new WeakMap();\r\nfunction initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, unblockSelector, ignoreClass, ignoreSelector, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, }) {\r\n function eventHandler(event) {\r\n let target = getEventTarget(event);\r\n const userTriggered = event.isTrusted;\r\n const tagName = target && toUpperCase(target.tagName);\r\n if (tagName === 'OPTION')\r\n target = target.parentElement;\r\n if (!target ||\r\n !tagName ||\r\n INPUT_TAGS.indexOf(tagName) < 0 ||\r\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\r\n return;\r\n }\r\n const el = target;\r\n if (el.classList.contains(ignoreClass) ||\r\n (ignoreSelector && el.matches(ignoreSelector))) {\r\n return;\r\n }\r\n const type = getInputType(target);\r\n let text = getInputValue(el, tagName, type);\r\n let isChecked = false;\r\n const isInputMasked = shouldMaskInput({\r\n maskInputOptions,\r\n tagName,\r\n type,\r\n });\r\n const forceMask = needMaskingText(target, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked);\r\n if (type === 'radio' || type === 'checkbox') {\r\n isChecked = target.checked;\r\n }\r\n text = maskInputValue({\r\n isMasked: forceMask,\r\n element: target,\r\n value: text,\r\n maskInputFn,\r\n });\r\n cbWithDedup(target, userTriggeredOnInput\r\n ? { text, isChecked, userTriggered }\r\n : { text, isChecked });\r\n const name = target.name;\r\n if (type === 'radio' && name && isChecked) {\r\n doc\r\n .querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`)\r\n .forEach((el) => {\r\n if (el !== target) {\r\n const text = maskInputValue({\r\n isMasked: forceMask,\r\n element: el,\r\n value: getInputValue(el, tagName, type),\r\n maskInputFn,\r\n });\r\n cbWithDedup(el, userTriggeredOnInput\r\n ? { text, isChecked: !isChecked, userTriggered: false }\r\n : { text, isChecked: !isChecked });\r\n }\r\n });\r\n }\r\n }\r\n function cbWithDedup(target, v) {\r\n const lastInputValue = lastInputValueMap.get(target);\r\n if (!lastInputValue ||\r\n lastInputValue.text !== v.text ||\r\n lastInputValue.isChecked !== v.isChecked) {\r\n lastInputValueMap.set(target, v);\r\n const id = mirror.getId(target);\r\n callbackWrapper(inputCb)({\r\n ...v,\r\n id,\r\n });\r\n }\r\n }\r\n const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];\r\n const handlers = events.map((eventName) => on(eventName, callbackWrapper(eventHandler), doc));\r\n const currentWindow = doc.defaultView;\r\n if (!currentWindow) {\r\n return () => {\r\n handlers.forEach((h) => h());\r\n };\r\n }\r\n const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, 'value');\r\n const hookProperties = [\r\n [currentWindow.HTMLInputElement.prototype, 'value'],\r\n [currentWindow.HTMLInputElement.prototype, 'checked'],\r\n [currentWindow.HTMLSelectElement.prototype, 'value'],\r\n [currentWindow.HTMLTextAreaElement.prototype, 'value'],\r\n [currentWindow.HTMLSelectElement.prototype, 'selectedIndex'],\r\n [currentWindow.HTMLOptionElement.prototype, 'selected'],\r\n ];\r\n if (propertyDescriptor && propertyDescriptor.set) {\r\n handlers.push(...hookProperties.map((p) => hookSetter(p[0], p[1], {\r\n set() {\r\n callbackWrapper(eventHandler)({\r\n target: this,\r\n isTrusted: false,\r\n });\r\n },\r\n }, false, currentWindow)));\r\n }\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction getNestedCSSRulePositions(rule) {\r\n const positions = [];\r\n function recurse(childRule, pos) {\r\n if ((hasNestedCSSRule('CSSGroupingRule') &&\r\n childRule.parentRule instanceof CSSGroupingRule) ||\r\n (hasNestedCSSRule('CSSMediaRule') &&\r\n childRule.parentRule instanceof CSSMediaRule) ||\r\n (hasNestedCSSRule('CSSSupportsRule') &&\r\n childRule.parentRule instanceof CSSSupportsRule) ||\r\n (hasNestedCSSRule('CSSConditionRule') &&\r\n childRule.parentRule instanceof CSSConditionRule)) {\r\n const rules = Array.from(childRule.parentRule.cssRules);\r\n const index = rules.indexOf(childRule);\r\n pos.unshift(index);\r\n }\r\n else if (childRule.parentStyleSheet) {\r\n const rules = Array.from(childRule.parentStyleSheet.cssRules);\r\n const index = rules.indexOf(childRule);\r\n pos.unshift(index);\r\n }\r\n return pos;\r\n }\r\n return recurse(rule, positions);\r\n}\r\nfunction getIdAndStyleId(sheet, mirror, styleMirror) {\r\n let id, styleId;\r\n if (!sheet)\r\n return {};\r\n if (sheet.ownerNode)\r\n id = mirror.getId(sheet.ownerNode);\r\n else\r\n styleId = styleMirror.getId(sheet);\r\n return {\r\n styleId,\r\n id,\r\n };\r\n}\r\nfunction initStyleSheetObserver({ styleSheetRuleCb, mirror, stylesheetManager }, { win }) {\r\n if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\r\n return () => {\r\n };\r\n }\r\n const insertRule = win.CSSStyleSheet.prototype.insertRule;\r\n win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [rule, index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n adds: [{ rule, index }],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\r\n win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n removes: [{ index }],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n let replace;\r\n if (win.CSSStyleSheet.prototype.replace) {\r\n replace = win.CSSStyleSheet.prototype.replace;\r\n win.CSSStyleSheet.prototype.replace = new Proxy(replace, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [text] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n replace: text,\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n }\r\n let replaceSync;\r\n if (win.CSSStyleSheet.prototype.replaceSync) {\r\n replaceSync = win.CSSStyleSheet.prototype.replaceSync;\r\n win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [text] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n replaceSync: text,\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n }\r\n const supportedNestedCSSRuleTypes = {};\r\n if (canMonkeyPatchNestedCSSRule('CSSGroupingRule')) {\r\n supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\r\n }\r\n else {\r\n if (canMonkeyPatchNestedCSSRule('CSSMediaRule')) {\r\n supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\r\n }\r\n if (canMonkeyPatchNestedCSSRule('CSSConditionRule')) {\r\n supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\r\n }\r\n if (canMonkeyPatchNestedCSSRule('CSSSupportsRule')) {\r\n supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\r\n }\r\n }\r\n const unmodifiedFunctions = {};\r\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\r\n unmodifiedFunctions[typeKey] = {\r\n insertRule: type.prototype.insertRule,\r\n deleteRule: type.prototype.deleteRule,\r\n };\r\n type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [rule, index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n adds: [\r\n {\r\n rule,\r\n index: [\r\n ...getNestedCSSRulePositions(thisArg),\r\n index || 0,\r\n ],\r\n },\r\n ],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n removes: [\r\n { index: [...getNestedCSSRulePositions(thisArg), index] },\r\n ],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n });\r\n return callbackWrapper(() => {\r\n win.CSSStyleSheet.prototype.insertRule = insertRule;\r\n win.CSSStyleSheet.prototype.deleteRule = deleteRule;\r\n replace && (win.CSSStyleSheet.prototype.replace = replace);\r\n replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);\r\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\r\n type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\r\n type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\r\n });\r\n });\r\n}\r\nfunction initAdoptedStyleSheetObserver({ mirror, stylesheetManager, }, host) {\r\n let hostId = null;\r\n if (host.nodeName === '#document')\r\n hostId = mirror.getId(host);\r\n else\r\n hostId = mirror.getId(host.host);\r\n const patchTarget = host.nodeName === '#document'\r\n ? host.defaultView?.Document\r\n : host.ownerDocument?.defaultView?.ShadowRoot;\r\n const originalPropertyDescriptor = patchTarget?.prototype\r\n ? Object.getOwnPropertyDescriptor(patchTarget?.prototype, 'adoptedStyleSheets')\r\n : undefined;\r\n if (hostId === null ||\r\n hostId === -1 ||\r\n !patchTarget ||\r\n !originalPropertyDescriptor)\r\n return () => {\r\n };\r\n Object.defineProperty(host, 'adoptedStyleSheets', {\r\n configurable: originalPropertyDescriptor.configurable,\r\n enumerable: originalPropertyDescriptor.enumerable,\r\n get() {\r\n return originalPropertyDescriptor.get?.call(this);\r\n },\r\n set(sheets) {\r\n const result = originalPropertyDescriptor.set?.call(this, sheets);\r\n if (hostId !== null && hostId !== -1) {\r\n try {\r\n stylesheetManager.adoptStyleSheets(sheets, hostId);\r\n }\r\n catch (e) {\r\n }\r\n }\r\n return result;\r\n },\r\n });\r\n return callbackWrapper(() => {\r\n Object.defineProperty(host, 'adoptedStyleSheets', {\r\n configurable: originalPropertyDescriptor.configurable,\r\n enumerable: originalPropertyDescriptor.enumerable,\r\n get: originalPropertyDescriptor.get,\r\n set: originalPropertyDescriptor.set,\r\n });\r\n });\r\n}\r\nfunction initStyleDeclarationObserver({ styleDeclarationCb, mirror, ignoreCSSAttributes, stylesheetManager, }, { win }) {\r\n const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\r\n win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [property, value, priority] = argumentsList;\r\n if (ignoreCSSAttributes.has(property)) {\r\n return setProperty.apply(thisArg, [property, value, priority]);\r\n }\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentRule?.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleDeclarationCb({\r\n id,\r\n styleId,\r\n set: {\r\n property,\r\n value,\r\n priority,\r\n },\r\n index: getNestedCSSRulePositions(thisArg.parentRule),\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\r\n win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [property] = argumentsList;\r\n if (ignoreCSSAttributes.has(property)) {\r\n return removeProperty.apply(thisArg, [property]);\r\n }\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentRule?.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleDeclarationCb({\r\n id,\r\n styleId,\r\n remove: {\r\n property,\r\n },\r\n index: getNestedCSSRulePositions(thisArg.parentRule),\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n return callbackWrapper(() => {\r\n win.CSSStyleDeclaration.prototype.setProperty = setProperty;\r\n win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\r\n });\r\n}\r\nfunction initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, unblockSelector, mirror, sampling, doc, }) {\r\n const handler = callbackWrapper((type) => throttle(callbackWrapper((event) => {\r\n const target = getEventTarget(event);\r\n if (!target ||\r\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\r\n return;\r\n }\r\n const { currentTime, volume, muted, playbackRate } = target;\r\n mediaInteractionCb({\r\n type,\r\n id: mirror.getId(target),\r\n currentTime,\r\n volume,\r\n muted,\r\n playbackRate,\r\n });\r\n }), sampling.media || 500));\r\n const handlers = [\r\n on('play', handler(0), doc),\r\n on('pause', handler(1), doc),\r\n on('seeked', handler(2), doc),\r\n on('volumechange', handler(3), doc),\r\n on('ratechange', handler(4), doc),\r\n ];\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initFontObserver({ fontCb, doc }) {\r\n const win = doc.defaultView;\r\n if (!win) {\r\n return () => {\r\n };\r\n }\r\n const handlers = [];\r\n const fontMap = new WeakMap();\r\n const originalFontFace = win.FontFace;\r\n win.FontFace = function FontFace(family, source, descriptors) {\r\n const fontFace = new originalFontFace(family, source, descriptors);\r\n fontMap.set(fontFace, {\r\n family,\r\n buffer: typeof source !== 'string',\r\n descriptors,\r\n fontSource: typeof source === 'string'\r\n ? source\r\n : JSON.stringify(Array.from(new Uint8Array(source))),\r\n });\r\n return fontFace;\r\n };\r\n const restoreHandler = patch(doc.fonts, 'add', function (original) {\r\n return function (fontFace) {\r\n setTimeout(callbackWrapper(() => {\r\n const p = fontMap.get(fontFace);\r\n if (p) {\r\n fontCb(p);\r\n fontMap.delete(fontFace);\r\n }\r\n }), 0);\r\n return original.apply(this, [fontFace]);\r\n };\r\n });\r\n handlers.push(() => {\r\n win.FontFace = originalFontFace;\r\n });\r\n handlers.push(restoreHandler);\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initSelectionObserver(param) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, selectionCb, } = param;\r\n let collapsed = true;\r\n const updateSelection = callbackWrapper(() => {\r\n const selection = doc.getSelection();\r\n if (!selection || (collapsed && selection?.isCollapsed))\r\n return;\r\n collapsed = selection.isCollapsed || false;\r\n const ranges = [];\r\n const count = selection.rangeCount || 0;\r\n for (let i = 0; i < count; i++) {\r\n const range = selection.getRangeAt(i);\r\n const { startContainer, startOffset, endContainer, endOffset } = range;\r\n const blocked = isBlocked(startContainer, blockClass, blockSelector, unblockSelector, true) ||\r\n isBlocked(endContainer, blockClass, blockSelector, unblockSelector, true);\r\n if (blocked)\r\n continue;\r\n ranges.push({\r\n start: mirror.getId(startContainer),\r\n startOffset,\r\n end: mirror.getId(endContainer),\r\n endOffset,\r\n });\r\n }\r\n selectionCb({ ranges });\r\n });\r\n updateSelection();\r\n return on('selectionchange', updateSelection);\r\n}\r\nfunction initCustomElementObserver({ doc, customElementCb, }) {\r\n const win = doc.defaultView;\r\n if (!win || !win.customElements)\r\n return () => { };\r\n const restoreHandler = patch(win.customElements, 'define', function (original) {\r\n return function (name, constructor, options) {\r\n try {\r\n customElementCb({\r\n define: {\r\n name,\r\n },\r\n });\r\n }\r\n catch (e) {\r\n }\r\n return original.apply(this, [name, constructor, options]);\r\n };\r\n });\r\n return restoreHandler;\r\n}\r\nfunction initObservers(o, _hooks = {}) {\r\n const currentWindow = o.doc.defaultView;\r\n if (!currentWindow) {\r\n return () => {\r\n };\r\n }\r\n const mutationObserver = initMutationObserver(o, o.doc);\r\n const mousemoveHandler = initMoveObserver(o);\r\n const mouseInteractionHandler = initMouseInteractionObserver(o);\r\n const scrollHandler = initScrollObserver(o);\r\n const viewportResizeHandler = initViewportResizeObserver(o, {\r\n win: currentWindow,\r\n });\r\n const inputHandler = initInputObserver(o);\r\n const mediaInteractionHandler = initMediaInteractionObserver(o);\r\n const styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });\r\n const adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);\r\n const styleDeclarationObserver = initStyleDeclarationObserver(o, {\r\n win: currentWindow,\r\n });\r\n const fontObserver = o.collectFonts\r\n ? initFontObserver(o)\r\n : () => {\r\n };\r\n const selectionObserver = initSelectionObserver(o);\r\n const customElementObserver = initCustomElementObserver(o);\r\n const pluginHandlers = [];\r\n for (const plugin of o.plugins) {\r\n pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));\r\n }\r\n return callbackWrapper(() => {\r\n mutationBuffers.forEach((b) => b.reset());\r\n mutationObserver.disconnect();\r\n mousemoveHandler();\r\n mouseInteractionHandler();\r\n scrollHandler();\r\n viewportResizeHandler();\r\n inputHandler();\r\n mediaInteractionHandler();\r\n styleSheetObserver();\r\n adoptedStyleSheetObserver();\r\n styleDeclarationObserver();\r\n fontObserver();\r\n selectionObserver();\r\n customElementObserver();\r\n pluginHandlers.forEach((h) => h());\r\n });\r\n}\r\nfunction hasNestedCSSRule(prop) {\r\n return typeof window[prop] !== 'undefined';\r\n}\r\nfunction canMonkeyPatchNestedCSSRule(prop) {\r\n return Boolean(typeof window[prop] !== 'undefined' &&\r\n window[prop].prototype &&\r\n 'insertRule' in window[prop].prototype &&\r\n 'deleteRule' in window[prop].prototype);\r\n}\n\nexport { INPUT_TAGS, initAdoptedStyleSheetObserver, initMutationObserver, initObservers, initScrollObserver, mutationBuffers };\n","class CrossOriginIframeMirror {\r\n constructor(generateIdFn) {\r\n this.generateIdFn = generateIdFn;\r\n this.iframeIdToRemoteIdMap = new WeakMap();\r\n this.iframeRemoteIdToIdMap = new WeakMap();\r\n }\r\n getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {\r\n const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);\r\n const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);\r\n let id = idToRemoteIdMap.get(remoteId);\r\n if (!id) {\r\n id = this.generateIdFn();\r\n idToRemoteIdMap.set(remoteId, id);\r\n remoteIdToIdMap.set(id, remoteId);\r\n }\r\n return id;\r\n }\r\n getIds(iframe, remoteId) {\r\n const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);\r\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\r\n return remoteId.map((id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap));\r\n }\r\n getRemoteId(iframe, id, map) {\r\n const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);\r\n if (typeof id !== 'number')\r\n return id;\r\n const remoteId = remoteIdToIdMap.get(id);\r\n if (!remoteId)\r\n return -1;\r\n return remoteId;\r\n }\r\n getRemoteIds(iframe, ids) {\r\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\r\n return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));\r\n }\r\n reset(iframe) {\r\n if (!iframe) {\r\n this.iframeIdToRemoteIdMap = new WeakMap();\r\n this.iframeRemoteIdToIdMap = new WeakMap();\r\n return;\r\n }\r\n this.iframeIdToRemoteIdMap.delete(iframe);\r\n this.iframeRemoteIdToIdMap.delete(iframe);\r\n }\r\n getIdToRemoteIdMap(iframe) {\r\n let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);\r\n if (!idToRemoteIdMap) {\r\n idToRemoteIdMap = new Map();\r\n this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);\r\n }\r\n return idToRemoteIdMap;\r\n }\r\n getRemoteIdToIdMap(iframe) {\r\n let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);\r\n if (!remoteIdToIdMap) {\r\n remoteIdToIdMap = new Map();\r\n this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);\r\n }\r\n return remoteIdToIdMap;\r\n }\r\n}\n\nexport { CrossOriginIframeMirror as default };\n","import { genId, NodeType } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport CrossOriginIframeMirror from './cross-origin-iframe-mirror.js';\nimport { EventType, IncrementalSource } from '../../../types/dist/rrweb-types.js';\n\nclass IframeManagerNoop {\r\n constructor() {\r\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\r\n this.crossOriginIframeRootIdMap = new WeakMap();\r\n }\r\n addIframe() {\r\n }\r\n addLoadListener() {\r\n }\r\n attachIframe() {\r\n }\r\n}\r\nclass IframeManager {\r\n constructor(options) {\r\n this.iframes = new WeakMap();\r\n this.crossOriginIframeMap = new WeakMap();\r\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\r\n this.crossOriginIframeRootIdMap = new WeakMap();\r\n this.mutationCb = options.mutationCb;\r\n this.wrappedEmit = options.wrappedEmit;\r\n this.stylesheetManager = options.stylesheetManager;\r\n this.recordCrossOriginIframes = options.recordCrossOriginIframes;\r\n this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));\r\n this.mirror = options.mirror;\r\n if (this.recordCrossOriginIframes) {\r\n window.addEventListener('message', this.handleMessage.bind(this));\r\n }\r\n }\r\n addIframe(iframeEl) {\r\n this.iframes.set(iframeEl, true);\r\n if (iframeEl.contentWindow)\r\n this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);\r\n }\r\n addLoadListener(cb) {\r\n this.loadListener = cb;\r\n }\r\n attachIframe(iframeEl, childSn) {\r\n this.mutationCb({\r\n adds: [\r\n {\r\n parentId: this.mirror.getId(iframeEl),\r\n nextId: null,\r\n node: childSn,\r\n },\r\n ],\r\n removes: [],\r\n texts: [],\r\n attributes: [],\r\n isAttachIframe: true,\r\n });\r\n this.loadListener?.(iframeEl);\r\n if (iframeEl.contentDocument &&\r\n iframeEl.contentDocument.adoptedStyleSheets &&\r\n iframeEl.contentDocument.adoptedStyleSheets.length > 0)\r\n this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));\r\n }\r\n handleMessage(message) {\r\n const crossOriginMessageEvent = message;\r\n if (crossOriginMessageEvent.data.type !== 'rrweb' ||\r\n crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin)\r\n return;\r\n const iframeSourceWindow = message.source;\r\n if (!iframeSourceWindow)\r\n return;\r\n const iframeEl = this.crossOriginIframeMap.get(message.source);\r\n if (!iframeEl)\r\n return;\r\n const transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event);\r\n if (transformedEvent)\r\n this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout);\r\n }\r\n transformCrossOriginEvent(iframeEl, e) {\r\n switch (e.type) {\r\n case EventType.FullSnapshot: {\r\n this.crossOriginIframeMirror.reset(iframeEl);\r\n this.crossOriginIframeStyleMirror.reset(iframeEl);\r\n this.replaceIdOnNode(e.data.node, iframeEl);\r\n const rootId = e.data.node.id;\r\n this.crossOriginIframeRootIdMap.set(iframeEl, rootId);\r\n this.patchRootIdOnNode(e.data.node, rootId);\r\n return {\r\n timestamp: e.timestamp,\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Mutation,\r\n adds: [\r\n {\r\n parentId: this.mirror.getId(iframeEl),\r\n nextId: null,\r\n node: e.data.node,\r\n },\r\n ],\r\n removes: [],\r\n texts: [],\r\n attributes: [],\r\n isAttachIframe: true,\r\n },\r\n };\r\n }\r\n case EventType.Meta:\r\n case EventType.Load:\r\n case EventType.DomContentLoaded: {\r\n return false;\r\n }\r\n case EventType.Plugin: {\r\n return e;\r\n }\r\n case EventType.Custom: {\r\n this.replaceIds(e.data.payload, iframeEl, ['id', 'parentId', 'previousId', 'nextId']);\r\n return e;\r\n }\r\n case EventType.IncrementalSnapshot: {\r\n switch (e.data.source) {\r\n case IncrementalSource.Mutation: {\r\n e.data.adds.forEach((n) => {\r\n this.replaceIds(n, iframeEl, [\r\n 'parentId',\r\n 'nextId',\r\n 'previousId',\r\n ]);\r\n this.replaceIdOnNode(n.node, iframeEl);\r\n const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);\r\n rootId && this.patchRootIdOnNode(n.node, rootId);\r\n });\r\n e.data.removes.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['parentId', 'id']);\r\n });\r\n e.data.attributes.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['id']);\r\n });\r\n e.data.texts.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['id']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource.Drag:\r\n case IncrementalSource.TouchMove:\r\n case IncrementalSource.MouseMove: {\r\n e.data.positions.forEach((p) => {\r\n this.replaceIds(p, iframeEl, ['id']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource.ViewportResize: {\r\n return false;\r\n }\r\n case IncrementalSource.MediaInteraction:\r\n case IncrementalSource.MouseInteraction:\r\n case IncrementalSource.Scroll:\r\n case IncrementalSource.CanvasMutation:\r\n case IncrementalSource.Input: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n return e;\r\n }\r\n case IncrementalSource.StyleSheetRule:\r\n case IncrementalSource.StyleDeclaration: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n this.replaceStyleIds(e.data, iframeEl, ['styleId']);\r\n return e;\r\n }\r\n case IncrementalSource.Font: {\r\n return e;\r\n }\r\n case IncrementalSource.Selection: {\r\n e.data.ranges.forEach((range) => {\r\n this.replaceIds(range, iframeEl, ['start', 'end']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource.AdoptedStyleSheet: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n this.replaceStyleIds(e.data, iframeEl, ['styleIds']);\r\n e.data.styles?.forEach((style) => {\r\n this.replaceStyleIds(style, iframeEl, ['styleId']);\r\n });\r\n return e;\r\n }\r\n }\r\n }\r\n }\r\n return false;\r\n }\r\n replace(iframeMirror, obj, iframeEl, keys) {\r\n for (const key of keys) {\r\n if (!Array.isArray(obj[key]) && typeof obj[key] !== 'number')\r\n continue;\r\n if (Array.isArray(obj[key])) {\r\n obj[key] = iframeMirror.getIds(iframeEl, obj[key]);\r\n }\r\n else {\r\n obj[key] = iframeMirror.getId(iframeEl, obj[key]);\r\n }\r\n }\r\n return obj;\r\n }\r\n replaceIds(obj, iframeEl, keys) {\r\n return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);\r\n }\r\n replaceStyleIds(obj, iframeEl, keys) {\r\n return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);\r\n }\r\n replaceIdOnNode(node, iframeEl) {\r\n this.replaceIds(node, iframeEl, ['id', 'rootId']);\r\n if ('childNodes' in node) {\r\n node.childNodes.forEach((child) => {\r\n this.replaceIdOnNode(child, iframeEl);\r\n });\r\n }\r\n }\r\n patchRootIdOnNode(node, rootId) {\r\n if (node.type !== NodeType.Document && !node.rootId)\r\n node.rootId = rootId;\r\n if ('childNodes' in node) {\r\n node.childNodes.forEach((child) => {\r\n this.patchRootIdOnNode(child, rootId);\r\n });\r\n }\r\n }\r\n}\n\nexport { IframeManager, IframeManagerNoop };\n","import { createMirror, snapshot } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { initObservers, mutationBuffers } from './observer.js';\nimport { polyfill, on, nowTimestamp, getWindowWidth, getWindowHeight, getWindowScroll, isSerializedIframe, isSerializedStylesheet, hasShadowRoot } from '../utils.js';\nimport { EventType, IncrementalSource } from '../../../types/dist/rrweb-types.js';\nimport { IframeManagerNoop, IframeManager } from './iframe-manager.js';\nimport { ShadowDomManagerNoop, ShadowDomManager } from './shadow-dom-manager.js';\nimport { CanvasManagerNoop } from './observers/canvas/canvas-manager.js';\nexport { CanvasManager } from './observers/canvas/canvas-manager.js';\nimport { StylesheetManager } from './stylesheet-manager.js';\nimport ProcessedNodeManager from './processed-node-manager.js';\nimport { callbackWrapper, unregisterErrorHandler, registerErrorHandler } from './error-handler.js';\n\nlet wrappedEmit;\r\nlet _wrappedEmit;\r\nlet _takeFullSnapshot;\r\nconst mirror = createMirror();\r\nfunction record(options = {}) {\r\n const { emit, checkoutEveryNms, checkoutEveryNth, blockClass = 'rr-block', blockSelector = null, unblockSelector = null, ignoreClass = 'rr-ignore', ignoreSelector = null, maskAllText = false, maskTextClass = 'rr-mask', unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, maskAllInputs, maskInputOptions: _maskInputOptions, slimDOMOptions: _slimDOMOptions, maskAttributeFn, maskInputFn, maskTextFn, maxCanvasSize = null, packFn, sampling = {}, dataURLOptions = {}, mousemoveWait, recordCanvas = false, recordCrossOriginIframes = false, recordAfter = options.recordAfter === 'DOMContentLoaded'\r\n ? options.recordAfter\r\n : 'load', userTriggeredOnInput = false, collectFonts = false, inlineImages = false, plugins, keepIframeSrcFn = () => false, ignoreCSSAttributes = new Set([]), errorHandler, onMutation, getCanvasManager, } = options;\r\n registerErrorHandler(errorHandler);\r\n const inEmittingFrame = recordCrossOriginIframes\r\n ? window.parent === window\r\n : true;\r\n let passEmitsToParent = false;\r\n if (!inEmittingFrame) {\r\n try {\r\n if (window.parent.document) {\r\n passEmitsToParent = false;\r\n }\r\n }\r\n catch (e) {\r\n passEmitsToParent = true;\r\n }\r\n }\r\n if (inEmittingFrame && !emit) {\r\n throw new Error('emit function is required');\r\n }\r\n if (mousemoveWait !== undefined && sampling.mousemove === undefined) {\r\n sampling.mousemove = mousemoveWait;\r\n }\r\n mirror.reset();\r\n const maskInputOptions = maskAllInputs === true\r\n ? {\r\n color: true,\r\n date: true,\r\n 'datetime-local': true,\r\n email: true,\r\n month: true,\r\n number: true,\r\n range: true,\r\n search: true,\r\n tel: true,\r\n text: true,\r\n time: true,\r\n url: true,\r\n week: true,\r\n textarea: true,\r\n select: true,\r\n radio: true,\r\n checkbox: true,\r\n }\r\n : _maskInputOptions !== undefined\r\n ? _maskInputOptions\r\n : {};\r\n const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all'\r\n ? {\r\n script: true,\r\n comment: true,\r\n headFavicon: true,\r\n headWhitespace: true,\r\n headMetaSocial: true,\r\n headMetaRobots: true,\r\n headMetaHttpEquiv: true,\r\n headMetaVerification: true,\r\n headMetaAuthorship: _slimDOMOptions === 'all',\r\n headMetaDescKeywords: _slimDOMOptions === 'all',\r\n }\r\n : _slimDOMOptions\r\n ? _slimDOMOptions\r\n : {};\r\n polyfill();\r\n let lastFullSnapshotEvent;\r\n let incrementalSnapshotCount = 0;\r\n const eventProcessor = (e) => {\r\n for (const plugin of plugins || []) {\r\n if (plugin.eventProcessor) {\r\n e = plugin.eventProcessor(e);\r\n }\r\n }\r\n if (packFn &&\r\n !passEmitsToParent) {\r\n e = packFn(e);\r\n }\r\n return e;\r\n };\r\n wrappedEmit = (r, isCheckout) => {\r\n const e = r;\r\n e.timestamp = nowTimestamp();\r\n if (mutationBuffers[0]?.isFrozen() &&\r\n e.type !== EventType.FullSnapshot &&\r\n !(e.type === EventType.IncrementalSnapshot &&\r\n e.data.source === IncrementalSource.Mutation)) {\r\n mutationBuffers.forEach((buf) => buf.unfreeze());\r\n }\r\n if (inEmittingFrame) {\r\n emit?.(eventProcessor(e), isCheckout);\r\n }\r\n else if (passEmitsToParent) {\r\n const message = {\r\n type: 'rrweb',\r\n event: eventProcessor(e),\r\n origin: window.location.origin,\r\n isCheckout,\r\n };\r\n window.parent.postMessage(message, '*');\r\n }\r\n if (e.type === EventType.FullSnapshot) {\r\n lastFullSnapshotEvent = e;\r\n incrementalSnapshotCount = 0;\r\n }\r\n else if (e.type === EventType.IncrementalSnapshot) {\r\n if (e.data.source === IncrementalSource.Mutation &&\r\n e.data.isAttachIframe) {\r\n return;\r\n }\r\n incrementalSnapshotCount++;\r\n const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\r\n const exceedTime = checkoutEveryNms &&\r\n lastFullSnapshotEvent &&\r\n e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\r\n if (exceedCount || exceedTime) {\r\n takeFullSnapshot(true);\r\n }\r\n }\r\n };\r\n _wrappedEmit = wrappedEmit;\r\n const wrappedMutationEmit = (m) => {\r\n wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Mutation,\r\n ...m,\r\n },\r\n });\r\n };\r\n const wrappedScrollEmit = (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Scroll,\r\n ...p,\r\n },\r\n });\r\n const wrappedCanvasMutationEmit = (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.CanvasMutation,\r\n ...p,\r\n },\r\n });\r\n const wrappedAdoptedStyleSheetEmit = (a) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.AdoptedStyleSheet,\r\n ...a,\r\n },\r\n });\r\n const stylesheetManager = new StylesheetManager({\r\n mutationCb: wrappedMutationEmit,\r\n adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit,\r\n });\r\n const iframeManager = typeof __RRWEB_EXCLUDE_IFRAME__ === 'boolean' && __RRWEB_EXCLUDE_IFRAME__\r\n ? new IframeManagerNoop()\r\n : new IframeManager({\r\n mirror,\r\n mutationCb: wrappedMutationEmit,\r\n stylesheetManager: stylesheetManager,\r\n recordCrossOriginIframes,\r\n wrappedEmit,\r\n });\r\n for (const plugin of plugins || []) {\r\n if (plugin.getMirror)\r\n plugin.getMirror({\r\n nodeMirror: mirror,\r\n crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,\r\n crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror,\r\n });\r\n }\r\n const processedNodeManager = new ProcessedNodeManager();\r\n const canvasManager = _getCanvasManager(getCanvasManager, {\r\n mirror,\r\n win: window,\r\n mutationCb: (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.CanvasMutation,\r\n ...p,\r\n },\r\n }),\r\n recordCanvas,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maxCanvasSize,\r\n sampling: sampling['canvas'],\r\n dataURLOptions,\r\n errorHandler,\r\n });\r\n const shadowDomManager = typeof __RRWEB_EXCLUDE_SHADOW_DOM__ === 'boolean' &&\r\n __RRWEB_EXCLUDE_SHADOW_DOM__\r\n ? new ShadowDomManagerNoop()\r\n : new ShadowDomManager({\r\n mutationCb: wrappedMutationEmit,\r\n scrollCb: wrappedScrollEmit,\r\n bypassOptions: {\r\n onMutation,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n dataURLOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n recordCanvas,\r\n inlineImages,\r\n sampling,\r\n slimDOMOptions,\r\n iframeManager,\r\n stylesheetManager,\r\n canvasManager,\r\n keepIframeSrcFn,\r\n processedNodeManager,\r\n },\r\n mirror,\r\n });\r\n const takeFullSnapshot = (isCheckout = false) => {\r\n wrappedEmit({\r\n type: EventType.Meta,\r\n data: {\r\n href: window.location.href,\r\n width: getWindowWidth(),\r\n height: getWindowHeight(),\r\n },\r\n }, isCheckout);\r\n stylesheetManager.reset();\r\n shadowDomManager.init();\r\n mutationBuffers.forEach((buf) => buf.lock());\r\n const node = snapshot(document, {\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n inlineStylesheet,\r\n maskAllInputs: maskInputOptions,\r\n maskAttributeFn,\r\n maskInputFn,\r\n maskTextFn,\r\n slimDOM: slimDOMOptions,\r\n dataURLOptions,\r\n recordCanvas,\r\n inlineImages,\r\n onSerialize: (n) => {\r\n if (isSerializedIframe(n, mirror)) {\r\n iframeManager.addIframe(n);\r\n }\r\n if (isSerializedStylesheet(n, mirror)) {\r\n stylesheetManager.trackLinkElement(n);\r\n }\r\n if (hasShadowRoot(n)) {\r\n shadowDomManager.addShadowRoot(n.shadowRoot, document);\r\n }\r\n },\r\n onIframeLoad: (iframe, childSn) => {\r\n iframeManager.attachIframe(iframe, childSn);\r\n shadowDomManager.observeAttachShadow(iframe);\r\n },\r\n onStylesheetLoad: (linkEl, childSn) => {\r\n stylesheetManager.attachLinkElement(linkEl, childSn);\r\n },\r\n keepIframeSrcFn,\r\n });\r\n if (!node) {\r\n return console.warn('Failed to snapshot the document');\r\n }\r\n wrappedEmit({\r\n type: EventType.FullSnapshot,\r\n data: {\r\n node,\r\n initialOffset: getWindowScroll(window),\r\n },\r\n });\r\n mutationBuffers.forEach((buf) => buf.unlock());\r\n if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)\r\n stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));\r\n };\r\n _takeFullSnapshot = takeFullSnapshot;\r\n try {\r\n const handlers = [];\r\n const observe = (doc) => {\r\n return callbackWrapper(initObservers)({\r\n onMutation,\r\n mutationCb: wrappedMutationEmit,\r\n mousemoveCb: (positions, source) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source,\r\n positions,\r\n },\r\n }),\r\n mouseInteractionCb: (d) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.MouseInteraction,\r\n ...d,\r\n },\r\n }),\r\n scrollCb: wrappedScrollEmit,\r\n viewportResizeCb: (d) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.ViewportResize,\r\n ...d,\r\n },\r\n }),\r\n inputCb: (v) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Input,\r\n ...v,\r\n },\r\n }),\r\n mediaInteractionCb: (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.MediaInteraction,\r\n ...p,\r\n },\r\n }),\r\n styleSheetRuleCb: (r) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.StyleSheetRule,\r\n ...r,\r\n },\r\n }),\r\n styleDeclarationCb: (r) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.StyleDeclaration,\r\n ...r,\r\n },\r\n }),\r\n canvasMutationCb: wrappedCanvasMutationEmit,\r\n fontCb: (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Font,\r\n ...p,\r\n },\r\n }),\r\n selectionCb: (p) => {\r\n wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Selection,\r\n ...p,\r\n },\r\n });\r\n },\r\n customElementCb: (c) => {\r\n wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.CustomElement,\r\n ...c,\r\n },\r\n });\r\n },\r\n blockClass,\r\n ignoreClass,\r\n ignoreSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n maskInputOptions,\r\n inlineStylesheet,\r\n sampling,\r\n recordCanvas,\r\n inlineImages,\r\n userTriggeredOnInput,\r\n collectFonts,\r\n doc,\r\n maskAttributeFn,\r\n maskInputFn,\r\n maskTextFn,\r\n keepIframeSrcFn,\r\n blockSelector,\r\n unblockSelector,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n mirror,\r\n iframeManager,\r\n stylesheetManager,\r\n shadowDomManager,\r\n processedNodeManager,\r\n canvasManager,\r\n ignoreCSSAttributes,\r\n plugins: plugins\r\n ?.filter((p) => p.observer)\r\n ?.map((p) => ({\r\n observer: p.observer,\r\n options: p.options,\r\n callback: (payload) => wrappedEmit({\r\n type: EventType.Plugin,\r\n data: {\r\n plugin: p.name,\r\n payload,\r\n },\r\n }),\r\n })) || [],\r\n }, {});\r\n };\r\n iframeManager.addLoadListener((iframeEl) => {\r\n try {\r\n handlers.push(observe(iframeEl.contentDocument));\r\n }\r\n catch (error) {\r\n console.warn(error);\r\n }\r\n });\r\n const init = () => {\r\n takeFullSnapshot();\r\n handlers.push(observe(document));\r\n };\r\n if (document.readyState === 'interactive' ||\r\n document.readyState === 'complete') {\r\n init();\r\n }\r\n else {\r\n handlers.push(on('DOMContentLoaded', () => {\r\n wrappedEmit({\r\n type: EventType.DomContentLoaded,\r\n data: {},\r\n });\r\n if (recordAfter === 'DOMContentLoaded')\r\n init();\r\n }));\r\n handlers.push(on('load', () => {\r\n wrappedEmit({\r\n type: EventType.Load,\r\n data: {},\r\n });\r\n if (recordAfter === 'load')\r\n init();\r\n }, window));\r\n }\r\n return () => {\r\n handlers.forEach((h) => h());\r\n processedNodeManager.destroy();\r\n _takeFullSnapshot = undefined;\r\n unregisterErrorHandler();\r\n };\r\n }\r\n catch (error) {\r\n console.warn(error);\r\n }\r\n}\r\nfunction addCustomEvent(tag, payload) {\r\n if (!_wrappedEmit) {\r\n throw new Error('please add custom event after start recording');\r\n }\r\n wrappedEmit({\r\n type: EventType.Custom,\r\n data: {\r\n tag,\r\n payload,\r\n },\r\n });\r\n}\r\nfunction freezePage() {\r\n mutationBuffers.forEach((buf) => buf.freeze());\r\n}\r\nfunction takeFullSnapshot(isCheckout) {\r\n if (!_takeFullSnapshot) {\r\n throw new Error('please take full snapshot after start recording');\r\n }\r\n _takeFullSnapshot(isCheckout);\r\n}\r\nrecord.mirror = mirror;\r\nrecord.takeFullSnapshot = takeFullSnapshot;\r\nfunction _getCanvasManager(getCanvasManagerFn, options) {\r\n try {\r\n return getCanvasManagerFn\r\n ? getCanvasManagerFn(options)\r\n : new CanvasManagerNoop();\r\n }\r\n catch {\r\n console.warn('Unable to initialize CanvasManager');\r\n return new CanvasManagerNoop();\r\n }\r\n}\n\nexport { addCustomEvent, record as default, freezePage, mirror, takeFullSnapshot };\n","import { initMutationObserver, initScrollObserver, initAdoptedStyleSheetObserver } from './observer.js';\nimport { setTimeout, patch, inDom } from '../utils.js';\nimport { isNativeShadowDom } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\n\nclass ShadowDomManagerNoop {\r\n init() {\r\n }\r\n addShadowRoot() {\r\n }\r\n observeAttachShadow() {\r\n }\r\n reset() {\r\n }\r\n}\r\nclass ShadowDomManager {\r\n constructor(options) {\r\n this.shadowDoms = new WeakSet();\r\n this.restoreHandlers = [];\r\n this.mutationCb = options.mutationCb;\r\n this.scrollCb = options.scrollCb;\r\n this.bypassOptions = options.bypassOptions;\r\n this.mirror = options.mirror;\r\n this.init();\r\n }\r\n init() {\r\n this.reset();\r\n this.patchAttachShadow(Element, document);\r\n }\r\n addShadowRoot(shadowRoot, doc) {\r\n if (!isNativeShadowDom(shadowRoot))\r\n return;\r\n if (this.shadowDoms.has(shadowRoot))\r\n return;\r\n this.shadowDoms.add(shadowRoot);\r\n const observer = initMutationObserver({\r\n ...this.bypassOptions,\r\n doc,\r\n mutationCb: this.mutationCb,\r\n mirror: this.mirror,\r\n shadowDomManager: this,\r\n }, shadowRoot);\r\n this.restoreHandlers.push(() => observer.disconnect());\r\n this.restoreHandlers.push(initScrollObserver({\r\n ...this.bypassOptions,\r\n scrollCb: this.scrollCb,\r\n doc: shadowRoot,\r\n mirror: this.mirror,\r\n }));\r\n setTimeout(() => {\r\n if (shadowRoot.adoptedStyleSheets &&\r\n shadowRoot.adoptedStyleSheets.length > 0)\r\n this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets, this.mirror.getId(shadowRoot.host));\r\n this.restoreHandlers.push(initAdoptedStyleSheetObserver({\r\n mirror: this.mirror,\r\n stylesheetManager: this.bypassOptions.stylesheetManager,\r\n }, shadowRoot));\r\n }, 0);\r\n }\r\n observeAttachShadow(iframeElement) {\r\n if (!iframeElement.contentWindow || !iframeElement.contentDocument)\r\n return;\r\n this.patchAttachShadow(iframeElement.contentWindow.Element, iframeElement.contentDocument);\r\n }\r\n patchAttachShadow(element, doc) {\r\n const manager = this;\r\n this.restoreHandlers.push(patch(element.prototype, 'attachShadow', function (original) {\r\n return function (option) {\r\n const shadowRoot = original.call(this, option);\r\n if (this.shadowRoot && inDom(this))\r\n manager.addShadowRoot(this.shadowRoot, doc);\r\n return shadowRoot;\r\n };\r\n }));\r\n }\r\n reset() {\r\n this.restoreHandlers.forEach((handler) => {\r\n try {\r\n handler();\r\n }\r\n catch (e) {\r\n }\r\n });\r\n this.restoreHandlers = [];\r\n this.shadowDoms = new WeakSet();\r\n }\r\n}\n\nexport { ShadowDomManager, ShadowDomManagerNoop };\n","import { onRequestAnimationFrame, isBlocked } from '../../../utils.js';\nimport { CanvasContext } from '../../../../../types/dist/rrweb-types.js';\nimport initCanvas2DMutationObserver from './2d.js';\nimport initCanvasContextObserver from './canvas.js';\nimport initCanvasWebGLMutationObserver from './webgl.js';\nimport { getImageBitmapDataUrlWorkerURL as t } from '../../../../../rrweb-worker/es/rrweb-worker/index.js';\nimport { callbackWrapper, registerErrorHandler } from '../../error-handler.js';\n\nclass CanvasManagerNoop {\r\n reset() {\r\n }\r\n freeze() {\r\n }\r\n unfreeze() {\r\n }\r\n lock() {\r\n }\r\n unlock() {\r\n }\r\n snapshot() {\r\n }\r\n}\r\nclass CanvasManager {\r\n reset() {\r\n this.pendingCanvasMutations.clear();\r\n this.resetObservers && this.resetObservers();\r\n }\r\n freeze() {\r\n this.frozen = true;\r\n }\r\n unfreeze() {\r\n this.frozen = false;\r\n }\r\n lock() {\r\n this.locked = true;\r\n }\r\n unlock() {\r\n this.locked = false;\r\n }\r\n constructor(options) {\r\n this.pendingCanvasMutations = new Map();\r\n this.rafStamps = { latestId: 0, invokeId: null };\r\n this.frozen = false;\r\n this.locked = false;\r\n this.processMutation = (target, mutation) => {\r\n const newFrame = this.rafStamps.invokeId &&\r\n this.rafStamps.latestId !== this.rafStamps.invokeId;\r\n if (newFrame || !this.rafStamps.invokeId)\r\n this.rafStamps.invokeId = this.rafStamps.latestId;\r\n if (!this.pendingCanvasMutations.has(target)) {\r\n this.pendingCanvasMutations.set(target, []);\r\n }\r\n this.pendingCanvasMutations.get(target).push(mutation);\r\n };\r\n const { sampling = 'all', win, blockClass, blockSelector, unblockSelector, maxCanvasSize, recordCanvas, dataURLOptions, errorHandler, } = options;\r\n this.mutationCb = options.mutationCb;\r\n this.mirror = options.mirror;\r\n this.options = options;\r\n if (errorHandler) {\r\n registerErrorHandler(errorHandler);\r\n }\r\n if (options.enableManualSnapshot) {\r\n return;\r\n }\r\n callbackWrapper(() => {\r\n if (recordCanvas && sampling === 'all')\r\n this.initCanvasMutationObserver(win, blockClass, blockSelector, unblockSelector);\r\n if (recordCanvas && typeof sampling === 'number')\r\n this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, {\r\n dataURLOptions,\r\n });\r\n })();\r\n }\r\n initCanvasFPSObserver(fps, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, options) {\r\n const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, true);\r\n const rafId = this.takeSnapshot(false, fps, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, options.dataURLOptions);\r\n this.resetObservers = () => {\r\n canvasContextReset();\r\n cancelAnimationFrame(rafId);\r\n };\r\n }\r\n initCanvasMutationObserver(win, blockClass, blockSelector, unblockSelector) {\r\n this.startRAFTimestamping();\r\n this.startPendingCanvasMutationFlusher();\r\n const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, false);\r\n const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector);\r\n const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector, this.mirror);\r\n this.resetObservers = () => {\r\n canvasContextReset();\r\n canvas2DReset();\r\n canvasWebGL1and2Reset();\r\n };\r\n }\r\n snapshot(canvasElement) {\r\n const { options } = this;\r\n const rafId = this.takeSnapshot(true, options.sampling === 'all' ? 2 : options.sampling || 2, options.win, options.blockClass, options.blockSelector, options.unblockSelector, options.maxCanvasSize, options.dataURLOptions, canvasElement);\r\n this.resetObservers = () => {\r\n cancelAnimationFrame(rafId);\r\n };\r\n }\r\n takeSnapshot(isManualSnapshot, fps, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, dataURLOptions, canvasElement) {\r\n const snapshotInProgressMap = new Map();\r\n const worker = new Worker(t());\r\n worker.onmessage = (e) => {\r\n const data = e.data;\r\n const { id } = data;\r\n snapshotInProgressMap.set(id, false);\r\n if (!('base64' in data))\r\n return;\r\n const { base64, type, width, height } = data;\r\n this.mutationCb({\r\n id,\r\n type: CanvasContext['2D'],\r\n commands: [\r\n {\r\n property: 'clearRect',\r\n args: [0, 0, width, height],\r\n },\r\n {\r\n property: 'drawImage',\r\n args: [\r\n {\r\n rr_type: 'ImageBitmap',\r\n args: [\r\n {\r\n rr_type: 'Blob',\r\n data: [{ rr_type: 'ArrayBuffer', base64 }],\r\n type,\r\n },\r\n ],\r\n },\r\n 0,\r\n 0,\r\n width,\r\n height,\r\n ],\r\n },\r\n ],\r\n });\r\n };\r\n const timeBetweenSnapshots = 1000 / fps;\r\n let lastSnapshotTime = 0;\r\n let rafId;\r\n const getCanvas = (canvasElement) => {\r\n if (canvasElement) {\r\n return [canvasElement];\r\n }\r\n const matchedCanvas = [];\r\n win.document.querySelectorAll('canvas').forEach((canvas) => {\r\n if (!isBlocked(canvas, blockClass, blockSelector, unblockSelector, true)) {\r\n matchedCanvas.push(canvas);\r\n }\r\n });\r\n return matchedCanvas;\r\n };\r\n const takeCanvasSnapshots = (timestamp) => {\r\n if (lastSnapshotTime &&\r\n timestamp - lastSnapshotTime < timeBetweenSnapshots) {\r\n rafId = onRequestAnimationFrame(takeCanvasSnapshots);\r\n return;\r\n }\r\n lastSnapshotTime = timestamp;\r\n getCanvas(canvasElement).forEach((canvas) => {\r\n const id = this.mirror.getId(canvas);\r\n if (snapshotInProgressMap.get(id))\r\n return;\r\n if (!canvas.width || !canvas.height)\r\n return;\r\n snapshotInProgressMap.set(id, true);\r\n if (!isManualSnapshot &&\r\n ['webgl', 'webgl2'].includes(canvas.__context)) {\r\n const context = canvas.getContext(canvas.__context);\r\n if (context?.getContextAttributes()?.preserveDrawingBuffer === false) {\r\n context.clear(context.COLOR_BUFFER_BIT);\r\n }\r\n }\r\n createImageBitmap(canvas)\r\n .then((bitmap) => {\r\n worker.postMessage({\r\n id,\r\n bitmap,\r\n width: canvas.width,\r\n height: canvas.height,\r\n dataURLOptions,\r\n maxCanvasSize,\r\n }, [bitmap]);\r\n })\r\n .catch((error) => {\r\n callbackWrapper(() => {\r\n throw error;\r\n })();\r\n });\r\n });\r\n rafId = onRequestAnimationFrame(takeCanvasSnapshots);\r\n };\r\n rafId = onRequestAnimationFrame(takeCanvasSnapshots);\r\n return rafId;\r\n }\r\n startPendingCanvasMutationFlusher() {\r\n onRequestAnimationFrame(() => this.flushPendingCanvasMutations());\r\n }\r\n startRAFTimestamping() {\r\n const setLatestRAFTimestamp = (timestamp) => {\r\n this.rafStamps.latestId = timestamp;\r\n onRequestAnimationFrame(setLatestRAFTimestamp);\r\n };\r\n onRequestAnimationFrame(setLatestRAFTimestamp);\r\n }\r\n flushPendingCanvasMutations() {\r\n this.pendingCanvasMutations.forEach((values, canvas) => {\r\n const id = this.mirror.getId(canvas);\r\n this.flushPendingCanvasMutationFor(canvas, id);\r\n });\r\n onRequestAnimationFrame(() => this.flushPendingCanvasMutations());\r\n }\r\n flushPendingCanvasMutationFor(canvas, id) {\r\n if (this.frozen || this.locked) {\r\n return;\r\n }\r\n const valuesWithType = this.pendingCanvasMutations.get(canvas);\r\n if (!valuesWithType || id === -1)\r\n return;\r\n const values = valuesWithType.map((value) => {\r\n const { type, ...rest } = value;\r\n return rest;\r\n });\r\n const { type } = valuesWithType[0];\r\n this.mutationCb({ id, type, commands: values });\r\n this.pendingCanvasMutations.delete(canvas);\r\n }\r\n}\n\nexport { CanvasManager, CanvasManagerNoop };\n","import { stringifyRule } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { StyleSheetMirror } from '../utils.js';\n\nclass StylesheetManager {\r\n constructor(options) {\r\n this.trackedLinkElements = new WeakSet();\r\n this.styleMirror = new StyleSheetMirror();\r\n this.mutationCb = options.mutationCb;\r\n this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;\r\n }\r\n attachLinkElement(linkEl, childSn) {\r\n if ('_cssText' in childSn.attributes)\r\n this.mutationCb({\r\n adds: [],\r\n removes: [],\r\n texts: [],\r\n attributes: [\r\n {\r\n id: childSn.id,\r\n attributes: childSn\r\n .attributes,\r\n },\r\n ],\r\n });\r\n this.trackLinkElement(linkEl);\r\n }\r\n trackLinkElement(linkEl) {\r\n if (this.trackedLinkElements.has(linkEl))\r\n return;\r\n this.trackedLinkElements.add(linkEl);\r\n this.trackStylesheetInLinkElement(linkEl);\r\n }\r\n adoptStyleSheets(sheets, hostId) {\r\n if (sheets.length === 0)\r\n return;\r\n const adoptedStyleSheetData = {\r\n id: hostId,\r\n styleIds: [],\r\n };\r\n const styles = [];\r\n for (const sheet of sheets) {\r\n let styleId;\r\n if (!this.styleMirror.has(sheet)) {\r\n styleId = this.styleMirror.add(sheet);\r\n styles.push({\r\n styleId,\r\n rules: Array.from(sheet.rules || CSSRule, (r, index) => ({\r\n rule: stringifyRule(r),\r\n index,\r\n })),\r\n });\r\n }\r\n else\r\n styleId = this.styleMirror.getId(sheet);\r\n adoptedStyleSheetData.styleIds.push(styleId);\r\n }\r\n if (styles.length > 0)\r\n adoptedStyleSheetData.styles = styles;\r\n this.adoptedStyleSheetCb(adoptedStyleSheetData);\r\n }\r\n reset() {\r\n this.styleMirror.reset();\r\n this.trackedLinkElements = new WeakSet();\r\n }\r\n trackStylesheetInLinkElement(linkEl) {\r\n }\r\n}\n\nexport { StylesheetManager };\n","import { onRequestAnimationFrame } from '../utils.js';\n\nclass ProcessedNodeManager {\r\n constructor() {\r\n this.nodeMap = new WeakMap();\r\n this.loop = true;\r\n this.periodicallyClear();\r\n }\r\n periodicallyClear() {\r\n onRequestAnimationFrame(() => {\r\n this.clear();\r\n if (this.loop)\r\n this.periodicallyClear();\r\n });\r\n }\r\n inOtherBuffer(node, thisBuffer) {\r\n const buffers = this.nodeMap.get(node);\r\n return (buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer));\r\n }\r\n add(node, buffer) {\r\n this.nodeMap.set(node, (this.nodeMap.get(node) || new Set()).add(buffer));\r\n }\r\n clear() {\r\n this.nodeMap = new WeakMap();\r\n }\r\n destroy() {\r\n this.loop = false;\r\n }\r\n}\n\nexport { ProcessedNodeManager as default };\n","type ClassOption = string | RegExp;\n\n/** Duplicate this from @sentry-internal/rrweb so we can export this as well. */\nexport const ReplayEventTypeDomContentLoaded = 0;\nexport const ReplayEventTypeLoad = 1;\nexport const ReplayEventTypeFullSnapshot = 2;\nexport const ReplayEventTypeIncrementalSnapshot = 3;\nexport const ReplayEventTypeMeta = 4;\nexport const ReplayEventTypeCustom = 5;\nexport const ReplayEventTypePlugin = 6;\n\nexport type ReplayEventType =\n | typeof ReplayEventTypeDomContentLoaded\n | typeof ReplayEventTypeLoad\n | typeof ReplayEventTypeFullSnapshot\n | typeof ReplayEventTypeIncrementalSnapshot\n | typeof ReplayEventTypeMeta\n | typeof ReplayEventTypeCustom\n | typeof ReplayEventTypePlugin;\n\n/**\n * This is a partial copy of rrweb's eventWithTime type which only contains the properties\n * we specifcally need in the SDK.\n */\nexport type ReplayEventWithTime = {\n type: ReplayEventType;\n data: unknown;\n timestamp: number;\n delay?: number;\n};\n\n/**\n * This is a partial copy of rrweb's recording options which only contains the properties\n * we specifically us in the SDK. Users can specify additional properties, hence we add the\n * Record union type.\n */\nexport type RrwebRecordOptions = {\n maskAllText?: boolean;\n maskAllInputs?: boolean;\n blockClass?: ClassOption;\n ignoreClass?: string;\n maskTextClass?: ClassOption;\n maskTextSelector?: string;\n blockSelector?: string;\n maskInputOptions?: Record;\n} & Record;\n\nexport interface CanvasManagerInterface {\n reset(): void;\n freeze(): void;\n unfreeze(): void;\n lock(): void;\n unlock(): void;\n snapshot(): void;\n}\n\nexport interface CanvasManagerOptions {\n recordCanvas: boolean;\n enableManualSnapshot?: boolean;\n blockClass: string | RegExp;\n blockSelector: string | null;\n unblockSelector: string | null;\n sampling?: 'all' | number;\n dataURLOptions: Partial<{\n type: string;\n quality: number;\n }>;\n mutationCb: (p: any) => void;\n win: typeof globalThis & Window;\n mirror: any;\n}\n","/**\n * Converts a timestamp to ms, if it was in s, or keeps it as ms.\n */\nexport function timestampToMs(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp : timestamp * 1000;\n}\n\n/**\n * Converts a timestamp to s, if it was in ms, or keeps it as s.\n */\nexport function timestampToS(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n","import { EventType } from '@sentry-internal/rrweb';\nimport type { Breadcrumb } from '@sentry/types';\nimport { normalize } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../../types';\n\n/**\n * Add a breadcrumb event to replay.\n */\nexport function addBreadcrumbEvent(replay: ReplayContainer, breadcrumb: Breadcrumb): void {\n if (breadcrumb.category === 'sentry.transaction') {\n return;\n }\n\n if (['ui.click', 'ui.input'].includes(breadcrumb.category as string)) {\n replay.triggerUserActivity();\n } else {\n replay.checkAndHandleExpiredSession();\n }\n\n replay.addUpdate(() => {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.throttledAddEvent({\n type: EventType.Custom,\n // TODO: We were converting from ms to seconds for breadcrumbs, spans,\n // but maybe we should just keep them as milliseconds\n timestamp: (breadcrumb.timestamp || 0) * 1000,\n data: {\n tag: 'breadcrumb',\n // normalize to max. 10 depth and 1_000 properties per object\n payload: normalize(breadcrumb, 10, 1_000),\n },\n });\n\n // Do not flush after console log messages\n return breadcrumb.category === 'console';\n });\n}\n","import type { INode } from '@sentry-internal/rrweb-snapshot';\n\nconst INTERACTIVE_SELECTOR = 'button,a';\n\n/** Get the closest interactive parent element, or else return the given element. */\nexport function getClosestInteractive(element: Element): Element {\n const closestInteractive = element.closest(INTERACTIVE_SELECTOR);\n return closestInteractive || element;\n}\n\n/**\n * For clicks, we check if the target is inside of a button or link\n * If so, we use this as the target instead\n * This is useful because if you click on the image in ,\n * The target will be the image, not the button, which we don't want here\n */\nexport function getClickTargetNode(event: Event | MouseEvent | Node): Node | INode | null {\n const target = getTargetNode(event);\n\n if (!target || !(target instanceof Element)) {\n return target;\n }\n\n return getClosestInteractive(target);\n}\n\n/** Get the event target node. */\nexport function getTargetNode(event: Node | { target: EventTarget | null }): Node | INode | null {\n if (isEventWithTarget(event)) {\n return event.target as Node | null;\n }\n\n return event;\n}\n\nfunction isEventWithTarget(event: unknown): event is { target: EventTarget | null } {\n return typeof event === 'object' && !!event && 'target' in event;\n}\n","import { fill } from '@sentry/utils';\n\nimport { WINDOW } from '../../constants';\n\ntype WindowOpenHandler = () => void;\n\nlet handlers: undefined | WindowOpenHandler[];\n\n/**\n * Register a handler to be called when `window.open()` is called.\n * Returns a cleanup function.\n */\nexport function onWindowOpen(cb: WindowOpenHandler): () => void {\n // Ensure to only register this once\n if (!handlers) {\n handlers = [];\n monkeyPatchWindowOpen();\n }\n\n handlers.push(cb);\n\n return () => {\n const pos = handlers ? handlers.indexOf(cb) : -1;\n if (pos > -1) {\n (handlers as WindowOpenHandler[]).splice(pos, 1);\n }\n };\n}\n\nfunction monkeyPatchWindowOpen(): void {\n fill(WINDOW, 'open', function (originalWindowOpen: () => void): () => void {\n return function (...args: unknown[]): void {\n if (handlers) {\n try {\n handlers.forEach(handler => handler());\n } catch (e) {\n // ignore errors in here\n }\n }\n\n return originalWindowOpen.apply(WINDOW, args);\n };\n });\n}\n","import { IncrementalSource, MouseInteractions, record } from '@sentry-internal/rrweb';\nimport type { Breadcrumb } from '@sentry/types';\n\nimport { WINDOW } from '../constants';\nimport type {\n RecordingEvent,\n ReplayClickDetector,\n ReplayContainer,\n ReplayMultiClickFrame,\n ReplaySlowClickFrame,\n SlowClickConfig,\n} from '../types';\nimport { ReplayEventTypeIncrementalSnapshot } from '../types';\nimport { timestampToS } from '../util/timestamp';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\nimport { getClosestInteractive } from './util/domUtils';\nimport { onWindowOpen } from './util/onWindowOpen';\n\ntype ClickBreadcrumb = Breadcrumb & {\n timestamp: number;\n};\n\ninterface Click {\n timestamp: number;\n mutationAfter?: number;\n scrollAfter?: number;\n clickBreadcrumb: ClickBreadcrumb;\n clickCount: number;\n node: HTMLElement;\n}\n\ntype IncrementalRecordingEvent = RecordingEvent & {\n type: typeof ReplayEventTypeIncrementalSnapshot;\n data: { source: IncrementalSource };\n};\n\ntype IncrementalMouseInteractionRecordingEvent = IncrementalRecordingEvent & {\n type: typeof ReplayEventTypeIncrementalSnapshot;\n data: { type: MouseInteractions; id: number };\n};\n\n/** Handle a click. */\nexport function handleClick(clickDetector: ReplayClickDetector, clickBreadcrumb: Breadcrumb, node: HTMLElement): void {\n clickDetector.handleClick(clickBreadcrumb, node);\n}\n\n/** A click detector class that can be used to detect slow or rage clicks on elements. */\nexport class ClickDetector implements ReplayClickDetector {\n // protected for testing\n protected _lastMutation: number;\n protected _lastScroll: number;\n\n private _clicks: Click[];\n private _teardown: undefined | (() => void);\n\n private _threshold: number;\n private _scollTimeout: number;\n private _timeout: number;\n private _ignoreSelector: string;\n\n private _replay: ReplayContainer;\n private _checkClickTimeout?: ReturnType;\n private _addBreadcrumbEvent: typeof addBreadcrumbEvent;\n\n public constructor(\n replay: ReplayContainer,\n slowClickConfig: SlowClickConfig,\n // Just for easier testing\n _addBreadcrumbEvent = addBreadcrumbEvent,\n ) {\n this._lastMutation = 0;\n this._lastScroll = 0;\n this._clicks = [];\n\n // We want everything in s, but options are in ms\n this._timeout = slowClickConfig.timeout / 1000;\n this._threshold = slowClickConfig.threshold / 1000;\n this._scollTimeout = slowClickConfig.scrollTimeout / 1000;\n this._replay = replay;\n this._ignoreSelector = slowClickConfig.ignoreSelector;\n this._addBreadcrumbEvent = _addBreadcrumbEvent;\n }\n\n /** Register click detection handlers on mutation or scroll. */\n public addListeners(): void {\n const cleanupWindowOpen = onWindowOpen(() => {\n // Treat window.open as mutation\n this._lastMutation = nowInSeconds();\n });\n\n this._teardown = () => {\n cleanupWindowOpen();\n\n this._clicks = [];\n this._lastMutation = 0;\n this._lastScroll = 0;\n };\n }\n\n /** Clean up listeners. */\n public removeListeners(): void {\n if (this._teardown) {\n this._teardown();\n }\n\n if (this._checkClickTimeout) {\n clearTimeout(this._checkClickTimeout);\n }\n }\n\n /** @inheritDoc */\n public handleClick(breadcrumb: Breadcrumb, node: HTMLElement): void {\n if (ignoreElement(node, this._ignoreSelector) || !isClickBreadcrumb(breadcrumb)) {\n return;\n }\n\n const newClick: Click = {\n timestamp: timestampToS(breadcrumb.timestamp),\n clickBreadcrumb: breadcrumb,\n // Set this to 0 so we know it originates from the click breadcrumb\n clickCount: 0,\n node,\n };\n\n // If there was a click in the last 1s on the same element, ignore it - only keep a single reference per second\n if (\n this._clicks.some(click => click.node === newClick.node && Math.abs(click.timestamp - newClick.timestamp) < 1)\n ) {\n return;\n }\n\n this._clicks.push(newClick);\n\n // If this is the first new click, set a timeout to check for multi clicks\n if (this._clicks.length === 1) {\n this._scheduleCheckClicks();\n }\n }\n\n /** @inheritDoc */\n public registerMutation(timestamp = Date.now()): void {\n this._lastMutation = timestampToS(timestamp);\n }\n\n /** @inheritDoc */\n public registerScroll(timestamp = Date.now()): void {\n this._lastScroll = timestampToS(timestamp);\n }\n\n /** @inheritDoc */\n public registerClick(element: HTMLElement): void {\n const node = getClosestInteractive(element);\n this._handleMultiClick(node as HTMLElement);\n }\n\n /** Count multiple clicks on elements. */\n private _handleMultiClick(node: HTMLElement): void {\n this._getClicks(node).forEach(click => {\n click.clickCount++;\n });\n }\n\n /** Get all pending clicks for a given node. */\n private _getClicks(node: HTMLElement): Click[] {\n return this._clicks.filter(click => click.node === node);\n }\n\n /** Check the clicks that happened. */\n private _checkClicks(): void {\n const timedOutClicks: Click[] = [];\n\n const now = nowInSeconds();\n\n this._clicks.forEach(click => {\n if (!click.mutationAfter && this._lastMutation) {\n click.mutationAfter = click.timestamp <= this._lastMutation ? this._lastMutation - click.timestamp : undefined;\n }\n if (!click.scrollAfter && this._lastScroll) {\n click.scrollAfter = click.timestamp <= this._lastScroll ? this._lastScroll - click.timestamp : undefined;\n }\n\n // All of these are in seconds!\n if (click.timestamp + this._timeout <= now) {\n timedOutClicks.push(click);\n }\n });\n\n // Remove \"old\" clicks\n for (const click of timedOutClicks) {\n const pos = this._clicks.indexOf(click);\n\n if (pos > -1) {\n this._generateBreadcrumbs(click);\n this._clicks.splice(pos, 1);\n }\n }\n\n // Trigger new check, unless no clicks left\n if (this._clicks.length) {\n this._scheduleCheckClicks();\n }\n }\n\n /** Generate matching breadcrumb(s) for the click. */\n private _generateBreadcrumbs(click: Click): void {\n const replay = this._replay;\n const hadScroll = click.scrollAfter && click.scrollAfter <= this._scollTimeout;\n const hadMutation = click.mutationAfter && click.mutationAfter <= this._threshold;\n\n const isSlowClick = !hadScroll && !hadMutation;\n const { clickCount, clickBreadcrumb } = click;\n\n // Slow click\n if (isSlowClick) {\n // If `mutationAfter` is set, it means a mutation happened after the threshold, but before the timeout\n // If not, it means we just timed out without scroll & mutation\n const timeAfterClickMs = Math.min(click.mutationAfter || this._timeout, this._timeout) * 1000;\n const endReason = timeAfterClickMs < this._timeout * 1000 ? 'mutation' : 'timeout';\n\n const breadcrumb: ReplaySlowClickFrame = {\n type: 'default',\n message: clickBreadcrumb.message,\n timestamp: clickBreadcrumb.timestamp,\n category: 'ui.slowClickDetected',\n data: {\n ...clickBreadcrumb.data,\n url: WINDOW.location.href,\n route: replay.getCurrentRoute(),\n timeAfterClickMs,\n endReason,\n // If clickCount === 0, it means multiClick was not correctly captured here\n // - we still want to send 1 in this case\n clickCount: clickCount || 1,\n },\n };\n\n this._addBreadcrumbEvent(replay, breadcrumb);\n return;\n }\n\n // Multi click\n if (clickCount > 1) {\n const breadcrumb: ReplayMultiClickFrame = {\n type: 'default',\n message: clickBreadcrumb.message,\n timestamp: clickBreadcrumb.timestamp,\n category: 'ui.multiClick',\n data: {\n ...clickBreadcrumb.data,\n url: WINDOW.location.href,\n route: replay.getCurrentRoute(),\n clickCount,\n metric: true,\n },\n };\n\n this._addBreadcrumbEvent(replay, breadcrumb);\n }\n }\n\n /** Schedule to check current clicks. */\n private _scheduleCheckClicks(): void {\n if (this._checkClickTimeout) {\n clearTimeout(this._checkClickTimeout);\n }\n\n this._checkClickTimeout = setTimeout(() => this._checkClicks(), 1000);\n }\n}\n\nconst SLOW_CLICK_TAGS = ['A', 'BUTTON', 'INPUT'];\n\n/** exported for tests only */\nexport function ignoreElement(node: HTMLElement, ignoreSelector: string): boolean {\n if (!SLOW_CLICK_TAGS.includes(node.tagName)) {\n return true;\n }\n\n // If tag, we only want to consider input[type='submit'] & input[type='button']\n if (node.tagName === 'INPUT' && !['submit', 'button'].includes(node.getAttribute('type') || '')) {\n return true;\n }\n\n // If tag, detect special variants that may not lead to an action\n // If target !== _self, we may open the link somewhere else, which would lead to no action\n // Also, when downloading a file, we may not leave the page, but still not trigger an action\n if (\n node.tagName === 'A' &&\n (node.hasAttribute('download') || (node.hasAttribute('target') && node.getAttribute('target') !== '_self'))\n ) {\n return true;\n }\n\n if (ignoreSelector && node.matches(ignoreSelector)) {\n return true;\n }\n\n return false;\n}\n\nfunction isClickBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is ClickBreadcrumb {\n return !!(breadcrumb.data && typeof breadcrumb.data.nodeId === 'number' && breadcrumb.timestamp);\n}\n\n// This is good enough for us, and is easier to test/mock than `timestampInSeconds`\nfunction nowInSeconds(): number {\n return Date.now() / 1000;\n}\n\n/** Update the click detector based on a recording event of rrweb. */\nexport function updateClickDetectorForRecordingEvent(clickDetector: ReplayClickDetector, event: RecordingEvent): void {\n try {\n // note: We only consider incremental snapshots here\n // This means that any full snapshot is ignored for mutation detection - the reason is that we simply cannot know if a mutation happened here.\n // E.g. think that we are buffering, an error happens and we take a full snapshot because we switched to session mode -\n // in this scenario, we would not know if a dead click happened because of the error, which is a key dead click scenario.\n // Instead, by ignoring full snapshots, we have the risk that we generate a false positive\n // (if a mutation _did_ happen but was \"swallowed\" by the full snapshot)\n // But this should be more unlikely as we'd generally capture the incremental snapshot right away\n\n if (!isIncrementalEvent(event)) {\n return;\n }\n\n const { source } = event.data;\n if (source === IncrementalSource.Mutation) {\n clickDetector.registerMutation(event.timestamp);\n }\n\n if (source === IncrementalSource.Scroll) {\n clickDetector.registerScroll(event.timestamp);\n }\n\n if (isIncrementalMouseInteraction(event)) {\n const { type, id } = event.data;\n const node = record.mirror.getNode(id);\n\n if (node instanceof HTMLElement && type === MouseInteractions.Click) {\n clickDetector.registerClick(node);\n }\n }\n } catch {\n // ignore errors here, e.g. if accessing something that does not exist\n }\n}\n\nfunction isIncrementalEvent(event: RecordingEvent): event is IncrementalRecordingEvent {\n return event.type === ReplayEventTypeIncrementalSnapshot;\n}\n\nfunction isIncrementalMouseInteraction(\n event: IncrementalRecordingEvent,\n): event is IncrementalMouseInteractionRecordingEvent {\n return event.data.source === IncrementalSource.MouseInteraction;\n}\n","var NodeType;\r\n(function (NodeType) {\r\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\r\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\r\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\r\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\r\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\r\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\r\n})(NodeType || (NodeType = {}));\n\nfunction isElement(n) {\r\n return n.nodeType === n.ELEMENT_NODE;\r\n}\r\nfunction isShadowRoot(n) {\r\n const host = n?.host;\r\n return Boolean(host?.shadowRoot === n);\r\n}\r\nfunction isNativeShadowDom(shadowRoot) {\r\n return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';\r\n}\r\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\r\n if (cssText.includes(' background-clip: text;') &&\r\n !cssText.includes(' -webkit-background-clip: text;')) {\r\n cssText = cssText.replace(' background-clip: text;', ' -webkit-background-clip: text; background-clip: text;');\r\n }\r\n return cssText;\r\n}\r\nfunction escapeImportStatement(rule) {\r\n const { cssText } = rule;\r\n if (cssText.split('\"').length < 3)\r\n return cssText;\r\n const statement = ['@import', `url(${JSON.stringify(rule.href)})`];\r\n if (rule.layerName === '') {\r\n statement.push(`layer`);\r\n }\r\n else if (rule.layerName) {\r\n statement.push(`layer(${rule.layerName})`);\r\n }\r\n if (rule.supportsText) {\r\n statement.push(`supports(${rule.supportsText})`);\r\n }\r\n if (rule.media.length) {\r\n statement.push(rule.media.mediaText);\r\n }\r\n return statement.join(' ') + ';';\r\n}\r\nfunction stringifyStylesheet(s) {\r\n try {\r\n const rules = s.rules || s.cssRules;\r\n return rules\r\n ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules, stringifyRule).join(''))\r\n : null;\r\n }\r\n catch (error) {\r\n return null;\r\n }\r\n}\r\nfunction stringifyRule(rule) {\r\n let importStringified;\r\n if (isCSSImportRule(rule)) {\r\n try {\r\n importStringified =\r\n stringifyStylesheet(rule.styleSheet) ||\r\n escapeImportStatement(rule);\r\n }\r\n catch (error) {\r\n }\r\n }\r\n else if (isCSSStyleRule(rule) && rule.selectorText.includes(':')) {\r\n return fixSafariColons(rule.cssText);\r\n }\r\n return importStringified || rule.cssText;\r\n}\r\nfunction fixSafariColons(cssStringified) {\r\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\r\n return cssStringified.replace(regex, '$1\\\\$2');\r\n}\r\nfunction isCSSImportRule(rule) {\r\n return 'styleSheet' in rule;\r\n}\r\nfunction isCSSStyleRule(rule) {\r\n return 'selectorText' in rule;\r\n}\r\nclass Mirror {\r\n constructor() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n getId(n) {\r\n if (!n)\r\n return -1;\r\n const id = this.getMeta(n)?.id;\r\n return id ?? -1;\r\n }\r\n getNode(id) {\r\n return this.idNodeMap.get(id) || null;\r\n }\r\n getIds() {\r\n return Array.from(this.idNodeMap.keys());\r\n }\r\n getMeta(n) {\r\n return this.nodeMetaMap.get(n) || null;\r\n }\r\n removeNodeFromMap(n) {\r\n const id = this.getId(n);\r\n this.idNodeMap.delete(id);\r\n if (n.childNodes) {\r\n n.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode));\r\n }\r\n }\r\n has(id) {\r\n return this.idNodeMap.has(id);\r\n }\r\n hasNode(node) {\r\n return this.nodeMetaMap.has(node);\r\n }\r\n add(n, meta) {\r\n const id = meta.id;\r\n this.idNodeMap.set(id, n);\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n replace(id, n) {\r\n const oldNode = this.getNode(id);\r\n if (oldNode) {\r\n const meta = this.nodeMetaMap.get(oldNode);\r\n if (meta)\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n this.idNodeMap.set(id, n);\r\n }\r\n reset() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n}\r\nfunction createMirror() {\r\n return new Mirror();\r\n}\r\nfunction shouldMaskInput({ maskInputOptions, tagName, type, }) {\r\n if (tagName === 'OPTION') {\r\n tagName = 'SELECT';\r\n }\r\n return Boolean(maskInputOptions[tagName.toLowerCase()] ||\r\n (type && maskInputOptions[type]) ||\r\n type === 'password' ||\r\n (tagName === 'INPUT' && !type && maskInputOptions['text']));\r\n}\r\nfunction maskInputValue({ isMasked, element, value, maskInputFn, }) {\r\n let text = value || '';\r\n if (!isMasked) {\r\n return text;\r\n }\r\n if (maskInputFn) {\r\n text = maskInputFn(text, element);\r\n }\r\n return '*'.repeat(text.length);\r\n}\r\nfunction toLowerCase(str) {\r\n return str.toLowerCase();\r\n}\r\nfunction toUpperCase(str) {\r\n return str.toUpperCase();\r\n}\r\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\r\nfunction is2DCanvasBlank(canvas) {\r\n const ctx = canvas.getContext('2d');\r\n if (!ctx)\r\n return true;\r\n const chunkSize = 50;\r\n for (let x = 0; x < canvas.width; x += chunkSize) {\r\n for (let y = 0; y < canvas.height; y += chunkSize) {\r\n const getImageData = ctx.getImageData;\r\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\r\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\r\n : getImageData;\r\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\r\n if (pixelBuffer.some((pixel) => pixel !== 0))\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isNodeMetaEqual(a, b) {\r\n if (!a || !b || a.type !== b.type)\r\n return false;\r\n if (a.type === NodeType.Document)\r\n return a.compatMode === b.compatMode;\r\n else if (a.type === NodeType.DocumentType)\r\n return (a.name === b.name &&\r\n a.publicId === b.publicId &&\r\n a.systemId === b.systemId);\r\n else if (a.type === NodeType.Comment ||\r\n a.type === NodeType.Text ||\r\n a.type === NodeType.CDATA)\r\n return a.textContent === b.textContent;\r\n else if (a.type === NodeType.Element)\r\n return (a.tagName === b.tagName &&\r\n JSON.stringify(a.attributes) ===\r\n JSON.stringify(b.attributes) &&\r\n a.isSVG === b.isSVG &&\r\n a.needBlock === b.needBlock);\r\n return false;\r\n}\r\nfunction getInputType(element) {\r\n const type = element.type;\r\n return element.hasAttribute('data-rr-is-password')\r\n ? 'password'\r\n : type\r\n ?\r\n toLowerCase(type)\r\n : null;\r\n}\r\nfunction getInputValue(el, tagName, type) {\r\n if (tagName === 'INPUT' && (type === 'radio' || type === 'checkbox')) {\r\n return el.getAttribute('value') || '';\r\n }\r\n return el.value;\r\n}\n\nlet _id = 1;\r\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\r\nconst IGNORED_NODE = -2;\r\nfunction genId() {\r\n return _id++;\r\n}\r\nfunction getValidTagName(element) {\r\n if (element instanceof HTMLFormElement) {\r\n return 'form';\r\n }\r\n const processedTagName = toLowerCase(element.tagName);\r\n if (tagNameRegex.test(processedTagName)) {\r\n return 'div';\r\n }\r\n return processedTagName;\r\n}\r\nfunction extractOrigin(url) {\r\n let origin = '';\r\n if (url.indexOf('//') > -1) {\r\n origin = url.split('/').slice(0, 3).join('/');\r\n }\r\n else {\r\n origin = url.split('/')[0];\r\n }\r\n origin = origin.split('?')[0];\r\n return origin;\r\n}\r\nlet canvasService;\r\nlet canvasCtx;\r\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\r\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\r\nconst URL_WWW_MATCH = /^www\\..*/i;\r\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\r\nfunction absoluteToStylesheet(cssText, href) {\r\n return (cssText || '').replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => {\r\n const filePath = path1 || path2 || path3;\r\n const maybeQuote = quote1 || quote2 || '';\r\n if (!filePath) {\r\n return origin;\r\n }\r\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (DATA_URI.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (filePath[0] === '/') {\r\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\r\n }\r\n const stack = href.split('/');\r\n const parts = filePath.split('/');\r\n stack.pop();\r\n for (const part of parts) {\r\n if (part === '.') {\r\n continue;\r\n }\r\n else if (part === '..') {\r\n stack.pop();\r\n }\r\n else {\r\n stack.push(part);\r\n }\r\n }\r\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\r\n });\r\n}\r\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\r\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\r\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\r\n if (attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n let pos = 0;\r\n function collectCharacters(regEx) {\r\n let chars;\r\n const match = regEx.exec(attributeValue.substring(pos));\r\n if (match) {\r\n chars = match[0];\r\n pos += chars.length;\r\n return chars;\r\n }\r\n return '';\r\n }\r\n const output = [];\r\n while (true) {\r\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\r\n if (pos >= attributeValue.length) {\r\n break;\r\n }\r\n let url = collectCharacters(SRCSET_NOT_SPACES);\r\n if (url.slice(-1) === ',') {\r\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\r\n output.push(url);\r\n }\r\n else {\r\n let descriptorsStr = '';\r\n url = absoluteToDoc(doc, url);\r\n let inParens = false;\r\n while (true) {\r\n const c = attributeValue.charAt(pos);\r\n if (c === '') {\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (!inParens) {\r\n if (c === ',') {\r\n pos += 1;\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (c === '(') {\r\n inParens = true;\r\n }\r\n }\r\n else {\r\n if (c === ')') {\r\n inParens = false;\r\n }\r\n }\r\n descriptorsStr += c;\r\n pos += 1;\r\n }\r\n }\r\n }\r\n return output.join(', ');\r\n}\r\nfunction absoluteToDoc(doc, attributeValue) {\r\n if (!attributeValue || attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n const a = doc.createElement('a');\r\n a.href = attributeValue;\r\n return a.href;\r\n}\r\nfunction isSVGElement(el) {\r\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\r\n}\r\nfunction getHref() {\r\n const a = document.createElement('a');\r\n a.href = '';\r\n return a.href;\r\n}\r\nfunction transformAttribute(doc, tagName, name, value, element, maskAttributeFn) {\r\n if (!value) {\r\n return value;\r\n }\r\n if (name === 'src' ||\r\n (name === 'href' && !(tagName === 'use' && value[0] === '#'))) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'xlink:href' && value[0] !== '#') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'background' &&\r\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'srcset') {\r\n return getAbsoluteSrcsetString(doc, value);\r\n }\r\n else if (name === 'style') {\r\n return absoluteToStylesheet(value, getHref());\r\n }\r\n else if (tagName === 'object' && name === 'data') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n if (typeof maskAttributeFn === 'function') {\r\n return maskAttributeFn(name, value, element);\r\n }\r\n return value;\r\n}\r\nfunction ignoreAttribute(tagName, name, _value) {\r\n return (tagName === 'video' || tagName === 'audio') && name === 'autoplay';\r\n}\r\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\r\n try {\r\n if (unblockSelector && element.matches(unblockSelector)) {\r\n return false;\r\n }\r\n if (typeof blockClass === 'string') {\r\n if (element.classList.contains(blockClass)) {\r\n return true;\r\n }\r\n }\r\n else {\r\n for (let eIndex = element.classList.length; eIndex--;) {\r\n const className = element.classList[eIndex];\r\n if (blockClass.test(className)) {\r\n return true;\r\n }\r\n }\r\n }\r\n if (blockSelector) {\r\n return element.matches(blockSelector);\r\n }\r\n }\r\n catch (e) {\r\n }\r\n return false;\r\n}\r\nfunction elementClassMatchesRegex(el, regex) {\r\n for (let eIndex = el.classList.length; eIndex--;) {\r\n const className = el.classList[eIndex];\r\n if (regex.test(className)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction classMatchesRegex(node, regex, checkAncestors) {\r\n if (!node)\r\n return false;\r\n if (checkAncestors) {\r\n return (distanceToMatch(node, (node) => elementClassMatchesRegex(node, regex)) >= 0);\r\n }\r\n else if (node.nodeType === node.ELEMENT_NODE) {\r\n return elementClassMatchesRegex(node, regex);\r\n }\r\n return false;\r\n}\r\nfunction distanceToMatch(node, matchPredicate, limit = Infinity, distance = 0) {\r\n if (!node)\r\n return -1;\r\n if (node.nodeType !== node.ELEMENT_NODE)\r\n return -1;\r\n if (distance > limit)\r\n return -1;\r\n if (matchPredicate(node))\r\n return distance;\r\n return distanceToMatch(node.parentNode, matchPredicate, limit, distance + 1);\r\n}\r\nfunction createMatchPredicate(className, selector) {\r\n return (node) => {\r\n const el = node;\r\n if (el === null)\r\n return false;\r\n try {\r\n if (className) {\r\n if (typeof className === 'string') {\r\n if (el.matches(`.${className}`))\r\n return true;\r\n }\r\n else if (elementClassMatchesRegex(el, className)) {\r\n return true;\r\n }\r\n }\r\n if (selector && el.matches(selector))\r\n return true;\r\n return false;\r\n }\r\n catch {\r\n return false;\r\n }\r\n };\r\n}\r\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText) {\r\n try {\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n if (el === null)\r\n return false;\r\n if (el.tagName === 'INPUT') {\r\n const autocomplete = el.getAttribute('autocomplete');\r\n const disallowedAutocompleteValues = [\r\n 'current-password',\r\n 'new-password',\r\n 'cc-number',\r\n 'cc-exp',\r\n 'cc-exp-month',\r\n 'cc-exp-year',\r\n 'cc-csc',\r\n ];\r\n if (disallowedAutocompleteValues.includes(autocomplete)) {\r\n return true;\r\n }\r\n }\r\n let maskDistance = -1;\r\n let unmaskDistance = -1;\r\n if (maskAllText) {\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector));\r\n if (unmaskDistance < 0) {\r\n return true;\r\n }\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector), unmaskDistance >= 0 ? unmaskDistance : Infinity);\r\n }\r\n else {\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector));\r\n if (maskDistance < 0) {\r\n return false;\r\n }\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector), maskDistance >= 0 ? maskDistance : Infinity);\r\n }\r\n return maskDistance >= 0\r\n ? unmaskDistance >= 0\r\n ? maskDistance <= unmaskDistance\r\n : true\r\n : unmaskDistance >= 0\r\n ? false\r\n : !!maskAllText;\r\n }\r\n catch (e) {\r\n }\r\n return !!maskAllText;\r\n}\r\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\r\n const win = iframeEl.contentWindow;\r\n if (!win) {\r\n return;\r\n }\r\n let fired = false;\r\n let readyState;\r\n try {\r\n readyState = win.document.readyState;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (readyState !== 'complete') {\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, iframeLoadTimeout);\r\n iframeEl.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n return;\r\n }\r\n const blankUrl = 'about:blank';\r\n if (win.location.href !== blankUrl ||\r\n iframeEl.src === blankUrl ||\r\n iframeEl.src === '') {\r\n setTimeout(listener, 0);\r\n return iframeEl.addEventListener('load', listener);\r\n }\r\n iframeEl.addEventListener('load', listener);\r\n}\r\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\r\n let fired = false;\r\n let styleSheetLoaded;\r\n try {\r\n styleSheetLoaded = link.sheet;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (styleSheetLoaded)\r\n return;\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, styleSheetLoadTimeout);\r\n link.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n}\r\nfunction serializeNode(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskAttributeFn, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, } = options;\r\n const rootId = getRootId(doc, mirror);\r\n switch (n.nodeType) {\r\n case n.DOCUMENT_NODE:\r\n if (n.compatMode !== 'CSS1Compat') {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n compatMode: n.compatMode,\r\n };\r\n }\r\n else {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n };\r\n }\r\n case n.DOCUMENT_TYPE_NODE:\r\n return {\r\n type: NodeType.DocumentType,\r\n name: n.name,\r\n publicId: n.publicId,\r\n systemId: n.systemId,\r\n rootId,\r\n };\r\n case n.ELEMENT_NODE:\r\n return serializeElementNode(n, {\r\n doc,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n inlineStylesheet,\r\n maskAttributeFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n rootId,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n });\r\n case n.TEXT_NODE:\r\n return serializeTextNode(n, {\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n maskTextFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n rootId,\r\n });\r\n case n.CDATA_SECTION_NODE:\r\n return {\r\n type: NodeType.CDATA,\r\n textContent: '',\r\n rootId,\r\n };\r\n case n.COMMENT_NODE:\r\n return {\r\n type: NodeType.Comment,\r\n textContent: n.textContent || '',\r\n rootId,\r\n };\r\n default:\r\n return false;\r\n }\r\n}\r\nfunction getRootId(doc, mirror) {\r\n if (!mirror.hasNode(doc))\r\n return undefined;\r\n const docId = mirror.getId(doc);\r\n return docId === 1 ? undefined : docId;\r\n}\r\nfunction serializeTextNode(n, options) {\r\n const { maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, maskTextFn, maskInputOptions, maskInputFn, rootId, } = options;\r\n const parentTagName = n.parentNode && n.parentNode.tagName;\r\n let textContent = n.textContent;\r\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\r\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\r\n const isTextarea = parentTagName === 'TEXTAREA' ? true : undefined;\r\n if (isStyle && textContent) {\r\n try {\r\n if (n.nextSibling || n.previousSibling) {\r\n }\r\n else if (n.parentNode.sheet?.cssRules) {\r\n textContent = stringifyStylesheet(n.parentNode.sheet);\r\n }\r\n }\r\n catch (err) {\r\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\r\n }\r\n textContent = absoluteToStylesheet(textContent, getHref());\r\n }\r\n if (isScript) {\r\n textContent = 'SCRIPT_PLACEHOLDER';\r\n }\r\n const forceMask = needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText);\r\n if (!isStyle && !isScript && !isTextarea && textContent && forceMask) {\r\n textContent = maskTextFn\r\n ? maskTextFn(textContent, n.parentElement)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (isTextarea && textContent && (maskInputOptions.textarea || forceMask)) {\r\n textContent = maskInputFn\r\n ? maskInputFn(textContent, n.parentNode)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (parentTagName === 'OPTION' && textContent) {\r\n const isInputMasked = shouldMaskInput({\r\n type: null,\r\n tagName: parentTagName,\r\n maskInputOptions,\r\n });\r\n textContent = maskInputValue({\r\n isMasked: needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked),\r\n element: n,\r\n value: textContent,\r\n maskInputFn,\r\n });\r\n }\r\n return {\r\n type: NodeType.Text,\r\n textContent: textContent || '',\r\n isStyle,\r\n rootId,\r\n };\r\n}\r\nfunction serializeElementNode(n, options) {\r\n const { doc, blockClass, blockSelector, unblockSelector, inlineStylesheet, maskInputOptions = {}, maskAttributeFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, rootId, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, } = options;\r\n const needBlock = _isBlockedElement(n, blockClass, blockSelector, unblockSelector);\r\n const tagName = getValidTagName(n);\r\n let attributes = {};\r\n const len = n.attributes.length;\r\n for (let i = 0; i < len; i++) {\r\n const attr = n.attributes[i];\r\n if (attr.name && !ignoreAttribute(tagName, attr.name, attr.value)) {\r\n attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value, n, maskAttributeFn);\r\n }\r\n }\r\n if (tagName === 'link' && inlineStylesheet) {\r\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\r\n return s.href === n.href;\r\n });\r\n let cssText = null;\r\n if (stylesheet) {\r\n cssText = stringifyStylesheet(stylesheet);\r\n }\r\n if (cssText) {\r\n delete attributes.rel;\r\n delete attributes.href;\r\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\r\n }\r\n }\r\n if (tagName === 'style' &&\r\n n.sheet &&\r\n !(n.innerText || n.textContent || '').trim().length) {\r\n const cssText = stringifyStylesheet(n.sheet);\r\n if (cssText) {\r\n attributes._cssText = absoluteToStylesheet(cssText, getHref());\r\n }\r\n }\r\n if (tagName === 'input' ||\r\n tagName === 'textarea' ||\r\n tagName === 'select' ||\r\n tagName === 'option') {\r\n const el = n;\r\n const type = getInputType(el);\r\n const value = getInputValue(el, toUpperCase(tagName), type);\r\n const checked = el.checked;\r\n if (type !== 'submit' && type !== 'button' && value) {\r\n const forceMask = needMaskingText(el, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, shouldMaskInput({\r\n type,\r\n tagName: toUpperCase(tagName),\r\n maskInputOptions,\r\n }));\r\n attributes.value = maskInputValue({\r\n isMasked: forceMask,\r\n element: el,\r\n value,\r\n maskInputFn,\r\n });\r\n }\r\n if (checked) {\r\n attributes.checked = checked;\r\n }\r\n }\r\n if (tagName === 'option') {\r\n if (n.selected && !maskInputOptions['select']) {\r\n attributes.selected = true;\r\n }\r\n else {\r\n delete attributes.selected;\r\n }\r\n }\r\n if (tagName === 'canvas' && recordCanvas) {\r\n if (n.__context === '2d') {\r\n if (!is2DCanvasBlank(n)) {\r\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n }\r\n else if (!('__context' in n)) {\r\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n const blankCanvas = document.createElement('canvas');\r\n blankCanvas.width = n.width;\r\n blankCanvas.height = n.height;\r\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n if (canvasDataURL !== blankCanvasDataURL) {\r\n attributes.rr_dataURL = canvasDataURL;\r\n }\r\n }\r\n }\r\n if (tagName === 'img' && inlineImages) {\r\n if (!canvasService) {\r\n canvasService = doc.createElement('canvas');\r\n canvasCtx = canvasService.getContext('2d');\r\n }\r\n const image = n;\r\n const oldValue = image.crossOrigin;\r\n image.crossOrigin = 'anonymous';\r\n const recordInlineImage = () => {\r\n image.removeEventListener('load', recordInlineImage);\r\n try {\r\n canvasService.width = image.naturalWidth;\r\n canvasService.height = image.naturalHeight;\r\n canvasCtx.drawImage(image, 0, 0);\r\n attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n catch (err) {\r\n console.warn(`Cannot inline img src=${image.currentSrc}! Error: ${err}`);\r\n }\r\n oldValue\r\n ? (attributes.crossOrigin = oldValue)\r\n : image.removeAttribute('crossorigin');\r\n };\r\n if (image.complete && image.naturalWidth !== 0)\r\n recordInlineImage();\r\n else\r\n image.addEventListener('load', recordInlineImage);\r\n }\r\n if (tagName === 'audio' || tagName === 'video') {\r\n attributes.rr_mediaState = n.paused\r\n ? 'paused'\r\n : 'played';\r\n attributes.rr_mediaCurrentTime = n.currentTime;\r\n }\r\n if (!newlyAddedElement) {\r\n if (n.scrollLeft) {\r\n attributes.rr_scrollLeft = n.scrollLeft;\r\n }\r\n if (n.scrollTop) {\r\n attributes.rr_scrollTop = n.scrollTop;\r\n }\r\n }\r\n if (needBlock) {\r\n const { width, height } = n.getBoundingClientRect();\r\n attributes = {\r\n class: attributes.class,\r\n rr_width: `${width}px`,\r\n rr_height: `${height}px`,\r\n };\r\n }\r\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\r\n if (!n.contentDocument) {\r\n attributes.rr_src = attributes.src;\r\n }\r\n delete attributes.src;\r\n }\r\n let isCustomElement;\r\n try {\r\n if (customElements.get(tagName))\r\n isCustomElement = true;\r\n }\r\n catch (e) {\r\n }\r\n return {\r\n type: NodeType.Element,\r\n tagName,\r\n attributes,\r\n childNodes: [],\r\n isSVG: isSVGElement(n) || undefined,\r\n needBlock,\r\n rootId,\r\n isCustom: isCustomElement,\r\n };\r\n}\r\nfunction lowerIfExists(maybeAttr) {\r\n if (maybeAttr === undefined || maybeAttr === null) {\r\n return '';\r\n }\r\n else {\r\n return maybeAttr.toLowerCase();\r\n }\r\n}\r\nfunction slimDOMExcluded(sn, slimDOMOptions) {\r\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\r\n return true;\r\n }\r\n else if (sn.type === NodeType.Element) {\r\n if (slimDOMOptions.script &&\r\n (sn.tagName === 'script' ||\r\n (sn.tagName === 'link' &&\r\n (sn.attributes.rel === 'preload' ||\r\n sn.attributes.rel === 'modulepreload') &&\r\n sn.attributes.as === 'script') ||\r\n (sn.tagName === 'link' &&\r\n sn.attributes.rel === 'prefetch' &&\r\n typeof sn.attributes.href === 'string' &&\r\n sn.attributes.href.endsWith('.js')))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headFavicon &&\r\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\r\n (sn.tagName === 'meta' &&\r\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\r\n lowerIfExists(sn.attributes.name) === 'application-name' ||\r\n lowerIfExists(sn.attributes.rel) === 'icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\r\n return true;\r\n }\r\n else if (sn.tagName === 'meta') {\r\n if (slimDOMOptions.headMetaDescKeywords &&\r\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaSocial &&\r\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\r\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\r\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaRobots &&\r\n (lowerIfExists(sn.attributes.name) === 'robots' ||\r\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\r\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaHttpEquiv &&\r\n sn.attributes['http-equiv'] !== undefined) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaAuthorship &&\r\n (lowerIfExists(sn.attributes.name) === 'author' ||\r\n lowerIfExists(sn.attributes.name) === 'generator' ||\r\n lowerIfExists(sn.attributes.name) === 'framework' ||\r\n lowerIfExists(sn.attributes.name) === 'publisher' ||\r\n lowerIfExists(sn.attributes.name) === 'progid' ||\r\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\r\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaVerification &&\r\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\r\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\r\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\r\n lowerIfExists(sn.attributes.name) === 'verification' ||\r\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n}\r\nfunction serializeNodeWithId(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputOptions = {}, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, onStylesheetLoad, stylesheetLoadTimeout = 5000, keepIframeSrcFn = () => false, newlyAddedElement = false, } = options;\r\n let { preserveWhiteSpace = true } = options;\r\n const _serializedNode = serializeNode(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n });\r\n if (!_serializedNode) {\r\n console.warn(n, 'not serialized');\r\n return null;\r\n }\r\n let id;\r\n if (mirror.hasNode(n)) {\r\n id = mirror.getId(n);\r\n }\r\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\r\n (!preserveWhiteSpace &&\r\n _serializedNode.type === NodeType.Text &&\r\n !_serializedNode.isStyle &&\r\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\r\n id = IGNORED_NODE;\r\n }\r\n else {\r\n id = genId();\r\n }\r\n const serializedNode = Object.assign(_serializedNode, { id });\r\n mirror.add(n, serializedNode);\r\n if (id === IGNORED_NODE) {\r\n return null;\r\n }\r\n if (onSerialize) {\r\n onSerialize(n);\r\n }\r\n let recordChild = !skipChild;\r\n if (serializedNode.type === NodeType.Element) {\r\n recordChild = recordChild && !serializedNode.needBlock;\r\n delete serializedNode.needBlock;\r\n const shadowRoot = n.shadowRoot;\r\n if (shadowRoot && isNativeShadowDom(shadowRoot))\r\n serializedNode.isShadowHost = true;\r\n }\r\n if ((serializedNode.type === NodeType.Document ||\r\n serializedNode.type === NodeType.Element) &&\r\n recordChild) {\r\n if (slimDOMOptions.headWhitespace &&\r\n serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'head') {\r\n preserveWhiteSpace = false;\r\n }\r\n const bypassOptions = {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n };\r\n for (const childN of Array.from(n.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n if (isElement(n) && n.shadowRoot) {\r\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n isNativeShadowDom(n.shadowRoot) &&\r\n (serializedChildNode.isShadow = true);\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n }\r\n }\r\n if (n.parentNode &&\r\n isShadowRoot(n.parentNode) &&\r\n isNativeShadowDom(n.parentNode)) {\r\n serializedNode.isShadow = true;\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'iframe') {\r\n onceIframeLoaded(n, () => {\r\n const iframeDoc = n.contentDocument;\r\n if (iframeDoc && onIframeLoad) {\r\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\r\n doc: iframeDoc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedIframeNode) {\r\n onIframeLoad(n, serializedIframeNode);\r\n }\r\n }\r\n }, iframeLoadTimeout);\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'link' &&\r\n serializedNode.attributes.rel === 'stylesheet') {\r\n onceStylesheetLoaded(n, () => {\r\n if (onStylesheetLoad) {\r\n const serializedLinkNode = serializeNodeWithId(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedLinkNode) {\r\n onStylesheetLoad(n, serializedLinkNode);\r\n }\r\n }\r\n }, stylesheetLoadTimeout);\r\n }\r\n return serializedNode;\r\n}\r\nfunction snapshot(n, options) {\r\n const { mirror = new Mirror(), blockClass = 'rr-block', blockSelector = null, unblockSelector = null, maskAllText = false, maskTextClass = 'rr-mask', unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskAllInputs = false, maskAttributeFn, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn = () => false, } = options || {};\r\n const maskInputOptions = maskAllInputs === true\r\n ? {\r\n color: true,\r\n date: true,\r\n 'datetime-local': true,\r\n email: true,\r\n month: true,\r\n number: true,\r\n range: true,\r\n search: true,\r\n tel: true,\r\n text: true,\r\n time: true,\r\n url: true,\r\n week: true,\r\n textarea: true,\r\n select: true,\r\n }\r\n : maskAllInputs === false\r\n ? {}\r\n : maskAllInputs;\r\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\r\n ?\r\n {\r\n script: true,\r\n comment: true,\r\n headFavicon: true,\r\n headWhitespace: true,\r\n headMetaDescKeywords: slimDOM === 'all',\r\n headMetaSocial: true,\r\n headMetaRobots: true,\r\n headMetaHttpEquiv: true,\r\n headMetaAuthorship: true,\r\n headMetaVerification: true,\r\n }\r\n : slimDOM === false\r\n ? {}\r\n : slimDOM;\r\n return serializeNodeWithId(n, {\r\n doc: n,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n newlyAddedElement: false,\r\n });\r\n}\r\nfunction visitSnapshot(node, onVisit) {\r\n function walk(current) {\r\n onVisit(current);\r\n if (current.type === NodeType.Document ||\r\n current.type === NodeType.Element) {\r\n current.childNodes.forEach(walk);\r\n }\r\n }\r\n walk(node);\r\n}\r\nfunction cleanupSnapshot() {\r\n _id = 1;\r\n}\n\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\r\nfunction parse(css, options = {}) {\r\n let lineno = 1;\r\n let column = 1;\r\n function updatePosition(str) {\r\n const lines = str.match(/\\n/g);\r\n if (lines) {\r\n lineno += lines.length;\r\n }\r\n const i = str.lastIndexOf('\\n');\r\n column = i === -1 ? column + str.length : str.length - i;\r\n }\r\n function position() {\r\n const start = { line: lineno, column };\r\n return (node) => {\r\n node.position = new Position(start);\r\n whitespace();\r\n return node;\r\n };\r\n }\r\n class Position {\r\n constructor(start) {\r\n this.start = start;\r\n this.end = { line: lineno, column };\r\n this.source = options.source;\r\n }\r\n }\r\n Position.prototype.content = css;\r\n const errorsList = [];\r\n function error(msg) {\r\n const err = new Error(`${options.source || ''}:${lineno}:${column}: ${msg}`);\r\n err.reason = msg;\r\n err.filename = options.source;\r\n err.line = lineno;\r\n err.column = column;\r\n err.source = css;\r\n if (options.silent) {\r\n errorsList.push(err);\r\n }\r\n else {\r\n throw err;\r\n }\r\n }\r\n function stylesheet() {\r\n const rulesList = rules();\r\n return {\r\n type: 'stylesheet',\r\n stylesheet: {\r\n source: options.source,\r\n rules: rulesList,\r\n parsingErrors: errorsList,\r\n },\r\n };\r\n }\r\n function open() {\r\n return match(/^{\\s*/);\r\n }\r\n function close() {\r\n return match(/^}/);\r\n }\r\n function rules() {\r\n let node;\r\n const rules = [];\r\n whitespace();\r\n comments(rules);\r\n while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {\r\n if (node) {\r\n rules.push(node);\r\n comments(rules);\r\n }\r\n }\r\n return rules;\r\n }\r\n function match(re) {\r\n const m = re.exec(css);\r\n if (!m) {\r\n return;\r\n }\r\n const str = m[0];\r\n updatePosition(str);\r\n css = css.slice(str.length);\r\n return m;\r\n }\r\n function whitespace() {\r\n match(/^\\s*/);\r\n }\r\n function comments(rules = []) {\r\n let c;\r\n while ((c = comment())) {\r\n if (c) {\r\n rules.push(c);\r\n }\r\n c = comment();\r\n }\r\n return rules;\r\n }\r\n function comment() {\r\n const pos = position();\r\n if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {\r\n return;\r\n }\r\n let i = 2;\r\n while ('' !== css.charAt(i) &&\r\n ('*' !== css.charAt(i) || '/' !== css.charAt(i + 1))) {\r\n ++i;\r\n }\r\n i += 2;\r\n if ('' === css.charAt(i - 1)) {\r\n return error('End of comment missing');\r\n }\r\n const str = css.slice(2, i - 2);\r\n column += 2;\r\n updatePosition(str);\r\n css = css.slice(i);\r\n column += 2;\r\n return pos({\r\n type: 'comment',\r\n comment: str,\r\n });\r\n }\r\n function selector() {\r\n whitespace();\r\n while (css[0] == '}') {\r\n error('extra closing bracket');\r\n css = css.slice(1);\r\n whitespace();\r\n }\r\n const m = match(/^((\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'|[^{])+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const cleanedInput = m[0]\r\n .trim()\r\n .replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/g, '')\r\n .replace(/\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'/g, (m) => {\r\n return m.replace(/,/g, '\\u200C');\r\n });\r\n return customSplit(cleanedInput).map((s) => s.replace(/\\u200C/g, ',').trim());\r\n }\r\n function customSplit(input) {\r\n const result = [];\r\n let currentSegment = '';\r\n let depthParentheses = 0;\r\n let depthBrackets = 0;\r\n let currentStringChar = null;\r\n for (const char of input) {\r\n const hasStringEscape = currentSegment.endsWith('\\\\');\r\n if (currentStringChar) {\r\n if (currentStringChar === char && !hasStringEscape) {\r\n currentStringChar = null;\r\n }\r\n }\r\n else if (char === '(') {\r\n depthParentheses++;\r\n }\r\n else if (char === ')') {\r\n depthParentheses--;\r\n }\r\n else if (char === '[') {\r\n depthBrackets++;\r\n }\r\n else if (char === ']') {\r\n depthBrackets--;\r\n }\r\n else if ('\\'\"'.includes(char)) {\r\n currentStringChar = char;\r\n }\r\n if (char === ',' && depthParentheses === 0 && depthBrackets === 0) {\r\n result.push(currentSegment);\r\n currentSegment = '';\r\n }\r\n else {\r\n currentSegment += char;\r\n }\r\n }\r\n if (currentSegment) {\r\n result.push(currentSegment);\r\n }\r\n return result;\r\n }\r\n function declaration() {\r\n const pos = position();\r\n const propMatch = match(/^(\\*?[-#\\/\\*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\r\n if (!propMatch) {\r\n return;\r\n }\r\n const prop = trim(propMatch[0]);\r\n if (!match(/^:\\s*/)) {\r\n return error(`property missing ':'`);\r\n }\r\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^\\)]*?\\)|[^};])+)/);\r\n const ret = pos({\r\n type: 'declaration',\r\n property: prop.replace(commentre, ''),\r\n value: val ? trim(val[0]).replace(commentre, '') : '',\r\n });\r\n match(/^[;\\s]*/);\r\n return ret;\r\n }\r\n function declarations() {\r\n const decls = [];\r\n if (!open()) {\r\n return error(`missing '{'`);\r\n }\r\n comments(decls);\r\n let decl;\r\n while ((decl = declaration())) {\r\n if (decl !== false) {\r\n decls.push(decl);\r\n comments(decls);\r\n }\r\n decl = declaration();\r\n }\r\n if (!close()) {\r\n return error(`missing '}'`);\r\n }\r\n return decls;\r\n }\r\n function keyframe() {\r\n let m;\r\n const vals = [];\r\n const pos = position();\r\n while ((m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/))) {\r\n vals.push(m[1]);\r\n match(/^,\\s*/);\r\n }\r\n if (!vals.length) {\r\n return;\r\n }\r\n return pos({\r\n type: 'keyframe',\r\n values: vals,\r\n declarations: declarations(),\r\n });\r\n }\r\n function atkeyframes() {\r\n const pos = position();\r\n let m = match(/^@([-\\w]+)?keyframes\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = m[1];\r\n m = match(/^([-\\w]+)\\s*/);\r\n if (!m) {\r\n return error('@keyframes missing name');\r\n }\r\n const name = m[1];\r\n if (!open()) {\r\n return error(`@keyframes missing '{'`);\r\n }\r\n let frame;\r\n let frames = comments();\r\n while ((frame = keyframe())) {\r\n frames.push(frame);\r\n frames = frames.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@keyframes missing '}'`);\r\n }\r\n return pos({\r\n type: 'keyframes',\r\n name,\r\n vendor,\r\n keyframes: frames,\r\n });\r\n }\r\n function atsupports() {\r\n const pos = position();\r\n const m = match(/^@supports *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const supports = trim(m[1]);\r\n if (!open()) {\r\n return error(`@supports missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@supports missing '}'`);\r\n }\r\n return pos({\r\n type: 'supports',\r\n supports,\r\n rules: style,\r\n });\r\n }\r\n function athost() {\r\n const pos = position();\r\n const m = match(/^@host\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@host missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@host missing '}'`);\r\n }\r\n return pos({\r\n type: 'host',\r\n rules: style,\r\n });\r\n }\r\n function atmedia() {\r\n const pos = position();\r\n const m = match(/^@media *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const media = trim(m[1]);\r\n if (!open()) {\r\n return error(`@media missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@media missing '}'`);\r\n }\r\n return pos({\r\n type: 'media',\r\n media,\r\n rules: style,\r\n });\r\n }\r\n function atcustommedia() {\r\n const pos = position();\r\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\r\n if (!m) {\r\n return;\r\n }\r\n return pos({\r\n type: 'custom-media',\r\n name: trim(m[1]),\r\n media: trim(m[2]),\r\n });\r\n }\r\n function atpage() {\r\n const pos = position();\r\n const m = match(/^@page */);\r\n if (!m) {\r\n return;\r\n }\r\n const sel = selector() || [];\r\n if (!open()) {\r\n return error(`@page missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@page missing '}'`);\r\n }\r\n return pos({\r\n type: 'page',\r\n selectors: sel,\r\n declarations: decls,\r\n });\r\n }\r\n function atdocument() {\r\n const pos = position();\r\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = trim(m[1]);\r\n const doc = trim(m[2]);\r\n if (!open()) {\r\n return error(`@document missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@document missing '}'`);\r\n }\r\n return pos({\r\n type: 'document',\r\n document: doc,\r\n vendor,\r\n rules: style,\r\n });\r\n }\r\n function atfontface() {\r\n const pos = position();\r\n const m = match(/^@font-face\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@font-face missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@font-face missing '}'`);\r\n }\r\n return pos({\r\n type: 'font-face',\r\n declarations: decls,\r\n });\r\n }\r\n const atimport = _compileAtrule('import');\r\n const atcharset = _compileAtrule('charset');\r\n const atnamespace = _compileAtrule('namespace');\r\n function _compileAtrule(name) {\r\n const re = new RegExp('^@' + name + '\\\\s*([^;]+);');\r\n return () => {\r\n const pos = position();\r\n const m = match(re);\r\n if (!m) {\r\n return;\r\n }\r\n const ret = { type: name };\r\n ret[name] = m[1].trim();\r\n return pos(ret);\r\n };\r\n }\r\n function atrule() {\r\n if (css[0] !== '@') {\r\n return;\r\n }\r\n return (atkeyframes() ||\r\n atmedia() ||\r\n atcustommedia() ||\r\n atsupports() ||\r\n atimport() ||\r\n atcharset() ||\r\n atnamespace() ||\r\n atdocument() ||\r\n atpage() ||\r\n athost() ||\r\n atfontface());\r\n }\r\n function rule() {\r\n const pos = position();\r\n const sel = selector();\r\n if (!sel) {\r\n return error('selector missing');\r\n }\r\n comments();\r\n return pos({\r\n type: 'rule',\r\n selectors: sel,\r\n declarations: declarations(),\r\n });\r\n }\r\n return addParent(stylesheet());\r\n}\r\nfunction trim(str) {\r\n return str ? str.replace(/^\\s+|\\s+$/g, '') : '';\r\n}\r\nfunction addParent(obj, parent) {\r\n const isNode = obj && typeof obj.type === 'string';\r\n const childParent = isNode ? obj : parent;\r\n for (const k of Object.keys(obj)) {\r\n const value = obj[k];\r\n if (Array.isArray(value)) {\r\n value.forEach((v) => {\r\n addParent(v, childParent);\r\n });\r\n }\r\n else if (value && typeof value === 'object') {\r\n addParent(value, childParent);\r\n }\r\n }\r\n if (isNode) {\r\n Object.defineProperty(obj, 'parent', {\r\n configurable: true,\r\n writable: true,\r\n enumerable: false,\r\n value: parent || null,\r\n });\r\n }\r\n return obj;\r\n}\n\nconst tagMap = {\r\n script: 'noscript',\r\n altglyph: 'altGlyph',\r\n altglyphdef: 'altGlyphDef',\r\n altglyphitem: 'altGlyphItem',\r\n animatecolor: 'animateColor',\r\n animatemotion: 'animateMotion',\r\n animatetransform: 'animateTransform',\r\n clippath: 'clipPath',\r\n feblend: 'feBlend',\r\n fecolormatrix: 'feColorMatrix',\r\n fecomponenttransfer: 'feComponentTransfer',\r\n fecomposite: 'feComposite',\r\n feconvolvematrix: 'feConvolveMatrix',\r\n fediffuselighting: 'feDiffuseLighting',\r\n fedisplacementmap: 'feDisplacementMap',\r\n fedistantlight: 'feDistantLight',\r\n fedropshadow: 'feDropShadow',\r\n feflood: 'feFlood',\r\n fefunca: 'feFuncA',\r\n fefuncb: 'feFuncB',\r\n fefuncg: 'feFuncG',\r\n fefuncr: 'feFuncR',\r\n fegaussianblur: 'feGaussianBlur',\r\n feimage: 'feImage',\r\n femerge: 'feMerge',\r\n femergenode: 'feMergeNode',\r\n femorphology: 'feMorphology',\r\n feoffset: 'feOffset',\r\n fepointlight: 'fePointLight',\r\n fespecularlighting: 'feSpecularLighting',\r\n fespotlight: 'feSpotLight',\r\n fetile: 'feTile',\r\n feturbulence: 'feTurbulence',\r\n foreignobject: 'foreignObject',\r\n glyphref: 'glyphRef',\r\n lineargradient: 'linearGradient',\r\n radialgradient: 'radialGradient',\r\n};\r\nfunction getTagName(n) {\r\n let tagName = tagMap[n.tagName] ? tagMap[n.tagName] : n.tagName;\r\n if (tagName === 'link' && n.attributes._cssText) {\r\n tagName = 'style';\r\n }\r\n return tagName;\r\n}\r\nfunction escapeRegExp(str) {\r\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\nconst HOVER_SELECTOR = /([^\\\\]):hover/;\r\nconst HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, 'g');\r\nfunction addHoverClass(cssText, cache) {\r\n const cachedStyle = cache?.stylesWithHoverClass.get(cssText);\r\n if (cachedStyle)\r\n return cachedStyle;\r\n if (cssText.length >= 1000000) {\r\n return cssText;\r\n }\r\n const ast = parse(cssText, {\r\n silent: true,\r\n });\r\n if (!ast.stylesheet) {\r\n return cssText;\r\n }\r\n const selectors = [];\r\n ast.stylesheet.rules.forEach((rule) => {\r\n if ('selectors' in rule) {\r\n (rule.selectors || []).forEach((selector) => {\r\n if (HOVER_SELECTOR.test(selector)) {\r\n selectors.push(selector);\r\n }\r\n });\r\n }\r\n });\r\n if (selectors.length === 0) {\r\n return cssText;\r\n }\r\n const selectorMatcher = new RegExp(selectors\r\n .filter((selector, index) => selectors.indexOf(selector) === index)\r\n .sort((a, b) => b.length - a.length)\r\n .map((selector) => {\r\n return escapeRegExp(selector);\r\n })\r\n .join('|'), 'g');\r\n const result = cssText.replace(selectorMatcher, (selector) => {\r\n const newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, '$1.\\\\:hover');\r\n return `${selector}, ${newSelector}`;\r\n });\r\n cache?.stylesWithHoverClass.set(cssText, result);\r\n return result;\r\n}\r\nfunction createCache() {\r\n const stylesWithHoverClass = new Map();\r\n return {\r\n stylesWithHoverClass,\r\n };\r\n}\r\nfunction buildNode(n, options) {\r\n const { doc, hackCss, cache } = options;\r\n switch (n.type) {\r\n case NodeType.Document:\r\n return doc.implementation.createDocument(null, '', null);\r\n case NodeType.DocumentType:\r\n return doc.implementation.createDocumentType(n.name || 'html', n.publicId, n.systemId);\r\n case NodeType.Element: {\r\n const tagName = getTagName(n);\r\n let node;\r\n if (n.isSVG) {\r\n node = doc.createElementNS('http://www.w3.org/2000/svg', tagName);\r\n }\r\n else {\r\n if (n.isCustom &&\r\n doc.defaultView?.customElements &&\r\n !doc.defaultView.customElements.get(n.tagName))\r\n doc.defaultView.customElements.define(n.tagName, class extends doc.defaultView.HTMLElement {\r\n });\r\n node = doc.createElement(tagName);\r\n }\r\n const specialAttributes = {};\r\n for (const name in n.attributes) {\r\n if (!Object.prototype.hasOwnProperty.call(n.attributes, name)) {\r\n continue;\r\n }\r\n let value = n.attributes[name];\r\n if (tagName === 'option' &&\r\n name === 'selected' &&\r\n value === false) {\r\n continue;\r\n }\r\n if (value === null) {\r\n continue;\r\n }\r\n if (value === true)\r\n value = '';\r\n if (name.startsWith('rr_')) {\r\n specialAttributes[name] = value;\r\n continue;\r\n }\r\n const isTextarea = tagName === 'textarea' && name === 'value';\r\n const isRemoteOrDynamicCss = tagName === 'style' && name === '_cssText';\r\n if (isRemoteOrDynamicCss && hackCss && typeof value === 'string') {\r\n value = addHoverClass(value, cache);\r\n }\r\n if ((isTextarea || isRemoteOrDynamicCss) && typeof value === 'string') {\r\n const child = doc.createTextNode(value);\r\n for (const c of Array.from(node.childNodes)) {\r\n if (c.nodeType === node.TEXT_NODE) {\r\n node.removeChild(c);\r\n }\r\n }\r\n node.appendChild(child);\r\n continue;\r\n }\r\n try {\r\n if (n.isSVG && name === 'xlink:href') {\r\n node.setAttributeNS('http://www.w3.org/1999/xlink', name, value.toString());\r\n }\r\n else if (name === 'onload' ||\r\n name === 'onclick' ||\r\n name.substring(0, 7) === 'onmouse') {\r\n node.setAttribute('_' + name, value.toString());\r\n }\r\n else if (tagName === 'meta' &&\r\n n.attributes['http-equiv'] === 'Content-Security-Policy' &&\r\n name === 'content') {\r\n node.setAttribute('csp-content', value.toString());\r\n continue;\r\n }\r\n else if (tagName === 'link' &&\r\n (n.attributes.rel === 'preload' ||\r\n n.attributes.rel === 'modulepreload') &&\r\n n.attributes.as === 'script') {\r\n }\r\n else if (tagName === 'link' &&\r\n n.attributes.rel === 'prefetch' &&\r\n typeof n.attributes.href === 'string' &&\r\n n.attributes.href.endsWith('.js')) {\r\n }\r\n else if (tagName === 'img' &&\r\n n.attributes.srcset &&\r\n n.attributes.rr_dataURL) {\r\n node.setAttribute('rrweb-original-srcset', n.attributes.srcset);\r\n }\r\n else {\r\n node.setAttribute(name, value.toString());\r\n }\r\n }\r\n catch (error) {\r\n }\r\n }\r\n for (const name in specialAttributes) {\r\n const value = specialAttributes[name];\r\n if (tagName === 'canvas' && name === 'rr_dataURL') {\r\n const image = document.createElement('img');\r\n image.onload = () => {\r\n const ctx = node.getContext('2d');\r\n if (ctx) {\r\n ctx.drawImage(image, 0, 0, image.width, image.height);\r\n }\r\n };\r\n image.src = value.toString();\r\n if (node.RRNodeType)\r\n node.rr_dataURL = value.toString();\r\n }\r\n else if (tagName === 'img' && name === 'rr_dataURL') {\r\n const image = node;\r\n if (!image.currentSrc.startsWith('data:')) {\r\n image.setAttribute('rrweb-original-src', n.attributes.src);\r\n image.src = value.toString();\r\n }\r\n }\r\n if (name === 'rr_width') {\r\n node.style.setProperty('width', value.toString());\r\n }\r\n else if (name === 'rr_height') {\r\n node.style.setProperty('height', value.toString());\r\n }\r\n else if (name === 'rr_mediaCurrentTime' &&\r\n typeof value === 'number') {\r\n node.currentTime = value;\r\n }\r\n else if (name === 'rr_mediaState') {\r\n switch (value) {\r\n case 'played':\r\n node\r\n .play()\r\n .catch((e) => console.warn('media playback error', e));\r\n break;\r\n case 'paused':\r\n node.pause();\r\n break;\r\n }\r\n }\r\n }\r\n if (n.isShadowHost) {\r\n if (!node.shadowRoot) {\r\n node.attachShadow({ mode: 'open' });\r\n }\r\n else {\r\n while (node.shadowRoot.firstChild) {\r\n node.shadowRoot.removeChild(node.shadowRoot.firstChild);\r\n }\r\n }\r\n }\r\n return node;\r\n }\r\n case NodeType.Text:\r\n return doc.createTextNode(n.isStyle && hackCss\r\n ? addHoverClass(n.textContent, cache)\r\n : n.textContent);\r\n case NodeType.CDATA:\r\n return doc.createCDATASection(n.textContent);\r\n case NodeType.Comment:\r\n return doc.createComment(n.textContent);\r\n default:\r\n return null;\r\n }\r\n}\r\nfunction buildNodeWithSN(n, options) {\r\n const { doc, mirror, skipChild = false, hackCss = true, afterAppend, cache, } = options;\r\n if (mirror.has(n.id)) {\r\n const nodeInMirror = mirror.getNode(n.id);\r\n const meta = mirror.getMeta(nodeInMirror);\r\n if (isNodeMetaEqual(meta, n))\r\n return mirror.getNode(n.id);\r\n }\r\n let node = buildNode(n, { doc, hackCss, cache });\r\n if (!node) {\r\n return null;\r\n }\r\n if (n.rootId && mirror.getNode(n.rootId) !== doc) {\r\n mirror.replace(n.rootId, doc);\r\n }\r\n if (n.type === NodeType.Document) {\r\n doc.close();\r\n doc.open();\r\n if (n.compatMode === 'BackCompat' &&\r\n n.childNodes &&\r\n n.childNodes[0].type !== NodeType.DocumentType) {\r\n if (n.childNodes[0].type === NodeType.Element &&\r\n 'xmlns' in n.childNodes[0].attributes &&\r\n n.childNodes[0].attributes.xmlns === 'http://www.w3.org/1999/xhtml') {\r\n doc.write('');\r\n }\r\n else {\r\n doc.write('');\r\n }\r\n }\r\n node = doc;\r\n }\r\n mirror.add(node, n);\r\n if ((n.type === NodeType.Document || n.type === NodeType.Element) &&\r\n !skipChild) {\r\n for (const childN of n.childNodes) {\r\n const childNode = buildNodeWithSN(childN, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n if (!childNode) {\r\n console.warn('Failed to rebuild', childN);\r\n continue;\r\n }\r\n if (childN.isShadow && isElement(node) && node.shadowRoot) {\r\n node.shadowRoot.appendChild(childNode);\r\n }\r\n else if (n.type === NodeType.Document &&\r\n childN.type == NodeType.Element) {\r\n const htmlElement = childNode;\r\n let body = null;\r\n htmlElement.childNodes.forEach((child) => {\r\n if (child.nodeName === 'BODY')\r\n body = child;\r\n });\r\n if (body) {\r\n htmlElement.removeChild(body);\r\n node.appendChild(childNode);\r\n htmlElement.appendChild(body);\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n if (afterAppend) {\r\n afterAppend(childNode, childN.id);\r\n }\r\n }\r\n }\r\n return node;\r\n}\r\nfunction visit(mirror, onVisit) {\r\n function walk(node) {\r\n onVisit(node);\r\n }\r\n for (const id of mirror.getIds()) {\r\n if (mirror.has(id)) {\r\n walk(mirror.getNode(id));\r\n }\r\n }\r\n}\r\nfunction handleScroll(node, mirror) {\r\n const n = mirror.getMeta(node);\r\n if (n?.type !== NodeType.Element) {\r\n return;\r\n }\r\n const el = node;\r\n for (const name in n.attributes) {\r\n if (!(Object.prototype.hasOwnProperty.call(n.attributes, name) &&\r\n name.startsWith('rr_'))) {\r\n continue;\r\n }\r\n const value = n.attributes[name];\r\n if (name === 'rr_scrollLeft') {\r\n el.scrollLeft = value;\r\n }\r\n if (name === 'rr_scrollTop') {\r\n el.scrollTop = value;\r\n }\r\n }\r\n}\r\nfunction rebuild(n, options) {\r\n const { doc, onVisit, hackCss = true, afterAppend, cache, mirror = new Mirror(), } = options;\r\n const node = buildNodeWithSN(n, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n visit(mirror, (visitedNode) => {\r\n if (onVisit) {\r\n onVisit(visitedNode);\r\n }\r\n handleScroll(visitedNode, mirror);\r\n });\r\n return node;\r\n}\n\nexport { IGNORED_NODE, Mirror, NodeType, addHoverClass, buildNodeWithSN, classMatchesRegex, cleanupSnapshot, createCache, createMatchPredicate, createMirror, distanceToMatch, escapeImportStatement, fixSafariColons, genId, getInputType, getInputValue, ignoreAttribute, is2DCanvasBlank, isCSSImportRule, isCSSStyleRule, isElement, isNativeShadowDom, isNodeMetaEqual, isShadowRoot, maskInputValue, needMaskingText, rebuild, serializeNodeWithId, shouldMaskInput, snapshot, stringifyRule, stringifyStylesheet, toLowerCase, toUpperCase, transformAttribute, visitSnapshot };\n","import type { ReplayBreadcrumbFrame } from '../types/replayFrame';\n\n/**\n * Create a breadcrumb for a replay.\n */\nexport function createBreadcrumb(\n breadcrumb: Omit & Partial>,\n): ReplayBreadcrumbFrame {\n return {\n timestamp: Date.now() / 1000,\n type: 'default',\n ...breadcrumb,\n };\n}\n","// Note that these are the serialized attributes and not attributes directly on\n// the DOM Node. Attributes we are interested in:\nconst ATTRIBUTES_TO_RECORD = new Set([\n 'id',\n 'class',\n 'aria-label',\n 'role',\n 'name',\n 'alt',\n 'title',\n 'data-test-id',\n 'data-testid',\n 'disabled',\n 'aria-disabled',\n 'data-sentry-component',\n]);\n\n/**\n * Inclusion list of attributes that we want to record from the DOM element\n */\nexport function getAttributesToRecord(attributes: Record): Record {\n const obj: Record = {};\n for (const key in attributes) {\n if (ATTRIBUTES_TO_RECORD.has(key)) {\n let normalizedKey = key;\n\n if (key === 'data-testid' || key === 'data-test-id') {\n normalizedKey = 'testId';\n }\n\n obj[normalizedKey] = attributes[key];\n }\n }\n\n return obj;\n}\n","import { record } from '@sentry-internal/rrweb';\nimport type { serializedElementNodeWithId, serializedNodeWithId } from '@sentry-internal/rrweb-snapshot';\nimport { NodeType } from '@sentry-internal/rrweb-snapshot';\nimport type { Breadcrumb, HandlerDataDom } from '@sentry/types';\nimport { htmlTreeAsString } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../types';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { handleClick } from './handleClick';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\nimport { getClickTargetNode, getTargetNode } from './util/domUtils';\nimport { getAttributesToRecord } from './util/getAttributesToRecord';\n\nexport const handleDomListener: (replay: ReplayContainer) => (handlerData: HandlerDataDom) => void = (\n replay: ReplayContainer,\n) => {\n return (handlerData: HandlerDataDom): void => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleDom(handlerData);\n\n if (!result) {\n return;\n }\n\n const isClick = handlerData.name === 'click';\n const event = isClick ? (handlerData.event as PointerEvent) : undefined;\n // Ignore clicks if ctrl/alt/meta/shift keys are held down as they alter behavior of clicks (e.g. open in new tab)\n if (\n isClick &&\n replay.clickDetector &&\n event &&\n event.target &&\n !event.altKey &&\n !event.metaKey &&\n !event.ctrlKey &&\n !event.shiftKey\n ) {\n handleClick(\n replay.clickDetector,\n result as Breadcrumb & { timestamp: number; data: { nodeId: number } },\n getClickTargetNode(handlerData.event as Event) as HTMLElement,\n );\n }\n\n addBreadcrumbEvent(replay, result);\n };\n};\n\n/** Get the base DOM breadcrumb. */\nexport function getBaseDomBreadcrumb(target: Node | null, message: string): Breadcrumb {\n const nodeId = record.mirror.getId(target);\n const node = nodeId && record.mirror.getNode(nodeId);\n const meta = node && record.mirror.getMeta(node);\n const element = meta && isElement(meta) ? meta : null;\n\n return {\n message,\n data: element\n ? {\n nodeId,\n node: {\n id: nodeId,\n tagName: element.tagName,\n textContent: Array.from(element.childNodes)\n .map((node: serializedNodeWithId) => node.type === NodeType.Text && node.textContent)\n .filter(Boolean) // filter out empty values\n .map(text => (text as string).trim())\n .join(''),\n attributes: getAttributesToRecord(element.attributes),\n },\n }\n : {},\n };\n}\n\n/**\n * An event handler to react to DOM events.\n * Exported for tests.\n */\nexport function handleDom(handlerData: HandlerDataDom): Breadcrumb | null {\n const { target, message } = getDomTarget(handlerData);\n\n return createBreadcrumb({\n category: `ui.${handlerData.name}`,\n ...getBaseDomBreadcrumb(target, message),\n });\n}\n\nfunction getDomTarget(handlerData: HandlerDataDom): { target: Node | null; message: string } {\n const isClick = handlerData.name === 'click';\n\n let message: string | undefined;\n let target: Node | null = null;\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n target = isClick ? getClickTargetNode(handlerData.event as Event) : getTargetNode(handlerData.event as Event);\n message = htmlTreeAsString(target, { maxStringLength: 200 }) || '';\n } catch (e) {\n message = '';\n }\n\n return { target, message };\n}\n\nfunction isElement(node: serializedNodeWithId): node is serializedElementNodeWithId {\n return node.type === NodeType.Element;\n}\n","import type { Breadcrumb } from '@sentry/types';\nimport { htmlTreeAsString } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../types';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { getBaseDomBreadcrumb } from './handleDom';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\n\n/** Handle keyboard events & create breadcrumbs. */\nexport function handleKeyboardEvent(replay: ReplayContainer, event: KeyboardEvent): void {\n if (!replay.isEnabled()) {\n return;\n }\n\n // Update user activity, but do not restart recording as it can create\n // noisy/low-value replays (e.g. user comes back from idle, hits alt-tab, new\n // session with a single \"keydown\" breadcrumb is created)\n replay.updateUserActivity();\n\n const breadcrumb = getKeyboardBreadcrumb(event);\n\n if (!breadcrumb) {\n return;\n }\n\n addBreadcrumbEvent(replay, breadcrumb);\n}\n\n/** exported only for tests */\nexport function getKeyboardBreadcrumb(event: KeyboardEvent): Breadcrumb | null {\n const { metaKey, shiftKey, ctrlKey, altKey, key, target } = event;\n\n // never capture for input fields\n if (!target || isInputElement(target as HTMLElement) || !key) {\n return null;\n }\n\n // Note: We do not consider shift here, as that means \"uppercase\"\n const hasModifierKey = metaKey || ctrlKey || altKey;\n const isCharacterKey = key.length === 1; // other keys like Escape, Tab, etc have a longer length\n\n // Do not capture breadcrumb if only a word key is pressed\n // This could leak e.g. user input\n if (!hasModifierKey && isCharacterKey) {\n return null;\n }\n\n const message = htmlTreeAsString(target, { maxStringLength: 200 }) || '';\n const baseBreadcrumb = getBaseDomBreadcrumb(target as Node, message);\n\n return createBreadcrumb({\n category: 'ui.keyDown',\n message,\n data: {\n ...baseBreadcrumb.data,\n metaKey,\n shiftKey,\n ctrlKey,\n altKey,\n key,\n },\n });\n}\n\nfunction isInputElement(target: HTMLElement): boolean {\n return target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable;\n}\n","import { record } from '@sentry-internal/rrweb';\nimport { browserPerformanceTimeOrigin } from '@sentry/utils';\n\nimport { WINDOW } from '../constants';\nimport type {\n AllPerformanceEntry,\n AllPerformanceEntryData,\n ExperimentalPerformanceResourceTiming,\n LargestContentfulPaintData,\n NavigationData,\n PaintData,\n ReplayPerformanceEntry,\n ResourceData,\n} from '../types';\n\n// Map entryType -> function to normalize data for event\nconst ENTRY_TYPES: Record<\n string,\n (entry: AllPerformanceEntry) => null | ReplayPerformanceEntry\n> = {\n // @ts-expect-error TODO: entry type does not fit the create* functions entry type\n resource: createResourceEntry,\n paint: createPaintEntry,\n // @ts-expect-error TODO: entry type does not fit the create* functions entry type\n navigation: createNavigationEntry,\n};\n\n/**\n * Create replay performance entries from the browser performance entries.\n */\nexport function createPerformanceEntries(\n entries: AllPerformanceEntry[],\n): ReplayPerformanceEntry[] {\n return entries.map(createPerformanceEntry).filter(Boolean) as ReplayPerformanceEntry[];\n}\n\nfunction createPerformanceEntry(entry: AllPerformanceEntry): ReplayPerformanceEntry | null {\n if (!ENTRY_TYPES[entry.entryType]) {\n return null;\n }\n\n return ENTRY_TYPES[entry.entryType](entry);\n}\n\nfunction getAbsoluteTime(time: number): number {\n // browserPerformanceTimeOrigin can be undefined if `performance` or\n // `performance.now` doesn't exist, but this is already checked by this integration\n return ((browserPerformanceTimeOrigin || WINDOW.performance.timeOrigin) + time) / 1000;\n}\n\nfunction createPaintEntry(entry: PerformancePaintTiming): ReplayPerformanceEntry {\n const { duration, entryType, name, startTime } = entry;\n\n const start = getAbsoluteTime(startTime);\n return {\n type: entryType,\n name,\n start,\n end: start + duration,\n data: undefined,\n };\n}\n\nfunction createNavigationEntry(entry: PerformanceNavigationTiming): ReplayPerformanceEntry | null {\n const {\n entryType,\n name,\n decodedBodySize,\n duration,\n domComplete,\n encodedBodySize,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n domInteractive,\n loadEventStart,\n loadEventEnd,\n redirectCount,\n startTime,\n transferSize,\n type,\n } = entry;\n\n // Ignore entries with no duration, they do not seem to be useful and cause dupes\n if (duration === 0) {\n return null;\n }\n\n return {\n type: `${entryType}.${type}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(domComplete),\n name,\n data: {\n size: transferSize,\n decodedBodySize,\n encodedBodySize,\n duration,\n domInteractive,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n loadEventStart,\n loadEventEnd,\n domComplete,\n redirectCount,\n },\n };\n}\n\nfunction createResourceEntry(\n entry: ExperimentalPerformanceResourceTiming,\n): ReplayPerformanceEntry | null {\n const {\n entryType,\n initiatorType,\n name,\n responseEnd,\n startTime,\n decodedBodySize,\n encodedBodySize,\n responseStatus,\n transferSize,\n } = entry;\n\n // Core SDK handles these\n if (['fetch', 'xmlhttprequest'].includes(initiatorType)) {\n return null;\n }\n\n return {\n type: `${entryType}.${initiatorType}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(responseEnd),\n name,\n data: {\n size: transferSize,\n statusCode: responseStatus,\n decodedBodySize,\n encodedBodySize,\n },\n };\n}\n\n/**\n * Add a LCP event to the replay based on an LCP metric.\n */\nexport function getLargestContentfulPaint(metric: {\n value: number;\n entries: PerformanceEntry[];\n}): ReplayPerformanceEntry {\n const entries = metric.entries;\n const lastEntry = entries[entries.length - 1] as (PerformanceEntry & { element?: Element }) | undefined;\n const element = lastEntry ? lastEntry.element : undefined;\n\n const value = metric.value;\n\n const end = getAbsoluteTime(value);\n\n const data: ReplayPerformanceEntry = {\n type: 'largest-contentful-paint',\n name: 'largest-contentful-paint',\n start: end,\n end,\n data: {\n value,\n size: value,\n nodeId: element ? record.mirror.getId(element) : undefined,\n },\n };\n\n return data;\n}\n","import { addLcpInstrumentationHandler, addPerformanceInstrumentationHandler } from '@sentry-internal/tracing';\n\nimport type { ReplayContainer } from '../types';\nimport { getLargestContentfulPaint } from '../util/createPerformanceEntries';\n\n/**\n * Sets up a PerformanceObserver to listen to all performance entry types.\n * Returns a callback to stop observing.\n */\nexport function setupPerformanceObserver(replay: ReplayContainer): () => void {\n function addPerformanceEntry(entry: PerformanceEntry): void {\n // It is possible for entries to come up multiple times\n if (!replay.performanceEntries.includes(entry)) {\n replay.performanceEntries.push(entry);\n }\n }\n\n function onEntries({ entries }: { entries: PerformanceEntry[] }): void {\n entries.forEach(addPerformanceEntry);\n }\n\n const clearCallbacks: (() => void)[] = [];\n\n (['navigation', 'paint', 'resource'] as const).forEach(type => {\n clearCallbacks.push(addPerformanceInstrumentationHandler(type, onEntries));\n });\n\n clearCallbacks.push(\n addLcpInstrumentationHandler(({ metric }) => {\n replay.replayPerformanceEntries.push(getLargestContentfulPaint(metric));\n }),\n );\n\n // A callback to cleanup all handlers\n return () => {\n clearCallbacks.forEach(clearCallback => clearCallback());\n };\n}\n","export default `var t=Uint8Array,n=Uint16Array,r=Int32Array,e=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),a=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=function(t,e){for(var i=new n(31),a=0;a<31;++a)i[a]=e+=1<>1|(21845&c)<<1;v=(61680&(v=(52428&v)>>2|(13107&v)<<2))>>4|(3855&v)<<4,u[c]=((65280&v)>>8|(255&v)<<8)>>1}var d=function(t,r,e){for(var i=t.length,a=0,s=new n(r);a>h]=l}else for(o=new n(i),a=0;a>15-t[a]);return o},g=new t(288);for(c=0;c<144;++c)g[c]=8;for(c=144;c<256;++c)g[c]=9;for(c=256;c<280;++c)g[c]=7;for(c=280;c<288;++c)g[c]=8;var w=new t(32);for(c=0;c<32;++c)w[c]=5;var p=d(g,9,0),y=d(w,5,0),m=function(t){return(t+7)/8|0},b=function(n,r,e){return(null==r||r<0)&&(r=0),(null==e||e>n.length)&&(e=n.length),new t(n.subarray(r,e))},M=[\"unexpected EOF\",\"invalid block type\",\"invalid length/literal\",\"invalid distance\",\"stream finished\",\"no stream handler\",,\"no callback\",\"invalid UTF-8 data\",\"extra field too long\",\"date not in range 1980-2099\",\"filename too long\",\"stream finishing\",\"invalid zip data\"],E=function(t,n,r){var e=new Error(n||M[t]);if(e.code=t,Error.captureStackTrace&&Error.captureStackTrace(e,E),!r)throw e;return e},z=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8},A=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8,t[e+2]|=r>>16},_=function(r,e){for(var i=[],a=0;ad&&(d=o[a].s);var g=new n(d+1),w=x(i[c-1],g,0);if(w>e){a=0;var p=0,y=w-e,m=1<e))break;p+=m-(1<>=y;p>0;){var M=o[a].s;g[M]=0&&p;--a){var E=o[a].s;g[E]==e&&(--g[E],++p)}w=e}return{t:new t(g),l:w}},x=function(t,n,r){return-1==t.s?Math.max(x(t.l,n,r+1),x(t.r,n,r+1)):n[t.s]=r},D=function(t){for(var r=t.length;r&&!t[--r];);for(var e=new n(++r),i=0,a=t[0],s=1,o=function(t){e[i++]=t},f=1;f<=r;++f)if(t[f]==a&&f!=r)++s;else{if(!a&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(a),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(a);s=1,a=t[f]}return{c:e.subarray(0,i),n:r}},T=function(t,n){for(var r=0,e=0;e>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var a=0;a4&&!H[a[K-1]];--K);var N,P,Q,R,V=v+5<<3,W=T(f,g)+T(h,w)+l,X=T(f,M)+T(h,C)+l+14+3*K+T(q,H)+2*q[16]+3*q[17]+7*q[18];if(c>=0&&V<=W&&V<=X)return k(r,m,t.subarray(c,c+v));if(z(r,m,1+(X15&&(z(r,m,tt[B]>>5&127),m+=tt[B]>>12)}}}else N=p,P=g,Q=y,R=w;for(B=0;B255){A(r,m,N[(nt=rt>>18&31)+257]),m+=P[nt+257],nt>7&&(z(r,m,rt>>23&31),m+=e[nt]);var et=31&rt;A(r,m,Q[et]),m+=R[et],et>3&&(A(r,m,rt>>5&8191),m+=i[et])}else A(r,m,N[rt]),m+=P[rt]}return A(r,m,N[256]),m+P[256]},U=new r([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),F=new t(0),I=function(){for(var t=new Int32Array(256),n=0;n<256;++n){for(var r=n,e=9;--e;)r=(1&r&&-306674912)^r>>>1;t[n]=r}return t}(),S=function(){var t=1,n=0;return{p:function(r){for(var e=t,i=n,a=0|r.length,s=0;s!=a;){for(var o=Math.min(s+2655,a);s>16),i=(65535&i)+15*(i>>16)}t=e,n=i},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},L=function(a,s,o,f,u){if(!u&&(u={l:1},s.dictionary)){var c=s.dictionary.subarray(-32768),v=new t(c.length+a.length);v.set(c),v.set(a,c.length),a=v,u.w=c.length}return function(a,s,o,f,u,c){var v=c.z||a.length,d=new t(f+v+5*(1+Math.ceil(v/7e3))+u),g=d.subarray(f,d.length-u),w=c.l,p=7&(c.r||0);if(s){p&&(g[0]=c.r>>3);for(var y=U[s-1],M=y>>13,E=8191&y,z=(1<7e3||q>24576)&&(N>423||!w)){p=C(a,g,0,F,I,S,O,q,G,j-G,p),q=L=O=0,G=j;for(var P=0;P<286;++P)I[P]=0;for(P=0;P<30;++P)S[P]=0}var Q=2,R=0,V=E,W=J-K&32767;if(N>2&&H==T(j-W))for(var X=Math.min(M,N)-1,Y=Math.min(32767,j),Z=Math.min(258,N);W<=Y&&--V&&J!=K;){if(a[j+Q]==a[j+Q-W]){for(var $=0;$Q){if(Q=$,R=W,$>X)break;var tt=Math.min(W,$-2),nt=0;for(P=0;Pnt&&(nt=et,K=rt)}}}W+=(J=K)-(K=A[J])&32767}if(R){F[q++]=268435456|h[Q]<<18|l[R];var it=31&h[Q],at=31&l[R];O+=e[it]+i[at],++I[257+it],++S[at],B=j+Q,++L}else F[q++]=a[j],++I[a[j]]}}for(j=Math.max(j,B);j=v&&(g[p/8|0]=w,st=v),p=k(g,p+1,a.subarray(j,st))}c.i=v}return b(d,0,f+m(p)+u)}(a,null==s.level?6:s.level,null==s.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(a.length)))):12+s.mem,o,f,u)},O=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},j=function(){function n(n,r){if(\"function\"==typeof n&&(r=n,n={}),this.ondata=r,this.o=n||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new t(98304),this.o.dictionary){var e=this.o.dictionary.subarray(-32768);this.b.set(e,32768-e.length),this.s.i=32768-e.length}}return n.prototype.p=function(t,n){this.ondata(L(t,this.o,0,0,this.s),n)},n.prototype.push=function(n,r){this.ondata||E(5),this.s.l&&E(4);var e=n.length+this.s.z;if(e>this.b.length){if(e>2*this.b.length-32768){var i=new t(-32768&e);i.set(this.b.subarray(0,this.s.z)),this.b=i}var a=this.b.length-this.s.z;a&&(this.b.set(n.subarray(0,a),this.s.z),this.s.z=this.b.length,this.p(this.b,!1)),this.b.set(this.b.subarray(-32768)),this.b.set(n.subarray(a),32768),this.s.z=n.length-a+32768,this.s.i=32766,this.s.w=32768}else this.b.set(n,this.s.z),this.s.z+=n.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2)},n}();function q(t,n){n||(n={});var r=function(){var t=-1;return{p:function(n){for(var r=t,e=0;e>>8;t=r},d:function(){return~t}}}(),e=t.length;r.p(t);var i,a=L(t,n,10+((i=n).filename?i.filename.length+1:0),8),s=a.length;return function(t,n){var r=n.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=n.level<2?4:9==n.level?2:0,t[9]=3,0!=n.mtime&&O(t,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),r){t[3]=8;for(var e=0;e<=r.length;++e)t[e+10]=r.charCodeAt(e)}}(a,n),O(a,s-8,r.d()),O(a,s-4,e),a}var B=function(){function t(t,n){this.c=S(),this.v=1,j.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),j.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=L(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(function(t,n){var r=n.level,e=0==r?0:r<6?1:9==r?3:2;if(t[0]=120,t[1]=e<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var i=S();i.p(n.dictionary),O(t,2,i.d())}}(r,this.o),this.v=0),n&&O(r,r.length-4,this.c.d()),this.ondata(r,n)},t}(),G=\"undefined\"!=typeof TextEncoder&&new TextEncoder,H=\"undefined\"!=typeof TextDecoder&&new TextDecoder;try{H.decode(F,{stream:!0})}catch(t){}var J=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||E(5),this.d&&E(4),this.ondata(K(t),this.d=n||!1)},t}();function K(n,r){if(r){for(var e=new t(n.length),i=0;i>1)),o=0,f=function(t){s[o++]=t};for(i=0;is.length){var h=new t(o+8+(a-i<<1));h.set(s),s=h}var l=n.charCodeAt(i);l<128||r?f(l):l<2048?(f(192|l>>6),f(128|63&l)):l>55295&&l<57344?(f(240|(l=65536+(1047552&l)|1023&n.charCodeAt(++i))>>18),f(128|l>>12&63),f(128|l>>6&63),f(128|63&l)):(f(224|l>>12),f(128|l>>6&63),f(128|63&l))}return b(s,0,o)}const N=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error(\"Adding invalid event\");const n=this._hasEvents?\",\":\"\";this.stream.push(n+t),this._hasEvents=!0}finish(){this.stream.push(\"]\",!0);const t=function(t){let n=0;for(let r=0,e=t.length;r{this._deflatedData.push(t)},this.stream=new J(((t,n)=>{this.deflate.push(t,n)})),this.stream.push(\"[\")}},P={clear:()=>{N.clear()},addEvent:t=>N.addEvent(t),finish:()=>N.finish(),compress:t=>function(t){return q(K(t))}(t)};addEventListener(\"message\",(function(t){const n=t.data.method,r=t.data.id,e=t.data.arg;if(n in P&&\"function\"==typeof P[n])try{const t=P[n](e);postMessage({id:r,method:n,success:!0,response:t})}catch(t){postMessage({id:r,method:n,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:\"init\",success:!0,response:void 0});`;\n","import { addBreadcrumb } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\n/**\n * Log a message in debug mode, and add a breadcrumb when _experiment.traceInternals is enabled.\n */\nexport function logInfo(message: string, shouldAddBreadcrumb?: boolean): void {\n if (!DEBUG_BUILD) {\n return;\n }\n\n logger.info(message);\n\n if (shouldAddBreadcrumb) {\n addLogBreadcrumb(message);\n }\n}\n\n/**\n * Log a message, and add a breadcrumb in the next tick.\n * This is necessary when the breadcrumb may be added before the replay is initialized.\n */\nexport function logInfoNextTick(message: string, shouldAddBreadcrumb?: boolean): void {\n if (!DEBUG_BUILD) {\n return;\n }\n\n logger.info(message);\n\n if (shouldAddBreadcrumb) {\n // Wait a tick here to avoid race conditions for some initial logs\n // which may be added before replay is initialized\n setTimeout(() => {\n addLogBreadcrumb(message);\n }, 0);\n }\n}\n\nfunction addLogBreadcrumb(message: string): void {\n addBreadcrumb(\n {\n category: 'console',\n data: {\n logger: 'replay',\n },\n level: 'info',\n message,\n },\n { level: 'info' },\n );\n}\n","import { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\n\n/** This error indicates that the event buffer size exceeded the limit.. */\nexport class EventBufferSizeExceededError extends Error {\n public constructor() {\n super(`Event buffer exceeded maximum size of ${REPLAY_MAX_EVENT_BUFFER_SIZE}.`);\n }\n}\n","import { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { timestampToMs } from '../util/timestamp';\nimport { EventBufferSizeExceededError } from './error';\n\n/**\n * A basic event buffer that does not do any compression.\n * Used as fallback if the compression worker cannot be loaded or is disabled.\n */\nexport class EventBufferArray implements EventBuffer {\n /** All the events that are buffered to be sent. */\n public events: RecordingEvent[];\n\n /** @inheritdoc */\n public hasCheckout: boolean;\n\n private _totalSize: number;\n\n public constructor() {\n this.events = [];\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n public get hasEvents(): boolean {\n return this.events.length > 0;\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return 'sync';\n }\n\n /** @inheritdoc */\n public destroy(): void {\n this.events = [];\n }\n\n /** @inheritdoc */\n public async addEvent(event: RecordingEvent): Promise {\n const eventSize = JSON.stringify(event).length;\n this._totalSize += eventSize;\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n throw new EventBufferSizeExceededError();\n }\n\n this.events.push(event);\n }\n\n /** @inheritdoc */\n public finish(): Promise {\n return new Promise(resolve => {\n // Make a copy of the events array reference and immediately clear the\n // events member so that we do not lose new events while uploading\n // attachment.\n const eventsRet = this.events;\n this.clear();\n resolve(JSON.stringify(eventsRet));\n });\n }\n\n /** @inheritdoc */\n public clear(): void {\n this.events = [];\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n const timestamp = this.events.map(event => event.timestamp).sort()[0];\n\n if (!timestamp) {\n return null;\n }\n\n return timestampToMs(timestamp);\n }\n}\n","import { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { WorkerRequest, WorkerResponse } from '../types';\nimport { logInfo } from '../util/log';\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nexport class WorkerHandler {\n private _worker: Worker;\n private _id: number;\n private _ensureReadyPromise?: Promise;\n\n public constructor(worker: Worker) {\n this._worker = worker;\n this._id = 0;\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occured.\n */\n public ensureReady(): Promise {\n // Ensure we only check once\n if (this._ensureReadyPromise) {\n return this._ensureReadyPromise;\n }\n\n this._ensureReadyPromise = new Promise((resolve, reject) => {\n this._worker.addEventListener(\n 'message',\n ({ data }: MessageEvent) => {\n if ((data as WorkerResponse).success) {\n resolve();\n } else {\n reject();\n }\n },\n { once: true },\n );\n\n this._worker.addEventListener(\n 'error',\n error => {\n reject(error);\n },\n { once: true },\n );\n });\n\n return this._ensureReadyPromise;\n }\n\n /**\n * Destroy the worker.\n */\n public destroy(): void {\n logInfo('[Replay] Destroying compression worker');\n this._worker.terminate();\n }\n\n /**\n * Post message to worker and wait for response before resolving promise.\n */\n public postMessage(method: WorkerRequest['method'], arg?: WorkerRequest['arg']): Promise {\n const id = this._getAndIncrementId();\n\n return new Promise((resolve, reject) => {\n const listener = ({ data }: MessageEvent): void => {\n const response = data as WorkerResponse;\n if (response.method !== method) {\n return;\n }\n\n // There can be multiple listeners for a single method, the id ensures\n // that the response matches the caller.\n if (response.id !== id) {\n return;\n }\n\n // At this point, we'll always want to remove listener regardless of result status\n this._worker.removeEventListener('message', listener);\n\n if (!response.success) {\n // TODO: Do some error handling, not sure what\n DEBUG_BUILD && logger.error('[Replay]', response.response);\n\n reject(new Error('Error in compression worker'));\n return;\n }\n\n resolve(response.response as T);\n };\n\n // Note: we can't use `once` option because it's possible it needs to\n // listen to multiple messages\n this._worker.addEventListener('message', listener);\n this._worker.postMessage({ id, method, arg });\n });\n }\n\n /** Get the current ID and increment it for the next call. */\n private _getAndIncrementId(): number {\n return this._id++;\n }\n}\n","import type { ReplayRecordingData } from '@sentry/types';\n\nimport { logger } from '@sentry/utils';\nimport { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { timestampToMs } from '../util/timestamp';\nimport { WorkerHandler } from './WorkerHandler';\nimport { EventBufferSizeExceededError } from './error';\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nexport class EventBufferCompressionWorker implements EventBuffer {\n /** @inheritdoc */\n public hasCheckout: boolean;\n\n private _worker: WorkerHandler;\n private _earliestTimestamp: number | null;\n private _totalSize;\n\n public constructor(worker: Worker) {\n this._worker = new WorkerHandler(worker);\n this._earliestTimestamp = null;\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n public get hasEvents(): boolean {\n return !!this._earliestTimestamp;\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return 'worker';\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occured.\n */\n public ensureReady(): Promise {\n return this._worker.ensureReady();\n }\n\n /**\n * Destroy the event buffer.\n */\n public destroy(): void {\n this._worker.destroy();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfuly received and processed by worker.\n */\n public addEvent(event: RecordingEvent): Promise {\n const timestamp = timestampToMs(event.timestamp);\n if (!this._earliestTimestamp || timestamp < this._earliestTimestamp) {\n this._earliestTimestamp = timestamp;\n }\n\n const data = JSON.stringify(event);\n this._totalSize += data.length;\n\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n return Promise.reject(new EventBufferSizeExceededError());\n }\n\n return this._sendEventToWorker(data);\n }\n\n /**\n * Finish the event buffer and return the compressed data.\n */\n public finish(): Promise {\n return this._finishRequest();\n }\n\n /** @inheritdoc */\n public clear(): void {\n this._earliestTimestamp = null;\n this._totalSize = 0;\n this.hasCheckout = false;\n\n // We do not wait on this, as we assume the order of messages is consistent for the worker\n this._worker.postMessage('clear').then(null, e => {\n DEBUG_BUILD && logger.warn('[Replay] Sending \"clear\" message to worker failed', e);\n });\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n return this._earliestTimestamp;\n }\n\n /**\n * Send the event to the worker.\n */\n private _sendEventToWorker(data: string): Promise {\n return this._worker.postMessage('addEvent', data);\n }\n\n /**\n * Finish the request and return the compressed data from the worker.\n */\n private async _finishRequest(): Promise {\n const response = await this._worker.postMessage('finish');\n\n this._earliestTimestamp = null;\n this._totalSize = 0;\n\n return response;\n }\n}\n","import type { ReplayRecordingData } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { logInfo } from '../util/log';\nimport { EventBufferArray } from './EventBufferArray';\nimport { EventBufferCompressionWorker } from './EventBufferCompressionWorker';\n\n/**\n * This proxy will try to use the compression worker, and fall back to use the simple buffer if an error occurs there.\n * This can happen e.g. if the worker cannot be loaded.\n * Exported only for testing.\n */\nexport class EventBufferProxy implements EventBuffer {\n private _fallback: EventBufferArray;\n private _compression: EventBufferCompressionWorker;\n private _used: EventBuffer;\n private _ensureWorkerIsLoadedPromise: Promise;\n\n public constructor(worker: Worker) {\n this._fallback = new EventBufferArray();\n this._compression = new EventBufferCompressionWorker(worker);\n this._used = this._fallback;\n\n this._ensureWorkerIsLoadedPromise = this._ensureWorkerIsLoaded();\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return this._used.type;\n }\n\n /** @inheritDoc */\n public get hasEvents(): boolean {\n return this._used.hasEvents;\n }\n\n /** @inheritdoc */\n public get hasCheckout(): boolean {\n return this._used.hasCheckout;\n }\n /** @inheritdoc */\n public set hasCheckout(value: boolean) {\n this._used.hasCheckout = value;\n }\n\n /** @inheritDoc */\n public destroy(): void {\n this._fallback.destroy();\n this._compression.destroy();\n }\n\n /** @inheritdoc */\n public clear(): void {\n return this._used.clear();\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n return this._used.getEarliestTimestamp();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfully added.\n */\n public addEvent(event: RecordingEvent): Promise {\n return this._used.addEvent(event);\n }\n\n /** @inheritDoc */\n public async finish(): Promise {\n // Ensure the worker is loaded, so the sent event is compressed\n await this.ensureWorkerIsLoaded();\n\n return this._used.finish();\n }\n\n /** Ensure the worker has loaded. */\n public ensureWorkerIsLoaded(): Promise {\n return this._ensureWorkerIsLoadedPromise;\n }\n\n /** Actually check if the worker has been loaded. */\n private async _ensureWorkerIsLoaded(): Promise {\n try {\n await this._compression.ensureReady();\n } catch (error) {\n // If the worker fails to load, we fall back to the simple buffer.\n // Nothing more to do from our side here\n logInfo('[Replay] Failed to load the compression worker, falling back to simple buffer');\n return;\n }\n\n // Now we need to switch over the array buffer to the compression worker\n await this._switchToCompressionWorker();\n }\n\n /** Switch the used buffer to the compression worker. */\n private async _switchToCompressionWorker(): Promise {\n const { events, hasCheckout } = this._fallback;\n\n const addEventPromises: Promise[] = [];\n for (const event of events) {\n addEventPromises.push(this._compression.addEvent(event));\n }\n\n this._compression.hasCheckout = hasCheckout;\n\n // We switch over to the new buffer immediately - any further events will be added\n // after the previously buffered ones\n this._used = this._compression;\n\n // Wait for original events to be re-added before resolving\n try {\n await Promise.all(addEventPromises);\n } catch (error) {\n DEBUG_BUILD && logger.warn('[Replay] Failed to add events when switching buffers.', error);\n }\n }\n}\n","import { getWorkerURL } from '@sentry-internal/replay-worker';\n\nimport type { EventBuffer } from '../types';\nimport { logInfo } from '../util/log';\nimport { EventBufferArray } from './EventBufferArray';\nimport { EventBufferProxy } from './EventBufferProxy';\n\ninterface CreateEventBufferParams {\n useCompression: boolean;\n workerUrl?: string;\n}\n\n// Treeshakable guard to remove the code of the included compression worker\ndeclare const __SENTRY_EXCLUDE_REPLAY_WORKER__: boolean;\n\n/**\n * Create an event buffer for replays.\n */\nexport function createEventBuffer({\n useCompression,\n workerUrl: customWorkerUrl,\n}: CreateEventBufferParams): EventBuffer {\n if (\n useCompression &&\n // eslint-disable-next-line no-restricted-globals\n window.Worker\n ) {\n const worker = _loadWorker(customWorkerUrl);\n\n if (worker) {\n return worker;\n }\n }\n\n logInfo('[Replay] Using simple buffer');\n return new EventBufferArray();\n}\n\nfunction _loadWorker(customWorkerUrl?: string): EventBufferProxy | void {\n try {\n const workerUrl = customWorkerUrl || _getWorkerUrl();\n\n if (!workerUrl) {\n return;\n }\n\n logInfo(`[Replay] Using compression worker${customWorkerUrl ? ` from ${customWorkerUrl}` : ''}`);\n const worker = new Worker(workerUrl);\n return new EventBufferProxy(worker);\n } catch (error) {\n logInfo('[Replay] Failed to create compression worker');\n // Fall back to use simple event buffer array\n }\n}\n\nfunction _getWorkerUrl(): string {\n if (typeof __SENTRY_EXCLUDE_REPLAY_WORKER__ === 'undefined' || !__SENTRY_EXCLUDE_REPLAY_WORKER__) {\n return getWorkerURL();\n }\n\n return '';\n}\n","import r from\"./worker\";function e(){const e=new Blob([r]);return URL.createObjectURL(e)}export{e as getWorkerURL};\n","import { WINDOW } from '../constants';\n\n/** If sessionStorage is available. */\nexport function hasSessionStorage(): boolean {\n try {\n // This can throw, e.g. when being accessed in a sandboxed iframe\n return 'sessionStorage' in WINDOW && !!WINDOW.sessionStorage;\n } catch {\n return false;\n }\n}\n","import { REPLAY_SESSION_KEY, WINDOW } from '../../src/constants';\nimport type { ReplayContainer } from '../../src/types';\nimport { hasSessionStorage } from '../util/hasSessionStorage';\n\n/**\n * Removes the session from Session Storage and unsets session in replay instance\n */\nexport function clearSession(replay: ReplayContainer): void {\n deleteSession();\n replay.session = undefined;\n}\n\n/**\n * Deletes a session from storage\n */\nfunction deleteSession(): void {\n if (!hasSessionStorage()) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.removeItem(REPLAY_SESSION_KEY);\n } catch {\n // Ignore potential SecurityError exceptions\n }\n}\n","/**\n * Given a sample rate, returns true if replay should be sampled.\n *\n * 1.0 = 100% sampling\n * 0.0 = 0% sampling\n */\nexport function isSampled(sampleRate?: number): boolean {\n if (sampleRate === undefined) {\n return false;\n }\n\n // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)\n return Math.random() < sampleRate;\n}\n","import { uuid4 } from '@sentry/utils';\n\nimport type { Sampled, Session } from '../types';\n\n/**\n * Get a session with defaults & applied sampling.\n */\nexport function makeSession(session: Partial & { sampled: Sampled }): Session {\n const now = Date.now();\n const id = session.id || uuid4();\n // Note that this means we cannot set a started/lastActivity of `0`, but this should not be relevant outside of tests.\n const started = session.started || now;\n const lastActivity = session.lastActivity || now;\n const segmentId = session.segmentId || 0;\n const sampled = session.sampled;\n const previousSessionId = session.previousSessionId;\n\n return {\n id,\n started,\n lastActivity,\n segmentId,\n sampled,\n previousSessionId,\n };\n}\n","import { REPLAY_SESSION_KEY, WINDOW } from '../constants';\nimport type { Session } from '../types';\nimport { hasSessionStorage } from '../util/hasSessionStorage';\n\n/**\n * Save a session to session storage.\n */\nexport function saveSession(session: Session): void {\n if (!hasSessionStorage()) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));\n } catch {\n // Ignore potential SecurityError exceptions\n }\n}\n","import type { Sampled, Session, SessionOptions } from '../types';\nimport { isSampled } from '../util/isSampled';\nimport { makeSession } from './Session';\nimport { saveSession } from './saveSession';\n\n/**\n * Get the sampled status for a session based on sample rates & current sampled status.\n */\nexport function getSessionSampleType(sessionSampleRate: number, allowBuffering: boolean): Sampled {\n return isSampled(sessionSampleRate) ? 'session' : allowBuffering ? 'buffer' : false;\n}\n\n/**\n * Create a new session, which in its current implementation is a Sentry event\n * that all replays will be saved to as attachments. Currently, we only expect\n * one of these Sentry events per \"replay session\".\n */\nexport function createSession(\n { sessionSampleRate, allowBuffering, stickySession = false }: SessionOptions,\n { previousSessionId }: { previousSessionId?: string } = {},\n): Session {\n const sampled = getSessionSampleType(sessionSampleRate, allowBuffering);\n const session = makeSession({\n sampled,\n previousSessionId,\n });\n\n if (stickySession) {\n saveSession(session);\n }\n\n return session;\n}\n","/**\n * Given an initial timestamp and an expiry duration, checks to see if current\n * time should be considered as expired.\n */\nexport function isExpired(\n initialTime: null | number,\n expiry: undefined | number,\n targetTime: number = +new Date(),\n): boolean {\n // Always expired if < 0\n if (initialTime === null || expiry === undefined || expiry < 0) {\n return true;\n }\n\n // Never expires if == 0\n if (expiry === 0) {\n return false;\n }\n\n return initialTime + expiry <= targetTime;\n}\n","import type { Session } from '../types';\nimport { isExpired } from './isExpired';\n\n/**\n * Checks to see if session is expired\n */\nexport function isSessionExpired(\n session: Session,\n {\n maxReplayDuration,\n sessionIdleExpire,\n targetTime = Date.now(),\n }: { maxReplayDuration: number; sessionIdleExpire: number; targetTime?: number },\n): boolean {\n return (\n // First, check that maximum session length has not been exceeded\n isExpired(session.started, maxReplayDuration, targetTime) ||\n // check that the idle timeout has not been exceeded (i.e. user has\n // performed an action within the last `sessionIdleExpire` ms)\n isExpired(session.lastActivity, sessionIdleExpire, targetTime)\n );\n}\n","import type { Session } from '../types';\nimport { isSessionExpired } from '../util/isSessionExpired';\n\n/** If the session should be refreshed or not. */\nexport function shouldRefreshSession(\n session: Session,\n { sessionIdleExpire, maxReplayDuration }: { sessionIdleExpire: number; maxReplayDuration: number },\n): boolean {\n // If not expired, all good, just keep the session\n if (!isSessionExpired(session, { sessionIdleExpire, maxReplayDuration })) {\n return false;\n }\n\n // If we are buffering & haven't ever flushed yet, always continue\n if (session.sampled === 'buffer' && session.segmentId === 0) {\n return false;\n }\n\n return true;\n}\n","import type { Session, SessionOptions } from '../types';\nimport { logInfoNextTick } from '../util/log';\nimport { createSession } from './createSession';\nimport { fetchSession } from './fetchSession';\nimport { shouldRefreshSession } from './shouldRefreshSession';\n\n/**\n * Get or create a session, when initializing the replay.\n * Returns a session that may be unsampled.\n */\nexport function loadOrCreateSession(\n {\n traceInternals,\n sessionIdleExpire,\n maxReplayDuration,\n previousSessionId,\n }: {\n sessionIdleExpire: number;\n maxReplayDuration: number;\n traceInternals?: boolean;\n previousSessionId?: string;\n },\n sessionOptions: SessionOptions,\n): Session {\n const existingSession = sessionOptions.stickySession && fetchSession(traceInternals);\n\n // No session exists yet, just create a new one\n if (!existingSession) {\n logInfoNextTick('[Replay] Creating new session', traceInternals);\n return createSession(sessionOptions, { previousSessionId });\n }\n\n if (!shouldRefreshSession(existingSession, { sessionIdleExpire, maxReplayDuration })) {\n return existingSession;\n }\n\n logInfoNextTick('[Replay] Session in sessionStorage is expired, creating new one...');\n return createSession(sessionOptions, { previousSessionId: existingSession.id });\n}\n","import { REPLAY_SESSION_KEY, WINDOW } from '../constants';\nimport type { Session } from '../types';\nimport { hasSessionStorage } from '../util/hasSessionStorage';\nimport { logInfoNextTick } from '../util/log';\nimport { makeSession } from './Session';\n\n/**\n * Fetches a session from storage\n */\nexport function fetchSession(traceInternals?: boolean): Session | null {\n if (!hasSessionStorage()) {\n return null;\n }\n\n try {\n // This can throw if cookies are disabled\n const sessionStringFromStorage = WINDOW.sessionStorage.getItem(REPLAY_SESSION_KEY);\n\n if (!sessionStringFromStorage) {\n return null;\n }\n\n const sessionObj = JSON.parse(sessionStringFromStorage) as Session;\n\n logInfoNextTick('[Replay] Loading existing session', traceInternals);\n\n return makeSession(sessionObj);\n } catch {\n return null;\n }\n}\n","import { EventType } from '@sentry-internal/rrweb';\nimport { getClient } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { EventBufferSizeExceededError } from '../eventBuffer/error';\nimport type { AddEventResult, RecordingEvent, ReplayContainer, ReplayFrameEvent, ReplayPluginOptions } from '../types';\nimport { logInfo } from './log';\nimport { timestampToMs } from './timestamp';\n\nfunction isCustomEvent(event: RecordingEvent): event is ReplayFrameEvent {\n return event.type === EventType.Custom;\n}\n\n/**\n * Add an event to the event buffer.\n * In contrast to `addEvent`, this does not return a promise & does not wait for the adding of the event to succeed/fail.\n * Instead this returns `true` if we tried to add the event, else false.\n * It returns `false` e.g. if we are paused, disabled, or out of the max replay duration.\n *\n * `isCheckout` is true if this is either the very first event, or an event triggered by `checkoutEveryNms`.\n */\nexport function addEventSync(replay: ReplayContainer, event: RecordingEvent, isCheckout?: boolean): boolean {\n if (!shouldAddEvent(replay, event)) {\n return false;\n }\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n _addEvent(replay, event, isCheckout);\n\n return true;\n}\n\n/**\n * Add an event to the event buffer.\n * Resolves to `null` if no event was added, else to `void`.\n *\n * `isCheckout` is true if this is either the very first event, or an event triggered by `checkoutEveryNms`.\n */\nexport function addEvent(\n replay: ReplayContainer,\n event: RecordingEvent,\n isCheckout?: boolean,\n): Promise {\n if (!shouldAddEvent(replay, event)) {\n return Promise.resolve(null);\n }\n\n return _addEvent(replay, event, isCheckout);\n}\n\nasync function _addEvent(\n replay: ReplayContainer,\n event: RecordingEvent,\n isCheckout?: boolean,\n): Promise {\n if (!replay.eventBuffer) {\n return null;\n }\n\n try {\n if (isCheckout && replay.recordingMode === 'buffer') {\n replay.eventBuffer.clear();\n }\n\n if (isCheckout) {\n replay.eventBuffer.hasCheckout = true;\n }\n\n const replayOptions = replay.getOptions();\n\n const eventAfterPossibleCallback = maybeApplyCallback(event, replayOptions.beforeAddRecordingEvent);\n\n if (!eventAfterPossibleCallback) {\n return;\n }\n\n return await replay.eventBuffer.addEvent(eventAfterPossibleCallback);\n } catch (error) {\n const reason = error && error instanceof EventBufferSizeExceededError ? 'addEventSizeExceeded' : 'addEvent';\n\n DEBUG_BUILD && logger.error(error);\n await replay.stop({ reason });\n\n const client = getClient();\n\n if (client) {\n client.recordDroppedEvent('internal_sdk_error', 'replay');\n }\n }\n}\n\n/** Exported only for tests. */\nexport function shouldAddEvent(replay: ReplayContainer, event: RecordingEvent): boolean {\n if (!replay.eventBuffer || replay.isPaused() || !replay.isEnabled()) {\n return false;\n }\n\n const timestampInMs = timestampToMs(event.timestamp);\n\n // Throw out events that happen more than 5 minutes ago. This can happen if\n // page has been left open and idle for a long period of time and user\n // comes back to trigger a new session. The performance entries rely on\n // `performance.timeOrigin`, which is when the page first opened.\n if (timestampInMs + replay.timeouts.sessionIdlePause < Date.now()) {\n return false;\n }\n\n // Throw out events that are +60min from the initial timestamp\n if (timestampInMs > replay.getContext().initialTimestamp + replay.getOptions().maxReplayDuration) {\n logInfo(\n `[Replay] Skipping event with timestamp ${timestampInMs} because it is after maxReplayDuration`,\n replay.getOptions()._experiments.traceInternals,\n );\n return false;\n }\n\n return true;\n}\n\nfunction maybeApplyCallback(\n event: RecordingEvent,\n callback: ReplayPluginOptions['beforeAddRecordingEvent'],\n): RecordingEvent | null | undefined {\n try {\n if (typeof callback === 'function' && isCustomEvent(event)) {\n return callback(event);\n }\n } catch (error) {\n DEBUG_BUILD &&\n logger.error('[Replay] An error occured in the `beforeAddRecordingEvent` callback, skipping the event...', error);\n return null;\n }\n\n return event;\n}\n","import type { ErrorEvent, Event, FeedbackEvent, ReplayEvent, TransactionEvent } from '@sentry/types';\n\n/** If the event is an error event */\nexport function isErrorEvent(event: Event): event is ErrorEvent {\n return !event.type;\n}\n\n/** If the event is a transaction event */\nexport function isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n\n/** If the event is an replay event */\nexport function isReplayEvent(event: Event): event is ReplayEvent {\n return event.type === 'replay_event';\n}\n\n/** If the event is a feedback event */\nexport function isFeedbackEvent(event: Event): event is FeedbackEvent {\n return event.type === 'feedback';\n}\n","import { getClient } from '@sentry/core';\nimport type { ErrorEvent, Event, TransactionEvent, Transport, TransportMakeRequestResponse } from '@sentry/types';\n\nimport type { ReplayContainer } from '../types';\nimport { isErrorEvent, isTransactionEvent } from '../util/eventUtils';\n\ntype AfterSendEventCallback = (event: Event, sendResponse: TransportMakeRequestResponse | void) => void;\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nexport function handleAfterSendEvent(replay: ReplayContainer): AfterSendEventCallback {\n // Custom transports may still be returning `Promise`, which means we cannot expect the status code to be available there\n // TODO (v8): remove this check as it will no longer be necessary\n const enforceStatusCode = isBaseTransportSend();\n\n return (event: Event, sendResponse: TransportMakeRequestResponse | void) => {\n if (!replay.isEnabled() || (!isErrorEvent(event) && !isTransactionEvent(event))) {\n return;\n }\n\n const statusCode = sendResponse && sendResponse.statusCode;\n\n // We only want to do stuff on successful error sending, otherwise you get error replays without errors attached\n // If not using the base transport, we allow `undefined` response (as a custom transport may not implement this correctly yet)\n // If we do use the base transport, we skip if we encountered an non-OK status code\n if (enforceStatusCode && (!statusCode || statusCode < 200 || statusCode >= 300)) {\n return;\n }\n\n if (isTransactionEvent(event)) {\n handleTransactionEvent(replay, event);\n return;\n }\n\n handleErrorEvent(replay, event);\n };\n}\n\nfunction handleTransactionEvent(replay: ReplayContainer, event: TransactionEvent): void {\n const replayContext = replay.getContext();\n\n // Collect traceIds in _context regardless of `recordingMode`\n // In error mode, _context gets cleared on every checkout\n // We limit to max. 100 transactions linked\n if (event.contexts && event.contexts.trace && event.contexts.trace.trace_id && replayContext.traceIds.size < 100) {\n replayContext.traceIds.add(event.contexts.trace.trace_id as string);\n }\n}\n\nfunction handleErrorEvent(replay: ReplayContainer, event: ErrorEvent): void {\n const replayContext = replay.getContext();\n\n // Add error to list of errorIds of replay. This is ok to do even if not\n // sampled because context will get reset at next checkout.\n // XXX: There is also a race condition where it's possible to capture an\n // error to Sentry before Replay SDK has loaded, but response returns after\n // it was loaded, and this gets called.\n // We limit to max. 100 errors linked\n if (event.event_id && replayContext.errorIds.size < 100) {\n replayContext.errorIds.add(event.event_id);\n }\n\n // If error event is tagged with replay id it means it was sampled (when in buffer mode)\n // Need to be very careful that this does not cause an infinite loop\n if (replay.recordingMode !== 'buffer' || !event.tags || !event.tags.replayId) {\n return;\n }\n\n const { beforeErrorSampling } = replay.getOptions();\n if (typeof beforeErrorSampling === 'function' && !beforeErrorSampling(event)) {\n return;\n }\n\n setTimeout(() => {\n // Capture current event buffer as new replay\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.sendBufferedReplayOrFlush();\n });\n}\n\nfunction isBaseTransportSend(): boolean {\n const client = getClient();\n if (!client) {\n return false;\n }\n\n const transport = client.getTransport();\n if (!transport) {\n return false;\n }\n\n return (\n (transport.send as Transport['send'] & { __sentry__baseTransport__?: true }).__sentry__baseTransport__ || false\n );\n}\n","import type { ErrorEvent, Event } from '@sentry/types';\n\nimport type { ReplayContainer } from '../types';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { isErrorEvent } from '../util/eventUtils';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\n\ntype BeforeSendEventCallback = (event: Event) => void;\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nexport function handleBeforeSendEvent(replay: ReplayContainer): BeforeSendEventCallback {\n return (event: Event) => {\n if (!replay.isEnabled() || !isErrorEvent(event)) {\n return;\n }\n\n handleHydrationError(replay, event);\n };\n}\n\nfunction handleHydrationError(replay: ReplayContainer, event: ErrorEvent): void {\n const exceptionValue = event.exception && event.exception.values && event.exception.values[0].value;\n if (typeof exceptionValue !== 'string') {\n return;\n }\n\n if (\n // Only matches errors in production builds of react-dom\n // Example https://reactjs.org/docs/error-decoder.html?invariant=423\n exceptionValue.match(/reactjs\\.org\\/docs\\/error-decoder\\.html\\?invariant=(418|419|422|423|425)/) ||\n // Development builds of react-dom\n // Error 1: Hydration failed because the initial UI does not match what was rendered on the server.\n // Error 2: Text content does not match server-rendered HTML. Warning: Text content did not match.\n exceptionValue.match(/(does not match server-rendered HTML|Hydration failed because)/i)\n ) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.hydrate-error',\n });\n addBreadcrumbEvent(replay, breadcrumb);\n }\n}\n","import type { Event, EventHint } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { ReplayContainer } from '../types';\nimport { isErrorEvent, isFeedbackEvent, isReplayEvent, isTransactionEvent } from '../util/eventUtils';\nimport { isRrwebError } from '../util/isRrwebError';\nimport { handleAfterSendEvent } from './handleAfterSendEvent';\nimport { addFeedbackBreadcrumb } from './util/addFeedbackBreadcrumb';\nimport { shouldSampleForBufferEvent } from './util/shouldSampleForBufferEvent';\n\n/**\n * Returns a listener to be added to `addEventProcessor(listener)`.\n */\nexport function handleGlobalEventListener(\n replay: ReplayContainer,\n includeAfterSendEventHandling = false,\n): (event: Event, hint: EventHint) => Event | null {\n const afterSendHandler = includeAfterSendEventHandling ? handleAfterSendEvent(replay) : undefined;\n\n return Object.assign(\n (event: Event, hint: EventHint) => {\n // Do nothing if replay has been disabled\n if (!replay.isEnabled()) {\n return event;\n }\n\n if (isReplayEvent(event)) {\n // Replays have separate set of breadcrumbs, do not include breadcrumbs\n // from core SDK\n delete event.breadcrumbs;\n return event;\n }\n\n // We only want to handle errors, transactions, and feedbacks, nothing else\n if (!isErrorEvent(event) && !isTransactionEvent(event) && !isFeedbackEvent(event)) {\n return event;\n }\n\n // Ensure we do not add replay_id if the session is expired\n const isSessionActive = replay.checkAndHandleExpiredSession();\n if (!isSessionActive) {\n return event;\n }\n\n if (isFeedbackEvent(event)) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.flush();\n event.contexts.feedback.replay_id = replay.getSessionId();\n // Add a replay breadcrumb for this piece of feedback\n addFeedbackBreadcrumb(replay, event);\n return event;\n }\n\n // Unless `captureExceptions` is enabled, we want to ignore errors coming from rrweb\n // As there can be a bunch of stuff going wrong in internals there, that we don't want to bubble up to users\n if (isRrwebError(event, hint) && !replay.getOptions()._experiments.captureExceptions) {\n DEBUG_BUILD && logger.log('[Replay] Ignoring error from rrweb internals', event);\n return null;\n }\n\n // When in buffer mode, we decide to sample here.\n // Later, in `handleAfterSendEvent`, if the replayId is set, we know that we sampled\n // And convert the buffer session to a full session\n const isErrorEventSampled = shouldSampleForBufferEvent(replay, event);\n\n // Tag errors if it has been sampled in buffer mode, or if it is session mode\n // Only tag transactions if in session mode\n const shouldTagReplayId = isErrorEventSampled || replay.recordingMode === 'session';\n\n if (shouldTagReplayId) {\n event.tags = { ...event.tags, replayId: replay.getSessionId() };\n }\n\n // In cases where a custom client is used that does not support the new hooks (yet),\n // we manually call this hook method here\n if (afterSendHandler) {\n // Pretend the error had a 200 response so we always capture it\n afterSendHandler(event, { statusCode: 200 });\n }\n\n return event;\n },\n { id: 'Replay' },\n );\n}\n","import { EventType } from '@sentry-internal/rrweb';\nimport type { FeedbackEvent } from '@sentry/types';\n\nimport type { ReplayBreadcrumbFrameEvent, ReplayContainer } from '../../types';\n\n/**\n * Add a feedback breadcrumb event to replay.\n */\nexport function addFeedbackBreadcrumb(replay: ReplayContainer, event: FeedbackEvent): void {\n replay.triggerUserActivity();\n replay.addUpdate(() => {\n if (!event.timestamp) {\n // Ignore events that don't have timestamps (this shouldn't happen, more of a typing issue)\n // Return true here so that we don't flush\n return true;\n }\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.throttledAddEvent({\n type: EventType.Custom,\n timestamp: event.timestamp * 1000,\n data: {\n tag: 'breadcrumb',\n payload: {\n timestamp: event.timestamp,\n type: 'default',\n category: 'sentry.feedback',\n data: {\n feedbackId: event.event_id,\n },\n },\n },\n } as ReplayBreadcrumbFrameEvent);\n\n return false;\n });\n}\n","import type { Event, EventHint } from '@sentry/types';\n\n/**\n * Returns true if we think the given event is an error originating inside of rrweb.\n */\nexport function isRrwebError(event: Event, hint: EventHint): boolean {\n if (event.type || !event.exception || !event.exception.values || !event.exception.values.length) {\n return false;\n }\n\n // @ts-expect-error this may be set by rrweb when it finds errors\n if (hint.originalException && hint.originalException.__rrweb__) {\n return true;\n }\n\n return false;\n}\n","import type { Event } from '@sentry/types';\n\nimport { UNABLE_TO_SEND_REPLAY } from '../../constants';\nimport type { ReplayContainer } from '../../types';\nimport { isSampled } from '../../util/isSampled';\n\n/**\n * Determine if event should be sampled (only applies in buffer mode).\n * When an event is captured by `hanldleGlobalEvent`, when in buffer mode\n * we determine if we want to sample the error or not.\n */\nexport function shouldSampleForBufferEvent(replay: ReplayContainer, event: Event): boolean {\n if (replay.recordingMode !== 'buffer') {\n return false;\n }\n\n // ignore this error because otherwise we could loop indefinitely with\n // trying to capture replay and failing\n if (event.message === UNABLE_TO_SEND_REPLAY) {\n return false;\n }\n\n // Require the event to be an error event & to have an exception\n if (!event.exception || event.type) {\n return false;\n }\n\n return isSampled(replay.getOptions().errorSampleRate);\n}\n","import { EventType } from '@sentry-internal/rrweb';\n\nimport type { AddEventResult, AllEntryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\n\n/**\n * Create a \"span\" for each performance entry.\n */\nexport function createPerformanceSpans(\n replay: ReplayContainer,\n entries: ReplayPerformanceEntry[],\n): Promise[] {\n return entries.map(({ type, start, end, name, data }) => {\n const response = replay.throttledAddEvent({\n type: EventType.Custom,\n timestamp: start,\n data: {\n tag: 'performanceSpan',\n payload: {\n op: type,\n description: name,\n startTimestamp: start,\n endTimestamp: end,\n data,\n },\n },\n });\n\n // If response is a string, it means its either THROTTLED or SKIPPED\n return typeof response === 'string' ? Promise.resolve(null) : response;\n });\n}\n","import type { HandlerDataHistory } from '@sentry/types';\n\nimport type { HistoryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { createPerformanceSpans } from '../util/createPerformanceSpans';\n\nfunction handleHistory(handlerData: HandlerDataHistory): ReplayPerformanceEntry {\n const { from, to } = handlerData;\n\n const now = Date.now() / 1000;\n\n return {\n type: 'navigation.push',\n start: now,\n end: now,\n name: to,\n data: {\n previous: from,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addHistoryInstrumentationHandler(listener)`.\n */\nexport function handleHistorySpanListener(replay: ReplayContainer): (handlerData: HandlerDataHistory) => void {\n return (handlerData: HandlerDataHistory) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleHistory(handlerData);\n\n if (result === null) {\n return;\n }\n\n // Need to collect visited URLs\n replay.getContext().urls.push(result.name);\n replay.triggerUserActivity();\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning false to flush\n return false;\n });\n };\n}\n","import type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../../types';\nimport { createPerformanceSpans } from '../../util/createPerformanceSpans';\nimport { shouldFilterRequest } from '../../util/shouldFilterRequest';\n\n/** Add a performance entry breadcrumb */\nexport function addNetworkBreadcrumb(\n replay: ReplayContainer,\n result: ReplayPerformanceEntry | null,\n): void {\n if (!replay.isEnabled()) {\n return;\n }\n\n if (result === null) {\n return;\n }\n\n if (shouldFilterRequest(replay, result.name)) {\n return;\n }\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning true will cause `addUpdate` to not flush\n // We do not want network requests to cause a flush. This will prevent\n // recurring/polling requests from keeping the replay session alive.\n return true;\n });\n}\n","import { getClient, isSentryRequestUrl } from '@sentry/core';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { ReplayContainer } from '../types';\n\n/**\n * Check whether a given request URL should be filtered out. This is so we\n * don't log Sentry ingest requests.\n */\nexport function shouldFilterRequest(replay: ReplayContainer, url: string): boolean {\n // If we enabled the `traceInternals` experiment, we want to trace everything\n if (DEBUG_BUILD && replay.getOptions()._experiments.traceInternals) {\n return false;\n }\n\n return isSentryRequestUrl(url, getClient());\n}\n","import type { HandlerDataXhr } from '@sentry/types';\nimport { SENTRY_XHR_DATA_KEY } from '@sentry/utils';\n\nimport type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { addNetworkBreadcrumb } from './util/addNetworkBreadcrumb';\n\n/** only exported for tests */\nexport function handleXhr(handlerData: HandlerDataXhr): ReplayPerformanceEntry | null {\n const { startTimestamp, endTimestamp, xhr } = handlerData;\n\n const sentryXhrData = xhr[SENTRY_XHR_DATA_KEY];\n\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return null;\n }\n\n // This is only used as a fallback, so we know the body sizes are never set here\n const { method, url, status_code: statusCode } = sentryXhrData;\n\n if (url === undefined) {\n return null;\n }\n\n return {\n type: 'resource.xhr',\n name: url,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n data: {\n method,\n statusCode,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addXhrInstrumentationHandler(listener)`.\n */\nexport function handleXhrSpanListener(replay: ReplayContainer): (handlerData: HandlerDataXhr) => void {\n return (handlerData: HandlerDataXhr) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleXhr(handlerData);\n\n addNetworkBreadcrumb(replay, result);\n };\n}\n","import type { TextEncoderInternal } from '@sentry/types';\nimport { dropUndefinedKeys, logger, stringMatchesSomePattern } from '@sentry/utils';\n\nimport { NETWORK_BODY_MAX_SIZE, WINDOW } from '../../constants';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type {\n NetworkBody,\n NetworkMetaWarning,\n NetworkRequestData,\n ReplayNetworkRequestData,\n ReplayNetworkRequestOrResponse,\n ReplayPerformanceEntry,\n} from '../../types';\n\n/** Get the size of a body. */\nexport function getBodySize(\n body: RequestInit['body'],\n textEncoder: TextEncoder | TextEncoderInternal,\n): number | undefined {\n if (!body) {\n return undefined;\n }\n\n try {\n if (typeof body === 'string') {\n return textEncoder.encode(body).length;\n }\n\n if (body instanceof URLSearchParams) {\n return textEncoder.encode(body.toString()).length;\n }\n\n if (body instanceof FormData) {\n const formDataStr = _serializeFormData(body);\n return textEncoder.encode(formDataStr).length;\n }\n\n if (body instanceof Blob) {\n return body.size;\n }\n\n if (body instanceof ArrayBuffer) {\n return body.byteLength;\n }\n\n // Currently unhandled types: ArrayBufferView, ReadableStream\n } catch {\n // just return undefined\n }\n\n return undefined;\n}\n\n/** Convert a Content-Length header to number/undefined. */\nexport function parseContentLengthHeader(header: string | null | undefined): number | undefined {\n if (!header) {\n return undefined;\n }\n\n const size = parseInt(header, 10);\n return isNaN(size) ? undefined : size;\n}\n\n/** Get the string representation of a body. */\nexport function getBodyString(body: unknown): [string | undefined, NetworkMetaWarning?] {\n try {\n if (typeof body === 'string') {\n return [body];\n }\n\n if (body instanceof URLSearchParams) {\n return [body.toString()];\n }\n\n if (body instanceof FormData) {\n return [_serializeFormData(body)];\n }\n\n if (!body) {\n return [undefined];\n }\n } catch {\n DEBUG_BUILD && logger.warn('[Replay] Failed to serialize body', body);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n DEBUG_BUILD && logger.info('[Replay] Skipping network body because of body type', body);\n\n return [undefined, 'UNPARSEABLE_BODY_TYPE'];\n}\n\n/** Merge a warning into an existing network request/response. */\nexport function mergeWarning(\n info: ReplayNetworkRequestOrResponse | undefined,\n warning: NetworkMetaWarning,\n): ReplayNetworkRequestOrResponse {\n if (!info) {\n return {\n headers: {},\n size: undefined,\n _meta: {\n warnings: [warning],\n },\n };\n }\n\n const newMeta = { ...info._meta };\n const existingWarnings = newMeta.warnings || [];\n newMeta.warnings = [...existingWarnings, warning];\n\n info._meta = newMeta;\n return info;\n}\n\n/** Convert ReplayNetworkRequestData to a PerformanceEntry. */\nexport function makeNetworkReplayBreadcrumb(\n type: string,\n data: ReplayNetworkRequestData | null,\n): ReplayPerformanceEntry | null {\n if (!data) {\n return null;\n }\n\n const { startTimestamp, endTimestamp, url, method, statusCode, request, response } = data;\n\n const result: ReplayPerformanceEntry = {\n type,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: dropUndefinedKeys({\n method,\n statusCode,\n request,\n response,\n }),\n };\n\n return result;\n}\n\n/** Build the request or response part of a replay network breadcrumb that was skipped. */\nexport function buildSkippedNetworkRequestOrResponse(bodySize: number | undefined): ReplayNetworkRequestOrResponse {\n return {\n headers: {},\n size: bodySize,\n _meta: {\n warnings: ['URL_SKIPPED'],\n },\n };\n}\n\n/** Build the request or response part of a replay network breadcrumb. */\nexport function buildNetworkRequestOrResponse(\n headers: Record,\n bodySize: number | undefined,\n body: string | undefined,\n): ReplayNetworkRequestOrResponse | undefined {\n if (!bodySize && Object.keys(headers).length === 0) {\n return undefined;\n }\n\n if (!bodySize) {\n return {\n headers,\n };\n }\n\n if (!body) {\n return {\n headers,\n size: bodySize,\n };\n }\n\n const info: ReplayNetworkRequestOrResponse = {\n headers,\n size: bodySize,\n };\n\n const { body: normalizedBody, warnings } = normalizeNetworkBody(body);\n info.body = normalizedBody;\n if (warnings && warnings.length > 0) {\n info._meta = {\n warnings,\n };\n }\n\n return info;\n}\n\n/** Filter a set of headers */\nexport function getAllowedHeaders(headers: Record, allowedHeaders: string[]): Record {\n return Object.keys(headers).reduce((filteredHeaders: Record, key: string) => {\n const normalizedKey = key.toLowerCase();\n // Avoid putting empty strings into the headers\n if (allowedHeaders.includes(normalizedKey) && headers[key]) {\n filteredHeaders[normalizedKey] = headers[key];\n }\n return filteredHeaders;\n }, {});\n}\n\nfunction _serializeFormData(formData: FormData): string {\n // This is a bit simplified, but gives us a decent estimate\n // This converts e.g. { name: 'Anne Smith', age: 13 } to 'name=Anne+Smith&age=13'\n // @ts-expect-error passing FormData to URLSearchParams actually works\n return new URLSearchParams(formData).toString();\n}\n\nfunction normalizeNetworkBody(body: string | undefined): {\n body: NetworkBody | undefined;\n warnings?: NetworkMetaWarning[];\n} {\n if (!body || typeof body !== 'string') {\n return {\n body,\n };\n }\n\n const exceedsSizeLimit = body.length > NETWORK_BODY_MAX_SIZE;\n const isProbablyJson = _strIsProbablyJson(body);\n\n if (exceedsSizeLimit) {\n const truncatedBody = body.slice(0, NETWORK_BODY_MAX_SIZE);\n\n if (isProbablyJson) {\n return {\n body: truncatedBody,\n warnings: ['MAYBE_JSON_TRUNCATED'],\n };\n }\n\n return {\n body: `${truncatedBody}…`,\n warnings: ['TEXT_TRUNCATED'],\n };\n }\n\n if (isProbablyJson) {\n try {\n const jsonBody = JSON.parse(body);\n return {\n body: jsonBody,\n };\n } catch {\n // fall back to just send the body as string\n }\n }\n\n return {\n body,\n };\n}\n\nfunction _strIsProbablyJson(str: string): boolean {\n const first = str[0];\n const last = str[str.length - 1];\n\n // Simple check: If this does not start & end with {} or [], it's not JSON\n return (first === '[' && last === ']') || (first === '{' && last === '}');\n}\n\n/** Match an URL against a list of strings/Regex. */\nexport function urlMatches(url: string, urls: (string | RegExp)[]): boolean {\n const fullUrl = getFullUrl(url);\n\n return stringMatchesSomePattern(fullUrl, urls);\n}\n\n/** exported for tests */\nexport function getFullUrl(url: string, baseURI = WINDOW.document.baseURI): string {\n // Short circuit for common cases:\n if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith(WINDOW.location.origin)) {\n return url;\n }\n const fixedUrl = new URL(url, baseURI);\n\n // If these do not match, we are not dealing with a relative URL, so just return it\n if (fixedUrl.origin !== new URL(baseURI).origin) {\n return url;\n }\n\n const fullUrl = fixedUrl.href;\n\n // Remove trailing slashes, if they don't match the original URL\n if (!url.endsWith('/') && fullUrl.endsWith('/')) {\n return fullUrl.slice(0, -1);\n }\n\n return fullUrl;\n}\n","import type { Breadcrumb, FetchBreadcrumbData, TextEncoderInternal } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type {\n FetchHint,\n NetworkMetaWarning,\n ReplayContainer,\n ReplayNetworkOptions,\n ReplayNetworkRequestData,\n ReplayNetworkRequestOrResponse,\n} from '../../types';\nimport { addNetworkBreadcrumb } from './addNetworkBreadcrumb';\nimport {\n buildNetworkRequestOrResponse,\n buildSkippedNetworkRequestOrResponse,\n getAllowedHeaders,\n getBodySize,\n getBodyString,\n makeNetworkReplayBreadcrumb,\n mergeWarning,\n parseContentLengthHeader,\n urlMatches,\n} from './networkUtils';\n\n/**\n * Capture a fetch breadcrumb to a replay.\n * This adds additional data (where approriate).\n */\nexport async function captureFetchBreadcrumbToReplay(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: Partial,\n options: ReplayNetworkOptions & {\n textEncoder: TextEncoderInternal;\n replay: ReplayContainer;\n },\n): Promise {\n try {\n const data = await _prepareFetchData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.fetch', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n DEBUG_BUILD && logger.error('[Replay] Failed to capture fetch breadcrumb', error);\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nexport function enrichFetchBreadcrumb(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: Partial,\n options: { textEncoder: TextEncoderInternal },\n): void {\n const { input, response } = hint;\n\n const body = input ? _getFetchRequestArgBody(input) : undefined;\n const reqSize = getBodySize(body, options.textEncoder);\n\n const resSize = response ? parseContentLengthHeader(response.headers.get('content-length')) : undefined;\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nasync function _prepareFetchData(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: Partial,\n options: ReplayNetworkOptions & {\n textEncoder: TextEncoderInternal;\n },\n): Promise {\n const now = Date.now();\n const { startTimestamp = now, endTimestamp = now } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n const captureDetails =\n urlMatches(url, options.networkDetailAllowUrls) && !urlMatches(url, options.networkDetailDenyUrls);\n\n const request = captureDetails\n ? _getRequestInfo(options, hint.input, requestBodySize)\n : buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = await _getResponseInfo(captureDetails, options, hint.response, responseBodySize);\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n}\n\nfunction _getRequestInfo(\n { networkCaptureBodies, networkRequestHeaders }: ReplayNetworkOptions,\n input: FetchHint['input'] | undefined,\n requestBodySize?: number,\n): ReplayNetworkRequestOrResponse | undefined {\n const headers = input ? getRequestHeaders(input, networkRequestHeaders) : {};\n\n if (!networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);\n }\n\n // We only want to transmit string or string-like bodies\n const requestBody = _getFetchRequestArgBody(input);\n const [bodyStr, warning] = getBodyString(requestBody);\n const data = buildNetworkRequestOrResponse(headers, requestBodySize, bodyStr);\n\n if (warning) {\n return mergeWarning(data, warning);\n }\n\n return data;\n}\n\n/** Exported only for tests. */\nexport async function _getResponseInfo(\n captureDetails: boolean,\n {\n networkCaptureBodies,\n textEncoder,\n networkResponseHeaders,\n }: Pick & {\n textEncoder: TextEncoderInternal;\n },\n response: Response | undefined,\n responseBodySize?: number,\n): Promise {\n if (!captureDetails && responseBodySize !== undefined) {\n return buildSkippedNetworkRequestOrResponse(responseBodySize);\n }\n\n const headers = response ? getAllHeaders(response.headers, networkResponseHeaders) : {};\n\n if (!response || (!networkCaptureBodies && responseBodySize !== undefined)) {\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n\n const [bodyText, warning] = await _parseFetchResponseBody(response);\n const result = getResponseData(bodyText, {\n networkCaptureBodies,\n textEncoder,\n responseBodySize,\n captureDetails,\n headers,\n });\n\n if (warning) {\n return mergeWarning(result, warning);\n }\n\n return result;\n}\n\nfunction getResponseData(\n bodyText: string | undefined,\n {\n networkCaptureBodies,\n textEncoder,\n responseBodySize,\n captureDetails,\n headers,\n }: {\n captureDetails: boolean;\n networkCaptureBodies: boolean;\n responseBodySize: number | undefined;\n headers: Record;\n textEncoder: TextEncoderInternal;\n },\n): ReplayNetworkRequestOrResponse | undefined {\n try {\n const size =\n bodyText && bodyText.length && responseBodySize === undefined\n ? getBodySize(bodyText, textEncoder)\n : responseBodySize;\n\n if (!captureDetails) {\n return buildSkippedNetworkRequestOrResponse(size);\n }\n\n if (networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, size, bodyText);\n }\n\n return buildNetworkRequestOrResponse(headers, size, undefined);\n } catch (error) {\n DEBUG_BUILD && logger.warn('[Replay] Failed to serialize response body', error);\n // fallback\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n}\n\nasync function _parseFetchResponseBody(response: Response): Promise<[string | undefined, NetworkMetaWarning?]> {\n const res = _tryCloneResponse(response);\n\n if (!res) {\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n try {\n const text = await _tryGetResponseText(res);\n return [text];\n } catch (error) {\n DEBUG_BUILD && logger.warn('[Replay] Failed to get text body from response', error);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n}\n\nfunction _getFetchRequestArgBody(fetchArgs: unknown[] = []): RequestInit['body'] | undefined {\n // We only support getting the body from the fetch options\n if (fetchArgs.length !== 2 || typeof fetchArgs[1] !== 'object') {\n return undefined;\n }\n\n return (fetchArgs[1] as RequestInit).body;\n}\n\nfunction getAllHeaders(headers: Headers, allowedHeaders: string[]): Record {\n const allHeaders: Record = {};\n\n allowedHeaders.forEach(header => {\n if (headers.get(header)) {\n allHeaders[header] = headers.get(header) as string;\n }\n });\n\n return allHeaders;\n}\n\nfunction getRequestHeaders(fetchArgs: unknown[], allowedHeaders: string[]): Record {\n if (fetchArgs.length === 1 && typeof fetchArgs[0] !== 'string') {\n return getHeadersFromOptions(fetchArgs[0] as Request | RequestInit, allowedHeaders);\n }\n\n if (fetchArgs.length === 2) {\n return getHeadersFromOptions(fetchArgs[1] as Request | RequestInit, allowedHeaders);\n }\n\n return {};\n}\n\nfunction getHeadersFromOptions(\n input: Request | RequestInit | undefined,\n allowedHeaders: string[],\n): Record {\n if (!input) {\n return {};\n }\n\n const headers = input.headers;\n\n if (!headers) {\n return {};\n }\n\n if (headers instanceof Headers) {\n return getAllHeaders(headers, allowedHeaders);\n }\n\n // We do not support this, as it is not really documented (anymore?)\n if (Array.isArray(headers)) {\n return {};\n }\n\n return getAllowedHeaders(headers, allowedHeaders);\n}\n\nfunction _tryCloneResponse(response: Response): Response | void {\n try {\n // We have to clone this, as the body can only be read once\n return response.clone();\n } catch (error) {\n // this can throw if the response was already consumed before\n DEBUG_BUILD && logger.warn('[Replay] Failed to clone response body', error);\n }\n}\n\n/**\n * Get the response body of a fetch request, or timeout after 500ms.\n * Fetch can return a streaming body, that may not resolve (or not for a long time).\n * If that happens, we rather abort after a short time than keep waiting for this.\n */\nfunction _tryGetResponseText(response: Response): Promise {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => reject(new Error('Timeout while trying to read response body')), 500);\n\n _getResponseText(response)\n .then(\n txt => resolve(txt),\n reason => reject(reason),\n )\n .finally(() => clearTimeout(timeout));\n });\n\n return _getResponseText(response);\n}\n\nasync function _getResponseText(response: Response): Promise {\n // Force this to be a promise, just to be safe\n // eslint-disable-next-line no-return-await\n return await response.text();\n}\n","import type { Breadcrumb, TextEncoderInternal, XhrBreadcrumbData } from '@sentry/types';\nimport { SENTRY_XHR_DATA_KEY, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type {\n NetworkMetaWarning,\n ReplayContainer,\n ReplayNetworkOptions,\n ReplayNetworkRequestData,\n XhrHint,\n} from '../../types';\nimport { addNetworkBreadcrumb } from './addNetworkBreadcrumb';\nimport {\n buildNetworkRequestOrResponse,\n buildSkippedNetworkRequestOrResponse,\n getAllowedHeaders,\n getBodySize,\n getBodyString,\n makeNetworkReplayBreadcrumb,\n mergeWarning,\n parseContentLengthHeader,\n urlMatches,\n} from './networkUtils';\n\n/**\n * Capture an XHR breadcrumb to a replay.\n * This adds additional data (where approriate).\n */\nexport async function captureXhrBreadcrumbToReplay(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: Partial,\n options: ReplayNetworkOptions & { replay: ReplayContainer },\n): Promise {\n try {\n const data = _prepareXhrData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.xhr', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n DEBUG_BUILD && logger.error('[Replay] Failed to capture xhr breadcrumb', error);\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nexport function enrichXhrBreadcrumb(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: Partial,\n options: { textEncoder: TextEncoderInternal },\n): void {\n const { xhr, input } = hint;\n\n if (!xhr) {\n return;\n }\n\n const reqSize = getBodySize(input, options.textEncoder);\n const resSize = xhr.getResponseHeader('content-length')\n ? parseContentLengthHeader(xhr.getResponseHeader('content-length'))\n : _getBodySize(xhr.response, xhr.responseType, options.textEncoder);\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nfunction _prepareXhrData(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: Partial,\n options: ReplayNetworkOptions,\n): ReplayNetworkRequestData | null {\n const now = Date.now();\n const { startTimestamp = now, endTimestamp = now, input, xhr } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n if (!url) {\n return null;\n }\n\n if (!xhr || !urlMatches(url, options.networkDetailAllowUrls) || urlMatches(url, options.networkDetailDenyUrls)) {\n const request = buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = buildSkippedNetworkRequestOrResponse(responseBodySize);\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n }\n\n const xhrInfo = xhr[SENTRY_XHR_DATA_KEY];\n const networkRequestHeaders = xhrInfo\n ? getAllowedHeaders(xhrInfo.request_headers, options.networkRequestHeaders)\n : {};\n const networkResponseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.networkResponseHeaders);\n\n const [requestBody, requestWarning] = options.networkCaptureBodies ? getBodyString(input) : [undefined];\n const [responseBody, responseWarning] = options.networkCaptureBodies ? _getXhrResponseBody(xhr) : [undefined];\n\n const request = buildNetworkRequestOrResponse(networkRequestHeaders, requestBodySize, requestBody);\n const response = buildNetworkRequestOrResponse(networkResponseHeaders, responseBodySize, responseBody);\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request: requestWarning ? mergeWarning(request, requestWarning) : request,\n response: responseWarning ? mergeWarning(response, responseWarning) : response,\n };\n}\n\nfunction getResponseHeaders(xhr: XMLHttpRequest): Record {\n const headers = xhr.getAllResponseHeaders();\n\n if (!headers) {\n return {};\n }\n\n return headers.split('\\r\\n').reduce((acc: Record, line: string) => {\n const [key, value] = line.split(': ');\n acc[key.toLowerCase()] = value;\n return acc;\n }, {});\n}\n\nfunction _getXhrResponseBody(xhr: XMLHttpRequest): [string | undefined, NetworkMetaWarning?] {\n // We collect errors that happen, but only log them if we can't get any response body\n const errors: unknown[] = [];\n\n try {\n return [xhr.responseText];\n } catch (e) {\n errors.push(e);\n }\n\n // Try to manually parse the response body, if responseText fails\n try {\n return _parseXhrResponse(xhr.response, xhr.responseType);\n } catch (e) {\n errors.push(e);\n }\n\n DEBUG_BUILD && logger.warn('[Replay] Failed to get xhr response body', ...errors);\n\n return [undefined];\n}\n\n/**\n * Get the string representation of the XHR response.\n * Based on MDN, these are the possible types of the response:\n * string\n * ArrayBuffer\n * Blob\n * Document\n * POJO\n *\n * Exported only for tests.\n */\nexport function _parseXhrResponse(\n body: XMLHttpRequest['response'],\n responseType: XMLHttpRequest['responseType'],\n): [string | undefined, NetworkMetaWarning?] {\n try {\n if (typeof body === 'string') {\n return [body];\n }\n\n if (body instanceof Document) {\n return [body.body.outerHTML];\n }\n\n if (responseType === 'json' && body && typeof body === 'object') {\n return [JSON.stringify(body)];\n }\n\n if (!body) {\n return [undefined];\n }\n } catch {\n DEBUG_BUILD && logger.warn('[Replay] Failed to serialize body', body);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n DEBUG_BUILD && logger.info('[Replay] Skipping network body because of body type', body);\n\n return [undefined, 'UNPARSEABLE_BODY_TYPE'];\n}\n\nfunction _getBodySize(\n body: XMLHttpRequest['response'],\n responseType: XMLHttpRequest['responseType'],\n textEncoder: TextEncoder | TextEncoderInternal,\n): number | undefined {\n try {\n const bodyStr = responseType === 'json' && body && typeof body === 'object' ? JSON.stringify(body) : body;\n return getBodySize(bodyStr, textEncoder);\n } catch {\n return undefined;\n }\n}\n","import { getClient } from '@sentry/core';\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n FetchBreadcrumbData,\n TextEncoderInternal,\n XhrBreadcrumbData,\n} from '@sentry/types';\nimport { addFetchInstrumentationHandler, addXhrInstrumentationHandler, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { FetchHint, ReplayContainer, ReplayNetworkOptions, XhrHint } from '../types';\nimport { handleFetchSpanListener } from './handleFetch';\nimport { handleXhrSpanListener } from './handleXhr';\nimport { captureFetchBreadcrumbToReplay, enrichFetchBreadcrumb } from './util/fetchUtils';\nimport { captureXhrBreadcrumbToReplay, enrichXhrBreadcrumb } from './util/xhrUtils';\n\ninterface ExtendedNetworkBreadcrumbsOptions extends ReplayNetworkOptions {\n replay: ReplayContainer;\n textEncoder: TextEncoderInternal;\n}\n\n/**\n * This method does two things:\n * - It enriches the regular XHR/fetch breadcrumbs with request/response size data\n * - It captures the XHR/fetch breadcrumbs to the replay\n * (enriching it with further data that is _not_ added to the regular breadcrumbs)\n */\nexport function handleNetworkBreadcrumbs(replay: ReplayContainer): void {\n const client = getClient();\n\n try {\n const textEncoder = new TextEncoder();\n\n const {\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n } = replay.getOptions();\n\n const options: ExtendedNetworkBreadcrumbsOptions = {\n replay,\n textEncoder,\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n };\n\n if (client && client.on) {\n client.on('beforeAddBreadcrumb', (breadcrumb, hint) => beforeAddNetworkBreadcrumb(options, breadcrumb, hint));\n } else {\n // Fallback behavior\n addFetchInstrumentationHandler(handleFetchSpanListener(replay));\n addXhrInstrumentationHandler(handleXhrSpanListener(replay));\n }\n } catch {\n // Do nothing\n }\n}\n\n/** just exported for tests */\nexport function beforeAddNetworkBreadcrumb(\n options: ExtendedNetworkBreadcrumbsOptions,\n breadcrumb: Breadcrumb,\n hint?: BreadcrumbHint,\n): void {\n if (!breadcrumb.data) {\n return;\n }\n\n try {\n if (_isXhrBreadcrumb(breadcrumb) && _isXhrHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichXhrBreadcrumb(breadcrumb, hint, options);\n\n // This call should not reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n captureXhrBreadcrumbToReplay(breadcrumb, hint, options);\n }\n\n if (_isFetchBreadcrumb(breadcrumb) && _isFetchHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichFetchBreadcrumb(breadcrumb, hint, options);\n\n // This call should not reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n captureFetchBreadcrumbToReplay(breadcrumb, hint, options);\n }\n } catch (e) {\n DEBUG_BUILD && logger.warn('Error when enriching network breadcrumb');\n }\n}\n\nfunction _isXhrBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is Breadcrumb & { data: XhrBreadcrumbData } {\n return breadcrumb.category === 'xhr';\n}\n\nfunction _isFetchBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is Breadcrumb & { data: FetchBreadcrumbData } {\n return breadcrumb.category === 'fetch';\n}\n\nfunction _isXhrHint(hint?: BreadcrumbHint): hint is XhrHint {\n return hint && hint.xhr;\n}\n\nfunction _isFetchHint(hint?: BreadcrumbHint): hint is FetchHint {\n return hint && hint.response;\n}\n","import type { HandlerDataFetch } from '@sentry/types';\n\nimport type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { addNetworkBreadcrumb } from './util/addNetworkBreadcrumb';\n\n/** only exported for tests */\nexport function handleFetch(handlerData: HandlerDataFetch): null | ReplayPerformanceEntry {\n const { startTimestamp, endTimestamp, fetchData, response } = handlerData;\n\n if (!endTimestamp) {\n return null;\n }\n\n // This is only used as a fallback, so we know the body sizes are never set here\n const { method, url } = fetchData;\n\n return {\n type: 'resource.fetch',\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: {\n method,\n statusCode: response ? (response as Response).status : undefined,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addFetchInstrumentationHandler(listener)`.\n */\nexport function handleFetchSpanListener(replay: ReplayContainer): (handlerData: HandlerDataFetch) => void {\n return (handlerData: HandlerDataFetch) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleFetch(handlerData);\n\n addNetworkBreadcrumb(replay, result);\n };\n}\n","import type { Breadcrumb, Scope } from '@sentry/types';\nimport { normalize } from '@sentry/utils';\n\nimport { CONSOLE_ARG_MAX_SIZE } from '../constants';\nimport type { ReplayContainer } from '../types';\nimport type { ReplayFrame } from '../types/replayFrame';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\n\nlet _LAST_BREADCRUMB: null | Breadcrumb = null;\n\ntype BreadcrumbWithCategory = Required>;\n\nfunction isBreadcrumbWithCategory(breadcrumb: Breadcrumb): breadcrumb is BreadcrumbWithCategory {\n return !!breadcrumb.category;\n}\n\nexport const handleScopeListener: (replay: ReplayContainer) => (scope: Scope) => void =\n (replay: ReplayContainer) =>\n (scope: Scope): void => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleScope(scope);\n\n if (!result) {\n return;\n }\n\n addBreadcrumbEvent(replay, result);\n };\n\n/**\n * An event handler to handle scope changes.\n */\nexport function handleScope(scope: Scope): Breadcrumb | null {\n // TODO (v8): Remove this guard. This was put in place because we introduced\n // Scope.getLastBreadcrumb mid-v7 which caused incompatibilities with older SDKs.\n // For now, we'll just return null if the method doesn't exist but we should eventually\n // get rid of this guard.\n const newBreadcrumb = scope.getLastBreadcrumb && scope.getLastBreadcrumb();\n\n // Listener can be called when breadcrumbs have not changed, so we store the\n // reference to the last crumb and only return a crumb if it has changed\n if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {\n return null;\n }\n\n _LAST_BREADCRUMB = newBreadcrumb;\n\n if (\n !isBreadcrumbWithCategory(newBreadcrumb) ||\n ['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||\n newBreadcrumb.category.startsWith('ui.')\n ) {\n return null;\n }\n\n if (newBreadcrumb.category === 'console') {\n return normalizeConsoleBreadcrumb(newBreadcrumb);\n }\n\n return createBreadcrumb(newBreadcrumb);\n}\n\n/** exported for tests only */\nexport function normalizeConsoleBreadcrumb(\n breadcrumb: Omit & BreadcrumbWithCategory,\n): ReplayFrame {\n const args = breadcrumb.data && breadcrumb.data.arguments;\n\n if (!Array.isArray(args) || args.length === 0) {\n return createBreadcrumb(breadcrumb);\n }\n\n let isTruncated = false;\n\n // Avoid giant args captures\n const normalizedArgs = args.map(arg => {\n if (!arg) {\n return arg;\n }\n if (typeof arg === 'string') {\n if (arg.length > CONSOLE_ARG_MAX_SIZE) {\n isTruncated = true;\n return `${arg.slice(0, CONSOLE_ARG_MAX_SIZE)}…`;\n }\n\n return arg;\n }\n if (typeof arg === 'object') {\n try {\n const normalizedArg = normalize(arg, 7);\n const stringified = JSON.stringify(normalizedArg);\n if (stringified.length > CONSOLE_ARG_MAX_SIZE) {\n isTruncated = true;\n // We use the pretty printed JSON string here as a base\n return `${JSON.stringify(normalizedArg, null, 2).slice(0, CONSOLE_ARG_MAX_SIZE)}…`;\n }\n return normalizedArg;\n } catch {\n // fall back to default\n }\n }\n\n return arg;\n });\n\n return createBreadcrumb({\n ...breadcrumb,\n data: {\n ...breadcrumb.data,\n arguments: normalizedArgs,\n ...(isTruncated ? { _meta: { warnings: ['CONSOLE_ARG_TRUNCATED'] } } : {}),\n },\n });\n}\n","import type { BaseClient } from '@sentry/core';\nimport { getCurrentScope } from '@sentry/core';\nimport { addEventProcessor, getClient } from '@sentry/core';\nimport type { Client, DynamicSamplingContext } from '@sentry/types';\nimport { addClickKeypressInstrumentationHandler, addHistoryInstrumentationHandler } from '@sentry/utils';\n\nimport { handleAfterSendEvent } from '../coreHandlers/handleAfterSendEvent';\nimport { handleBeforeSendEvent } from '../coreHandlers/handleBeforeSendEvent';\nimport { handleDomListener } from '../coreHandlers/handleDom';\nimport { handleGlobalEventListener } from '../coreHandlers/handleGlobalEvent';\nimport { handleHistorySpanListener } from '../coreHandlers/handleHistory';\nimport { handleNetworkBreadcrumbs } from '../coreHandlers/handleNetworkBreadcrumbs';\nimport { handleScopeListener } from '../coreHandlers/handleScope';\nimport type { ReplayContainer } from '../types';\n\n/**\n * Add global listeners that cannot be removed.\n */\nexport function addGlobalListeners(replay: ReplayContainer): void {\n // Listeners from core SDK //\n const scope = getCurrentScope();\n const client = getClient();\n\n scope.addScopeListener(handleScopeListener(replay));\n addClickKeypressInstrumentationHandler(handleDomListener(replay));\n addHistoryInstrumentationHandler(handleHistorySpanListener(replay));\n handleNetworkBreadcrumbs(replay);\n\n // Tag all (non replay) events that get sent to Sentry with the current\n // replay ID so that we can reference them later in the UI\n const eventProcessor = handleGlobalEventListener(replay, !hasHooks(client));\n if (client && client.addEventProcessor) {\n client.addEventProcessor(eventProcessor);\n } else {\n addEventProcessor(eventProcessor);\n }\n\n // If a custom client has no hooks yet, we continue to use the \"old\" implementation\n if (hasHooks(client)) {\n client.on('beforeSendEvent', handleBeforeSendEvent(replay));\n client.on('afterSendEvent', handleAfterSendEvent(replay));\n client.on('createDsc', (dsc: DynamicSamplingContext) => {\n const replayId = replay.getSessionId();\n // We do not want to set the DSC when in buffer mode, as that means the replay has not been sent (yet)\n if (replayId && replay.isEnabled() && replay.recordingMode === 'session') {\n // Ensure to check that the session is still active - it could have expired in the meanwhile\n const isSessionActive = replay.checkAndHandleExpiredSession();\n if (isSessionActive) {\n dsc.replay_id = replayId;\n }\n }\n });\n\n client.on('startTransaction', transaction => {\n replay.lastTransaction = transaction;\n });\n\n // We may be missing the initial startTransaction due to timing issues,\n // so we capture it on finish again.\n client.on('finishTransaction', transaction => {\n replay.lastTransaction = transaction;\n });\n\n // We want to flush replay\n client.on('beforeSendFeedback', (feedbackEvent, options) => {\n const replayId = replay.getSessionId();\n if (options && options.includeReplay && replay.isEnabled() && replayId) {\n // This should never reject\n if (feedbackEvent.contexts && feedbackEvent.contexts.feedback) {\n feedbackEvent.contexts.feedback.replay_id = replayId;\n }\n }\n });\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction hasHooks(client: Client | undefined): client is BaseClient {\n return !!(client && client.on);\n}\n","import { WINDOW } from '../constants';\nimport type { AddEventResult, MemoryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { createPerformanceSpans } from './createPerformanceSpans';\n\ntype ReplayMemoryEntry = ReplayPerformanceEntry & { data: { memory: MemoryInfo } };\n\ninterface MemoryInfo {\n jsHeapSizeLimit: number;\n totalJSHeapSize: number;\n usedJSHeapSize: number;\n}\n\n/**\n * Create a \"span\" for the total amount of memory being used by JS objects\n * (including v8 internal objects).\n */\nexport async function addMemoryEntry(replay: ReplayContainer): Promise> {\n // window.performance.memory is a non-standard API and doesn't work on all browsers, so we try-catch this\n try {\n return Promise.all(\n createPerformanceSpans(replay, [\n // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard (we check that it exists above)\n createMemoryEntry(WINDOW.performance.memory),\n ]),\n );\n } catch (error) {\n // Do nothing\n return [];\n }\n}\n\nfunction createMemoryEntry(memoryEntry: MemoryInfo): ReplayMemoryEntry {\n const { jsHeapSizeLimit, totalJSHeapSize, usedJSHeapSize } = memoryEntry;\n // we don't want to use `getAbsoluteTime` because it adds the event time to the\n // time origin, so we get the current timestamp instead\n const time = Date.now() / 1000;\n return {\n type: 'memory',\n name: 'memory',\n start: time,\n end: time,\n data: {\n memory: {\n jsHeapSizeLimit,\n totalJSHeapSize,\n usedJSHeapSize,\n },\n },\n };\n}\n","import { EventType } from '@sentry-internal/rrweb';\nimport { logger } from '@sentry/utils';\n\nimport { updateClickDetectorForRecordingEvent } from '../coreHandlers/handleClick';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { saveSession } from '../session/saveSession';\nimport type { RecordingEvent, ReplayContainer, ReplayOptionFrameEvent } from '../types';\nimport { addEventSync } from './addEvent';\nimport { logInfo } from './log';\n\ntype RecordingEmitCallback = (event: RecordingEvent, isCheckout?: boolean) => void;\n\n/**\n * Handler for recording events.\n *\n * Adds to event buffer, and has varying flushing behaviors if the event was a checkout.\n */\nexport function getHandleRecordingEmit(replay: ReplayContainer): RecordingEmitCallback {\n let hadFirstEvent = false;\n\n return (event: RecordingEvent, _isCheckout?: boolean) => {\n // If this is false, it means session is expired, create and a new session and wait for checkout\n if (!replay.checkAndHandleExpiredSession()) {\n DEBUG_BUILD && logger.warn('[Replay] Received replay event after session expired.');\n\n return;\n }\n\n // `_isCheckout` is only set when the checkout is due to `checkoutEveryNms`\n // We also want to treat the first event as a checkout, so we handle this specifically here\n const isCheckout = _isCheckout || !hadFirstEvent;\n hadFirstEvent = true;\n\n if (replay.clickDetector) {\n updateClickDetectorForRecordingEvent(replay.clickDetector, event);\n }\n\n // The handler returns `true` if we do not want to trigger debounced flush, `false` if we want to debounce flush.\n replay.addUpdate(() => {\n // The session is always started immediately on pageload/init, but for\n // error-only replays, it should reflect the most recent checkout\n // when an error occurs. Clear any state that happens before this current\n // checkout. This needs to happen before `addEvent()` which updates state\n // dependent on this reset.\n if (replay.recordingMode === 'buffer' && isCheckout) {\n replay.setInitialState();\n }\n\n // If the event is not added (e.g. due to being paused, disabled, or out of the max replay duration),\n // Skip all further steps\n if (!addEventSync(replay, event, isCheckout)) {\n // Return true to skip scheduling a debounced flush\n return true;\n }\n\n // Different behavior for full snapshots (type=2), ignore other event types\n // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16\n if (!isCheckout) {\n return false;\n }\n\n // Additionally, create a meta event that will capture certain SDK settings.\n // In order to handle buffer mode, this needs to either be done when we\n // receive checkout events or at flush time.\n //\n // `isCheckout` is always true, but want to be explicit that it should\n // only be added for checkouts\n addSettingsEvent(replay, isCheckout);\n\n // If there is a previousSessionId after a full snapshot occurs, then\n // the replay session was started due to session expiration. The new session\n // is started before triggering a new checkout and contains the id\n // of the previous session. Do not immediately flush in this case\n // to avoid capturing only the checkout and instead the replay will\n // be captured if they perform any follow-up actions.\n if (replay.session && replay.session.previousSessionId) {\n return true;\n }\n\n // When in buffer mode, make sure we adjust the session started date to the current earliest event of the buffer\n // this should usually be the timestamp of the checkout event, but to be safe...\n if (replay.recordingMode === 'buffer' && replay.session && replay.eventBuffer) {\n const earliestEvent = replay.eventBuffer.getEarliestTimestamp();\n if (earliestEvent) {\n logInfo(\n `[Replay] Updating session start time to earliest event in buffer to ${new Date(earliestEvent)}`,\n replay.getOptions()._experiments.traceInternals,\n );\n\n replay.session.started = earliestEvent;\n\n if (replay.getOptions().stickySession) {\n saveSession(replay.session);\n }\n }\n }\n\n if (replay.recordingMode === 'session') {\n // If the full snapshot is due to an initial load, we will not have\n // a previous session ID. In this case, we want to buffer events\n // for a set amount of time before flushing. This can help avoid\n // capturing replays of users that immediately close the window.\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n void replay.flush();\n }\n\n return true;\n });\n };\n}\n\n/**\n * Exported for tests\n */\nexport function createOptionsEvent(replay: ReplayContainer): ReplayOptionFrameEvent {\n const options = replay.getOptions();\n return {\n type: EventType.Custom,\n timestamp: Date.now(),\n data: {\n tag: 'options',\n payload: {\n shouldRecordCanvas: replay.isRecordingCanvas(),\n sessionSampleRate: options.sessionSampleRate,\n errorSampleRate: options.errorSampleRate,\n useCompressionOption: options.useCompression,\n blockAllMedia: options.blockAllMedia,\n maskAllText: options.maskAllText,\n maskAllInputs: options.maskAllInputs,\n useCompression: replay.eventBuffer ? replay.eventBuffer.type === 'worker' : false,\n networkDetailHasUrls: options.networkDetailAllowUrls.length > 0,\n networkCaptureBodies: options.networkCaptureBodies,\n networkRequestHasHeaders: options.networkRequestHeaders.length > 0,\n networkResponseHasHeaders: options.networkResponseHeaders.length > 0,\n },\n },\n };\n}\n\n/**\n * Add a \"meta\" event that contains a simplified view on current configuration\n * options. This should only be included on the first segment of a recording.\n */\nfunction addSettingsEvent(replay: ReplayContainer, isCheckout?: boolean): void {\n // Only need to add this event when sending the first segment\n if (!isCheckout || !replay.session || replay.session.segmentId !== 0) {\n return;\n }\n\n addEventSync(replay, createOptionsEvent(replay), false);\n}\n","import type { DsnComponents, ReplayEnvelope, ReplayEvent, ReplayRecordingData } from '@sentry/types';\nimport { createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader } from '@sentry/utils';\n\n/**\n * Create a replay envelope ready to be sent.\n * This includes both the replay event, as well as the recording data.\n */\nexport function createReplayEnvelope(\n replayEvent: ReplayEvent,\n recordingData: ReplayRecordingData,\n dsn: DsnComponents,\n tunnel?: string,\n): ReplayEnvelope {\n return createEnvelope(\n createEventEnvelopeHeaders(replayEvent, getSdkMetadataForEnvelopeHeader(replayEvent), tunnel, dsn),\n [\n [{ type: 'replay_event' }, replayEvent],\n [\n {\n type: 'replay_recording',\n // If string then we need to encode to UTF8, otherwise will have\n // wrong size. TextEncoder has similar browser support to\n // MutationObserver, although it does not accept IE11.\n length:\n typeof recordingData === 'string' ? new TextEncoder().encode(recordingData).length : recordingData.length,\n },\n recordingData,\n ],\n ],\n );\n}\n","import type { ReplayRecordingData } from '@sentry/types';\n\n/**\n * Prepare the recording data ready to be sent.\n */\nexport function prepareRecordingData({\n recordingData,\n headers,\n}: {\n recordingData: ReplayRecordingData;\n headers: Record;\n}): ReplayRecordingData {\n let payloadWithSequence;\n\n // XXX: newline is needed to separate sequence id from events\n const replayHeaders = `${JSON.stringify(headers)}\n`;\n\n if (typeof recordingData === 'string') {\n payloadWithSequence = `${replayHeaders}${recordingData}`;\n } else {\n const enc = new TextEncoder();\n // XXX: newline is needed to separate sequence id from events\n const sequence = enc.encode(replayHeaders);\n // Merge the two Uint8Arrays\n payloadWithSequence = new Uint8Array(sequence.length + recordingData.length);\n payloadWithSequence.set(sequence);\n payloadWithSequence.set(recordingData, sequence.length);\n }\n\n return payloadWithSequence;\n}\n","import type { IntegrationIndex, Scope } from '@sentry/core';\nimport { getIsolationScope } from '@sentry/core';\nimport { prepareEvent } from '@sentry/core';\nimport type { Client, EventHint, ReplayEvent } from '@sentry/types';\n\n/**\n * Prepare a replay event & enrich it with the SDK metadata.\n */\nexport async function prepareReplayEvent({\n client,\n scope,\n replayId: event_id,\n event,\n}: {\n client: Client & { _integrations?: IntegrationIndex };\n scope: Scope;\n replayId: string;\n event: ReplayEvent;\n}): Promise {\n const integrations =\n typeof client._integrations === 'object' && client._integrations !== null && !Array.isArray(client._integrations)\n ? Object.keys(client._integrations)\n : undefined;\n\n const eventHint: EventHint = { event_id, integrations };\n\n if (client.emit) {\n client.emit('preprocessEvent', event, eventHint);\n }\n\n const preparedEvent = (await prepareEvent(\n client.getOptions(),\n event,\n eventHint,\n scope,\n client,\n getIsolationScope(),\n )) as ReplayEvent | null;\n\n // If e.g. a global event processor returned null\n if (!preparedEvent) {\n return null;\n }\n\n // This normally happens in browser client \"_prepareEvent\"\n // but since we do not use this private method from the client, but rather the plain import\n // we need to do this manually.\n preparedEvent.platform = preparedEvent.platform || 'javascript';\n\n // extract the SDK name because `client._prepareEvent` doesn't add it to the event\n const metadata = client.getSdkMetadata && client.getSdkMetadata();\n const { name, version } = (metadata && metadata.sdk) || {};\n\n preparedEvent.sdk = {\n ...preparedEvent.sdk,\n name: name || 'sentry.javascript.unknown',\n version: version || '0.0.0',\n };\n\n return preparedEvent;\n}\n","import { getClient, getCurrentScope } from '@sentry/core';\nimport type { ReplayEvent, TransportMakeRequestResponse } from '@sentry/types';\nimport type { RateLimits } from '@sentry/utils';\nimport { isRateLimited, updateRateLimits } from '@sentry/utils';\n\nimport { REPLAY_EVENT_NAME, UNABLE_TO_SEND_REPLAY } from '../constants';\nimport type { SendReplayData } from '../types';\nimport { createReplayEnvelope } from './createReplayEnvelope';\nimport { logInfo } from './log';\nimport { prepareRecordingData } from './prepareRecordingData';\nimport { prepareReplayEvent } from './prepareReplayEvent';\n\n/**\n * Send replay attachment using `fetch()`\n */\nexport async function sendReplayRequest({\n recordingData,\n replayId,\n segmentId: segment_id,\n eventContext,\n timestamp,\n session,\n}: SendReplayData): Promise {\n const preparedRecordingData = prepareRecordingData({\n recordingData,\n headers: {\n segment_id,\n },\n });\n\n const { urls, errorIds, traceIds, initialTimestamp } = eventContext;\n\n const client = getClient();\n const scope = getCurrentScope();\n const transport = client && client.getTransport();\n const dsn = client && client.getDsn();\n\n if (!client || !transport || !dsn || !session.sampled) {\n return;\n }\n\n const baseEvent: ReplayEvent = {\n type: REPLAY_EVENT_NAME,\n replay_start_timestamp: initialTimestamp / 1000,\n timestamp: timestamp / 1000,\n error_ids: errorIds,\n trace_ids: traceIds,\n urls,\n replay_id: replayId,\n segment_id,\n replay_type: session.sampled,\n };\n\n const replayEvent = await prepareReplayEvent({ scope, client, replayId, event: baseEvent });\n\n if (!replayEvent) {\n // Taken from baseclient's `_processEvent` method, where this is handled for errors/transactions\n client.recordDroppedEvent('event_processor', 'replay', baseEvent);\n logInfo('An event processor returned `null`, will not send event.');\n return;\n }\n\n /*\n For reference, the fully built event looks something like this:\n {\n \"type\": \"replay_event\",\n \"timestamp\": 1670837008.634,\n \"error_ids\": [\n \"errorId\"\n ],\n \"trace_ids\": [\n \"traceId\"\n ],\n \"urls\": [\n \"https://example.com\"\n ],\n \"replay_id\": \"eventId\",\n \"segment_id\": 3,\n \"replay_type\": \"error\",\n \"platform\": \"javascript\",\n \"event_id\": \"eventId\",\n \"environment\": \"production\",\n \"sdk\": {\n \"integrations\": [\n \"BrowserTracing\",\n \"Replay\"\n ],\n \"name\": \"sentry.javascript.browser\",\n \"version\": \"7.25.0\"\n },\n \"sdkProcessingMetadata\": {},\n \"contexts\": {\n },\n }\n */\n\n // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to\n // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may\n // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid\n // of this `delete`, lest we miss putting it back in the next time the property is in use.)\n delete replayEvent.sdkProcessingMetadata;\n\n const envelope = createReplayEnvelope(replayEvent, preparedRecordingData, dsn, client.getOptions().tunnel);\n\n let response: void | TransportMakeRequestResponse;\n\n try {\n response = await transport.send(envelope);\n } catch (err) {\n const error = new Error(UNABLE_TO_SEND_REPLAY);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-expect-error This needs lib es2022 and newer\n error.cause = err;\n } catch {\n // nothing to do\n }\n throw error;\n }\n\n // TODO (v8): we can remove this guard once transport.send's type signature doesn't include void anymore\n if (!response) {\n return response;\n }\n\n // If the status code is invalid, we want to immediately stop & not retry\n if (typeof response.statusCode === 'number' && (response.statusCode < 200 || response.statusCode >= 300)) {\n throw new TransportStatusCodeError(response.statusCode);\n }\n\n const rateLimits = updateRateLimits({}, response);\n if (isRateLimited(rateLimits, 'replay')) {\n throw new RateLimitError(rateLimits);\n }\n\n return response;\n}\n\n/**\n * This error indicates that the transport returned an invalid status code.\n */\nexport class TransportStatusCodeError extends Error {\n public constructor(statusCode: number) {\n super(`Transport returned status code ${statusCode}`);\n }\n}\n\n/**\n * This error indicates that we hit a rate limit API error.\n */\nexport class RateLimitError extends Error {\n public rateLimits: RateLimits;\n\n public constructor(rateLimits: RateLimits) {\n super('Rate limit hit');\n this.rateLimits = rateLimits;\n }\n}\n","import { captureException, setContext } from '@sentry/core';\n\nimport { RETRY_BASE_INTERVAL, RETRY_MAX_COUNT, UNABLE_TO_SEND_REPLAY } from '../constants';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { SendReplayData } from '../types';\nimport { RateLimitError, TransportStatusCodeError, sendReplayRequest } from './sendReplayRequest';\n\n/**\n * Finalize and send the current replay event to Sentry\n */\nexport async function sendReplay(\n replayData: SendReplayData,\n retryConfig = {\n count: 0,\n interval: RETRY_BASE_INTERVAL,\n },\n): Promise {\n const { recordingData, options } = replayData;\n\n // short circuit if there's no events to upload (this shouldn't happen as _runFlush makes this check)\n if (!recordingData.length) {\n return;\n }\n\n try {\n await sendReplayRequest(replayData);\n return true;\n } catch (err) {\n if (err instanceof TransportStatusCodeError || err instanceof RateLimitError) {\n throw err;\n }\n\n // Capture error for every failed replay\n setContext('Replays', {\n _retryCount: retryConfig.count,\n });\n\n if (DEBUG_BUILD && options._experiments && options._experiments.captureExceptions) {\n captureException(err);\n }\n\n // If an error happened here, it's likely that uploading the attachment\n // failed, we'll can retry with the same events payload\n if (retryConfig.count >= RETRY_MAX_COUNT) {\n const error = new Error(`${UNABLE_TO_SEND_REPLAY} - max retries exceeded`);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-expect-error This needs lib es2022 and newer\n error.cause = err;\n } catch {\n // nothing to do\n }\n\n throw error;\n }\n\n // will retry in intervals of 5, 10, 30\n retryConfig.interval *= ++retryConfig.count;\n\n return new Promise((resolve, reject) => {\n setTimeout(async () => {\n try {\n await sendReplay(replayData, retryConfig);\n resolve(true);\n } catch (err) {\n reject(err);\n }\n }, retryConfig.interval);\n });\n }\n}\n","export const THROTTLED = '__THROTTLED';\nexport const SKIPPED = '__SKIPPED';\n\n/**\n * Create a throttled function off a given function.\n * When calling the throttled function, it will call the original function only\n * if it hasn't been called more than `maxCount` times in the last `durationSeconds`.\n *\n * Returns `THROTTLED` if throttled for the first time, after that `SKIPPED`,\n * or else the return value of the original function.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function throttle any>(\n fn: T,\n maxCount: number,\n durationSeconds: number,\n): (...rest: Parameters) => ReturnType | typeof THROTTLED | typeof SKIPPED {\n const counter = new Map();\n\n const _cleanup = (now: number): void => {\n const threshold = now - durationSeconds;\n counter.forEach((_value, key) => {\n if (key < threshold) {\n counter.delete(key);\n }\n });\n };\n\n const _getTotalCount = (): number => {\n return [...counter.values()].reduce((a, b) => a + b, 0);\n };\n\n let isThrottled = false;\n\n return (...rest: Parameters): ReturnType | typeof THROTTLED | typeof SKIPPED => {\n // Date in second-precision, which we use as basis for the throttling\n const now = Math.floor(Date.now() / 1000);\n\n // First, make sure to delete any old entries\n _cleanup(now);\n\n // If already over limit, do nothing\n if (_getTotalCount() >= maxCount) {\n const wasThrottled = isThrottled;\n isThrottled = true;\n return wasThrottled ? SKIPPED : THROTTLED;\n }\n\n isThrottled = false;\n const count = counter.get(now) || 0;\n counter.set(now, count + 1);\n\n return fn(...rest);\n };\n}\n","/* eslint-disable max-lines */ // TODO: We might want to split this file up\nimport { EventType, record } from '@sentry-internal/rrweb';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n captureException,\n getClient,\n getCurrentScope,\n spanToJSON,\n} from '@sentry/core';\nimport type { ReplayRecordingMode, Transaction } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport {\n BUFFER_CHECKOUT_TIME,\n SESSION_IDLE_EXPIRE_DURATION,\n SESSION_IDLE_PAUSE_DURATION,\n SLOW_CLICK_SCROLL_TIMEOUT,\n SLOW_CLICK_THRESHOLD,\n WINDOW,\n} from './constants';\nimport { ClickDetector } from './coreHandlers/handleClick';\nimport { handleKeyboardEvent } from './coreHandlers/handleKeyboardEvent';\nimport { setupPerformanceObserver } from './coreHandlers/performanceObserver';\nimport { DEBUG_BUILD } from './debug-build';\nimport { createEventBuffer } from './eventBuffer';\nimport { clearSession } from './session/clearSession';\nimport { loadOrCreateSession } from './session/loadOrCreateSession';\nimport { saveSession } from './session/saveSession';\nimport { shouldRefreshSession } from './session/shouldRefreshSession';\n\nimport type {\n AddEventResult,\n AddUpdateCallback,\n AllPerformanceEntry,\n AllPerformanceEntryData,\n EventBuffer,\n InternalEventContext,\n PopEventContext,\n RecordingEvent,\n RecordingOptions,\n ReplayBreadcrumbFrame,\n ReplayCanvasIntegrationOptions,\n ReplayContainer as ReplayContainerInterface,\n ReplayPerformanceEntry,\n ReplayPluginOptions,\n SendBufferedReplayOptions,\n Session,\n SlowClickConfig,\n Timeouts,\n} from './types';\nimport { ReplayEventTypeCustom } from './types';\nimport { addEvent, addEventSync } from './util/addEvent';\nimport { addGlobalListeners } from './util/addGlobalListeners';\nimport { addMemoryEntry } from './util/addMemoryEntry';\nimport { createBreadcrumb } from './util/createBreadcrumb';\nimport { createPerformanceEntries } from './util/createPerformanceEntries';\nimport { createPerformanceSpans } from './util/createPerformanceSpans';\nimport { debounce } from './util/debounce';\nimport { getHandleRecordingEmit } from './util/handleRecordingEmit';\nimport { isExpired } from './util/isExpired';\nimport { isSessionExpired } from './util/isSessionExpired';\nimport { logInfo, logInfoNextTick } from './util/log';\nimport { sendReplay } from './util/sendReplay';\nimport type { SKIPPED } from './util/throttle';\nimport { THROTTLED, throttle } from './util/throttle';\n\n/**\n * The main replay container class, which holds all the state and methods for recording and sending replays.\n */\nexport class ReplayContainer implements ReplayContainerInterface {\n public eventBuffer: EventBuffer | null;\n\n public performanceEntries: AllPerformanceEntry[];\n\n public replayPerformanceEntries: ReplayPerformanceEntry[];\n\n public session: Session | undefined;\n\n public clickDetector: ClickDetector | undefined;\n\n /**\n * Recording can happen in one of three modes:\n * - session: Record the whole session, sending it continuously\n * - buffer: Always keep the last 60s of recording, requires:\n * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs\n * - or calling `flush()` to send the replay\n */\n public recordingMode: ReplayRecordingMode;\n\n /**\n * The current or last active transcation.\n * This is only available when performance is enabled.\n */\n public lastTransaction?: Transaction;\n\n /**\n * These are here so we can overwrite them in tests etc.\n * @hidden\n */\n public readonly timeouts: Timeouts;\n\n private _throttledAddEvent: (\n event: RecordingEvent,\n isCheckout?: boolean,\n ) => typeof THROTTLED | typeof SKIPPED | Promise;\n\n /**\n * Options to pass to `rrweb.record()`\n */\n private readonly _recordingOptions: RecordingOptions;\n\n private readonly _options: ReplayPluginOptions;\n\n private _performanceCleanupCallback?: () => void;\n\n private _debouncedFlush: ReturnType;\n private _flushLock: Promise | undefined;\n\n /**\n * Timestamp of the last user activity. This lives across sessions.\n */\n private _lastActivity: number;\n\n /**\n * Is the integration currently active?\n */\n private _isEnabled: boolean;\n\n /**\n * Paused is a state where:\n * - DOM Recording is not listening at all\n * - Nothing will be added to event buffer (e.g. core SDK events)\n */\n private _isPaused: boolean;\n\n /**\n * Have we attached listeners to the core SDK?\n * Note we have to track this as there is no way to remove instrumentation handlers.\n */\n private _hasInitializedCoreListeners: boolean;\n\n /**\n * Function to stop recording\n */\n private _stopRecording: ReturnType | undefined;\n\n private _context: InternalEventContext;\n\n /**\n * Internal use for canvas recording options\n */\n private _canvas: ReplayCanvasIntegrationOptions | undefined;\n\n public constructor({\n options,\n recordingOptions,\n }: {\n options: ReplayPluginOptions;\n recordingOptions: RecordingOptions;\n }) {\n this.eventBuffer = null;\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n this.recordingMode = 'session';\n this.timeouts = {\n sessionIdlePause: SESSION_IDLE_PAUSE_DURATION,\n sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION,\n } as const;\n this._lastActivity = Date.now();\n this._isEnabled = false;\n this._isPaused = false;\n this._hasInitializedCoreListeners = false;\n this._context = {\n errorIds: new Set(),\n traceIds: new Set(),\n urls: [],\n initialTimestamp: Date.now(),\n initialUrl: '',\n };\n\n this._recordingOptions = recordingOptions;\n this._options = options;\n\n this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {\n maxWait: this._options.flushMaxDelay,\n });\n\n this._throttledAddEvent = throttle(\n (event: RecordingEvent, isCheckout?: boolean) => addEvent(this, event, isCheckout),\n // Max 300 events...\n 300,\n // ... per 5s\n 5,\n );\n\n const { slowClickTimeout, slowClickIgnoreSelectors } = this.getOptions();\n\n const slowClickConfig: SlowClickConfig | undefined = slowClickTimeout\n ? {\n threshold: Math.min(SLOW_CLICK_THRESHOLD, slowClickTimeout),\n timeout: slowClickTimeout,\n scrollTimeout: SLOW_CLICK_SCROLL_TIMEOUT,\n ignoreSelector: slowClickIgnoreSelectors ? slowClickIgnoreSelectors.join(',') : '',\n }\n : undefined;\n\n if (slowClickConfig) {\n this.clickDetector = new ClickDetector(this, slowClickConfig);\n }\n }\n\n /** Get the event context. */\n public getContext(): InternalEventContext {\n return this._context;\n }\n\n /** If recording is currently enabled. */\n public isEnabled(): boolean {\n return this._isEnabled;\n }\n\n /** If recording is currently paused. */\n public isPaused(): boolean {\n return this._isPaused;\n }\n\n /**\n * Determine if canvas recording is enabled\n */\n public isRecordingCanvas(): boolean {\n return Boolean(this._canvas);\n }\n\n /** Get the replay integration options. */\n public getOptions(): ReplayPluginOptions {\n return this._options;\n }\n\n /**\n * Initializes the plugin based on sampling configuration. Should not be\n * called outside of constructor.\n */\n public initializeSampling(previousSessionId?: string): void {\n const { errorSampleRate, sessionSampleRate } = this._options;\n\n // If neither sample rate is > 0, then do nothing - user will need to call one of\n // `start()` or `startBuffering` themselves.\n if (errorSampleRate <= 0 && sessionSampleRate <= 0) {\n return;\n }\n\n // Otherwise if there is _any_ sample rate set, try to load an existing\n // session, or create a new one.\n this._initializeSessionForSampling(previousSessionId);\n\n if (!this.session) {\n // This should not happen, something wrong has occurred\n this._handleException(new Error('Unable to initialize and create session'));\n return;\n }\n\n if (this.session.sampled === false) {\n // This should only occur if `errorSampleRate` is 0 and was unsampled for\n // session-based replay. In this case there is nothing to do.\n return;\n }\n\n // If segmentId > 0, it means we've previously already captured this session\n // In this case, we still want to continue in `session` recording mode\n this.recordingMode = this.session.sampled === 'buffer' && this.session.segmentId === 0 ? 'buffer' : 'session';\n\n logInfoNextTick(\n `[Replay] Starting replay in ${this.recordingMode} mode`,\n this._options._experiments.traceInternals,\n );\n\n this._initializeRecording();\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will throw an error if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * _performanceObserver, Recording, Sentry SDK, etc)\n */\n public start(): void {\n if (this._isEnabled && this.recordingMode === 'session') {\n throw new Error('Replay recording is already in progress');\n }\n\n if (this._isEnabled && this.recordingMode === 'buffer') {\n throw new Error('Replay buffering is in progress, call `flush()` to save the replay');\n }\n\n logInfoNextTick('[Replay] Starting replay in session mode', this._options._experiments.traceInternals);\n\n // Required as user activity is initially set in\n // constructor, so if `start()` is called after\n // session idle expiration, a replay will not be\n // created due to an idle timeout.\n this._updateUserActivity();\n\n const session = loadOrCreateSession(\n {\n maxReplayDuration: this._options.maxReplayDuration,\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n traceInternals: this._options._experiments.traceInternals,\n },\n {\n stickySession: this._options.stickySession,\n // This is intentional: create a new session-based replay when calling `start()`\n sessionSampleRate: 1,\n allowBuffering: false,\n },\n );\n\n this.session = session;\n\n this._initializeRecording();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, an error occurs.\n */\n public startBuffering(): void {\n if (this._isEnabled) {\n throw new Error('Replay recording is already in progress');\n }\n\n logInfoNextTick('[Replay] Starting replay in buffer mode', this._options._experiments.traceInternals);\n\n const session = loadOrCreateSession(\n {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n traceInternals: this._options._experiments.traceInternals,\n },\n {\n stickySession: this._options.stickySession,\n sessionSampleRate: 0,\n allowBuffering: true,\n },\n );\n\n this.session = session;\n\n this.recordingMode = 'buffer';\n this._initializeRecording();\n }\n\n /**\n * Start recording.\n *\n * Note that this will cause a new DOM checkout\n */\n public startRecording(): void {\n try {\n const canvasOptions = this._canvas;\n\n this._stopRecording = record({\n ...this._recordingOptions,\n // When running in error sampling mode, we need to overwrite `checkoutEveryNms`\n // Without this, it would record forever, until an error happens, which we don't want\n // instead, we'll always keep the last 60 seconds of replay before an error happened\n ...(this.recordingMode === 'buffer' && { checkoutEveryNms: BUFFER_CHECKOUT_TIME }),\n emit: getHandleRecordingEmit(this),\n onMutation: this._onMutationHandler,\n ...(canvasOptions\n ? {\n recordCanvas: canvasOptions.recordCanvas,\n getCanvasManager: canvasOptions.getCanvasManager,\n sampling: canvasOptions.sampling,\n dataURLOptions: canvasOptions.dataURLOptions,\n }\n : {}),\n });\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Stops the recording, if it was running.\n *\n * Returns true if it was previously stopped, or is now stopped,\n * otherwise false.\n */\n public stopRecording(): boolean {\n try {\n if (this._stopRecording) {\n this._stopRecording();\n this._stopRecording = undefined;\n }\n\n return true;\n } catch (err) {\n this._handleException(err);\n return false;\n }\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n public async stop({ forceFlush = false, reason }: { forceFlush?: boolean; reason?: string } = {}): Promise {\n if (!this._isEnabled) {\n return;\n }\n\n // We can't move `_isEnabled` after awaiting a flush, otherwise we can\n // enter into an infinite loop when `stop()` is called while flushing.\n this._isEnabled = false;\n\n try {\n logInfo(\n `[Replay] Stopping Replay${reason ? ` triggered by ${reason}` : ''}`,\n this._options._experiments.traceInternals,\n );\n\n this._removeListeners();\n this.stopRecording();\n\n this._debouncedFlush.cancel();\n // See comment above re: `_isEnabled`, we \"force\" a flush, ignoring the\n // `_isEnabled` state of the plugin since it was disabled above.\n if (forceFlush) {\n await this._flush({ force: true });\n }\n\n // After flush, destroy event buffer\n this.eventBuffer && this.eventBuffer.destroy();\n this.eventBuffer = null;\n\n // Clear session from session storage, note this means if a new session\n // is started after, it will not have `previousSessionId`\n clearSession(this);\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Pause some replay functionality. See comments for `_isPaused`.\n * This differs from stop as this only stops DOM recording, it is\n * not as thorough of a shutdown as `stop()`.\n */\n public pause(): void {\n if (this._isPaused) {\n return;\n }\n\n this._isPaused = true;\n this.stopRecording();\n\n logInfo('[Replay] Pausing replay', this._options._experiments.traceInternals);\n }\n\n /**\n * Resumes recording, see notes for `pause().\n *\n * Note that calling `startRecording()` here will cause a\n * new DOM checkout.`\n */\n public resume(): void {\n if (!this._isPaused || !this._checkSession()) {\n return;\n }\n\n this._isPaused = false;\n this.startRecording();\n\n logInfo('[Replay] Resuming replay', this._options._experiments.traceInternals);\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n public async sendBufferedReplayOrFlush({ continueRecording = true }: SendBufferedReplayOptions = {}): Promise {\n if (this.recordingMode === 'session') {\n return this.flushImmediate();\n }\n\n const activityTime = Date.now();\n\n logInfo('[Replay] Converting buffer to session', this._options._experiments.traceInternals);\n\n // Allow flush to complete before resuming as a session recording, otherwise\n // the checkout from `startRecording` may be included in the payload.\n // Prefer to keep the error replay as a separate (and smaller) segment\n // than the session replay.\n await this.flushImmediate();\n\n const hasStoppedRecording = this.stopRecording();\n\n if (!continueRecording || !hasStoppedRecording) {\n return;\n }\n\n // To avoid race conditions where this is called multiple times, we check here again that we are still buffering\n if ((this.recordingMode as ReplayRecordingMode) === 'session') {\n return;\n }\n\n // Re-start recording in session-mode\n this.recordingMode = 'session';\n\n // Once this session ends, we do not want to refresh it\n if (this.session) {\n this._updateUserActivity(activityTime);\n this._updateSessionActivity(activityTime);\n this._maybeSaveSession();\n }\n\n this.startRecording();\n }\n\n /**\n * We want to batch uploads of replay events. Save events only if\n * `` milliseconds have elapsed since the last event\n * *OR* if `` milliseconds have elapsed.\n *\n * Accepts a callback to perform side-effects and returns true to stop batch\n * processing and hand back control to caller.\n */\n public addUpdate(cb: AddUpdateCallback): void {\n // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'buffer'`)\n const cbResult = cb();\n\n // If this option is turned on then we will only want to call `flush`\n // explicitly\n if (this.recordingMode === 'buffer') {\n return;\n }\n\n // If callback is true, we do not want to continue with flushing -- the\n // caller will need to handle it.\n if (cbResult === true) {\n return;\n }\n\n // addUpdate is called quite frequently - use _debouncedFlush so that it\n // respects the flush delays and does not flush immediately\n this._debouncedFlush();\n }\n\n /**\n * Updates the user activity timestamp and resumes recording. This should be\n * called in an event handler for a user action that we consider as the user\n * being \"active\" (e.g. a mouse click).\n */\n public triggerUserActivity(): void {\n this._updateUserActivity();\n\n // This case means that recording was once stopped due to inactivity.\n // Ensure that recording is resumed.\n if (!this._stopRecording) {\n // Create a new session, otherwise when the user action is flushed, it\n // will get rejected due to an expired session.\n if (!this._checkSession()) {\n return;\n }\n\n // Note: This will cause a new DOM checkout\n this.resume();\n return;\n }\n\n // Otherwise... recording was never suspended, continue as normalish\n this.checkAndHandleExpiredSession();\n\n this._updateSessionActivity();\n }\n\n /**\n * Updates the user activity timestamp *without* resuming\n * recording. Some user events (e.g. keydown) can be create\n * low-value replays that only contain the keypress as a\n * breadcrumb. Instead this would require other events to\n * create a new replay after a session has expired.\n */\n public updateUserActivity(): void {\n this._updateUserActivity();\n this._updateSessionActivity();\n }\n\n /**\n * Only flush if `this.recordingMode === 'session'`\n */\n public conditionalFlush(): Promise {\n if (this.recordingMode === 'buffer') {\n return Promise.resolve();\n }\n\n return this.flushImmediate();\n }\n\n /**\n * Flush using debounce flush\n */\n public flush(): Promise {\n return this._debouncedFlush() as Promise;\n }\n\n /**\n * Always flush via `_debouncedFlush` so that we do not have flushes triggered\n * from calling both `flush` and `_debouncedFlush`. Otherwise, there could be\n * cases of mulitple flushes happening closely together.\n */\n public flushImmediate(): Promise {\n this._debouncedFlush();\n // `.flush` is provided by the debounced function, analogously to lodash.debounce\n return this._debouncedFlush.flush() as Promise;\n }\n\n /**\n * Cancels queued up flushes.\n */\n public cancelFlush(): void {\n this._debouncedFlush.cancel();\n }\n\n /** Get the current sesion (=replay) ID */\n public getSessionId(): string | undefined {\n return this.session && this.session.id;\n }\n\n /**\n * Checks if recording should be stopped due to user inactivity. Otherwise\n * check if session is expired and create a new session if so. Triggers a new\n * full snapshot on new session.\n *\n * Returns true if session is not expired, false otherwise.\n * @hidden\n */\n public checkAndHandleExpiredSession(): boolean | void {\n // Prevent starting a new session if the last user activity is older than\n // SESSION_IDLE_PAUSE_DURATION. Otherwise non-user activity can trigger a new\n // session+recording. This creates noisy replays that do not have much\n // content in them.\n if (\n this._lastActivity &&\n isExpired(this._lastActivity, this.timeouts.sessionIdlePause) &&\n this.session &&\n this.session.sampled === 'session'\n ) {\n // Pause recording only for session-based replays. Otherwise, resuming\n // will create a new replay and will conflict with users who only choose\n // to record error-based replays only. (e.g. the resumed replay will not\n // contain a reference to an error)\n this.pause();\n return;\n }\n\n // --- There is recent user activity --- //\n // This will create a new session if expired, based on expiry length\n if (!this._checkSession()) {\n // Check session handles the refreshing itself\n return false;\n }\n\n return true;\n }\n\n /**\n * Capture some initial state that can change throughout the lifespan of the\n * replay. This is required because otherwise they would be captured at the\n * first flush.\n */\n public setInitialState(): void {\n const urlPath = `${WINDOW.location.pathname}${WINDOW.location.hash}${WINDOW.location.search}`;\n const url = `${WINDOW.location.origin}${urlPath}`;\n\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n\n // Reset _context as well\n this._clearContext();\n\n this._context.initialUrl = url;\n this._context.initialTimestamp = Date.now();\n this._context.urls.push(url);\n }\n\n /**\n * Add a breadcrumb event, that may be throttled.\n * If it was throttled, we add a custom breadcrumb to indicate that.\n */\n public throttledAddEvent(\n event: RecordingEvent,\n isCheckout?: boolean,\n ): typeof THROTTLED | typeof SKIPPED | Promise {\n const res = this._throttledAddEvent(event, isCheckout);\n\n // If this is THROTTLED, it means we have throttled the event for the first time\n // In this case, we want to add a breadcrumb indicating that something was skipped\n if (res === THROTTLED) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.throttled',\n });\n\n this.addUpdate(() => {\n // Return `false` if the event _was_ added, as that means we schedule a flush\n return !addEventSync(this, {\n type: ReplayEventTypeCustom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n metric: true,\n },\n });\n });\n }\n\n return res;\n }\n\n /**\n * This will get the parametrized route name of the current page.\n * This is only available if performance is enabled, and if an instrumented router is used.\n */\n public getCurrentRoute(): string | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const lastTransaction = this.lastTransaction || getCurrentScope().getTransaction();\n\n const attributes = (lastTransaction && spanToJSON(lastTransaction).data) || {};\n const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n if (!lastTransaction || !source || !['route', 'custom'].includes(source)) {\n return undefined;\n }\n\n return spanToJSON(lastTransaction).description;\n }\n\n /**\n * Initialize and start all listeners to varying events (DOM,\n * Performance Observer, Recording, Sentry SDK, etc)\n */\n private _initializeRecording(): void {\n this.setInitialState();\n\n // this method is generally called on page load or manually - in both cases\n // we should treat it as an activity\n this._updateSessionActivity();\n\n this.eventBuffer = createEventBuffer({\n useCompression: this._options.useCompression,\n workerUrl: this._options.workerUrl,\n });\n\n this._removeListeners();\n this._addListeners();\n\n // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout\n this._isEnabled = true;\n this._isPaused = false;\n\n this.startRecording();\n }\n\n /** A wrapper to conditionally capture exceptions. */\n private _handleException(error: unknown): void {\n DEBUG_BUILD && logger.error('[Replay]', error);\n\n if (DEBUG_BUILD && this._options._experiments && this._options._experiments.captureExceptions) {\n captureException(error);\n }\n }\n\n /**\n * Loads (or refreshes) the current session.\n */\n private _initializeSessionForSampling(previousSessionId?: string): void {\n // Whenever there is _any_ error sample rate, we always allow buffering\n // Because we decide on sampling when an error occurs, we need to buffer at all times if sampling for errors\n const allowBuffering = this._options.errorSampleRate > 0;\n\n const session = loadOrCreateSession(\n {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n traceInternals: this._options._experiments.traceInternals,\n previousSessionId,\n },\n {\n stickySession: this._options.stickySession,\n sessionSampleRate: this._options.sessionSampleRate,\n allowBuffering,\n },\n );\n\n this.session = session;\n }\n\n /**\n * Checks and potentially refreshes the current session.\n * Returns false if session is not recorded.\n */\n private _checkSession(): boolean {\n // If there is no session yet, we do not want to refresh anything\n // This should generally not happen, but to be safe....\n if (!this.session) {\n return false;\n }\n\n const currentSession = this.session;\n\n if (\n shouldRefreshSession(currentSession, {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n })\n ) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._refreshSession(currentSession);\n return false;\n }\n\n return true;\n }\n\n /**\n * Refresh a session with a new one.\n * This stops the current session (without forcing a flush, as that would never work since we are expired),\n * and then does a new sampling based on the refreshed session.\n */\n private async _refreshSession(session: Session): Promise {\n if (!this._isEnabled) {\n return;\n }\n await this.stop({ reason: 'refresh session' });\n this.initializeSampling(session.id);\n }\n\n /**\n * Adds listeners to record events for the replay\n */\n private _addListeners(): void {\n try {\n WINDOW.document.addEventListener('visibilitychange', this._handleVisibilityChange);\n WINDOW.addEventListener('blur', this._handleWindowBlur);\n WINDOW.addEventListener('focus', this._handleWindowFocus);\n WINDOW.addEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.addListeners();\n }\n\n // There is no way to remove these listeners, so ensure they are only added once\n if (!this._hasInitializedCoreListeners) {\n addGlobalListeners(this);\n\n this._hasInitializedCoreListeners = true;\n }\n } catch (err) {\n this._handleException(err);\n }\n\n this._performanceCleanupCallback = setupPerformanceObserver(this);\n }\n\n /**\n * Cleans up listeners that were created in `_addListeners`\n */\n private _removeListeners(): void {\n try {\n WINDOW.document.removeEventListener('visibilitychange', this._handleVisibilityChange);\n\n WINDOW.removeEventListener('blur', this._handleWindowBlur);\n WINDOW.removeEventListener('focus', this._handleWindowFocus);\n WINDOW.removeEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.removeListeners();\n }\n\n if (this._performanceCleanupCallback) {\n this._performanceCleanupCallback();\n }\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Handle when visibility of the page content changes. Opening a new tab will\n * cause the state to change to hidden because of content of current page will\n * be hidden. Likewise, moving a different window to cover the contents of the\n * page will also trigger a change to a hidden state.\n */\n private _handleVisibilityChange: () => void = () => {\n if (WINDOW.document.visibilityState === 'visible') {\n this._doChangeToForegroundTasks();\n } else {\n this._doChangeToBackgroundTasks();\n }\n };\n\n /**\n * Handle when page is blurred\n */\n private _handleWindowBlur: () => void = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.blur',\n });\n\n // Do not count blur as a user action -- it's part of the process of them\n // leaving the page\n this._doChangeToBackgroundTasks(breadcrumb);\n };\n\n /**\n * Handle when page is focused\n */\n private _handleWindowFocus: () => void = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.focus',\n });\n\n // Do not count focus as a user action -- instead wait until they focus and\n // interactive with page\n this._doChangeToForegroundTasks(breadcrumb);\n };\n\n /** Ensure page remains active when a key is pressed. */\n private _handleKeyboardEvent: (event: KeyboardEvent) => void = (event: KeyboardEvent) => {\n handleKeyboardEvent(this, event);\n };\n\n /**\n * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)\n */\n private _doChangeToBackgroundTasks(breadcrumb?: ReplayBreadcrumbFrame): void {\n if (!this.session) {\n return;\n }\n\n const expired = isSessionExpired(this.session, {\n maxReplayDuration: this._options.maxReplayDuration,\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n });\n\n if (expired) {\n return;\n }\n\n if (breadcrumb) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Send replay when the page/tab becomes hidden. There is no reason to send\n // replay if it becomes visible, since no actions we care about were done\n // while it was hidden\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n void this.conditionalFlush();\n }\n\n /**\n * Tasks to run when we consider a page to be visible (via focus and/or visibility)\n */\n private _doChangeToForegroundTasks(breadcrumb?: ReplayBreadcrumbFrame): void {\n if (!this.session) {\n return;\n }\n\n const isSessionActive = this.checkAndHandleExpiredSession();\n\n if (!isSessionActive) {\n // If the user has come back to the page within SESSION_IDLE_PAUSE_DURATION\n // ms, we will re-use the existing session, otherwise create a new\n // session\n logInfo('[Replay] Document has become active, but session has expired');\n return;\n }\n\n if (breadcrumb) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n }\n\n /**\n * Update user activity (across session lifespans)\n */\n private _updateUserActivity(_lastActivity: number = Date.now()): void {\n this._lastActivity = _lastActivity;\n }\n\n /**\n * Updates the session's last activity timestamp\n */\n private _updateSessionActivity(_lastActivity: number = Date.now()): void {\n if (this.session) {\n this.session.lastActivity = _lastActivity;\n this._maybeSaveSession();\n }\n }\n\n /**\n * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb\n */\n private _createCustomBreadcrumb(breadcrumb: ReplayBreadcrumbFrame): void {\n this.addUpdate(() => {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.throttledAddEvent({\n type: EventType.Custom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n },\n });\n });\n }\n\n /**\n * Observed performance events are added to `this.performanceEntries`. These\n * are included in the replay event before it is finished and sent to Sentry.\n */\n private _addPerformanceEntries(): Promise> {\n const performanceEntries = createPerformanceEntries(this.performanceEntries).concat(this.replayPerformanceEntries);\n\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n\n return Promise.all(createPerformanceSpans(this, performanceEntries));\n }\n\n /**\n * Clear _context\n */\n private _clearContext(): void {\n // XXX: `initialTimestamp` and `initialUrl` do not get cleared\n this._context.errorIds.clear();\n this._context.traceIds.clear();\n this._context.urls = [];\n }\n\n /** Update the initial timestamp based on the buffer content. */\n private _updateInitialTimestampFromEventBuffer(): void {\n const { session, eventBuffer } = this;\n if (!session || !eventBuffer) {\n return;\n }\n\n // we only ever update this on the initial segment\n if (session.segmentId) {\n return;\n }\n\n const earliestEvent = eventBuffer.getEarliestTimestamp();\n if (earliestEvent && earliestEvent < this._context.initialTimestamp) {\n this._context.initialTimestamp = earliestEvent;\n }\n }\n\n /**\n * Return and clear _context\n */\n private _popEventContext(): PopEventContext {\n const _context = {\n initialTimestamp: this._context.initialTimestamp,\n initialUrl: this._context.initialUrl,\n errorIds: Array.from(this._context.errorIds),\n traceIds: Array.from(this._context.traceIds),\n urls: this._context.urls,\n };\n\n this._clearContext();\n\n return _context;\n }\n\n /**\n * Flushes replay event buffer to Sentry.\n *\n * Performance events are only added right before flushing - this is\n * due to the buffered performance observer events.\n *\n * Should never be called directly, only by `flush`\n */\n private async _runFlush(): Promise {\n const replayId = this.getSessionId();\n\n if (!this.session || !this.eventBuffer || !replayId) {\n DEBUG_BUILD && logger.error('[Replay] No session or eventBuffer found to flush.');\n return;\n }\n\n await this._addPerformanceEntries();\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer || !this.eventBuffer.hasEvents) {\n return;\n }\n\n // Only attach memory event if eventBuffer is not empty\n await addMemoryEntry(this);\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer) {\n return;\n }\n\n // if this changed in the meanwhile, e.g. because the session was refreshed or similar, we abort here\n if (replayId !== this.getSessionId()) {\n return;\n }\n\n try {\n // This uses the data from the eventBuffer, so we need to call this before `finish()\n this._updateInitialTimestampFromEventBuffer();\n\n const timestamp = Date.now();\n\n // Check total duration again, to avoid sending outdated stuff\n // We leave 30s wiggle room to accomodate late flushing etc.\n // This _could_ happen when the browser is suspended during flushing, in which case we just want to stop\n if (timestamp - this._context.initialTimestamp > this._options.maxReplayDuration + 30_000) {\n throw new Error('Session is too long, not sending replay');\n }\n\n const eventContext = this._popEventContext();\n // Always increment segmentId regardless of outcome of sending replay\n const segmentId = this.session.segmentId++;\n this._maybeSaveSession();\n\n // Note this empties the event buffer regardless of outcome of sending replay\n const recordingData = await this.eventBuffer.finish();\n\n await sendReplay({\n replayId,\n recordingData,\n segmentId,\n eventContext,\n session: this.session,\n options: this.getOptions(),\n timestamp,\n });\n } catch (err) {\n this._handleException(err);\n\n // This means we retried 3 times and all of them failed,\n // or we ran into a problem we don't want to retry, like rate limiting.\n // In this case, we want to completely stop the replay - otherwise, we may get inconsistent segments\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.stop({ reason: 'sendReplay' });\n\n const client = getClient();\n\n if (client) {\n client.recordDroppedEvent('send_error', 'replay');\n }\n }\n }\n\n /**\n * Flush recording data to Sentry. Creates a lock so that only a single flush\n * can be active at a time. Do not call this directly.\n */\n private _flush = async ({\n force = false,\n }: {\n /**\n * If true, flush while ignoring the `_isEnabled` state of\n * Replay integration. (By default, flush is noop if integration\n * is stopped).\n */\n force?: boolean;\n } = {}): Promise => {\n if (!this._isEnabled && !force) {\n // This can happen if e.g. the replay was stopped because of exceeding the retry limit\n return;\n }\n\n if (!this.checkAndHandleExpiredSession()) {\n DEBUG_BUILD && logger.error('[Replay] Attempting to finish replay event after session expired.');\n return;\n }\n\n if (!this.session) {\n // should never happen, as we would have bailed out before\n return;\n }\n\n const start = this.session.started;\n const now = Date.now();\n const duration = now - start;\n\n // A flush is about to happen, cancel any queued flushes\n this._debouncedFlush.cancel();\n\n // If session is too short, or too long (allow some wiggle room over maxReplayDuration), do not send it\n // This _should_ not happen, but it may happen if flush is triggered due to a page activity change or similar\n const tooShort = duration < this._options.minReplayDuration;\n const tooLong = duration > this._options.maxReplayDuration + 5_000;\n if (tooShort || tooLong) {\n logInfo(\n `[Replay] Session duration (${Math.floor(duration / 1000)}s) is too ${\n tooShort ? 'short' : 'long'\n }, not sending replay.`,\n this._options._experiments.traceInternals,\n );\n\n if (tooShort) {\n this._debouncedFlush();\n }\n return;\n }\n\n const eventBuffer = this.eventBuffer;\n if (eventBuffer && this.session.segmentId === 0 && !eventBuffer.hasCheckout) {\n logInfo('[Replay] Flushing initial segment without checkout.', this._options._experiments.traceInternals);\n // TODO FN: Evaluate if we want to stop here, or remove this again?\n }\n\n // this._flushLock acts as a lock so that future calls to `_flush()`\n // will be blocked until this promise resolves\n if (!this._flushLock) {\n this._flushLock = this._runFlush();\n await this._flushLock;\n this._flushLock = undefined;\n return;\n }\n\n // Wait for previous flush to finish, then call the debounced `_flush()`.\n // It's possible there are other flush requests queued and waiting for it\n // to resolve. We want to reduce all outstanding requests (as well as any\n // new flush requests that occur within a second of the locked flush\n // completing) into a single flush.\n\n try {\n await this._flushLock;\n } catch (err) {\n DEBUG_BUILD && logger.error(err);\n } finally {\n this._debouncedFlush();\n }\n };\n\n /** Save the session, if it is sticky */\n private _maybeSaveSession(): void {\n if (this.session && this._options.stickySession) {\n saveSession(this.session);\n }\n }\n\n /** Handler for rrweb.record.onMutation */\n private _onMutationHandler = (mutations: unknown[]): boolean => {\n const count = mutations.length;\n\n const mutationLimit = this._options.mutationLimit;\n const mutationBreadcrumbLimit = this._options.mutationBreadcrumbLimit;\n const overMutationLimit = mutationLimit && count > mutationLimit;\n\n // Create a breadcrumb if a lot of mutations happen at the same time\n // We can show this in the UI as an information with potential performance improvements\n if (count > mutationBreadcrumbLimit || overMutationLimit) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.mutations',\n data: {\n count,\n limit: overMutationLimit,\n },\n });\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Stop replay if over the mutation limit\n if (overMutationLimit) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.stop({ reason: 'mutationLimit', forceFlush: this.recordingMode === 'session' });\n return false;\n }\n\n // `true` means we use the regular mutation handling by rrweb\n return true;\n };\n}\n","type DebouncedCallback = {\n (): void | unknown;\n flush: () => void | unknown;\n cancel: () => void;\n};\ntype CallbackFunction = () => unknown;\ntype DebounceOptions = { maxWait?: number };\n\n/**\n * Heavily simplified debounce function based on lodash.debounce.\n *\n * This function takes a callback function (@param fun) and delays its invocation\n * by @param wait milliseconds. Optionally, a maxWait can be specified in @param options,\n * which ensures that the callback is invoked at least once after the specified max. wait time.\n *\n * @param func the function whose invocation is to be debounced\n * @param wait the minimum time until the function is invoked after it was called once\n * @param options the options object, which can contain the `maxWait` property\n *\n * @returns the debounced version of the function, which needs to be called at least once to start the\n * debouncing process. Subsequent calls will reset the debouncing timer and, in case @paramfunc\n * was already invoked in the meantime, return @param func's return value.\n * The debounced function has two additional properties:\n * - `flush`: Invokes the debounced function immediately and returns its return value\n * - `cancel`: Cancels the debouncing process and resets the debouncing timer\n */\nexport function debounce(func: CallbackFunction, wait: number, options?: DebounceOptions): DebouncedCallback {\n let callbackReturnValue: unknown;\n\n let timerId: ReturnType | undefined;\n let maxTimerId: ReturnType | undefined;\n\n const maxWait = options && options.maxWait ? Math.max(options.maxWait, wait) : 0;\n\n function invokeFunc(): unknown {\n cancelTimers();\n callbackReturnValue = func();\n return callbackReturnValue;\n }\n\n function cancelTimers(): void {\n timerId !== undefined && clearTimeout(timerId);\n maxTimerId !== undefined && clearTimeout(maxTimerId);\n timerId = maxTimerId = undefined;\n }\n\n function flush(): unknown {\n if (timerId !== undefined || maxTimerId !== undefined) {\n return invokeFunc();\n }\n return callbackReturnValue;\n }\n\n function debounced(): unknown {\n if (timerId) {\n clearTimeout(timerId);\n }\n timerId = setTimeout(invokeFunc, wait);\n\n if (maxWait && maxTimerId === undefined) {\n maxTimerId = setTimeout(invokeFunc, maxWait);\n }\n\n return callbackReturnValue;\n }\n\n debounced.cancel = cancelTimers;\n debounced.flush = flush;\n return debounced;\n}\n","import { consoleSandbox } from '@sentry/utils';\n\nimport type { DeprecatedPrivacyOptions, ReplayIntegrationPrivacyOptions } from '../types';\n\ntype GetPrivacyOptions = Required> &\n Omit;\ninterface GetPrivacyReturn {\n maskTextSelector: string;\n unmaskTextSelector: string;\n blockSelector: string;\n unblockSelector: string;\n ignoreSelector: string;\n\n blockClass?: RegExp;\n maskTextClass?: RegExp;\n}\n\nfunction getOption(\n selectors: string[],\n defaultSelectors: string[],\n deprecatedClassOption?: string | RegExp,\n deprecatedSelectorOption?: string,\n): string {\n const deprecatedSelectors = typeof deprecatedSelectorOption === 'string' ? deprecatedSelectorOption.split(',') : [];\n\n const allSelectors = [\n ...selectors,\n // @deprecated\n ...deprecatedSelectors,\n\n // sentry defaults\n ...defaultSelectors,\n ];\n\n // @deprecated\n if (typeof deprecatedClassOption !== 'undefined') {\n // NOTE: No support for RegExp\n if (typeof deprecatedClassOption === 'string') {\n allSelectors.push(`.${deprecatedClassOption}`);\n }\n\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Replay] You are using a deprecated configuration item for privacy. Read the documentation on how to use the new privacy configuration.',\n );\n });\n }\n\n return allSelectors.join(',');\n}\n\n/**\n * Returns privacy related configuration for use in rrweb\n */\nexport function getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n\n // eslint-disable-next-line deprecation/deprecation\n blockClass,\n // eslint-disable-next-line deprecation/deprecation\n blockSelector,\n // eslint-disable-next-line deprecation/deprecation\n maskTextClass,\n // eslint-disable-next-line deprecation/deprecation\n maskTextSelector,\n // eslint-disable-next-line deprecation/deprecation\n ignoreClass,\n}: GetPrivacyOptions): GetPrivacyReturn {\n const defaultBlockedElements = ['base[href=\"/\"]'];\n\n const maskSelector = getOption(mask, ['.sentry-mask', '[data-sentry-mask]'], maskTextClass, maskTextSelector);\n const unmaskSelector = getOption(unmask, ['.sentry-unmask', '[data-sentry-unmask]']);\n\n const options: GetPrivacyReturn = {\n // We are making the decision to make text and input selectors the same\n maskTextSelector: maskSelector,\n unmaskTextSelector: unmaskSelector,\n\n blockSelector: getOption(\n block,\n ['.sentry-block', '[data-sentry-block]', ...defaultBlockedElements],\n blockClass,\n blockSelector,\n ),\n unblockSelector: getOption(unblock, ['.sentry-unblock', '[data-sentry-unblock]']),\n ignoreSelector: getOption(ignore, ['.sentry-ignore', '[data-sentry-ignore]', 'input[type=\"file\"]'], ignoreClass),\n };\n\n if (blockClass instanceof RegExp) {\n options.blockClass = blockClass;\n }\n\n if (maskTextClass instanceof RegExp) {\n options.maskTextClass = maskTextClass;\n }\n\n return options;\n}\n","import { getClient } from '@sentry/core';\nimport type { BrowserClientReplayOptions, Integration, IntegrationFn } from '@sentry/types';\nimport { consoleSandbox, dropUndefinedKeys, isBrowser } from '@sentry/utils';\n\nimport {\n DEFAULT_FLUSH_MAX_DELAY,\n DEFAULT_FLUSH_MIN_DELAY,\n MAX_REPLAY_DURATION,\n MIN_REPLAY_DURATION,\n MIN_REPLAY_DURATION_LIMIT,\n} from './constants';\nimport { ReplayContainer } from './replay';\nimport type {\n RecordingOptions,\n ReplayCanvasIntegrationOptions,\n ReplayConfiguration,\n ReplayPluginOptions,\n SendBufferedReplayOptions,\n} from './types';\nimport { getPrivacyOptions } from './util/getPrivacyOptions';\nimport { maskAttribute } from './util/maskAttribute';\n\nconst MEDIA_SELECTORS =\n 'img,image,svg,video,object,picture,embed,map,audio,link[rel=\"icon\"],link[rel=\"apple-touch-icon\"]';\n\nconst DEFAULT_NETWORK_HEADERS = ['content-length', 'content-type', 'accept'];\n\nlet _initialized = false;\n\ntype InitialReplayPluginOptions = Omit &\n Partial>;\n\nexport const replayIntegration = ((options?: ReplayConfiguration) => {\n // eslint-disable-next-line deprecation/deprecation\n return new Replay(options);\n}) satisfies IntegrationFn;\n\n/**\n * The main replay integration class, to be passed to `init({ integrations: [] })`.\n * @deprecated Use `replayIntegration()` instead.\n */\nexport class Replay implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Replay';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n /**\n * Options to pass to `rrweb.record()`\n */\n private readonly _recordingOptions: RecordingOptions;\n\n /**\n * Initial options passed to the replay integration, merged with default values.\n * Note: `sessionSampleRate` and `errorSampleRate` are not required here, as they\n * can only be finally set when setupOnce() is called.\n *\n * @private\n */\n private readonly _initialOptions: InitialReplayPluginOptions;\n\n private _replay?: ReplayContainer;\n\n public constructor({\n flushMinDelay = DEFAULT_FLUSH_MIN_DELAY,\n flushMaxDelay = DEFAULT_FLUSH_MAX_DELAY,\n minReplayDuration = MIN_REPLAY_DURATION,\n maxReplayDuration = MAX_REPLAY_DURATION,\n stickySession = true,\n useCompression = true,\n workerUrl,\n _experiments = {},\n sessionSampleRate,\n errorSampleRate,\n maskAllText = true,\n maskAllInputs = true,\n blockAllMedia = true,\n\n mutationBreadcrumbLimit = 750,\n mutationLimit = 10_000,\n\n slowClickTimeout = 7_000,\n slowClickIgnoreSelectors = [],\n\n networkDetailAllowUrls = [],\n networkDetailDenyUrls = [],\n networkCaptureBodies = true,\n networkRequestHeaders = [],\n networkResponseHeaders = [],\n\n mask = [],\n maskAttributes = ['title', 'placeholder'],\n unmask = [],\n block = [],\n unblock = [],\n ignore = [],\n maskFn,\n\n beforeAddRecordingEvent,\n beforeErrorSampling,\n\n // eslint-disable-next-line deprecation/deprecation\n blockClass,\n // eslint-disable-next-line deprecation/deprecation\n blockSelector,\n // eslint-disable-next-line deprecation/deprecation\n maskInputOptions,\n // eslint-disable-next-line deprecation/deprecation\n maskTextClass,\n // eslint-disable-next-line deprecation/deprecation\n maskTextSelector,\n // eslint-disable-next-line deprecation/deprecation\n ignoreClass,\n }: ReplayConfiguration = {}) {\n // eslint-disable-next-line deprecation/deprecation\n this.name = Replay.id;\n\n const privacyOptions = getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n ignoreClass,\n });\n\n this._recordingOptions = {\n maskAllInputs,\n maskAllText,\n maskInputOptions: { ...(maskInputOptions || {}), password: true },\n maskTextFn: maskFn,\n maskInputFn: maskFn,\n maskAttributeFn: (key: string, value: string, el: HTMLElement): string =>\n maskAttribute({\n maskAttributes,\n maskAllText,\n privacyOptions,\n key,\n value,\n el,\n }),\n\n ...privacyOptions,\n\n // Our defaults\n slimDOMOptions: 'all',\n inlineStylesheet: true,\n // Disable inline images as it will increase segment/replay size\n inlineImages: false,\n // collect fonts, but be aware that `sentry.io` needs to be an allowed\n // origin for playback\n collectFonts: true,\n errorHandler: (err: Error & { __rrweb__?: boolean }) => {\n try {\n err.__rrweb__ = true;\n } catch (error) {\n // ignore errors here\n // this can happen if the error is frozen or does not allow mutation for other reasons\n }\n },\n };\n\n this._initialOptions = {\n flushMinDelay,\n flushMaxDelay,\n minReplayDuration: Math.min(minReplayDuration, MIN_REPLAY_DURATION_LIMIT),\n maxReplayDuration: Math.min(maxReplayDuration, MAX_REPLAY_DURATION),\n stickySession,\n sessionSampleRate,\n errorSampleRate,\n useCompression,\n workerUrl,\n blockAllMedia,\n maskAllInputs,\n maskAllText,\n mutationBreadcrumbLimit,\n mutationLimit,\n slowClickTimeout,\n slowClickIgnoreSelectors,\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders: _getMergedNetworkHeaders(networkRequestHeaders),\n networkResponseHeaders: _getMergedNetworkHeaders(networkResponseHeaders),\n beforeAddRecordingEvent,\n beforeErrorSampling,\n\n _experiments,\n };\n\n if (typeof sessionSampleRate === 'number') {\n // eslint-disable-next-line\n console.warn(\n `[Replay] You are passing \\`sessionSampleRate\\` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure \\`replaysSessionSampleRate\\` directly in the SDK init options, e.g.:\nSentry.init({ replaysSessionSampleRate: ${sessionSampleRate} })`,\n );\n\n this._initialOptions.sessionSampleRate = sessionSampleRate;\n }\n\n if (typeof errorSampleRate === 'number') {\n // eslint-disable-next-line\n console.warn(\n `[Replay] You are passing \\`errorSampleRate\\` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure \\`replaysOnErrorSampleRate\\` directly in the SDK init options, e.g.:\nSentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,\n );\n\n this._initialOptions.errorSampleRate = errorSampleRate;\n }\n\n if (this._initialOptions.blockAllMedia) {\n // `blockAllMedia` is a more user friendly option to configure blocking\n // embedded media elements\n this._recordingOptions.blockSelector = !this._recordingOptions.blockSelector\n ? MEDIA_SELECTORS\n : `${this._recordingOptions.blockSelector},${MEDIA_SELECTORS}`;\n }\n\n if (this._isInitialized && isBrowser()) {\n throw new Error('Multiple Sentry Session Replay instances are not supported');\n }\n\n this._isInitialized = true;\n }\n\n /** If replay has already been initialized */\n protected get _isInitialized(): boolean {\n return _initialized;\n }\n\n /** Update _isInitialized */\n protected set _isInitialized(value: boolean) {\n _initialized = value;\n }\n\n /**\n * Setup and initialize replay container\n */\n public setupOnce(): void {\n if (!isBrowser()) {\n return;\n }\n\n this._setup();\n\n // Once upon a time, we tried to create a transaction in `setupOnce` and it would\n // potentially create a transaction before some native SDK integrations have run\n // and applied their own global event processor. An example is:\n // https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts\n //\n // So we call `this._initialize()` in next event loop as a workaround to wait for other\n // global event processors to finish. This is no longer needed, but keeping it\n // here to avoid any future issues.\n setTimeout(() => this._initialize());\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will throw an error if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * PerformanceObserver, Recording, Sentry SDK, etc)\n */\n public start(): void {\n if (!this._replay) {\n return;\n }\n\n this._replay.start();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, until an error occurs.\n */\n public startBuffering(): void {\n if (!this._replay) {\n return;\n }\n\n this._replay.startBuffering();\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n public stop(): Promise {\n if (!this._replay) {\n return Promise.resolve();\n }\n\n return this._replay.stop({ forceFlush: this._replay.recordingMode === 'session' });\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n public flush(options?: SendBufferedReplayOptions): Promise {\n if (!this._replay || !this._replay.isEnabled()) {\n return Promise.resolve();\n }\n\n return this._replay.sendBufferedReplayOrFlush(options);\n }\n\n /**\n * Get the current session ID.\n */\n public getReplayId(): string | undefined {\n if (!this._replay || !this._replay.isEnabled()) {\n return;\n }\n\n return this._replay.getSessionId();\n }\n\n /**\n * Initializes replay.\n */\n protected _initialize(): void {\n if (!this._replay) {\n return;\n }\n\n // We have to run this in _initialize, because this runs in setTimeout\n // So when this runs all integrations have been added\n // Before this, we cannot access integrations on the client,\n // so we need to mutate the options here\n this._maybeLoadFromReplayCanvasIntegration();\n\n this._replay.initializeSampling();\n }\n\n /** Setup the integration. */\n private _setup(): void {\n // Client is not available in constructor, so we need to wait until setupOnce\n const finalOptions = loadReplayOptionsFromClient(this._initialOptions);\n\n this._replay = new ReplayContainer({\n options: finalOptions,\n recordingOptions: this._recordingOptions,\n });\n }\n\n /** Get canvas options from ReplayCanvas integration, if it is also added. */\n private _maybeLoadFromReplayCanvasIntegration(): void {\n // To save bundle size, we skip checking for stuff here\n // and instead just try-catch everything - as generally this should all be defined\n /* eslint-disable @typescript-eslint/no-non-null-assertion */\n try {\n const client = getClient()!;\n const canvasIntegration = client.getIntegrationByName!('ReplayCanvas') as Integration & {\n getOptions(): ReplayCanvasIntegrationOptions;\n };\n if (!canvasIntegration) {\n return;\n }\n\n this._replay!['_canvas'] = canvasIntegration.getOptions();\n } catch {\n // ignore errors here\n }\n /* eslint-enable @typescript-eslint/no-non-null-assertion */\n }\n}\n\n/** Parse Replay-related options from SDK options */\nfunction loadReplayOptionsFromClient(initialOptions: InitialReplayPluginOptions): ReplayPluginOptions {\n const client = getClient();\n const opt = client && (client.getOptions() as BrowserClientReplayOptions);\n\n const finalOptions = { sessionSampleRate: 0, errorSampleRate: 0, ...dropUndefinedKeys(initialOptions) };\n\n if (!opt) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn('SDK client is not available.');\n });\n return finalOptions;\n }\n\n if (\n initialOptions.sessionSampleRate == null && // TODO remove once deprecated rates are removed\n initialOptions.errorSampleRate == null && // TODO remove once deprecated rates are removed\n opt.replaysSessionSampleRate == null &&\n opt.replaysOnErrorSampleRate == null\n ) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n 'Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.',\n );\n });\n }\n\n if (typeof opt.replaysSessionSampleRate === 'number') {\n finalOptions.sessionSampleRate = opt.replaysSessionSampleRate;\n }\n\n if (typeof opt.replaysOnErrorSampleRate === 'number') {\n finalOptions.errorSampleRate = opt.replaysOnErrorSampleRate;\n }\n\n return finalOptions;\n}\n\nfunction _getMergedNetworkHeaders(headers: string[]): string[] {\n return [...DEFAULT_NETWORK_HEADERS, ...headers.map(header => header.toLowerCase())];\n}\n","import type { getPrivacyOptions } from './getPrivacyOptions';\n\ninterface MaskAttributeParams {\n maskAttributes: string[];\n maskAllText: boolean;\n privacyOptions: ReturnType;\n key: string;\n value: string;\n el: HTMLElement;\n}\n\n/**\n * Masks an attribute if necessary, otherwise return attribute value as-is.\n */\nexport function maskAttribute({\n el,\n key,\n maskAttributes,\n maskAllText,\n privacyOptions,\n value,\n}: MaskAttributeParams): string {\n // We only mask attributes if `maskAllText` is true\n if (!maskAllText) {\n return value;\n }\n\n // unmaskTextSelector takes precendence\n if (privacyOptions.unmaskTextSelector && el.matches(privacyOptions.unmaskTextSelector)) {\n return value;\n }\n\n if (\n maskAttributes.includes(key) ||\n // Need to mask `value` attribute for `` if it's a button-like\n // type\n (key === 'value' && el.tagName === 'INPUT' && ['submit', 'button'].includes(el.getAttribute('type') || ''))\n ) {\n return value.replace(/[\\S]/g, '*');\n }\n\n return value;\n}\n","// eslint-disable-next-line deprecation/deprecation\nimport { Replay as InternalReplay, replayIntegration as internalReplayIntegration } from './integration';\nimport type {\n CanvasManagerInterface as InternalCanvasManagerInterface,\n CanvasManagerOptions as InternalCanvasManagerOptions,\n ReplayBreadcrumbFrame as InternalReplayBreadcrumbFrame,\n ReplayBreadcrumbFrameEvent as InternalReplayBreadcrumbFrameEvent,\n ReplayConfiguration as InternalReplayConfiguration,\n ReplayEventType as InternalReplayEventType,\n ReplayEventWithTime as InternalReplayEventWithTime,\n ReplayFrame as InternalReplayFrame,\n ReplayFrameEvent as InternalReplayFrameEvent,\n ReplayOptionFrameEvent as InternalReplayOptionFrameEvent,\n ReplaySpanFrame as InternalReplaySpanFrame,\n ReplaySpanFrameEvent as InternalReplaySpanFrameEvent,\n} from './types';\nimport { getReplay as internalGetReplay } from './util/getReplay';\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\nconst getReplay = internalGetReplay;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\nconst replayIntegration = internalReplayIntegration;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\n// eslint-disable-next-line deprecation/deprecation\nclass Replay extends InternalReplay {}\n\n// eslint-disable-next-line deprecation/deprecation\nexport { replayIntegration, getReplay, Replay, internalReplayIntegration, internalGetReplay, InternalReplay };\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplayConfiguration = InternalReplayConfiguration;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplayEventType = InternalReplayEventType;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplayEventWithTime = InternalReplayEventWithTime;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplayBreadcrumbFrame = InternalReplayBreadcrumbFrame;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplayBreadcrumbFrameEvent = InternalReplayBreadcrumbFrameEvent;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplayOptionFrameEvent = InternalReplayOptionFrameEvent;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplayFrame = InternalReplayFrame;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplayFrameEvent = InternalReplayFrameEvent;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplaySpanFrame = InternalReplaySpanFrame;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplaySpanFrameEvent = InternalReplaySpanFrameEvent;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype CanvasManagerInterface = InternalCanvasManagerInterface;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype CanvasManagerOptions = InternalCanvasManagerOptions;\n\nexport type {\n // eslint-disable-next-line deprecation/deprecation\n CanvasManagerInterface,\n // eslint-disable-next-line deprecation/deprecation\n CanvasManagerOptions,\n // eslint-disable-next-line deprecation/deprecation\n ReplayBreadcrumbFrame,\n // eslint-disable-next-line deprecation/deprecation\n ReplayBreadcrumbFrameEvent,\n // eslint-disable-next-line deprecation/deprecation\n ReplayConfiguration,\n // eslint-disable-next-line deprecation/deprecation\n ReplayEventType,\n // eslint-disable-next-line deprecation/deprecation\n ReplayEventWithTime,\n // eslint-disable-next-line deprecation/deprecation\n ReplayFrame,\n // eslint-disable-next-line deprecation/deprecation\n ReplayFrameEvent,\n // eslint-disable-next-line deprecation/deprecation\n ReplayOptionFrameEvent,\n // eslint-disable-next-line deprecation/deprecation\n ReplaySpanFrame,\n // eslint-disable-next-line deprecation/deprecation\n ReplaySpanFrameEvent,\n InternalCanvasManagerInterface,\n InternalCanvasManagerOptions,\n InternalReplayBreadcrumbFrame,\n InternalReplayBreadcrumbFrameEvent,\n InternalReplayConfiguration,\n InternalReplayEventType,\n InternalReplayEventWithTime,\n InternalReplayFrame,\n InternalReplayFrameEvent,\n InternalReplayOptionFrameEvent,\n InternalReplaySpanFrame,\n InternalReplaySpanFrameEvent,\n};\n\n// TODO (v8): Remove deprecated types\nexport * from './types/deprecated';\n","/*!\n * cookie\n * Copyright(c) 2012-2014 Roman Shtylman\n * Copyright(c) 2015 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n/**\n * Module exports.\n * @public\n */\n\nvar parse_1 = parse;\nvar serialize_1 = serialize;\n\n/**\n * Module variables.\n * @private\n */\n\nvar __toString = Object.prototype.toString;\n\n/**\n * RegExp to match field-content in RFC 7230 sec 3.2\n *\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n * obs-text = %x80-FF\n */\n\nvar fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\n\n/**\n * Parse a cookie header.\n *\n * Parse the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n *\n * @param {string} str\n * @param {object} [options]\n * @return {object}\n * @public\n */\n\nfunction parse(str, options) {\n if (typeof str !== 'string') {\n throw new TypeError('argument str must be a string');\n }\n\n var obj = {};\n var opt = options || {};\n var dec = opt.decode || decode;\n\n var index = 0;\n while (index < str.length) {\n var eqIdx = str.indexOf('=', index);\n\n // no more cookie pairs\n if (eqIdx === -1) {\n break\n }\n\n var endIdx = str.indexOf(';', index);\n\n if (endIdx === -1) {\n endIdx = str.length;\n } else if (endIdx < eqIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(';', eqIdx - 1) + 1;\n continue\n }\n\n var key = str.slice(index, eqIdx).trim();\n\n // only assign once\n if (undefined === obj[key]) {\n var val = str.slice(eqIdx + 1, endIdx).trim();\n\n // quoted values\n if (val.charCodeAt(0) === 0x22) {\n val = val.slice(1, -1);\n }\n\n obj[key] = tryDecode(val, dec);\n }\n\n index = endIdx + 1;\n }\n\n return obj;\n}\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize the a name value pair into a cookie string suitable for\n * http headers. An optional options object specified cookie parameters.\n *\n * serialize('foo', 'bar', { httpOnly: true })\n * => \"foo=bar; httpOnly\"\n *\n * @param {string} name\n * @param {string} val\n * @param {object} [options]\n * @return {string}\n * @public\n */\n\nfunction serialize(name, val, options) {\n var opt = options || {};\n var enc = opt.encode || encode;\n\n if (typeof enc !== 'function') {\n throw new TypeError('option encode is invalid');\n }\n\n if (!fieldContentRegExp.test(name)) {\n throw new TypeError('argument name is invalid');\n }\n\n var value = enc(val);\n\n if (value && !fieldContentRegExp.test(value)) {\n throw new TypeError('argument val is invalid');\n }\n\n var str = name + '=' + value;\n\n if (null != opt.maxAge) {\n var maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError('option maxAge is invalid')\n }\n\n str += '; Max-Age=' + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!fieldContentRegExp.test(opt.domain)) {\n throw new TypeError('option domain is invalid');\n }\n\n str += '; Domain=' + opt.domain;\n }\n\n if (opt.path) {\n if (!fieldContentRegExp.test(opt.path)) {\n throw new TypeError('option path is invalid');\n }\n\n str += '; Path=' + opt.path;\n }\n\n if (opt.expires) {\n var expires = opt.expires;\n\n if (!isDate(expires) || isNaN(expires.valueOf())) {\n throw new TypeError('option expires is invalid');\n }\n\n str += '; Expires=' + expires.toUTCString();\n }\n\n if (opt.httpOnly) {\n str += '; HttpOnly';\n }\n\n if (opt.secure) {\n str += '; Secure';\n }\n\n if (opt.partitioned) {\n str += '; Partitioned';\n }\n\n if (opt.priority) {\n var priority = typeof opt.priority === 'string'\n ? opt.priority.toLowerCase()\n : opt.priority;\n\n switch (priority) {\n case 'low':\n str += '; Priority=Low';\n break\n case 'medium':\n str += '; Priority=Medium';\n break\n case 'high':\n str += '; Priority=High';\n break\n default:\n throw new TypeError('option priority is invalid')\n }\n }\n\n if (opt.sameSite) {\n var sameSite = typeof opt.sameSite === 'string'\n ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n str += '; SameSite=Strict';\n break;\n case 'lax':\n str += '; SameSite=Lax';\n break;\n case 'strict':\n str += '; SameSite=Strict';\n break;\n case 'none':\n str += '; SameSite=None';\n break;\n default:\n throw new TypeError('option sameSite is invalid');\n }\n }\n\n return str;\n}\n\n/**\n * URL-decode string value. Optimized to skip native call when no %.\n *\n * @param {string} str\n * @returns {string}\n */\n\nfunction decode (str) {\n return str.indexOf('%') !== -1\n ? decodeURIComponent(str)\n : str\n}\n\n/**\n * URL-encode value.\n *\n * @param {string} val\n * @returns {string}\n */\n\nfunction encode (val) {\n return encodeURIComponent(val)\n}\n\n/**\n * Determine if value is a Date.\n *\n * @param {*} val\n * @private\n */\n\nfunction isDate (val) {\n return __toString.call(val) === '[object Date]' ||\n val instanceof Date\n}\n\n/**\n * Try decoding a string using a decoding function.\n *\n * @param {string} str\n * @param {function} decode\n * @private\n */\n\nfunction tryDecode(str, decode) {\n try {\n return decode(str);\n } catch (e) {\n return str;\n }\n}\n\nfunction hasDocumentCookie() {\n const testingValue = typeof global === 'undefined'\n ? undefined\n : global.TEST_HAS_DOCUMENT_COOKIE;\n if (typeof testingValue === 'boolean') {\n return testingValue;\n }\n // Can we get/set cookies on document.cookie?\n return typeof document === 'object' && typeof document.cookie === 'string';\n}\nfunction parseCookies(cookies) {\n if (typeof cookies === 'string') {\n return parse_1(cookies);\n }\n else if (typeof cookies === 'object' && cookies !== null) {\n return cookies;\n }\n else {\n return {};\n }\n}\nfunction readCookie(value, options = {}) {\n const cleanValue = cleanupCookieValue(value);\n if (!options.doNotParse) {\n try {\n return JSON.parse(cleanValue);\n }\n catch (e) {\n // At least we tried\n }\n }\n // Ignore clean value if we failed the deserialization\n // It is not relevant anymore to trim those values\n return value;\n}\nfunction cleanupCookieValue(value) {\n // express prepend j: before serializing a cookie\n if (value && value[0] === 'j' && value[1] === ':') {\n return value.substr(2);\n }\n return value;\n}\n\nclass Cookies {\n constructor(cookies, defaultSetOptions = {}) {\n this.changeListeners = [];\n this.HAS_DOCUMENT_COOKIE = false;\n this.update = () => {\n if (!this.HAS_DOCUMENT_COOKIE) {\n return;\n }\n const previousCookies = this.cookies;\n this.cookies = parse_1(document.cookie);\n this._checkChanges(previousCookies);\n };\n const domCookies = typeof document === 'undefined' ? '' : document.cookie;\n this.cookies = parseCookies(cookies || domCookies);\n this.defaultSetOptions = defaultSetOptions;\n this.HAS_DOCUMENT_COOKIE = hasDocumentCookie();\n }\n _emitChange(params) {\n for (let i = 0; i < this.changeListeners.length; ++i) {\n this.changeListeners[i](params);\n }\n }\n _checkChanges(previousCookies) {\n const names = new Set(Object.keys(previousCookies).concat(Object.keys(this.cookies)));\n names.forEach((name) => {\n if (previousCookies[name] !== this.cookies[name]) {\n this._emitChange({\n name,\n value: readCookie(this.cookies[name]),\n });\n }\n });\n }\n _startPolling() {\n this.pollingInterval = setInterval(this.update, 300);\n }\n _stopPolling() {\n if (this.pollingInterval) {\n clearInterval(this.pollingInterval);\n }\n }\n get(name, options = {}) {\n if (!options.doNotUpdate) {\n this.update();\n }\n return readCookie(this.cookies[name], options);\n }\n getAll(options = {}) {\n if (!options.doNotUpdate) {\n this.update();\n }\n const result = {};\n for (let name in this.cookies) {\n result[name] = readCookie(this.cookies[name], options);\n }\n return result;\n }\n set(name, value, options) {\n if (options) {\n options = Object.assign(Object.assign({}, this.defaultSetOptions), options);\n }\n else {\n options = this.defaultSetOptions;\n }\n const stringValue = typeof value === 'string' ? value : JSON.stringify(value);\n this.cookies = Object.assign(Object.assign({}, this.cookies), { [name]: stringValue });\n if (this.HAS_DOCUMENT_COOKIE) {\n document.cookie = serialize_1(name, stringValue, options);\n }\n this._emitChange({ name, value, options });\n }\n remove(name, options) {\n const finalOptions = (options = Object.assign(Object.assign(Object.assign({}, this.defaultSetOptions), options), { expires: new Date(1970, 1, 1, 0, 0, 1), maxAge: 0 }));\n this.cookies = Object.assign({}, this.cookies);\n delete this.cookies[name];\n if (this.HAS_DOCUMENT_COOKIE) {\n document.cookie = serialize_1(name, '', finalOptions);\n }\n this._emitChange({ name, value: undefined, options });\n }\n addChangeListener(callback) {\n this.changeListeners.push(callback);\n if (this.HAS_DOCUMENT_COOKIE && this.changeListeners.length === 1) {\n if (typeof window === 'object' && 'cookieStore' in window) {\n window.cookieStore.addEventListener('change', this.update);\n }\n else {\n this._startPolling();\n }\n }\n }\n removeChangeListener(callback) {\n const idx = this.changeListeners.indexOf(callback);\n if (idx >= 0) {\n this.changeListeners.splice(idx, 1);\n }\n if (this.HAS_DOCUMENT_COOKIE && this.changeListeners.length === 0) {\n if (typeof window === 'object' && 'cookieStore' in window) {\n window.cookieStore.removeEventListener('change', this.update);\n }\n else {\n this._stopPolling();\n }\n }\n }\n}\n\nexport { Cookies as default };\n","import Cookies from 'universal-cookie';\nexport { default as Cookies } from 'universal-cookie';\nimport * as React from 'react';\nimport { useContext, useState, useLayoutEffect, useMemo } from 'react';\n\nconst CookiesContext = React.createContext(new Cookies());\nconst { Provider, Consumer } = CookiesContext;\n\nclass CookiesProvider extends React.Component {\n constructor(props) {\n super(props);\n if (props.cookies) {\n this.cookies = props.cookies;\n }\n else {\n this.cookies = new Cookies(undefined, props.defaultSetOptions);\n }\n }\n render() {\n return React.createElement(Provider, { value: this.cookies }, this.props.children);\n }\n}\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\nfunction getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nvar reactIs$1 = {exports: {}};\n\nvar reactIs_production_min = {};\n\n/** @license React v16.13.1\n * react-is.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar hasRequiredReactIs_production_min;\n\nfunction requireReactIs_production_min () {\n\tif (hasRequiredReactIs_production_min) return reactIs_production_min;\n\thasRequiredReactIs_production_min = 1;\nvar b=\"function\"===typeof Symbol&&Symbol.for,c=b?Symbol.for(\"react.element\"):60103,d=b?Symbol.for(\"react.portal\"):60106,e=b?Symbol.for(\"react.fragment\"):60107,f=b?Symbol.for(\"react.strict_mode\"):60108,g=b?Symbol.for(\"react.profiler\"):60114,h=b?Symbol.for(\"react.provider\"):60109,k=b?Symbol.for(\"react.context\"):60110,l=b?Symbol.for(\"react.async_mode\"):60111,m=b?Symbol.for(\"react.concurrent_mode\"):60111,n=b?Symbol.for(\"react.forward_ref\"):60112,p=b?Symbol.for(\"react.suspense\"):60113,q=b?\n\tSymbol.for(\"react.suspense_list\"):60120,r=b?Symbol.for(\"react.memo\"):60115,t=b?Symbol.for(\"react.lazy\"):60116,v=b?Symbol.for(\"react.block\"):60121,w=b?Symbol.for(\"react.fundamental\"):60117,x=b?Symbol.for(\"react.responder\"):60118,y=b?Symbol.for(\"react.scope\"):60119;\n\tfunction z(a){if(\"object\"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}reactIs_production_min.AsyncMode=l;reactIs_production_min.ConcurrentMode=m;reactIs_production_min.ContextConsumer=k;reactIs_production_min.ContextProvider=h;reactIs_production_min.Element=c;reactIs_production_min.ForwardRef=n;reactIs_production_min.Fragment=e;reactIs_production_min.Lazy=t;reactIs_production_min.Memo=r;reactIs_production_min.Portal=d;\n\treactIs_production_min.Profiler=g;reactIs_production_min.StrictMode=f;reactIs_production_min.Suspense=p;reactIs_production_min.isAsyncMode=function(a){return A(a)||z(a)===l};reactIs_production_min.isConcurrentMode=A;reactIs_production_min.isContextConsumer=function(a){return z(a)===k};reactIs_production_min.isContextProvider=function(a){return z(a)===h};reactIs_production_min.isElement=function(a){return \"object\"===typeof a&&null!==a&&a.$$typeof===c};reactIs_production_min.isForwardRef=function(a){return z(a)===n};reactIs_production_min.isFragment=function(a){return z(a)===e};reactIs_production_min.isLazy=function(a){return z(a)===t};\n\treactIs_production_min.isMemo=function(a){return z(a)===r};reactIs_production_min.isPortal=function(a){return z(a)===d};reactIs_production_min.isProfiler=function(a){return z(a)===g};reactIs_production_min.isStrictMode=function(a){return z(a)===f};reactIs_production_min.isSuspense=function(a){return z(a)===p};\n\treactIs_production_min.isValidElementType=function(a){return \"string\"===typeof a||\"function\"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||\"object\"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};reactIs_production_min.typeOf=z;\n\treturn reactIs_production_min;\n}\n\nvar reactIs_development = {};\n\n/** @license React v16.13.1\n * react-is.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar hasRequiredReactIs_development;\n\nfunction requireReactIs_development () {\n\tif (hasRequiredReactIs_development) return reactIs_development;\n\thasRequiredReactIs_development = 1;\n\n\n\n\tif (process.env.NODE_ENV !== \"production\") {\n\t (function() {\n\n\t// The Symbol used to tag the ReactElement-like types. If there is no native Symbol\n\t// nor polyfill, then a plain number is used for performance.\n\tvar hasSymbol = typeof Symbol === 'function' && Symbol.for;\n\tvar REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;\n\tvar REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;\n\tvar REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;\n\tvar REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;\n\tvar REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;\n\tvar REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;\n\tvar REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary\n\t// (unstable) APIs that have been removed. Can we remove the symbols?\n\n\tvar REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;\n\tvar REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;\n\tvar REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;\n\tvar REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;\n\tvar REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;\n\tvar REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;\n\tvar REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;\n\tvar REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;\n\tvar REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;\n\tvar REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;\n\tvar REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;\n\n\tfunction isValidElementType(type) {\n\t return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.\n\t type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);\n\t}\n\n\tfunction typeOf(object) {\n\t if (typeof object === 'object' && object !== null) {\n\t var $$typeof = object.$$typeof;\n\n\t switch ($$typeof) {\n\t case REACT_ELEMENT_TYPE:\n\t var type = object.type;\n\n\t switch (type) {\n\t case REACT_ASYNC_MODE_TYPE:\n\t case REACT_CONCURRENT_MODE_TYPE:\n\t case REACT_FRAGMENT_TYPE:\n\t case REACT_PROFILER_TYPE:\n\t case REACT_STRICT_MODE_TYPE:\n\t case REACT_SUSPENSE_TYPE:\n\t return type;\n\n\t default:\n\t var $$typeofType = type && type.$$typeof;\n\n\t switch ($$typeofType) {\n\t case REACT_CONTEXT_TYPE:\n\t case REACT_FORWARD_REF_TYPE:\n\t case REACT_LAZY_TYPE:\n\t case REACT_MEMO_TYPE:\n\t case REACT_PROVIDER_TYPE:\n\t return $$typeofType;\n\n\t default:\n\t return $$typeof;\n\t }\n\n\t }\n\n\t case REACT_PORTAL_TYPE:\n\t return $$typeof;\n\t }\n\t }\n\n\t return undefined;\n\t} // AsyncMode is deprecated along with isAsyncMode\n\n\tvar AsyncMode = REACT_ASYNC_MODE_TYPE;\n\tvar ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;\n\tvar ContextConsumer = REACT_CONTEXT_TYPE;\n\tvar ContextProvider = REACT_PROVIDER_TYPE;\n\tvar Element = REACT_ELEMENT_TYPE;\n\tvar ForwardRef = REACT_FORWARD_REF_TYPE;\n\tvar Fragment = REACT_FRAGMENT_TYPE;\n\tvar Lazy = REACT_LAZY_TYPE;\n\tvar Memo = REACT_MEMO_TYPE;\n\tvar Portal = REACT_PORTAL_TYPE;\n\tvar Profiler = REACT_PROFILER_TYPE;\n\tvar StrictMode = REACT_STRICT_MODE_TYPE;\n\tvar Suspense = REACT_SUSPENSE_TYPE;\n\tvar hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated\n\n\tfunction isAsyncMode(object) {\n\t {\n\t if (!hasWarnedAboutDeprecatedIsAsyncMode) {\n\t hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint\n\n\t console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');\n\t }\n\t }\n\n\t return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;\n\t}\n\tfunction isConcurrentMode(object) {\n\t return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;\n\t}\n\tfunction isContextConsumer(object) {\n\t return typeOf(object) === REACT_CONTEXT_TYPE;\n\t}\n\tfunction isContextProvider(object) {\n\t return typeOf(object) === REACT_PROVIDER_TYPE;\n\t}\n\tfunction isElement(object) {\n\t return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;\n\t}\n\tfunction isForwardRef(object) {\n\t return typeOf(object) === REACT_FORWARD_REF_TYPE;\n\t}\n\tfunction isFragment(object) {\n\t return typeOf(object) === REACT_FRAGMENT_TYPE;\n\t}\n\tfunction isLazy(object) {\n\t return typeOf(object) === REACT_LAZY_TYPE;\n\t}\n\tfunction isMemo(object) {\n\t return typeOf(object) === REACT_MEMO_TYPE;\n\t}\n\tfunction isPortal(object) {\n\t return typeOf(object) === REACT_PORTAL_TYPE;\n\t}\n\tfunction isProfiler(object) {\n\t return typeOf(object) === REACT_PROFILER_TYPE;\n\t}\n\tfunction isStrictMode(object) {\n\t return typeOf(object) === REACT_STRICT_MODE_TYPE;\n\t}\n\tfunction isSuspense(object) {\n\t return typeOf(object) === REACT_SUSPENSE_TYPE;\n\t}\n\n\treactIs_development.AsyncMode = AsyncMode;\n\treactIs_development.ConcurrentMode = ConcurrentMode;\n\treactIs_development.ContextConsumer = ContextConsumer;\n\treactIs_development.ContextProvider = ContextProvider;\n\treactIs_development.Element = Element;\n\treactIs_development.ForwardRef = ForwardRef;\n\treactIs_development.Fragment = Fragment;\n\treactIs_development.Lazy = Lazy;\n\treactIs_development.Memo = Memo;\n\treactIs_development.Portal = Portal;\n\treactIs_development.Profiler = Profiler;\n\treactIs_development.StrictMode = StrictMode;\n\treactIs_development.Suspense = Suspense;\n\treactIs_development.isAsyncMode = isAsyncMode;\n\treactIs_development.isConcurrentMode = isConcurrentMode;\n\treactIs_development.isContextConsumer = isContextConsumer;\n\treactIs_development.isContextProvider = isContextProvider;\n\treactIs_development.isElement = isElement;\n\treactIs_development.isForwardRef = isForwardRef;\n\treactIs_development.isFragment = isFragment;\n\treactIs_development.isLazy = isLazy;\n\treactIs_development.isMemo = isMemo;\n\treactIs_development.isPortal = isPortal;\n\treactIs_development.isProfiler = isProfiler;\n\treactIs_development.isStrictMode = isStrictMode;\n\treactIs_development.isSuspense = isSuspense;\n\treactIs_development.isValidElementType = isValidElementType;\n\treactIs_development.typeOf = typeOf;\n\t })();\n\t}\n\treturn reactIs_development;\n}\n\nif (process.env.NODE_ENV === 'production') {\n reactIs$1.exports = requireReactIs_production_min();\n} else {\n reactIs$1.exports = requireReactIs_development();\n}\n\nvar reactIsExports = reactIs$1.exports;\n\nvar reactIs = reactIsExports;\n\n/**\n * Copyright 2015, Yahoo! Inc.\n * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.\n */\nvar REACT_STATICS = {\n childContextTypes: true,\n contextType: true,\n contextTypes: true,\n defaultProps: true,\n displayName: true,\n getDefaultProps: true,\n getDerivedStateFromError: true,\n getDerivedStateFromProps: true,\n mixins: true,\n propTypes: true,\n type: true\n};\nvar KNOWN_STATICS = {\n name: true,\n length: true,\n prototype: true,\n caller: true,\n callee: true,\n arguments: true,\n arity: true\n};\nvar FORWARD_REF_STATICS = {\n '$$typeof': true,\n render: true,\n defaultProps: true,\n displayName: true,\n propTypes: true\n};\nvar MEMO_STATICS = {\n '$$typeof': true,\n compare: true,\n defaultProps: true,\n displayName: true,\n propTypes: true,\n type: true\n};\nvar TYPE_STATICS = {};\nTYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;\nTYPE_STATICS[reactIs.Memo] = MEMO_STATICS;\n\nfunction getStatics(component) {\n // React v16.11 and below\n if (reactIs.isMemo(component)) {\n return MEMO_STATICS;\n } // React v16.12 and above\n\n\n return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;\n}\n\nvar defineProperty = Object.defineProperty;\nvar getOwnPropertyNames = Object.getOwnPropertyNames;\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nvar getPrototypeOf = Object.getPrototypeOf;\nvar objectPrototype = Object.prototype;\nfunction hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {\n if (typeof sourceComponent !== 'string') {\n // don't hoist over string (html) components\n if (objectPrototype) {\n var inheritedComponent = getPrototypeOf(sourceComponent);\n\n if (inheritedComponent && inheritedComponent !== objectPrototype) {\n hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);\n }\n }\n\n var keys = getOwnPropertyNames(sourceComponent);\n\n if (getOwnPropertySymbols) {\n keys = keys.concat(getOwnPropertySymbols(sourceComponent));\n }\n\n var targetStatics = getStatics(targetComponent);\n var sourceStatics = getStatics(sourceComponent);\n\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n\n if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {\n var descriptor = getOwnPropertyDescriptor(sourceComponent, key);\n\n try {\n // Avoid failures from read-only properties\n defineProperty(targetComponent, key, descriptor);\n } catch (e) {}\n }\n }\n }\n\n return targetComponent;\n}\n\nvar hoistNonReactStatics_cjs = hoistNonReactStatics;\n\nvar hoistStatics = /*@__PURE__*/getDefaultExportFromCjs(hoistNonReactStatics_cjs);\n\nfunction withCookies(WrappedComponent) {\n // @ts-ignore\n const name = WrappedComponent.displayName || WrappedComponent.name;\n class CookieWrapper extends React.Component {\n constructor() {\n super(...arguments);\n this.onChange = () => {\n // Make sure to update children with new values\n this.forceUpdate();\n };\n }\n listen() {\n this.props.cookies.addChangeListener(this.onChange);\n }\n unlisten(cookies) {\n (cookies || this.props.cookies).removeChangeListener(this.onChange);\n }\n componentDidMount() {\n this.listen();\n }\n componentDidUpdate(prevProps) {\n if (prevProps.cookies !== this.props.cookies) {\n this.unlisten(prevProps.cookies);\n this.listen();\n }\n }\n componentWillUnmount() {\n this.unlisten();\n }\n render() {\n const _a = this.props, { forwardedRef, cookies } = _a, restProps = __rest(_a, [\"forwardedRef\", \"cookies\"]);\n const allCookies = cookies.getAll({ doNotUpdate: true });\n return (React.createElement(WrappedComponent, Object.assign({}, restProps, { ref: forwardedRef, cookies: cookies, allCookies: allCookies })));\n }\n }\n CookieWrapper.displayName = `withCookies(${name})`;\n CookieWrapper.WrappedComponent = WrappedComponent;\n const ForwardedComponent = React.forwardRef((props, ref) => {\n return (React.createElement(Consumer, null, (cookies) => (React.createElement(CookieWrapper, Object.assign({ cookies: cookies }, props, { forwardedRef: ref })))));\n });\n ForwardedComponent.displayName = CookieWrapper.displayName;\n ForwardedComponent.WrappedComponent = CookieWrapper.WrappedComponent;\n return hoistStatics(ForwardedComponent, WrappedComponent);\n}\n\nfunction isInBrowser() {\n return (typeof window !== 'undefined' &&\n typeof window.document !== 'undefined' &&\n typeof window.document.createElement !== 'undefined');\n}\n\nfunction useCookies(dependencies, options) {\n const cookies = useContext(CookiesContext);\n if (!cookies) {\n throw new Error('Missing ');\n }\n const defaultOptions = { doNotUpdate: true };\n const getOptions = Object.assign(Object.assign({}, defaultOptions), options);\n const [allCookies, setCookies] = useState(() => cookies.getAll(getOptions));\n if (isInBrowser()) {\n useLayoutEffect(() => {\n function onChange() {\n const newCookies = cookies.getAll(getOptions);\n if (shouldUpdate(dependencies || null, newCookies, allCookies)) {\n setCookies(newCookies);\n }\n }\n cookies.addChangeListener(onChange);\n return () => {\n cookies.removeChangeListener(onChange);\n };\n }, [cookies, allCookies]);\n }\n const setCookie = useMemo(() => cookies.set.bind(cookies), [cookies]);\n const removeCookie = useMemo(() => cookies.remove.bind(cookies), [cookies]);\n const updateCookies = useMemo(() => cookies.update.bind(cookies), [cookies]);\n return [allCookies, setCookie, removeCookie, updateCookies];\n}\nfunction shouldUpdate(dependencies, newCookies, oldCookies) {\n if (!dependencies) {\n return true;\n }\n for (let dependency of dependencies) {\n if (newCookies[dependency] !== oldCookies[dependency]) {\n return true;\n }\n }\n return false;\n}\n\nexport { CookiesProvider, useCookies, withCookies };\n","function styleInject(css, ref) {\n if ( ref === void 0 ) ref = {};\n var insertAt = ref.insertAt;\n\n if (!css || typeof document === 'undefined') { return; }\n\n var head = document.head || document.getElementsByTagName('head')[0];\n var style = document.createElement('style');\n style.type = 'text/css';\n\n if (insertAt === 'top') {\n if (head.firstChild) {\n head.insertBefore(style, head.firstChild);\n } else {\n head.appendChild(style);\n }\n } else {\n head.appendChild(style);\n }\n\n if (style.styleSheet) {\n style.styleSheet.cssText = css;\n } else {\n style.appendChild(document.createTextNode(css));\n }\n}\n\nexport default styleInject;\n","// inspired by: https://gist.github.com/ncou/3a0a1f89c8e22416d0d607f621a948a9\n\nexport default class Timer {\n constructor(private readonly callback, private readonly delay) {}\n\n private timerId;\n private start;\n private remaining = this.delay;\n\n resume() {\n this.start = new Date().getTime();\n\n this.clear();\n\n this.timerId = setTimeout(this.callback, this.remaining);\n\n return this;\n }\n\n pause() {\n this.clear();\n\n this.remaining -= new Date().getTime() - this.start;\n\n return this;\n }\n\n clear() {\n if (this.timerId) {\n clearTimeout(this.timerId);\n }\n\n return this;\n }\n}\n","import * as React from 'react';\nimport {\n createContext,\n useContext,\n cloneElement,\n useReducer,\n useState,\n useEffect,\n useMemo,\n} from 'react';\nimport './index.css';\nimport Timer from './Timer';\n\nconst NotifierContext = createContext({\n notify: (children, overrideConfig = {}) => {},\n dismissAll: () => {},\n});\n\nconst ADD = 'add';\nconst DISMISS = 'dismiss';\nconst DISMISS_ALL = 'dismiss_all';\n\nlet id = 1;\n\nexport const positions = {\n TOP: 'top',\n TOP_RIGHT: 'topRight',\n TOP_LEFT: 'topLeft',\n BOTTOM_RIGHT: 'bottomRight',\n BOTTOM_LEFT: 'bottomLeft',\n BOTTOM: 'bottom',\n};\n\nconst initialState = {\n [positions.TOP]: [],\n [positions.TOP_RIGHT]: [],\n [positions.TOP_LEFT]: [],\n [positions.BOTTOM_RIGHT]: [],\n [positions.BOTTOM_LEFT]: [],\n [positions.BOTTOM]: [],\n};\n\nfunction reducer(state, action) {\n switch (action.type) {\n case ADD:\n return {\n ...state,\n [action.notification.position]: [\n ...state[action.notification.position],\n action.notification,\n ],\n };\n case DISMISS:\n // we extract the position from the `id`\n const [position] = action.notification.id.split('-');\n return {\n ...state,\n [position]: state[position].filter(\n ({ id }) => id !== action.notification.id,\n ),\n };\n case DISMISS_ALL:\n return { ...initialState };\n default:\n return state;\n }\n}\n\nfunction useNotifications(defaultConfig) {\n const [notifications, dispatch] = useReducer(reducer, initialState);\n\n const notify = (children, overrideConfig = {}) => {\n const config = { ...defaultConfig, ...overrideConfig };\n\n const newId = id++;\n\n dispatch({\n type: ADD,\n notification: {\n // `id` is compose of the position and a unique number\n // so a first notification created on the top position will have the `id` = \"top-1\"\n // then the second one on the bottom right will be `bottomRight-2`\n // this system allow us to understand in which array is the notification using only the `id`\n // check `DISMISS` action in the reducer\n id: `${config.position}-${newId}`,\n children,\n position: config.position,\n duration: config.duration,\n },\n });\n };\n\n const dismiss = id => {\n dispatch({ type: DISMISS, notification: { id } });\n };\n\n const dismissAll = () => {\n dispatch({ type: DISMISS_ALL });\n };\n\n return { notifications, notify, dismiss, dismissAll };\n}\n\nconst defaultConfig = {\n max: null,\n duration: 5000,\n position: positions.BOTTOM_RIGHT,\n};\n\nfunction NotifierContextProvider({ children, config: overrideConfig = {} }) {\n const config = useMemo(() => ({ ...defaultConfig, ...overrideConfig }), [\n overrideConfig,\n ]);\n const { notifications, notify, dismiss, dismissAll } = useNotifications(\n config,\n );\n\n return (\n \n {children}\n\n \n {notifications => {\n return notifications.map(({ id, children, duration }) => (\n dismiss(id)}\n position={positions.TOP_LEFT}\n >\n {children}\n \n ));\n }}\n \n\n \n {notifications => {\n return notifications.map(({ id, children, duration }) => (\n dismiss(id)}\n position={positions.TOP_RIGHT}\n >\n {children}\n \n ));\n }}\n \n\n \n {notifications => {\n return notifications.map(({ id, children, duration }) => (\n dismiss(id)}\n >\n {children}\n \n ));\n }}\n \n\n \n {notifications => {\n return notifications.map(({ id, children, duration }) => (\n dismiss(id)}\n >\n {children}\n \n ));\n }}\n \n\n \n {notifications => {\n return notifications.map(({ id, children, duration }) => (\n dismiss(id)}\n position={positions.BOTTOM_LEFT}\n >\n {children}\n \n ));\n }}\n \n\n \n {notifications => {\n return notifications.map(({ id, children, duration }) => (\n dismiss(id)}\n position={positions.BOTTOM_RIGHT}\n >\n {children}\n \n ));\n }}\n \n \n );\n}\n\nfunction NotificationBag({ className, notifications, max = null, children }) {\n const displayedNotifications = useMemo(() => {\n return max\n ? notifications.slice(Math.max(notifications.length - max, 0))\n : notifications;\n }, [notifications, max]);\n\n return

;\n}\n\nconst animations = {\n [positions.TOP]: {\n enter: 'react-headless-notifier-animate-enter-top',\n exit: 'react-headless-notifier-animate-exit-top',\n },\n [positions.TOP_RIGHT]: {\n enter: 'react-headless-notifier-animate-enter-right',\n exit: 'react-headless-notifier-animate-exit-right',\n },\n [positions.TOP_LEFT]: {\n enter: 'react-headless-notifier-animate-enter-left',\n exit: 'react-headless-notifier-animate-exit-left',\n },\n [positions.BOTTOM]: {\n enter: 'react-headless-notifier-animate-enter-bottom',\n exit: 'react-headless-notifier-animate-exit-bottom',\n },\n [positions.BOTTOM_RIGHT]: {\n enter: 'react-headless-notifier-animate-enter-right',\n exit: 'react-headless-notifier-animate-exit-right',\n },\n [positions.BOTTOM_LEFT]: {\n enter: 'react-headless-notifier-animate-enter-left',\n exit: 'react-headless-notifier-animate-exit-left',\n },\n};\n\nfunction NotificationWrapper({\n children,\n duration,\n onDismiss: handleDismiss,\n position,\n}) {\n const [active, setActive] = useState(true);\n const timer = useMemo(() => new Timer(() => setActive(false), duration), [\n duration,\n ]);\n const [running, setRunning] = useState(true);\n\n useEffect(() => {\n return () => timer.clear();\n }, []);\n\n useEffect(() => {\n running ? timer.resume() : timer.pause();\n }, [running]);\n\n const { enter, exit } = useMemo(() => animations[position], [position]);\n\n return (\n setRunning(false)}\n onMouseLeave={() => setRunning(true)}\n className={`react-headless-notifier-mb-4 react-headless-notifier-transform-gpu react-headless-notifier-transition-all ${\n active ? enter : exit\n }`}\n onAnimationEnd={() => {\n if (!active) handleDismiss();\n }}\n >\n {cloneElement(children, { id, dismiss: () => setActive(false) })}\n \n );\n}\n\nfunction useNotifier() {\n return useContext(NotifierContext);\n}\n\nexport { NotifierContext, NotifierContextProvider, useNotifier };\n","////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: any;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n\n /**\n * The delta between this location and the former location in the history stack\n */\n delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. May be either a URL or the pieces of a\n * URL path.\n */\nexport type To = string | Partial;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n /**\n * The last action that modified the current location. This will always be\n * Action.Pop when a history instance is first created. This value is mutable.\n */\n readonly action: Action;\n\n /**\n * The current location. This value is mutable.\n */\n readonly location: Location;\n\n /**\n * Returns a valid href for the given `to` value that may be used as\n * the value of an attribute.\n *\n * @param to - The destination URL\n */\n createHref(to: To): string;\n\n /**\n * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 1 });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\nexport function warning(cond: any, message: string) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly {\n let location: Readonly = {\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\",\n ...(typeof to === \"string\" ? parsePath(to) : to),\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: (to && (to as Location).key) || key || createKey(),\n };\n return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial) {\n if (search && search !== \"?\")\n pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\")\n pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial {\n let parsedPath: Partial = {};\n\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n window?: Window;\n v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n createHref: (window: Window, to: To) => string,\n validateLocation: ((location: Location, to: To) => void) | null,\n options: UrlHistoryOptions = {}\n): UrlHistory {\n let { window = document.defaultView!, v5Compat = false } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 1 });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { warning, invariant, parsePath } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n deferred = \"deferred\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: any;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n type: ResultType.deferred;\n deferredData: DeferredData;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n status: number;\n location: string;\n revalidate: boolean;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n type: ResultType.error;\n error: any;\n headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n | SuccessResult\n | DeferredResult\n | RedirectResult\n | ErrorResult;\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase;\n\n/**\n * Users can specify either lowercase or uppercase form methods on
,\n * useSubmit(), , etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\";\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport interface Submission {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n}\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs {\n request: Request;\n params: Params;\n context?: any;\n}\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs extends DataFunctionArgs {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable | null;\n\n/**\n * Route loader function signature\n */\nexport interface LoaderFunction {\n (args: LoaderFunctionArgs): Promise | DataFunctionValue;\n}\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (args: ActionFunctionArgs): Promise | DataFunctionValue;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n formData?: Submission[\"formData\"];\n actionResult?: DataResult;\n defaultShouldRevalidate: boolean;\n }): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction {\n (): Promise>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n caseSensitive?: boolean;\n path?: string;\n id?: string;\n loader?: LoaderFunction;\n action?: ActionFunction;\n hasErrorBoundary?: boolean;\n shouldRevalidate?: ShouldRevalidateFunction;\n handle?: any;\n lazy?: LazyRouteFunction;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam | _PathParam\n : // find params after `:`\n Path extends `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\n : Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\ntype PathParam =\n // check if path is just a wildcard\n Path extends \"*\" | \"/*\"\n ? \"*\"\n : // look for wildcard at the end of the path\n Path extends `${infer Rest}/*`\n ? \"*\" | _PathParam\n : // look for params in the absence of wildcards\n _PathParam;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey =\n // if could not find path params, fallback to `string`\n [PathParam] extends [never] ? string : PathParam;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params = {\n readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The route object that was used to match.\n */\n route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n extends AgnosticRouteMatch {}\n\nfunction isIndexRoute(\n route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n routes: AgnosticRouteObject[],\n mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: number[] = [],\n manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, index];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(\n route.index !== true || !route.children,\n `Cannot specify children on an index route`\n );\n invariant(\n !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\n\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename = \"/\"\n): AgnosticRouteMatch[] | null {\n let location =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n let pathname = stripBasename(location.pathname || \"/\", basename);\n\n if (pathname == null) {\n return null;\n }\n\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n\n let matches = null;\n for (let i = 0; matches == null && i < branches.length; ++i) {\n matches = matchRouteBranch(\n branches[i],\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n safelyDecodeURI(pathname)\n );\n }\n\n return matches;\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explodes _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:\\w+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch,\n pathname: string\n): AgnosticRouteMatch[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch[] = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname =\n matchedPathname === \"/\"\n ? pathname\n : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath(\n { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n remainingPathname\n );\n\n if (!match) return null;\n\n Object.assign(matchedParams, match.params);\n\n let route = meta.route;\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(\n joinPaths([matchedPathname, match.pathnameBase])\n ),\n route,\n });\n\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n\n return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/utils/generate-path\n */\nexport function generatePath(\n originalPath: Path,\n params: {\n [key in PathParam]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam;\n const starParam = params[star];\n\n // Apply the splat\n return starParam;\n }\n\n const keyMatch = segment.match(/^:(\\w+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam];\n\n if (optional === \"?\") {\n return param == null ? \"\" : param;\n }\n\n if (param == null) {\n invariant(false, `Missing \":${key}\" param`);\n }\n\n return param;\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern {\n /**\n * A string to match against a URL pathname. May contain `:id`-style segments\n * to indicate placeholders for dynamic parameters. May also end with `/*` to\n * indicate matching the rest of the URL pathname.\n */\n path: Path;\n /**\n * Should be `true` if the static portions of the `path` should be matched in\n * the same case.\n */\n caseSensitive?: boolean;\n /**\n * Should be `true` if this pattern should match the entire URL pathname.\n */\n end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The pattern that was used to match.\n */\n pattern: PathPattern;\n}\n\ntype Mutable = {\n -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey,\n Path extends string\n>(\n pattern: PathPattern | Path,\n pathname: string\n): PathMatch | null {\n if (typeof pattern === \"string\") {\n pattern = { path: pattern, caseSensitive: false, end: true };\n }\n\n let [matcher, paramNames] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = paramNames.reduce>(\n (memo, paramName, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n memo[paramName] = safelyDecodeURIComponent(\n captureGroups[index] || \"\",\n paramName\n );\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, string[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let paramNames: string[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^$?{}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(/\\/:(\\w+)/g, (_: string, paramName: string) => {\n paramNames.push(paramName);\n return \"/([^\\\\/]+)\";\n });\n\n if (path.endsWith(\"*\")) {\n paramNames.push(\"*\");\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, paramNames];\n}\n\nfunction safelyDecodeURI(value: string) {\n try {\n return decodeURI(value);\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\n}\n\nfunction safelyDecodeURIComponent(value: string, paramName: string) {\n try {\n return decodeURIComponent(value);\n } catch (error) {\n warning(\n false,\n `The value for the URL param \"${paramName}\" will not be decoded because` +\n ` the string \"${value}\" is a malformed URL segment. This is probably` +\n ` due to a bad percent encoding (${error}).`\n );\n\n return value;\n }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n pathname: string,\n basename: string\n): string | null {\n if (basename === \"/\") return pathname;\n\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\")\n ? basename.length - 1\n : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n\n return pathname.slice(startIndex) || \"/\";\n}\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\",\n } = typeof to === \"string\" ? parsePath(to) : to;\n\n let pathname = toPathname\n ? toPathname.startsWith(\"/\")\n ? toPathname\n : resolvePathname(toPathname, fromPathname)\n : fromPathname;\n\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash),\n };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n\n relativeSegments.forEach((segment) => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n char: string,\n field: string,\n dest: string,\n path: Partial\n) {\n return (\n `Cannot include a '${char}' character in a manually specified ` +\n `\\`to.${field}\\` field [${JSON.stringify(\n path\n )}]. Please separate it out to the ` +\n `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n `a string in and the router will parse it for you.`\n );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\n );\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = { ...toArg };\n\n invariant(\n !to.pathname || !to.pathname.includes(\"?\"),\n getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n );\n invariant(\n !to.pathname || !to.pathname.includes(\"#\"),\n getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n );\n invariant(\n !to.search || !to.search.includes(\"#\"),\n getInvalidPathError(\"#\", \"search\", \"hash\", to)\n );\n }\n\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n let from: string;\n\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (isPathRelative || toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n if (toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n // Each leading .. segment means \"go up one route\" instead of \"go up one\n // URL segment\". This is a key difference from how works and a\n // major reason we call this a \"to\" value instead of a \"href\".\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n // If there are more \"..\" segments than parent routes, resolve relative to\n // the root / URL.\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\n}\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n !search || search === \"?\"\n ? \"\"\n : search.startsWith(\"?\")\n ? search\n : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = (\n data: Data,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n\n return new Response(JSON.stringify(data), {\n ...responseInit,\n headers,\n });\n};\n\nexport interface TrackedPromise extends Promise {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeysSet: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, null, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n if (error) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record,\n init?: number | ResponseInit\n) => DeferredData;\n\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n */\nexport class ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n error?: Error;\n internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n","import arrayWithHoles from \"./arrayWithHoles.js\";\nimport iterableToArray from \"./iterableToArray.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableRest from \"./nonIterableRest.js\";\nexport default function _toArray(arr) {\n return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest();\n}","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n DataResult,\n DeferredData,\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n DeferredResult,\n ErrorResult,\n FormEncType,\n FormMethod,\n DetectErrorBoundaryFunction,\n RedirectResult,\n RouteData,\n AgnosticRouteObject,\n Submission,\n SuccessResult,\n AgnosticRouteMatch,\n ShouldRevalidateFunction,\n RouteManifest,\n ImmutableRouteKey,\n ActionFunction,\n LoaderFunction,\n V7_MutationFormMethod,\n V7_FormMethod,\n HTMLFormMethod,\n MutationFormMethod,\n MapRoutePropertiesFunction,\n} from \"./utils\";\nimport {\n ErrorResponse,\n ResultType,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n resolveTo,\n stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): Promise;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To | null, opts?: RouterNavigateOptions): Promise;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterNavigateOptions\n ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(key?: string): Fetcher;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete the fetcher for a given key\n * @param key\n */\n deleteFetcher(key?: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map;\n}\n\n/**\n * State maintained internally by the router. During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n /**\n * The action of the most recent navigation\n */\n historyAction: HistoryAction;\n\n /**\n * The current location reflected by the router\n */\n location: Location;\n\n /**\n * The current set of route matches\n */\n matches: AgnosticDataRouteMatch[];\n\n /**\n * Tracks whether we've completed our initial data load\n */\n initialized: boolean;\n\n /**\n * Current scroll position we should start at for a new view\n * - number -> scroll position to restore to\n * - false -> do not restore scroll at all (used during submissions)\n * - null -> don't have a saved position, scroll to hash or top of page\n */\n restoreScrollPosition: number | false | null;\n\n /**\n * Indicate whether this navigation should skip resetting the scroll position\n * if we are unable to restore the scroll position\n */\n preventScrollReset: boolean;\n\n /**\n * Tracks the state of the current navigation\n */\n navigation: Navigation;\n\n /**\n * Tracks any in-progress revalidations\n */\n revalidation: RevalidationState;\n\n /**\n * Data from the loaders for the current matches\n */\n loaderData: RouteData;\n\n /**\n * Data from the action for the current matches\n */\n actionData: RouteData | null;\n\n /**\n * Errors caught from loaders for the current matches\n */\n errors: RouteData | null;\n\n /**\n * Map of current fetchers\n */\n fetchers: Map;\n\n /**\n * Map of current blockers\n */\n blockers: Map;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_normalizeFormMethod: boolean;\n v7_prependBasename: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n hydrationData?: HydrationState;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record;\n actionHeaders: Record;\n activeDeferreds: Record | null;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(\n request: Request,\n opts?: { requestContext?: unknown }\n ): Promise;\n queryRoute(\n request: Request,\n opts?: { routeId?: string; requestContext?: unknown }\n ): Promise;\n}\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (state: RouterState): void;\n}\n\ninterface UseMatchesMatch {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: unknown;\n handle: unknown;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UseMatchesMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\ntype BaseNavigateOptions = {\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n fromRouteId?: string;\n};\n\n/**\n * Options for a navigate() call for a Link navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a Form navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n formData: FormData;\n};\n\n/**\n * Options to pass to navigate() for either a Link or Form navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions =\n | Omit\n | Omit;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: FormMethod | V7_FormMethod | undefined;\n formAction: string | undefined;\n formEncType: FormEncType | undefined;\n formData: FormData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n data: TData | undefined;\n \" _hasFetcherDoneAnything \"?: boolean;\n };\n Loading: {\n state: \"loading\";\n formMethod: FormMethod | V7_FormMethod | undefined;\n formAction: string | undefined;\n formEncType: FormEncType | undefined;\n formData: FormData | undefined;\n data: TData | undefined;\n \" _hasFetcherDoneAnything \"?: boolean;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n data: TData | undefined;\n \" _hasFetcherDoneAnything \"?: boolean;\n };\n};\n\nexport type Fetcher =\n FetcherStates[keyof FetcherStates];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\ninterface HandleActionResult extends ShortCircuitable {\n /**\n * Error thrown from the current action, keyed by the route containing the\n * error boundary to render the error. To be committed to the state after\n * loaders have completed\n */\n pendingActionError?: RouteData;\n /**\n * Data returned from the current action, keyed by the route owning the action.\n * To be committed to the state after loaders have completed\n */\n pendingActionData?: RouteData;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n /**\n * loaderData returned from the current set of loaders\n */\n loaderData?: RouterState[\"loaderData\"];\n /**\n * errors thrown from the current set of loaders\n */\n errors?: RouterState[\"errors\"];\n}\n\n/**\n * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\n/**\n * Wrapper object to allow us to throw any response out from callLoaderOrAction\n * for queryRouter while preserving whether or not it was thrown or returned\n * from the loader/action\n */\ninterface QueryRouteResponse {\n type: ResultType.data | ResultType.error;\n response: Response;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\nconst validMutationMethods = new Set(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst isBrowser =\n typeof window !== \"undefined\" &&\n typeof window.document !== \"undefined\" &&\n typeof window.document.createElement !== \"undefined\";\nconst isServer = !isBrowser;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_normalizeFormMethod: false,\n v7_prependBasename: false,\n ...init.future,\n };\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record | null = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition: GetScrollPositionFunction | null = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialErrors: RouteData | null = null;\n\n if (initialMatches == null) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n let initialized =\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n !initialMatches.some((m) => m.route.lazy) &&\n // And we have to either have no loaders or have been provided hydrationData\n (!initialMatches.some((m) => m.route.loader) || init.hydrationData != null);\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n blockers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: HistoryAction = HistoryAction.Pop;\n\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let ignoreNextHistoryUpdate = false;\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n ignoreNextHistoryUpdate = true;\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked\n init.history.go(delta);\n },\n reset() {\n deleteBlocker(blockerKey!);\n updateState({ blockers: new Map(router.state.blockers) });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location);\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(newState: Partial): void {\n state = {\n ...state,\n ...newState,\n };\n subscribers.forEach((subscriber) => subscriber(state));\n }\n\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(\n location: Location,\n newState: Partial>\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n for (let [key] of blockerFunctions) {\n deleteBlocker(key);\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n\n updateState({\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers: new Map(state.blockers),\n });\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.Replace) {\n init.history.replace(location, location.state);\n }\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\n }\n\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(\n to: number | To | null,\n opts?: RouterNavigateOptions\n ): Promise {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n to,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n deleteBlocker(blockerKey!);\n updateState({ blockers: new Map(state.blockers) });\n },\n });\n return;\n }\n\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n { overrideNavigation: state.navigation }\n );\n }\n\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(\n historyAction: HistoryAction,\n location: Location,\n opts?: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponse;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n }\n ): Promise {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(routesToUse, location, basename);\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n completeNavigation(location, {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n });\n return;\n }\n\n // Short circuit if it's only a hash change and not a mutation submission\n // For example, on /page#hash and submit a which will\n // default to a navigation to /page\n if (\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches });\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let pendingActionData: RouteData | undefined;\n let pendingError: RouteData | undefined;\n\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingError = {\n [findNearestBoundary(matches).route.id]: opts.pendingError,\n };\n } else if (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\n // Call action if we received an action submission\n let actionOutput = await handleAction(\n request,\n location,\n opts.submission,\n matches,\n { replace: opts.replace }\n );\n\n if (actionOutput.shortCircuited) {\n return;\n }\n\n pendingActionData = actionOutput.pendingActionData;\n pendingError = actionOutput.pendingActionError;\n\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n ...opts.submission,\n };\n loadingNavigation = navigation;\n\n // Create a GET request for the loaders\n request = new Request(request.url, { signal: request.signal });\n }\n\n // Call loaders\n let { shortCircuited, loaderData, errors } = await handleLoaders(\n request,\n location,\n matches,\n loadingNavigation,\n opts && opts.submission,\n opts && opts.fetcherSubmission,\n opts && opts.replace,\n pendingActionData,\n pendingError\n );\n\n if (shortCircuited) {\n return;\n }\n\n // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches,\n ...(pendingActionData ? { actionData: pendingActionData } : {}),\n loaderData,\n errors,\n });\n }\n\n // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n async function handleAction(\n request: Request,\n location: Location,\n submission: Submission,\n matches: AgnosticDataRouteMatch[],\n opts?: { replace?: boolean }\n ): Promise {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n ...submission,\n };\n updateState({ navigation });\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n replace =\n result.location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(state, result, { submission, replace });\n return { shortCircuited: true };\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n // By default, all submissions are REPLACE navigations, but if the\n // action threw an error that'll be rendered in an errorElement, we fall\n // back to PUSH so that the user can use the back button to get back to\n // the pre-submission form location to try again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n // Send back an empty object we can use to clear out any prior actionData\n pendingActionData: {},\n pendingActionError: { [boundaryMatch.route.id]: result.error },\n };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n return {\n pendingActionData: { [actionMatch.route.id]: result.data },\n };\n }\n\n // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n async function handleLoaders(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n overrideNavigation?: Navigation,\n submission?: Submission,\n fetcherSubmission?: Submission,\n replace?: boolean,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n ): Promise {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation = overrideNavigation;\n if (!loadingNavigation) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n ...submission,\n };\n loadingNavigation = navigation;\n }\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission || fetcherSubmission\n ? submission || fetcherSubmission\n : loadingNavigation.formMethod &&\n loadingNavigation.formAction &&\n loadingNavigation.formData &&\n loadingNavigation.formEncType\n ? {\n formMethod: loadingNavigation.formMethod,\n formAction: loadingNavigation.formAction,\n formData: loadingNavigation.formData,\n formEncType: loadingNavigation.formEncType,\n }\n : undefined;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n fetchLoadMatches,\n routesToUse,\n basename,\n pendingActionData,\n pendingError\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n );\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(location, {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors: pendingError || null,\n ...(pendingActionData ? { actionData: pendingActionData } : {}),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n });\n return { shortCircuited: true };\n }\n\n // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n if (!isUninterruptedRevalidation) {\n revalidatingFetchers.forEach((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n data: fetcher && fetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n \" _hasFetcherDoneAnything \": true,\n };\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n let actionData = pendingActionData || state.actionData;\n updateState({\n navigation: loadingNavigation,\n ...(actionData\n ? Object.keys(actionData).length === 0\n ? { actionData: null }\n : { actionData }\n : {}),\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n });\n }\n\n pendingNavigationLoadId = ++incrementingLoadId;\n revalidatingFetchers.forEach((rf) => {\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(results);\n if (redirect) {\n await startRedirectNavigation(state, redirect, { replace });\n return { shortCircuited: true };\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n matchesToLoad,\n loaderResults,\n pendingError,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe((aborted) => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n function getFetcher(key: string): Fetcher {\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n if (fetchControllers.has(key)) abortFetcher(key);\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath })\n );\n return;\n }\n\n let { path, submission } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n true,\n normalizedPath,\n opts\n );\n let match = getTargetMatch(matches, path);\n\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(key, routeId, path, match, matches, submission);\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, { routeId, path });\n handleFetcherLoader(key, routeId, path, match, matches, submission);\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n requestMatches: AgnosticDataRouteMatch[],\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action && !match.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\n setFetcherError(key, routeId, error);\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n ...submission,\n data: existingFetcher && existingFetcher.data,\n \" _hasFetcherDoneAnything \": true,\n };\n state.fetchers.set(key, fetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n\n // Call the action for the fetcher\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n fetchControllers.set(key, abortController);\n\n let actionResult = await callLoaderOrAction(\n \"action\",\n fetchRequest,\n match,\n requestMatches,\n manifest,\n mapRouteProperties,\n basename\n );\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by ou our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n fetchRedirectIds.add(key);\n let loadingFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n ...submission,\n data: undefined,\n \" _hasFetcherDoneAnything \": true,\n };\n state.fetchers.set(key, loadingFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n\n return startRedirectNavigation(state, actionResult, {\n submission,\n isFetchActionRedirect: true,\n });\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(\n init.history,\n\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n data: actionResult.data,\n ...submission,\n \" _hasFetcherDoneAnything \": true,\n };\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n fetchLoadMatches,\n routesToUse,\n basename,\n { [match.route.id]: actionResult.data },\n undefined // No need to send through errors since we short circuit above\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n data: existingFetcher && existingFetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n \" _hasFetcherDoneAnything \": true,\n };\n state.fetchers.set(staleKey, revalidatingFetcher);\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect(results);\n if (redirect) {\n return startRedirectNavigation(state, redirect);\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n state.matches,\n matchesToLoad,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n let doneFetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: actionResult.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n \" _hasFetcherDoneAnything \": true,\n };\n state.fetchers.set(key, doneFetcher);\n\n let didAbortFetchLoads = abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n ...(didAbortFetchLoads ? { fetchers: new Map(state.fetchers) } : {}),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n // Put this fetcher into it's loading state\n let loadingFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n ...submission,\n data: existingFetcher && existingFetcher.data,\n \" _hasFetcherDoneAnything \": true,\n };\n state.fetchers.set(key, loadingFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n\n // Call the loader for this fetcher route match\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n fetchControllers.set(key, abortController);\n\n let result: DataResult = await callLoaderOrAction(\n \"loader\",\n fetchRequest,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename\n );\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\n\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(state, result);\n return;\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n state.fetchers.delete(key);\n // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch -\n // do we need to behave any differently with our non-redirect errors?\n // What if it was a non-redirect Response?\n updateState({\n fetchers: new Map(state.fetchers),\n errors: {\n [boundaryMatch.route.id]: result.error,\n },\n });\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n let doneFetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: result.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n \" _hasFetcherDoneAnything \": true,\n };\n state.fetchers.set(key, doneFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n state: RouterState,\n redirect: RedirectResult,\n {\n submission,\n replace,\n isFetchActionRedirect,\n }: {\n submission?: Submission;\n replace?: boolean;\n isFetchActionRedirect?: boolean;\n } = {}\n ) {\n if (redirect.revalidate) {\n isRevalidationRequired = true;\n }\n\n let redirectLocation = createLocation(\n state.location,\n redirect.location,\n // TODO: This can be removed once we get rid of useTransition in Remix v2\n {\n _isRedirect: true,\n ...(isFetchActionRedirect ? { _isFetchActionRedirect: true } : {}),\n }\n );\n invariant(\n redirectLocation,\n \"Expected a location on the redirect navigation\"\n );\n // Check if this an absolute external redirect that goes to a new origin\n if (\n ABSOLUTE_URL_REGEX.test(redirect.location) &&\n isBrowser &&\n typeof window?.location !== \"undefined\"\n ) {\n let url = init.history.createURL(redirect.location);\n let isDifferentBasename = stripBasename(url.pathname, basename) == null;\n\n if (window.location.origin !== url.origin || isDifferentBasename) {\n if (replace) {\n window.location.replace(redirect.location);\n } else {\n window.location.assign(redirect.location);\n }\n return;\n }\n }\n\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectHistoryAction =\n replace === true ? HistoryAction.Replace : HistoryAction.Push;\n\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let { formMethod, formAction, formEncType, formData } = state.navigation;\n if (!submission && formMethod && formAction && formData && formEncType) {\n submission = {\n formMethod,\n formAction,\n formEncType,\n formData,\n };\n }\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n if (\n redirectPreserveMethodStatusCodes.has(redirect.status) &&\n submission &&\n isMutationMethod(submission.formMethod)\n ) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: {\n ...submission,\n formAction: redirect.location,\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n } else if (isFetchActionRedirect) {\n // For a fetch action redirect, we kick off a new loading navigation\n // without the fetcher submission, but we send it along for shouldRevalidate\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation: {\n state: \"loading\",\n location: redirectLocation,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n },\n fetcherSubmission: submission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n } else {\n // Otherwise, we kick off a new loading navigation, preserving the\n // submission info for the duration of this navigation\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation: {\n state: \"loading\",\n location: redirectLocation,\n formMethod: submission ? submission.formMethod : undefined,\n formAction: submission ? submission.formAction : undefined,\n formEncType: submission ? submission.formEncType : undefined,\n formData: submission ? submission.formData : undefined,\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n }\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n // Call all navigation loaders and revalidating fetcher loaders in parallel,\n // then slice off the results into separate arrays so we can handle them\n // accordingly\n let results = await Promise.all([\n ...matchesToLoad.map((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename\n )\n ),\n ...fetchersToLoad.map((f) => {\n if (f.matches && f.match && f.controller) {\n return callLoaderOrAction(\n \"loader\",\n createClientSideRequest(init.history, f.path, f.controller.signal),\n f.match,\n f.matches,\n manifest,\n mapRouteProperties,\n basename\n );\n } else {\n let error: ErrorResult = {\n type: ResultType.error,\n error: getInternalRouterError(404, { pathname: f.path }),\n };\n return error;\n }\n }),\n ]);\n let loaderResults = results.slice(0, matchesToLoad.length);\n let fetcherResults = results.slice(matchesToLoad.length);\n\n await Promise.all([\n resolveDeferredResults(\n currentMatches,\n matchesToLoad,\n loaderResults,\n loaderResults.map(() => request.signal),\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map((f) => f.match),\n fetcherResults,\n fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)),\n true\n ),\n ]);\n\n return { results, loaderResults, fetcherResults };\n }\n\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true;\n\n // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.push(key);\n abortFetcher(key);\n }\n });\n }\n\n function setFetcherError(key: string, routeId: string, error: any) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState({\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n });\n }\n\n function deleteFetcher(key: string): void {\n if (fetchControllers.has(key)) abortFetcher(key);\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n state.fetchers.delete(key);\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n invariant(controller, `Expected fetch controller: ${key}`);\n controller.abort();\n fetchControllers.delete(key);\n }\n\n function markFetchersDone(keys: string[]) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: fetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n \" _hasFetcherDoneAnything \": true,\n };\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n state.blockers.set(key, newBlocker);\n updateState({ blockers: new Map(state.blockers) });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\n }\n\n function cancelActiveDeferreds(\n predicate?: (routeId: string) => boolean\n ): string[] {\n let cancelledRouteIds: string[] = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the component\n function enableScrollRestoration(\n positions: Record,\n getPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || ((location) => location.key);\n\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered \n // and therefore have no savedScrollPositions available\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({ restoreScrollPosition: y });\n }\n }\n\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n let userMatches = matches.map((m) =>\n createUseMatchesMatch(m, state.loaderData)\n );\n let key = getScrollRestorationKey(location, userMatches) || location.key;\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n let userMatches = matches.map((m) =>\n createUseMatchesMatch(m, state.loaderData)\n );\n let key = getScrollRestorationKey(location, userMatches) || location.key;\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n inFlightDataRoutes = newRoutes;\n }\n\n router = {\n get basename() {\n return basename;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher,\n dispose,\n getBlocker,\n deleteBlocker,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n */\n async function query(\n request: Request,\n { requestContext }: { requestContext?: unknown } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(request, location, matches, requestContext);\n if (isResponse(result)) {\n return result;\n }\n\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n }: { requestContext?: unknown; routeId?: string } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n match\n );\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch\n ): Promise | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction, we throw\n // it to bail out and then return or throw here based on whether the user\n // returned or threw\n if (isQueryRouteResponse(e)) {\n if (e.type === ResultType.error && !isRedirectResponse(e.response)) {\n throw e.response;\n }\n return e.response;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n isRouteRequest: boolean\n ): Promise | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n true,\n isRouteRequest,\n requestContext\n );\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted`);\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.status,\n headers: {\n Location: result.location,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n let context = await loadRouteData(\n request,\n matches,\n requestContext,\n undefined,\n {\n [boundaryMatch.route.id]: result.error,\n }\n );\n\n // action status codes take precedence over loader status codes\n return {\n ...context,\n statusCode: isRouteErrorResponse(result.error)\n ? result.error.status\n : 500,\n actionData: null,\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n let context = await loadRouteData(loaderRequest, matches, requestContext);\n\n return {\n ...context,\n // action status codes take precedence over loader status codes\n ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n actionData: {\n [actionMatch.route.id]: result.data,\n },\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n async function loadRouteData(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch,\n pendingActionError?: RouteData\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(pendingActionError || {})[0]\n );\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors: pendingActionError || null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let results = await Promise.all([\n ...matchesToLoad.map((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n true,\n isRouteRequest,\n requestContext\n )\n ),\n ]);\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted`);\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionError,\n activeDeferreds\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\n };\n }\n\n return {\n dataRoutes,\n query,\n queryRoute,\n };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n routes: AgnosticDataRouteObject[],\n context: StaticHandlerContext,\n error: any\n) {\n let newContext: StaticHandlerContext = {\n ...context,\n statusCode: 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error,\n },\n };\n return newContext;\n}\n\nfunction isSubmissionNavigation(\n opts: RouterNavigateOptions\n): opts is SubmissionNavigateOptions {\n return opts != null && \"formData\" in opts;\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n prependBasename: boolean,\n to: To | null,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId != null && relative !== \"path\") {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route. When using relative:path,\n // fromRouteId is ignored since that is always relative to the current\n // location path\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getPathContributingMatches(contextualMatches).map((m) => m.pathnameBase),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Add an ?index param for matched index routes if we don't already have one\n if (\n (to == null || to === \"\" || to === \".\") &&\n activeRouteMatch &&\n activeRouteMatch.route.index &&\n !hasNakedIndexQuery(path.search)\n ) {\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n normalizeFormMethod: boolean,\n isFetcher: boolean,\n path: string,\n opts?: RouterNavigateOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponse;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n // Create a Submission on non-GET navigations\n let submission: Submission | undefined;\n if (opts.formData) {\n let formMethod = opts.formMethod || \"get\";\n submission = {\n formMethod: normalizeFormMethod\n ? (formMethod.toUpperCase() as V7_FormMethod)\n : (formMethod.toLowerCase() as FormMethod),\n formAction: stripHashFromPath(path),\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData: opts.formData,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n let searchParams = convertFormDataToSearchParams(opts.formData);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n matches: AgnosticDataRouteMatch[],\n boundaryId?: string\n) {\n let boundaryMatches = matches;\n if (boundaryId) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n boundaryMatches = matches.slice(0, index);\n }\n }\n return boundaryMatches;\n}\n\nfunction getMatchesToLoad(\n history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n fetchLoadMatches: Map,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingError\n ? Object.values(pendingError)[0]\n : pendingActionData\n ? Object.values(pendingActionData)[0]\n : undefined;\n\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n\n let navigationMatches = boundaryMatches.filter((match, index) => {\n if (match.route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n if (match.route.loader == null) {\n return false;\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\n return true;\n }\n\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n defaultShouldRevalidate:\n // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n // Clicked the same link, resubmitted a GET form\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate if fetcher won't be present in the subsequent render\n if (!matches.some((m) => m.route.id === f.routeId)) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n if (cancelledFetcherLoads.includes(key)) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // hit a static href, so they _always_ check shouldRevalidate and the\n // default is strictly if a revalidation is explicitly required (action\n // submissions, useRevalidator, X-Remix-Revalidate).\n let shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n defaultShouldRevalidate: isRevalidationRequired,\n });\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: Parameters[0]\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n basename: string,\n isStaticRequest: boolean = false,\n isRouteRequest: boolean = false,\n requestContext?: unknown\n): Promise {\n let resultType;\n let result;\n let onReject: (() => void) | undefined;\n\n let runHandler = (handler: ActionFunction | LoaderFunction) => {\n // Setup a promise we can race against so that abort signals short circuit\n let reject: () => void;\n let abortPromise = new Promise((_, r) => (reject = r));\n onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n return Promise.race([\n handler({ request, params: match.params, context: requestContext }),\n abortPromise,\n ]);\n };\n\n try {\n let handler = match.route[type];\n\n if (match.route.lazy) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let values = await Promise.all([\n runHandler(handler),\n loadLazyRouteModule(match.route, mapRouteProperties, manifest),\n ]);\n result = values[0];\n } else {\n // Load lazy route module, then run any returned handler\n await loadLazyRouteModule(match.route, mapRouteProperties, manifest);\n\n handler = match.route[type];\n if (handler) {\n // Handler still run even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, data: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n\n invariant(\n result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n resultType = ResultType.error;\n result = e;\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n if (isResponse(result)) {\n let status = result.status;\n\n // Process redirects\n if (redirectStatusCodes.has(status)) {\n let location = result.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n // Support relative routing in internal redirects\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n location = normalizeTo(\n new URL(request.url),\n matches.slice(0, matches.indexOf(match) + 1),\n basename,\n true,\n location\n );\n } else if (!isStaticRequest) {\n // Strip off the protocol+origin for same-origin + same-basename absolute\n // redirects. If this is a static request, we can let it go back to the\n // browser as-is\n let currentUrl = new URL(request.url);\n let url = location.startsWith(\"//\")\n ? new URL(currentUrl.protocol + location)\n : new URL(location);\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n location = url.pathname + url.search + url.hash;\n }\n }\n\n // Don't process redirects in the router during static requests requests.\n // Instead, throw the Response and let the server handle it with an HTTP\n // redirect. We also update the Location header in place in this flow so\n // basename and relative routing is taken into account\n if (isStaticRequest) {\n result.headers.set(\"Location\", location);\n throw result;\n }\n\n return {\n type: ResultType.redirect,\n status,\n location,\n revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null,\n };\n }\n\n // For SSR single-route requests, we want to hand Responses back directly\n // without unwrapping. We do this with the QueryRouteResponse wrapper\n // interface so we can know whether it was returned or thrown\n if (isRouteRequest) {\n // eslint-disable-next-line no-throw-literal\n throw {\n type: resultType || ResultType.data,\n response: result,\n };\n }\n\n let data: any;\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n data = await result.json();\n } else {\n data = await result.text();\n }\n\n if (resultType === ResultType.error) {\n return {\n type: resultType,\n error: new ErrorResponse(status, result.statusText, data),\n headers: result.headers,\n };\n }\n\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n if (resultType === ResultType.error) {\n return { type: resultType, error: result };\n }\n\n if (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n return { type: ResultType.data, data: result };\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType, formData } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n init.body =\n formEncType === \"application/x-www-form-urlencoded\"\n ? convertFormDataToSearchParams(formData)\n : formData;\n }\n\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, value instanceof File ? value.name : value);\n }\n\n return searchParams;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record;\n} {\n // Fill in loaderData/errors from our loaders\n let loaderData: RouterState[\"loaderData\"] = {};\n let errors: RouterState[\"errors\"] | null = null;\n let statusCode: number | undefined;\n let foundError = false;\n let loaderHeaders: Record = {};\n\n // Process loader results into state.loaderData/state.errors\n results.forEach((result, index) => {\n let id = matchesToLoad[index].route.id;\n invariant(\n !isRedirectResult(result),\n \"Cannot handle redirect results in processLoaderData\"\n );\n if (isErrorResult(result)) {\n // Look upwards from the matched route for the closest ancestor\n // error boundary, defaulting to the root match\n let boundaryMatch = findNearestBoundary(matches, id);\n let error = result.error;\n // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n if (pendingError) {\n error = Object.values(pendingError)[0];\n pendingError = undefined;\n }\n\n errors = errors || {};\n\n // Prefer higher error values if lower errors bubble to the same boundary\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n } else {\n loaderData[id] = result.data;\n }\n\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (\n result.statusCode != null &&\n result.statusCode !== 200 &&\n !foundError\n ) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n });\n\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here. Also clear out any loaderData for the\n // throwing route\n if (pendingError) {\n errors = pendingError;\n loaderData[Object.keys(pendingError)[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: DataResult[],\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingError,\n activeDeferreds\n );\n\n // Process results from our revalidating fetchers\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let { key, match, controller } = revalidatingFetchers[index];\n invariant(\n fetcherResults !== undefined && fetcherResults[index] !== undefined,\n \"Did not find corresponding fetcher result\"\n );\n let result = fetcherResults[index];\n\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n continue;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: result.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n \" _hasFetcherDoneAnything \": true,\n };\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[],\n errors: RouteData | null | undefined\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route = routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\";\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponse(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(results: DataResult[]): RedirectResult | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return result;\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // No hash -> hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // current hash -> same hash\n return true;\n } else if (b.hash !== \"\") {\n // current hash -> new hash\n return true;\n }\n\n return false;\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\n}\n\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isQueryRouteResponse(obj: any): obj is QueryRouteResponse {\n return (\n obj &&\n isResponse(obj.response) &&\n (obj.type === ResultType.data || ResultType.error)\n );\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: (AgnosticDataRouteMatch | null)[],\n results: DataResult[],\n signals: (AbortSignal | null)[],\n isFetcher: boolean,\n currentLoaderData?: RouteData\n) {\n for (let index = 0; index < results.length; index++) {\n let result = results[index];\n let match = matchesToLoad[index];\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n let signal = signals[index];\n invariant(\n signal,\n \"Expected an AbortSignal for revalidating fetcher deferred result\"\n );\n await resolveDeferredData(result, signal, isFetcher).then((result) => {\n if (result) {\n results[index] = result || results[index];\n }\n });\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise {\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData,\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e,\n };\n }\n }\n\n return {\n type: ResultType.data,\n data: result.deferredData.data,\n };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\n// Note: This should match the format exported by useMatches, so if you change\n// this please also change that :) Eventually we'll DRY this up\nfunction createUseMatchesMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UseMatchesMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id] as unknown,\n handle: route.handle as unknown,\n };\n}\n\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n hasNakedIndexQuery(search || \"\")\n ) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n//#endregion\n","import * as React from \"react\";\nimport type {\n AgnosticRouteMatch,\n AgnosticIndexRouteObject,\n AgnosticNonIndexRouteObject,\n History,\n Location,\n RelativeRoutingType,\n Router,\n StaticHandlerContext,\n To,\n TrackedPromise,\n LazyRouteFunction,\n} from \"@remix-run/router\";\nimport type { Action as NavigationType } from \"@remix-run/router\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticIndexRouteObject[\"path\"];\n id?: AgnosticIndexRouteObject[\"id\"];\n loader?: AgnosticIndexRouteObject[\"loader\"];\n action?: AgnosticIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticIndexRouteObject[\"handle\"];\n index: true;\n children?: undefined;\n element?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction;\n}\n\nexport interface NonIndexRouteObject {\n caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticNonIndexRouteObject[\"path\"];\n id?: AgnosticNonIndexRouteObject[\"id\"];\n loader?: AgnosticNonIndexRouteObject[\"loader\"];\n action?: AgnosticNonIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticNonIndexRouteObject[\"handle\"];\n index?: false;\n children?: RouteObject[];\n element?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n children?: DataRouteObject[];\n id: string;\n};\n\nexport interface RouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch {}\n\nexport interface DataRouteMatch extends RouteMatch {}\n\nexport interface DataRouterContextObject extends NavigationContextObject {\n router: Router;\n staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n React.createContext(null);\nif (__DEV__) {\n DataRouterContext.displayName = \"DataRouter\";\n}\n\nexport const DataRouterStateContext = React.createContext<\n Router[\"state\"] | null\n>(null);\nif (__DEV__) {\n DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nexport const AwaitContext = React.createContext(null);\nif (__DEV__) {\n AwaitContext.displayName = \"Await\";\n}\n\nexport interface NavigateOptions {\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n createHref: History[\"createHref\"];\n // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n encodeLocation?: History[\"encodeLocation\"];\n go: History[\"go\"];\n push(to: To, state?: any, opts?: NavigateOptions): void;\n replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n basename: string;\n navigator: Navigator;\n static: boolean;\n}\n\nexport const NavigationContext = React.createContext(\n null!\n);\n\nif (__DEV__) {\n NavigationContext.displayName = \"Navigation\";\n}\n\ninterface LocationContextObject {\n location: Location;\n navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext(\n null!\n);\n\nif (__DEV__) {\n LocationContext.displayName = \"Location\";\n}\n\nexport interface RouteContextObject {\n outlet: React.ReactElement | null;\n matches: RouteMatch[];\n isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext({\n outlet: null,\n matches: [],\n isDataRoute: false,\n});\n\nif (__DEV__) {\n RouteContext.displayName = \"Route\";\n}\n\nexport const RouteErrorContext = React.createContext(null);\n\nif (__DEV__) {\n RouteErrorContext.displayName = \"RouteError\";\n}\n","import * as React from \"react\";\nimport type {\n Blocker,\n BlockerFunction,\n Location,\n ParamParseKey,\n Params,\n Path,\n PathMatch,\n PathPattern,\n RelativeRoutingType,\n Router as RemixRouter,\n RevalidationState,\n To,\n} from \"@remix-run/router\";\nimport {\n Action as NavigationType,\n UNSAFE_invariant as invariant,\n isRouteErrorResponse,\n joinPaths,\n matchPath,\n matchRoutes,\n parsePath,\n resolveTo,\n UNSAFE_getPathContributingMatches as getPathContributingMatches,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n NavigateOptions,\n RouteContextObject,\n RouteMatch,\n RouteObject,\n DataRouteMatch,\n} from \"./context\";\nimport {\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n RouteErrorContext,\n AwaitContext,\n} from \"./context\";\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/hooks/use-href\n */\nexport function useHref(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useHref() may be used only in the context of a component.`\n );\n\n let { basename, navigator } = React.useContext(NavigationContext);\n let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n let joinedPathname = pathname;\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the href. If this is a root navigation, then just use the raw\n // basename which allows the basename to have full control over the presence\n // of a trailing slash on root links\n if (basename !== \"/\") {\n joinedPathname =\n pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n }\n\n return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a .\n *\n * @see https://reactrouter.com/hooks/use-in-router-context\n */\nexport function useInRouterContext(): boolean {\n return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/hooks/use-location\n */\nexport function useLocation(): Location {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useLocation() may be used only in the context of a component.`\n );\n\n return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/hooks/use-navigation-type\n */\nexport function useNavigationType(): NavigationType {\n return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * .\n *\n * @see https://reactrouter.com/hooks/use-match\n */\nexport function useMatch<\n ParamKey extends ParamParseKey,\n Path extends string\n>(pattern: PathPattern | Path): PathMatch | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useMatch() may be used only in the context of a component.`\n );\n\n let { pathname } = useLocation();\n return React.useMemo(\n () => matchPath(pattern, pathname),\n [pathname, pattern]\n );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n (to: To, options?: NavigateOptions): void;\n (delta: number): void;\n}\n\nconst navigateEffectWarning =\n `You should call navigate() in a React.useEffect(), not when ` +\n `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n cb: Parameters[0]\n) {\n let isStatic = React.useContext(NavigationContext).static;\n if (!isStatic) {\n // We should be able to get rid of this once react 18.3 is released\n // See: https://github.com/facebook/react/pull/26395\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(cb);\n }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/hooks/use-navigate\n */\nexport function useNavigate(): NavigateFunction {\n let { isDataRoute } = React.useContext(RouteContext);\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useNavigate() may be used only in the context of a component.`\n );\n\n let { basename, navigator } = React.useContext(NavigationContext);\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n\n let routePathnamesJson = JSON.stringify(\n getPathContributingMatches(matches).map((match) => match.pathnameBase)\n );\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our history listener yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n navigator.go(to);\n return;\n }\n\n let path = resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n options.relative === \"path\"\n );\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to handing off to history. If this is a root navigation, then we\n // navigate to the raw basename which allows the basename to have full\n // control over the presence of a trailing slash on root links\n if (basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\"\n ? basename\n : joinPaths([basename, path.pathname]);\n }\n\n (!!options.replace ? navigator.replace : navigator.push)(\n path,\n options.state,\n options\n );\n },\n [basename, navigator, routePathnamesJson, locationPathname]\n );\n\n return navigate;\n}\n\nconst OutletContext = React.createContext(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/hooks/use-outlet-context\n */\nexport function useOutletContext(): Context {\n return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by to render child routes.\n *\n * @see https://reactrouter.com/hooks/use-outlet\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n let outlet = React.useContext(RouteContext).outlet;\n if (outlet) {\n return (\n {outlet}\n );\n }\n return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/hooks/use-params\n */\nexport function useParams<\n ParamsOrKey extends string | Record = string\n>(): Readonly<\n [ParamsOrKey] extends [string] ? Params : Partial\n> {\n let { matches } = React.useContext(RouteContext);\n let routeMatch = matches[matches.length - 1];\n return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/hooks/use-resolved-path\n */\nexport function useResolvedPath(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n\n let routePathnamesJson = JSON.stringify(\n getPathContributingMatches(matches).map((match) => match.pathnameBase)\n );\n\n return React.useMemo(\n () =>\n resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n relative === \"path\"\n ),\n [to, routePathnamesJson, locationPathname, relative]\n );\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an to render their child route's\n * element.\n *\n * @see https://reactrouter.com/hooks/use-routes\n */\nexport function useRoutes(\n routes: RouteObject[],\n locationArg?: Partial | string\n): React.ReactElement | null {\n return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nexport function useRoutesImpl(\n routes: RouteObject[],\n locationArg?: Partial | string,\n dataRouterState?: RemixRouter[\"state\"]\n): React.ReactElement | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useRoutes() may be used only in the context of a component.`\n );\n\n let { navigator } = React.useContext(NavigationContext);\n let { matches: parentMatches } = React.useContext(RouteContext);\n let routeMatch = parentMatches[parentMatches.length - 1];\n let parentParams = routeMatch ? routeMatch.params : {};\n let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n let parentRoute = routeMatch && routeMatch.route;\n\n if (__DEV__) {\n // You won't get a warning about 2 different under a \n // without a trailing *, but this is a best-effort warning anyway since we\n // cannot even give the warning unless they land at the parent route.\n //\n // Example:\n //\n // \n // {/* This route path MUST end with /* because otherwise\n // it will never match /blog/post/123 */}\n // } />\n // } />\n // \n //\n // function Blog() {\n // return (\n // \n // } />\n // \n // );\n // }\n let parentPath = (parentRoute && parentRoute.path) || \"\";\n warningOnce(\n parentPathname,\n !parentRoute || parentPath.endsWith(\"*\"),\n `You rendered descendant (or called \\`useRoutes()\\`) at ` +\n `\"${parentPathname}\" (under ) but the ` +\n `parent route path has no trailing \"*\". This means if you navigate ` +\n `deeper, the parent won't match anymore and therefore the child ` +\n `routes will never render.\\n\\n` +\n `Please change the parent to .`\n );\n }\n\n let locationFromContext = useLocation();\n\n let location;\n if (locationArg) {\n let parsedLocationArg =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n invariant(\n parentPathnameBase === \"/\" ||\n parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n `When overriding the location using \\`\\` or \\`useRoutes(routes, location)\\`, ` +\n `the location pathname must begin with the portion of the URL pathname that was ` +\n `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n );\n\n location = parsedLocationArg;\n } else {\n location = locationFromContext;\n }\n\n let pathname = location.pathname || \"/\";\n let remainingPathname =\n parentPathnameBase === \"/\"\n ? pathname\n : pathname.slice(parentPathnameBase.length) || \"/\";\n\n let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n if (__DEV__) {\n warning(\n parentRoute || matches != null,\n `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n );\n\n warning(\n matches == null ||\n matches[matches.length - 1].route.element !== undefined ||\n matches[matches.length - 1].route.Component !== undefined,\n `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n `does not have an element or Component. This means it will render an with a ` +\n `null value by default resulting in an \"empty\" page.`\n );\n }\n\n let renderedMatches = _renderMatches(\n matches &&\n matches.map((match) =>\n Object.assign({}, match, {\n params: Object.assign({}, parentParams, match.params),\n pathname: joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathname).pathname\n : match.pathname,\n ]),\n pathnameBase:\n match.pathnameBase === \"/\"\n ? parentPathnameBase\n : joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathnameBase).pathname\n : match.pathnameBase,\n ]),\n })\n ),\n parentMatches,\n dataRouterState\n );\n\n // When a user passes in a `locationArg`, the associated routes need to\n // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n // to use the scoped location instead of the global location.\n if (locationArg && renderedMatches) {\n return (\n \n {renderedMatches}\n \n );\n }\n\n return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n let error = useRouteError();\n let message = isRouteErrorResponse(error)\n ? `${error.status} ${error.statusText}`\n : error instanceof Error\n ? error.message\n : JSON.stringify(error);\n let stack = error instanceof Error ? error.stack : null;\n let lightgrey = \"rgba(200,200,200, 0.5)\";\n let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n let devInfo = null;\n if (__DEV__) {\n console.error(\n \"Error handled by React Router default ErrorBoundary:\",\n error\n );\n\n devInfo = (\n <>\n

💿 Hey developer 👋

\n

\n You can provide a way better UX than this when your app throws errors\n by providing your own ErrorBoundary or{\" \"}\n errorElement prop on your route.\n

\n \n );\n }\n\n return (\n <>\n

Unexpected Application Error!

\n

{message}

\n {stack ?
{stack}
: null}\n {devInfo}\n \n );\n}\n\nconst defaultErrorElement = ;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n location: Location;\n revalidation: RevalidationState;\n error: any;\n component: React.ReactNode;\n routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n location: Location;\n revalidation: RevalidationState;\n error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n RenderErrorBoundaryProps,\n RenderErrorBoundaryState\n> {\n constructor(props: RenderErrorBoundaryProps) {\n super(props);\n this.state = {\n location: props.location,\n revalidation: props.revalidation,\n error: props.error,\n };\n }\n\n static getDerivedStateFromError(error: any) {\n return { error: error };\n }\n\n static getDerivedStateFromProps(\n props: RenderErrorBoundaryProps,\n state: RenderErrorBoundaryState\n ) {\n // When we get into an error state, the user will likely click \"back\" to the\n // previous page that didn't have an error. Because this wraps the entire\n // application, that will have no effect--the error page continues to display.\n // This gives us a mechanism to recover from the error when the location changes.\n //\n // Whether we're in an error state or not, we update the location in state\n // so that when we are in an error state, it gets reset when a new location\n // comes in and the user recovers from the error.\n if (\n state.location !== props.location ||\n (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n ) {\n return {\n error: props.error,\n location: props.location,\n revalidation: props.revalidation,\n };\n }\n\n // If we're not changing locations, preserve the location but still surface\n // any new errors that may come through. We retain the existing error, we do\n // this because the error provided from the app state may be cleared without\n // the location changing.\n return {\n error: props.error || state.error,\n location: state.location,\n revalidation: props.revalidation || state.revalidation,\n };\n }\n\n componentDidCatch(error: any, errorInfo: any) {\n console.error(\n \"React Router caught the following error during render\",\n error,\n errorInfo\n );\n }\n\n render() {\n return this.state.error ? (\n \n \n \n ) : (\n this.props.children\n );\n }\n}\n\ninterface RenderedRouteProps {\n routeContext: RouteContextObject;\n match: RouteMatch;\n children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n let dataRouterContext = React.useContext(DataRouterContext);\n\n // Track how deep we got in our render pass to emulate SSR componentDidCatch\n // in a DataStaticRouter\n if (\n dataRouterContext &&\n dataRouterContext.static &&\n dataRouterContext.staticContext &&\n (match.route.errorElement || match.route.ErrorBoundary)\n ) {\n dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n }\n\n return (\n \n {children}\n \n );\n}\n\nexport function _renderMatches(\n matches: RouteMatch[] | null,\n parentMatches: RouteMatch[] = [],\n dataRouterState: RemixRouter[\"state\"] | null = null\n): React.ReactElement | null {\n if (matches == null) {\n if (dataRouterState?.errors) {\n // Don't bail if we have data router errors so we can render them in the\n // boundary. Use the pre-matched (or shimmed) matches\n matches = dataRouterState.matches as DataRouteMatch[];\n } else {\n return null;\n }\n }\n\n let renderedMatches = matches;\n\n // If we have data errors, trim matches to the highest error boundary\n let errors = dataRouterState?.errors;\n if (errors != null) {\n let errorIndex = renderedMatches.findIndex(\n (m) => m.route.id && errors?.[m.route.id]\n );\n invariant(\n errorIndex >= 0,\n `Could not find a matching route for errors on route IDs: ${Object.keys(\n errors\n ).join(\",\")}`\n );\n renderedMatches = renderedMatches.slice(\n 0,\n Math.min(renderedMatches.length, errorIndex + 1)\n );\n }\n\n return renderedMatches.reduceRight((outlet, match, index) => {\n let error = match.route.id ? errors?.[match.route.id] : null;\n // Only data routers handle errors\n let errorElement: React.ReactNode | null = null;\n if (dataRouterState) {\n errorElement = match.route.errorElement || defaultErrorElement;\n }\n let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n let getChildren = () => {\n let children: React.ReactNode;\n if (error) {\n children = errorElement;\n } else if (match.route.Component) {\n // Note: This is a de-optimized path since React won't re-use the\n // ReactElement since it's identity changes with each new\n // React.createElement call. We keep this so folks can use\n // `` in `` but generally `Component`\n // usage is only advised in `RouterProvider` when we can convert it to\n // `element` ahead of time.\n children = ;\n } else if (match.route.element) {\n children = match.route.element;\n } else {\n children = outlet;\n }\n return (\n \n );\n };\n // Only wrap in an error boundary within data router usages when we have an\n // ErrorBoundary/errorElement on this route. Otherwise let it bubble up to\n // an ancestor ErrorBoundary/errorElement\n return dataRouterState &&\n (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n \n ) : (\n getChildren()\n );\n }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n UseBlocker = \"useBlocker\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n UseBlocker = \"useBlocker\",\n UseLoaderData = \"useLoaderData\",\n UseActionData = \"useActionData\",\n UseRouteError = \"useRouteError\",\n UseNavigation = \"useNavigation\",\n UseRouteLoaderData = \"useRouteLoaderData\",\n UseMatches = \"useMatches\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n hookName: DataRouterHook | DataRouterStateHook\n) {\n return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n let ctx = React.useContext(DataRouterContext);\n invariant(ctx, getDataRouterConsoleError(hookName));\n return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n let state = React.useContext(DataRouterStateContext);\n invariant(state, getDataRouterConsoleError(hookName));\n return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n let route = React.useContext(RouteContext);\n invariant(route, getDataRouterConsoleError(hookName));\n return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n let route = useRouteContext(hookName);\n let thisRoute = route.matches[route.matches.length - 1];\n invariant(\n thisRoute.route.id,\n `${hookName} can only be used on routes that contain a unique \"id\"`\n );\n return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nexport function useNavigation() {\n let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nexport function useRevalidator() {\n let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n return {\n revalidate: dataRouterContext.router.revalidate,\n state: state.revalidation,\n };\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nexport function useMatches() {\n let { matches, loaderData } = useDataRouterState(\n DataRouterStateHook.UseMatches\n );\n return React.useMemo(\n () =>\n matches.map((match) => {\n let { pathname, params } = match;\n // Note: This structure matches that created by createUseMatchesMatch\n // in the @remix-run/router , so if you change this please also change\n // that :) Eventually we'll DRY this up\n return {\n id: match.route.id,\n pathname,\n params,\n data: loaderData[match.route.id] as unknown,\n handle: match.route.handle as unknown,\n };\n }),\n [matches, loaderData]\n );\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nexport function useLoaderData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n if (state.errors && state.errors[routeId] != null) {\n console.error(\n `You cannot \\`useLoaderData\\` in an errorElement (routeId: ${routeId})`\n );\n return undefined;\n }\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nexport function useActionData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseActionData);\n\n let route = React.useContext(RouteContext);\n invariant(route, `useActionData must be used inside a RouteContext`);\n\n return Object.values(state?.actionData || {})[0];\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error. This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nexport function useRouteError(): unknown {\n let error = React.useContext(RouteErrorContext);\n let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n // If this was a render error, we put it in a RouteError context inside\n // of RenderErrorBoundary\n if (error) {\n return error;\n }\n\n // Otherwise look for errors from our data router state\n return state.errors?.[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor value\n */\nexport function useAsyncValue(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._data;\n}\n\n/**\n * Returns the error from the nearest ancestor value\n */\nexport function useAsyncError(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation. Mostly used to avoid\n * using half-filled form data. This does not handle hard-reloads or\n * cross-origin navigations.\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n let { router } = useDataRouterContext(DataRouterHook.UseBlocker);\n let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n let [blockerKey] = React.useState(() => String(++blockerId));\n\n let blockerFunction = React.useCallback(\n (args) => {\n return typeof shouldBlock === \"function\"\n ? !!shouldBlock(args)\n : !!shouldBlock;\n },\n [shouldBlock]\n );\n\n let blocker = router.getBlocker(blockerKey, blockerFunction);\n\n // Cleanup on unmount\n React.useEffect(\n () => () => router.deleteBlocker(blockerKey),\n [router, blockerKey]\n );\n\n // Prefer the blocker from state since DataRouterContext is memoized so this\n // ensures we update on blocker state updates\n return state.blockers.get(blockerKey) || blocker;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable(): NavigateFunction {\n let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our router subscriber yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n router.navigate(to);\n } else {\n router.navigate(to, { fromRouteId: id, ...options });\n }\n },\n [router, id]\n );\n\n return navigate;\n}\n\nconst alreadyWarned: Record = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n if (!cond && !alreadyWarned[key]) {\n alreadyWarned[key] = true;\n warning(false, message);\n }\n}\n","import * as React from \"react\";\nimport type {\n TrackedPromise,\n InitialEntry,\n Location,\n MemoryHistory,\n Router as RemixRouter,\n To,\n LazyRouteFunction,\n RelativeRoutingType,\n RouterState,\n} from \"@remix-run/router\";\nimport {\n Action as NavigationType,\n AbortedDeferredError,\n createMemoryHistory,\n UNSAFE_invariant as invariant,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n UNSAFE_getPathContributingMatches as getPathContributingMatches,\n} from \"@remix-run/router\";\n\nimport type {\n DataRouteObject,\n IndexRouteObject,\n RouteMatch,\n RouteObject,\n Navigator,\n NonIndexRouteObject,\n} from \"./context\";\nimport {\n LocationContext,\n NavigationContext,\n DataRouterContext,\n DataRouterStateContext,\n AwaitContext,\n RouteContext,\n} from \"./context\";\nimport {\n useAsyncValue,\n useInRouterContext,\n useNavigate,\n useOutlet,\n useRoutes,\n _renderMatches,\n useRoutesImpl,\n useLocation,\n} from \"./hooks\";\n\nexport interface RouterProviderProps {\n fallbackElement?: React.ReactNode;\n router: RemixRouter;\n}\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n fallbackElement,\n router,\n}: RouterProviderProps): React.ReactElement {\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/)\n let [state, setState] = React.useState(router.state);\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n let navigator = React.useMemo((): Navigator => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: (n) => router.navigate(n),\n push: (to, state, opts) =>\n router.navigate(to, {\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n replace: (to, state, opts) =>\n router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n };\n }, [router]);\n\n let basename = router.basename || \"/\";\n\n let dataRouterContext = React.useMemo(\n () => ({\n router,\n navigator,\n static: false,\n basename,\n }),\n [router, navigator, basename]\n );\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a \n \n \n )}\n \n \n \n );\n}\n","import E,{Fragment as F,createContext as C,useContext as I,useEffect as h,useMemo as S,useReducer as N,useRef as g}from\"react\";import{match as x}from'../../utils/match.js';import{forwardRefWithAs as L,render as O,Features as U}from'../../utils/render.js';import{optionalRef as K,useSyncRefs as B}from'../../hooks/use-sync-refs.js';import{useId as _}from'../../hooks/use-id.js';import{Keys as m}from'../keyboard.js';import{isDisabledReactIssue7711 as G}from'../../utils/bugs.js';import{OpenClosedProvider as j,State as R,useOpenClosed as W}from'../../internal/open-closed.js';import{useResolveButtonType as $}from'../../hooks/use-resolve-button-type.js';import{getOwnerDocument as J}from'../../utils/owner.js';import{useEvent as A}from'../../hooks/use-event.js';import{startTransition as X}from'../../utils/start-transition.js';var q=(o=>(o[o.Open=0]=\"Open\",o[o.Closed=1]=\"Closed\",o))(q||{}),z=(t=>(t[t.ToggleDisclosure=0]=\"ToggleDisclosure\",t[t.CloseDisclosure=1]=\"CloseDisclosure\",t[t.SetButtonId=2]=\"SetButtonId\",t[t.SetPanelId=3]=\"SetPanelId\",t[t.LinkPanel=4]=\"LinkPanel\",t[t.UnlinkPanel=5]=\"UnlinkPanel\",t))(z||{});let Q={[0]:e=>({...e,disclosureState:x(e.disclosureState,{[0]:1,[1]:0})}),[1]:e=>e.disclosureState===1?e:{...e,disclosureState:1},[4](e){return e.linkedPanel===!0?e:{...e,linkedPanel:!0}},[5](e){return e.linkedPanel===!1?e:{...e,linkedPanel:!1}},[2](e,n){return e.buttonId===n.buttonId?e:{...e,buttonId:n.buttonId}},[3](e,n){return e.panelId===n.panelId?e:{...e,panelId:n.panelId}}},k=C(null);k.displayName=\"DisclosureContext\";function M(e){let n=I(k);if(n===null){let o=new Error(`<${e} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(o,M),o}return n}let v=C(null);v.displayName=\"DisclosureAPIContext\";function w(e){let n=I(v);if(n===null){let o=new Error(`<${e} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(o,w),o}return n}let H=C(null);H.displayName=\"DisclosurePanelContext\";function V(){return I(H)}function Y(e,n){return x(n.type,Q,e,n)}let Z=F;function ee(e,n){let{defaultOpen:o=!1,...u}=e,T=g(null),l=B(n,K(a=>{T.current=a},e.as===void 0||e.as===F)),t=g(null),f=g(null),s=N(Y,{disclosureState:o?0:1,linkedPanel:!1,buttonRef:f,panelRef:t,buttonId:null,panelId:null}),[{disclosureState:i,buttonId:c},D]=s,d=A(a=>{D({type:1});let r=J(T);if(!r||!c)return;let p=(()=>a?a instanceof HTMLElement?a:a.current instanceof HTMLElement?a.current:r.getElementById(c):r.getElementById(c))();p==null||p.focus()}),P=S(()=>({close:d}),[d]),b=S(()=>({open:i===0,close:d}),[i,d]),y={ref:l};return E.createElement(k.Provider,{value:s},E.createElement(v.Provider,{value:P},E.createElement(j,{value:x(i,{[0]:R.Open,[1]:R.Closed})},O({ourProps:y,theirProps:u,slot:b,defaultTag:Z,name:\"Disclosure\"}))))}let te=\"button\";function ne(e,n){let o=_(),{id:u=`headlessui-disclosure-button-${o}`,...T}=e,[l,t]=M(\"Disclosure.Button\"),f=V(),s=f===null?!1:f===l.panelId,i=g(null),c=B(i,n,s?null:l.buttonRef);h(()=>{if(!s)return t({type:2,buttonId:u}),()=>{t({type:2,buttonId:null})}},[u,t,s]);let D=A(r=>{var p;if(s){if(l.disclosureState===1)return;switch(r.key){case m.Space:case m.Enter:r.preventDefault(),r.stopPropagation(),t({type:0}),(p=l.buttonRef.current)==null||p.focus();break}}else switch(r.key){case m.Space:case m.Enter:r.preventDefault(),r.stopPropagation(),t({type:0});break}}),d=A(r=>{switch(r.key){case m.Space:r.preventDefault();break}}),P=A(r=>{var p;G(r.currentTarget)||e.disabled||(s?(t({type:0}),(p=l.buttonRef.current)==null||p.focus()):t({type:0}))}),b=S(()=>({open:l.disclosureState===0}),[l]),y=$(e,i),a=s?{ref:c,type:y,onKeyDown:D,onClick:P}:{ref:c,id:u,type:y,\"aria-expanded\":e.disabled?void 0:l.disclosureState===0,\"aria-controls\":l.linkedPanel?l.panelId:void 0,onKeyDown:D,onKeyUp:d,onClick:P};return O({ourProps:a,theirProps:T,slot:b,defaultTag:te,name:\"Disclosure.Button\"})}let le=\"div\",oe=U.RenderStrategy|U.Static;function re(e,n){let o=_(),{id:u=`headlessui-disclosure-panel-${o}`,...T}=e,[l,t]=M(\"Disclosure.Panel\"),{close:f}=w(\"Disclosure.Panel\"),s=B(n,l.panelRef,P=>{X(()=>t({type:P?4:5}))});h(()=>(t({type:3,panelId:u}),()=>{t({type:3,panelId:null})}),[u,t]);let i=W(),c=(()=>i!==null?(i&R.Open)===R.Open:l.disclosureState===0)(),D=S(()=>({open:l.disclosureState===0,close:f}),[l,f]),d={ref:s,id:u};return E.createElement(H.Provider,{value:l.panelId},O({ourProps:d,theirProps:T,slot:D,defaultTag:le,features:oe,visible:c,name:\"Disclosure.Panel\"}))}let se=L(ee),ue=L(ne),ie=L(re),ve=Object.assign(se,{Button:ue,Panel:ie});export{ve as Disclosure};\n","function f(r){throw new Error(\"Unexpected object: \"+r)}var a=(e=>(e[e.First=0]=\"First\",e[e.Previous=1]=\"Previous\",e[e.Next=2]=\"Next\",e[e.Last=3]=\"Last\",e[e.Specific=4]=\"Specific\",e[e.Nothing=5]=\"Nothing\",e))(a||{});function x(r,n){let t=n.resolveItems();if(t.length<=0)return null;let l=n.resolveActiveIndex(),s=l!=null?l:-1,d=(()=>{switch(r.focus){case 0:return t.findIndex(e=>!n.resolveDisabled(e));case 1:{let e=t.slice().reverse().findIndex((i,c,u)=>s!==-1&&u.length-c-1>=s?!1:!n.resolveDisabled(i));return e===-1?e:t.length-1-e}case 2:return t.findIndex((e,i)=>i<=s?!1:!n.resolveDisabled(e));case 3:{let e=t.slice().reverse().findIndex(i=>!n.resolveDisabled(i));return e===-1?e:t.length-1-e}case 4:return t.findIndex(e=>n.resolveId(e)===r.id);case 5:return null;default:f(r)}})();return d===-1?l:d}export{a as Focus,x as calculateActiveIndex};\n","import{useRef as o}from\"react\";function t(e){return[e.screenX,e.screenY]}function u(){let e=o([-1,-1]);return{wasMoved(r){let n=t(r);return e.current[0]===n[0]&&e.current[1]===n[1]?!1:(e.current=n,!0)},update(r){e.current=t(r)}}}export{u as useTrackedPointer};\n","import B,{Fragment as G,createContext as V,createRef as N,useContext as X,useEffect as $,useMemo as P,useReducer as q,useRef as H}from\"react\";import{match as K}from'../../utils/match.js';import{forwardRefWithAs as v,render as x,Features as j}from'../../utils/render.js';import{disposables as L}from'../../utils/disposables.js';import{useDisposables as Q}from'../../hooks/use-disposables.js';import{useIsoMorphicEffect as h}from'../../hooks/use-iso-morphic-effect.js';import{useSyncRefs as D}from'../../hooks/use-sync-refs.js';import{useId as k}from'../../hooks/use-id.js';import{Keys as d}from'../keyboard.js';import{Focus as y,calculateActiveIndex as z}from'../../utils/calculate-active-index.js';import{isDisabledReactIssue7711 as Y}from'../../utils/bugs.js';import{isFocusableElement as Z,FocusableMode as ee,sortByDomNode as te,Focus as W,focusFrom as ne,restoreFocusIfNecessary as J}from'../../utils/focus-management.js';import{useOutsideClick as re}from'../../hooks/use-outside-click.js';import{useTreeWalker as oe}from'../../hooks/use-tree-walker.js';import{useOpenClosed as ae,State as C,OpenClosedProvider as se}from'../../internal/open-closed.js';import{useResolveButtonType as ie}from'../../hooks/use-resolve-button-type.js';import{useOwnerDocument as ue}from'../../hooks/use-owner.js';import{useEvent as T}from'../../hooks/use-event.js';import{useTrackedPointer as le}from'../../hooks/use-tracked-pointer.js';var pe=(r=>(r[r.Open=0]=\"Open\",r[r.Closed=1]=\"Closed\",r))(pe||{}),ce=(r=>(r[r.Pointer=0]=\"Pointer\",r[r.Other=1]=\"Other\",r))(ce||{}),me=(a=>(a[a.OpenMenu=0]=\"OpenMenu\",a[a.CloseMenu=1]=\"CloseMenu\",a[a.GoToItem=2]=\"GoToItem\",a[a.Search=3]=\"Search\",a[a.ClearSearch=4]=\"ClearSearch\",a[a.RegisterItem=5]=\"RegisterItem\",a[a.UnregisterItem=6]=\"UnregisterItem\",a))(me||{});function w(e,u=r=>r){let r=e.activeItemIndex!==null?e.items[e.activeItemIndex]:null,i=te(u(e.items.slice()),t=>t.dataRef.current.domRef.current),s=r?i.indexOf(r):null;return s===-1&&(s=null),{items:i,activeItemIndex:s}}let de={[1](e){return e.menuState===1?e:{...e,activeItemIndex:null,menuState:1}},[0](e){return e.menuState===0?e:{...e,menuState:0}},[2]:(e,u)=>{var s;let r=w(e),i=z(u,{resolveItems:()=>r.items,resolveActiveIndex:()=>r.activeItemIndex,resolveId:t=>t.id,resolveDisabled:t=>t.dataRef.current.disabled});return{...e,...r,searchQuery:\"\",activeItemIndex:i,activationTrigger:(s=u.trigger)!=null?s:1}},[3]:(e,u)=>{let i=e.searchQuery!==\"\"?0:1,s=e.searchQuery+u.value.toLowerCase(),o=(e.activeItemIndex!==null?e.items.slice(e.activeItemIndex+i).concat(e.items.slice(0,e.activeItemIndex+i)):e.items).find(l=>{var m;return((m=l.dataRef.current.textValue)==null?void 0:m.startsWith(s))&&!l.dataRef.current.disabled}),a=o?e.items.indexOf(o):-1;return a===-1||a===e.activeItemIndex?{...e,searchQuery:s}:{...e,searchQuery:s,activeItemIndex:a,activationTrigger:1}},[4](e){return e.searchQuery===\"\"?e:{...e,searchQuery:\"\",searchActiveItemIndex:null}},[5]:(e,u)=>{let r=w(e,i=>[...i,{id:u.id,dataRef:u.dataRef}]);return{...e,...r}},[6]:(e,u)=>{let r=w(e,i=>{let s=i.findIndex(t=>t.id===u.id);return s!==-1&&i.splice(s,1),i});return{...e,...r,activationTrigger:1}}},U=V(null);U.displayName=\"MenuContext\";function F(e){let u=X(U);if(u===null){let r=new Error(`<${e} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(r,F),r}return u}function fe(e,u){return K(u.type,de,e,u)}let Te=G;function ye(e,u){let r=q(fe,{menuState:1,buttonRef:N(),itemsRef:N(),items:[],searchQuery:\"\",activeItemIndex:null,activationTrigger:1}),[{menuState:i,itemsRef:s,buttonRef:t},o]=r,a=D(u);re([t,s],(g,A)=>{var I;o({type:1}),Z(A,ee.Loose)||(g.preventDefault(),(I=t.current)==null||I.focus())},i===0);let l=T(()=>{o({type:1})}),m=P(()=>({open:i===0,close:l}),[i,l]),M=e,f={ref:a};return B.createElement(U.Provider,{value:r},B.createElement(se,{value:K(i,{[0]:C.Open,[1]:C.Closed})},x({ourProps:f,theirProps:M,slot:m,defaultTag:Te,name:\"Menu\"})))}let Ie=\"button\";function Me(e,u){var I;let r=k(),{id:i=`headlessui-menu-button-${r}`,...s}=e,[t,o]=F(\"Menu.Button\"),a=D(t.buttonRef,u),l=Q(),m=T(p=>{switch(p.key){case d.Space:case d.Enter:case d.ArrowDown:p.preventDefault(),p.stopPropagation(),o({type:0}),l.nextFrame(()=>o({type:2,focus:y.First}));break;case d.ArrowUp:p.preventDefault(),p.stopPropagation(),o({type:0}),l.nextFrame(()=>o({type:2,focus:y.Last}));break}}),M=T(p=>{switch(p.key){case d.Space:p.preventDefault();break}}),f=T(p=>{if(Y(p.currentTarget))return p.preventDefault();e.disabled||(t.menuState===0?(o({type:1}),l.nextFrame(()=>{var R;return(R=t.buttonRef.current)==null?void 0:R.focus({preventScroll:!0})})):(p.preventDefault(),o({type:0})))}),g=P(()=>({open:t.menuState===0}),[t]),A={ref:a,id:i,type:ie(e,t.buttonRef),\"aria-haspopup\":\"menu\",\"aria-controls\":(I=t.itemsRef.current)==null?void 0:I.id,\"aria-expanded\":e.disabled?void 0:t.menuState===0,onKeyDown:m,onKeyUp:M,onClick:f};return x({ourProps:A,theirProps:s,slot:g,defaultTag:Ie,name:\"Menu.Button\"})}let ge=\"div\",Re=j.RenderStrategy|j.Static;function Ae(e,u){var R,E;let r=k(),{id:i=`headlessui-menu-items-${r}`,...s}=e,[t,o]=F(\"Menu.Items\"),a=D(t.itemsRef,u),l=ue(t.itemsRef),m=Q(),M=ae(),f=(()=>M!==null?(M&C.Open)===C.Open:t.menuState===0)();$(()=>{let n=t.itemsRef.current;n&&t.menuState===0&&n!==(l==null?void 0:l.activeElement)&&n.focus({preventScroll:!0})},[t.menuState,t.itemsRef,l]),oe({container:t.itemsRef.current,enabled:t.menuState===0,accept(n){return n.getAttribute(\"role\")===\"menuitem\"?NodeFilter.FILTER_REJECT:n.hasAttribute(\"role\")?NodeFilter.FILTER_SKIP:NodeFilter.FILTER_ACCEPT},walk(n){n.setAttribute(\"role\",\"none\")}});let g=T(n=>{var S,O;switch(m.dispose(),n.key){case d.Space:if(t.searchQuery!==\"\")return n.preventDefault(),n.stopPropagation(),o({type:3,value:n.key});case d.Enter:if(n.preventDefault(),n.stopPropagation(),o({type:1}),t.activeItemIndex!==null){let{dataRef:c}=t.items[t.activeItemIndex];(O=(S=c.current)==null?void 0:S.domRef.current)==null||O.click()}J(t.buttonRef.current);break;case d.ArrowDown:return n.preventDefault(),n.stopPropagation(),o({type:2,focus:y.Next});case d.ArrowUp:return n.preventDefault(),n.stopPropagation(),o({type:2,focus:y.Previous});case d.Home:case d.PageUp:return n.preventDefault(),n.stopPropagation(),o({type:2,focus:y.First});case d.End:case d.PageDown:return n.preventDefault(),n.stopPropagation(),o({type:2,focus:y.Last});case d.Escape:n.preventDefault(),n.stopPropagation(),o({type:1}),L().nextFrame(()=>{var c;return(c=t.buttonRef.current)==null?void 0:c.focus({preventScroll:!0})});break;case d.Tab:n.preventDefault(),n.stopPropagation(),o({type:1}),L().nextFrame(()=>{ne(t.buttonRef.current,n.shiftKey?W.Previous:W.Next)});break;default:n.key.length===1&&(o({type:3,value:n.key}),m.setTimeout(()=>o({type:4}),350));break}}),A=T(n=>{switch(n.key){case d.Space:n.preventDefault();break}}),I=P(()=>({open:t.menuState===0}),[t]),p={\"aria-activedescendant\":t.activeItemIndex===null||(R=t.items[t.activeItemIndex])==null?void 0:R.id,\"aria-labelledby\":(E=t.buttonRef.current)==null?void 0:E.id,id:i,onKeyDown:g,onKeyUp:A,role:\"menu\",tabIndex:0,ref:a};return x({ourProps:p,theirProps:s,slot:I,defaultTag:ge,features:Re,visible:f,name:\"Menu.Items\"})}let be=G;function Ee(e,u){let r=k(),{id:i=`headlessui-menu-item-${r}`,disabled:s=!1,...t}=e,[o,a]=F(\"Menu.Item\"),l=o.activeItemIndex!==null?o.items[o.activeItemIndex].id===i:!1,m=H(null),M=D(u,m);h(()=>{if(o.menuState!==0||!l||o.activationTrigger===0)return;let c=L();return c.requestAnimationFrame(()=>{var b,_;(_=(b=m.current)==null?void 0:b.scrollIntoView)==null||_.call(b,{block:\"nearest\"})}),c.dispose},[m,l,o.menuState,o.activationTrigger,o.activeItemIndex]);let f=H({disabled:s,domRef:m});h(()=>{f.current.disabled=s},[f,s]),h(()=>{var c,b;f.current.textValue=(b=(c=m.current)==null?void 0:c.textContent)==null?void 0:b.toLowerCase()},[f,m]),h(()=>(a({type:5,id:i,dataRef:f}),()=>a({type:6,id:i})),[f,i]);let g=T(()=>{a({type:1})}),A=T(c=>{if(s)return c.preventDefault();a({type:1}),J(o.buttonRef.current)}),I=T(()=>{if(s)return a({type:2,focus:y.Nothing});a({type:2,focus:y.Specific,id:i})}),p=le(),R=T(c=>p.update(c)),E=T(c=>{p.wasMoved(c)&&(s||l||a({type:2,focus:y.Specific,id:i,trigger:0}))}),n=T(c=>{p.wasMoved(c)&&(s||l&&a({type:2,focus:y.Nothing}))}),S=P(()=>({active:l,disabled:s,close:g}),[l,s,g]);return x({ourProps:{id:i,ref:M,role:\"menuitem\",tabIndex:s===!0?void 0:-1,\"aria-disabled\":s===!0?!0:void 0,disabled:void 0,onClick:A,onFocus:I,onPointerEnter:R,onMouseEnter:R,onPointerMove:E,onMouseMove:E,onPointerLeave:n,onMouseLeave:n},theirProps:t,slot:S,defaultTag:be,name:\"Menu.Item\"})}let Se=v(ye),Pe=v(Me),ve=v(Ae),xe=v(Ee),ot=Object.assign(Se,{Button:Pe,Items:ve,Item:xe});export{ot as Menu};\n","import{useRef as E,useEffect as m}from\"react\";import{useIsoMorphicEffect as T}from'./use-iso-morphic-effect.js';import{getOwnerDocument as N}from'../utils/owner.js';function F({container:e,accept:t,walk:r,enabled:c=!0}){let o=E(t),l=E(r);m(()=>{o.current=t,l.current=r},[t,r]),T(()=>{if(!e||!c)return;let n=N(e);if(!n)return;let f=o.current,p=l.current,d=Object.assign(i=>f(i),{acceptNode:f}),u=n.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,d,!1);for(;u.nextNode();)p(u.currentNode)},[e,c,o,l])}export{F as useTreeWalker};\n","import * as React from \"react\";\nfunction Bars3Icon({\n title,\n titleId,\n ...props\n}, svgRef) {\n return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n xmlns: \"http://www.w3.org/2000/svg\",\n fill: \"none\",\n viewBox: \"0 0 24 24\",\n strokeWidth: 1.5,\n stroke: \"currentColor\",\n \"aria-hidden\": \"true\",\n ref: svgRef,\n \"aria-labelledby\": titleId\n }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n id: titleId\n }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\",\n d: \"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5\"\n }));\n}\nconst ForwardRef = React.forwardRef(Bars3Icon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction SunIcon({\n title,\n titleId,\n ...props\n}, svgRef) {\n return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n xmlns: \"http://www.w3.org/2000/svg\",\n fill: \"none\",\n viewBox: \"0 0 24 24\",\n strokeWidth: 1.5,\n stroke: \"currentColor\",\n \"aria-hidden\": \"true\",\n ref: svgRef,\n \"aria-labelledby\": titleId\n }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n id: titleId\n }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\",\n d: \"M12 3v2.25m6.364.386l-1.591 1.591M21 12h-2.25m-.386 6.364l-1.591-1.591M12 18.75V21m-4.773-4.227l-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0z\"\n }));\n}\nconst ForwardRef = React.forwardRef(SunIcon);\nexport default ForwardRef;","import * as React from \"react\";\nfunction MoonIcon({\n title,\n titleId,\n ...props\n}, svgRef) {\n return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n xmlns: \"http://www.w3.org/2000/svg\",\n fill: \"none\",\n viewBox: \"0 0 24 24\",\n strokeWidth: 1.5,\n stroke: \"currentColor\",\n \"aria-hidden\": \"true\",\n ref: svgRef,\n \"aria-labelledby\": titleId\n }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n id: titleId\n }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\",\n d: \"M21.752 15.002A9.718 9.718 0 0118 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 003 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 009.002-5.998z\"\n }));\n}\nconst ForwardRef = React.forwardRef(MoonIcon);\nexport default ForwardRef;","import { Fragment, useEffect, useState } from \"react\";\n\nimport clsx from \"clsx\";\nimport jwtDecode from \"jwt-decode\";\nimport { NavLink } from \"react-router-dom\";\nimport { useQueryClient } from \"react-query\";\nimport { Outlet, useNavigate } from \"react-router\";\n\nimport * as Sentry from \"@sentry/react\";\nimport { Disclosure, Menu, Transition } from \"@headlessui/react\";\nimport {\n Bars3Icon,\n MoonIcon,\n SunIcon,\n XMarkIcon,\n} from \"@heroicons/react/24/outline\";\n\nimport useUser from \"../data/user/useUser\";\nimport useApiHelper from \"../hooks/useApiHelper\";\nimport { ErrorFallback } from \"../ErrorFallback\";\nimport { Button } from \"../components/base/Button\";\nimport { useTheme } from \"../contexts/ThemeContext\";\nimport { Avatar } from \"../components/shared/Avatar\";\nimport { useUserContext } from \"../contexts/UserContext\";\nimport { usePageTitle } from \"../contexts/PageTitleContext\";\nimport { LoadingWheel } from \"../components/base/LoadingWheel\";\nimport { FullscreenLoading } from \"../components/shared/FullscreenLoading\";\nimport { authAPIURL, CDNURL, isProd, pdOrgId } from \"../config\";\nimport useUserOrganisations from \"../data/user/useUserOrganisations\";\n\nexport default function AuthenticatedLayout() {\n const navigate = useNavigate();\n const queryClient = useQueryClient();\n const {\n theme: { isDark, logo },\n setTheme,\n } = useTheme();\n const {\n isLoggedIn,\n isInstaller,\n isSuperAdmin,\n organisationName,\n organisationId,\n installerId,\n installerName,\n superAdminId,\n loading: userLoading,\n setUser,\n } = useUserContext();\n const { pageTitle, subTitle } = usePageTitle();\n const { post, get } = useApiHelper({\n apiUrl: authAPIURL,\n options: { credentials: \"include\" },\n headers: { Authorization: \"\" },\n });\n const { user } = useUser();\n const { userOrganisations } = useUserOrganisations();\n const [loading, setLoading] = useState(true);\n\n // ! stops tailwind stripping the class\n const bgBackdrop = \"bg-backdrop\"; //eslint-disable-line\n\n const getNavigation = () => {\n let type = \"customer\";\n\n if (superAdminId && installerId) {\n type = \"installerActAsCustomer\";\n } else if (superAdminId) {\n type = \"installer\";\n } else if (installerId) {\n type = \"installerActAsCustomer\";\n } else {\n if (isSuperAdmin) {\n type = \"superadmin\";\n } else if (isInstaller) {\n type = \"installer\";\n } else {\n type = \"customer\";\n }\n }\n\n switch (type) {\n case \"superadmin\":\n let routes = [\n { name: \"Dashboard\", href: \"dashboard\" },\n { name: \"Alerts\", href: \"alerts\" },\n { name: \"Jobs\", href: \"jobs\" },\n { name: \"Live Readings\", href: \"/\", end: true },\n { name: \"Historical Readings\", href: \"history\" },\n { name: \"Installers\", href: \"installers\" },\n { name: \"Customers\", href: \"customers\" },\n { name: \"Devices\", href: \"hardware\" },\n ];\n\n !isProd && routes.push({ name: \"System\", href: \"system\" });\n\n return routes;\n case \"installer\":\n return [\n { name: \"Live Readings\", href: \"/\", end: true },\n { name: \"Historical Readings\", href: \"history\" },\n { name: \"Customers\", href: \"customers\" },\n { name: \"Devices\", href: \"hardware\" },\n ];\n case \"installerActAsCustomer\":\n return [\n { name: \"Live Readings\", href: \"/\", end: true },\n { name: \"Historical Readings\", href: \"history\" },\n { name: \"Devices\", href: \"hardware\" },\n ];\n case \"customer\":\n default:\n return [\n { name: \"Live Readings\", href: \"/\", end: true },\n { name: \"Historical Readings\", href: \"history\" },\n { name: \"Devices\", href: \"hardware\" },\n ];\n }\n };\n\n const handleLogout = () => {\n get(\"/v1/sso/logout\", { withCredentials: true }).then(() => {\n setUser({ type: \"loading\", payload: true });\n setUser({ type: \"logout\" });\n queryClient.clear();\n setTheme({ type: \"reset\" });\n setUser({ type: \"loading\", payload: false });\n navigate(\"/login\");\n });\n };\n\n const handleInstallerSwitchBack = async () => {\n try {\n let tokenResponse = await post(\n \"/v1/sso/token\",\n {\n organisationId: installerId ?? \"\",\n type: \"portal\",\n },\n { withCredentials: true }\n );\n\n let decodedToken = jwtDecode<{ oid: string }>(tokenResponse.data.token!);\n\n setUser({ type: \"loading\", payload: true });\n setUser({\n type: \"installerSwitchBack\",\n payload: {\n token: tokenResponse.data.token!,\n organisationId: decodedToken.oid,\n },\n });\n queryClient.clear();\n navigate(\"/customers\");\n } catch (err: any) {\n console.error(err);\n }\n };\n\n const handleSuperAdminSwitchBack = async () => {\n try {\n let tokenResponse = await post(\n \"/v1/sso/token\",\n {\n organisationId: pdOrgId,\n type: \"portal\",\n },\n {\n withCredentials: true,\n }\n );\n\n let decodedToken = jwtDecode<{ oid: string; uid: string }>(\n tokenResponse.data.token!\n );\n\n setUser({ type: \"loading\", payload: true });\n setUser({ type: \"superAdminSwitchBack\" });\n setUser({\n type: \"login\",\n payload: {\n token: tokenResponse.data.token!,\n userId: decodedToken.uid,\n organisationId: decodedToken.oid,\n },\n });\n queryClient.clear();\n navigate(\"/installers\");\n } catch (err: any) {\n console.error(err);\n }\n };\n\n const handleLoginAsCustomer = async (organisationId: string) => {\n try {\n let tokenResponse = await post(\n \"/v1/sso/token\",\n {\n organisationId: organisationId,\n type: \"portal\",\n },\n {\n withCredentials: true,\n }\n );\n\n let decodedToken = jwtDecode<{ oid: string }>(tokenResponse.data.token!);\n\n setUser({ type: \"loading\", payload: true });\n setUser({\n type: \"installerLoginAs\",\n payload: {\n token: tokenResponse.data.token!,\n organisationId: decodedToken.oid,\n installerId: user.data?.defaultOrganisation!,\n installerName: installerId ? organisationName! : installerName!,\n },\n });\n\n queryClient.clear();\n queryClient.cancelQueries();\n\n navigate(\"/\");\n } catch (err) {\n console.error(\"err\", err);\n } finally {\n setUser({ type: \"loading\", payload: false });\n }\n };\n\n const getUserNavigation = () => {\n return [\n { name: \"Settings\", onClick: () => navigate(\"settings\") },\n { name: \"Sign out\", onClick: handleLogout },\n ];\n };\n\n useEffect(() => {\n if (!userLoading) {\n if (isLoggedIn) {\n setLoading(false);\n } else {\n navigate(\"/login\");\n }\n }\n }, [userLoading, isLoggedIn, navigate]);\n\n if (loading) {\n return ;\n } else {\n return (\n }>\n
\n {installerId !== undefined ||\n (isSuperAdmin && organisationId !== pdOrgId) ? (\n
\n {isSuperAdmin && organisationId !== pdOrgId && (\n <>\n Acting as installer\n \n {\" \"}\n {installerId ? installerName : organisationName}\n \n \n Switch Back\n \n \n )}\n {installerId !== undefined && (\n <>\n {isSuperAdmin && organisationId !== pdOrgId && (\n |\n )}\n Acting as customer\n {organisationName}\n \n Switch Back\n \n \n )}\n
\n ) : (\n <>\n )}\n
\n \n {({ open }) => (\n <>\n
\n
\n
\n \n
\n
\n
\n {getNavigation().map((item) => (\n \n clsx(\n isActive\n ? `bg-white/20 text-primaryContrast`\n : `text-primaryContrast hover:bg-white/40`,\n \"rounded-md py-2 px-3 text-sm font-medium\"\n )\n }\n >\n {item.name}\n \n ))}\n
\n
\n
\n {/* Mobile menu button */}\n \n Open main menu\n {open ? (\n \n ) : (\n \n )}\n \n
\n
\n
\n \n setTheme({\n type: \"dark\",\n payload: !isDark,\n })\n }\n className=\"flex-shrink-0 rounded-full bg-primary p-1 text-primaryContrast focus:outline-none focus:ring-1 focus:ring-primaryContrast\"\n >\n Toggle dark mode\n {isDark ? (\n \n ) : (\n \n )}\n \n {/* Hidden as notifications don't exist yet */}\n {/* \n View notifications\n \n */}\n\n {/* Profile dropdown */}\n \n
\n {user.isLoading ? (\n \n ) : (\n \n \n Open user menu\n \n \n \n )}\n
\n \n \n {getUserNavigation().map((item) => (\n \n {({ active }) => (\n \n {item.name}\n \n )}\n \n ))}\n
\n {userOrganisations.isLoading ? (\n
\n \n
\n ) : (\n <>\n {userOrganisations.data\n ?.filter(\n (organisation) =>\n organisation.id !== organisationId &&\n organisation.id !==\n user.data?.defaultOrganisation\n )\n .map((organisation) => {\n let nameParts =\n organisation.organisationName.split(\n \" \"\n );\n\n return (\n \n {({ active }) => (\n \n handleLoginAsCustomer(\n organisation.id\n )\n }\n className={clsx(\n active\n ? \"bg-gray-100 dark:bg-gray-700\"\n : \"\",\n \"w-full block px-4 py-2 text-sm text-left text-gray-700 dark:text-gray-200\"\n )}\n >\n
\n
\n \n
\n
\n \n {\n organisation.organisationName\n }\n \n \n {\n organisation.organisationNumber\n }\n \n
\n
\n \n )}\n
\n );\n })}\n \n )}\n \n \n
\n \n \n \n \n\n \n
\n {getNavigation().map((item) => (\n \n clsx(\n isActive\n ? `bg-white/20 text-white`\n : `text-white hover:bg-white/40`,\n \"block rounded-md py-2 px-3 text-base font-medium\"\n )\n }\n >\n {item.name}\n \n ))}\n
\n
\n
\n
\n \n
\n
\n
\n {`${user.data?.forename} ${user.data?.surname}`}\n
\n
\n {user.data?.email}\n
\n
\n \n setTheme({\n type: \"dark\",\n payload: !isDark,\n })\n }\n className=\"ml-auto flex-shrink-0 rounded-full bg-white/20 p-2 text-white focus:outline-none focus:ring-1 focus:ring-white\"\n >\n Toggle dark mode\n {isDark ? (\n \n ) : (\n \n )}\n \n {/* Hidden as notifications don't exist yet */}\n {/* \n View notifications\n \n */}\n
\n
\n {getUserNavigation().map((item) => (\n \n {item.name}\n \n ))}\n
\n
\n
\n \n )}\n
\n
\n
\n

\n {pageTitle}\n

\n {subTitle !== undefined && (\n

\n {subTitle}\n

\n )}\n
\n
\n \n\n
\n
\n \n
\n
\n \n \n );\n }\n}\n","import { useQuery } from \"react-query\";\n\nimport { userQueryKeys } from \"../QueryKeys\";\nimport useApiHelper from \"../../hooks/useApiHelper\";\nimport { IDefaultResponseWithData } from \"../../types/system/DefaultResponse\";\nimport { IUserOrganisation } from \"../../types/UserOrganisation/UserOrganisation\";\n\nexport default function useUserOrganisations() {\n const { get } = useApiHelper();\n\n const userOrganisations = useQuery({\n queryKey: userQueryKeys.organisations(),\n queryFn: () =>\n get>(\n `/v1/user/organisations`,\n ).then((res) => res.data.data),\n });\n\n return {\n userOrganisations,\n };\n}\n","import { Dispatch, SetStateAction, useEffect, useState } from \"react\";\n\nimport { Alert } from \"../../base/Alert\";\nimport { Button } from \"../../base/Button\";\nimport { authAPIURL } from \"../../../config\";\nimport { Modal, ModalControlProps } from \"../../../layouts/Modal\";\nimport { TextField } from \"../../base/TextField\";\nimport useApiHelper from \"../../../hooks/useApiHelper\";\nimport { SectionLoading } from \"../../shared/SectionLoading\";\nimport { MFAEnableResponse } from \"../../../types/responses/mfa/MFAEnableResponse\";\nimport { MFARecoveryCodesResponse } from \"../../../types/responses/mfa/MFARecoveryCodesResponse\";\nimport { useNotification } from \"../../../hooks/useNotifications\";\nimport useUser from \"../../../data/user/useUser\";\nimport { futimesSync } from \"fs\";\n\ninterface StepButtonsProps {\n handleNext: () => void;\n handleBack: () => void;\n handleCancel: () => void;\n step: number;\n}\n\nfunction StepButtons({\n handleNext,\n handleBack,\n handleCancel,\n step,\n}: StepButtonsProps) {\n return (\n
\n \n
\n \n \n
\n
\n );\n}\n\nfunction RecoveryCodes(buttonProps: StepButtonsProps) {\n const { get } = useApiHelper({\n apiUrl: authAPIURL,\n withCredentials: true,\n });\n const [recoveryCodes, setRecoveryCodes] = useState();\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(false);\n let running = false;\n\n const handleCopyCodes = async () =>\n await navigator.clipboard.writeText(recoveryCodes!.join(\"\\n\"));\n\n const handleDownloadCodes = () => {\n var element = document.createElement(\"a\");\n element.setAttribute(\n \"href\",\n \"data:text/plain;charset=utf-8,\" +\n encodeURIComponent(recoveryCodes!.join(\"\\n\")),\n );\n element.setAttribute(\"download\", \"planet-devices-recovery-codes.txt\");\n\n element.style.display = \"none\";\n document.body.appendChild(element);\n\n element.click();\n\n document.body.removeChild(element);\n };\n\n const getRecoveryCodes = async () => {\n try {\n const codesResponse =\n await get(\"/v1/mfa/recover\");\n\n if (codesResponse.status === 200) {\n setRecoveryCodes(codesResponse.data.codes);\n } else {\n throw Error(\"Error getting MFA details\");\n }\n } catch {\n setError(true);\n } finally {\n setLoading(false);\n }\n };\n\n useEffect(() => {\n if (!running) {\n running = true;\n getRecoveryCodes();\n }\n }, []);\n\n return loading ? (\n \n ) : error ? (\n
\n \n
\n ) : (\n
\n

\n Please take a copy of these codes and keep them safe, they will allow\n you to gain access to your account in the event of an authenticator not\n being available\n

\n
\n {recoveryCodes?.map((code) => (\n
\n {code}\n
\n ))}\n
\n
\n
\n \n \n
\n
\n\n \n
\n );\n}\n\nfunction VerifyOTP(buttonProps: StepButtonsProps) {\n const { post } = useApiHelper({\n apiUrl: authAPIURL,\n withCredentials: true,\n });\n const [otp, setOtp] = useState();\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState(false);\n const [otpIncorrect, setOtpIncorrect] = useState(false);\n\n const verifyOTP = async () => {\n setLoading(true);\n try {\n const verifyResponse = await post(\"/v1/mfa/verify\", { code: otp });\n\n if (verifyResponse.status === 200) {\n buttonProps.handleNext();\n } else {\n throw Error(\"Error getting MFA details\");\n }\n } catch (e: any) {\n if (e.response.status && e.response.status === 400) {\n setOtpIncorrect(true);\n } else {\n setError(true);\n }\n } finally {\n setLoading(false);\n }\n };\n\n return loading ? (\n \n ) : error ? (\n
\n \n
\n ) : (\n
\n

\n Please enter the 6 digit code shown on your app to verify the setup has\n been successful\n

\n {otpIncorrect && (\n \n )}\n
\n setOtp(e.currentTarget.value)}\n />\n
\n \n
\n );\n}\n\nfunction QRDisplay(buttonProps: StepButtonsProps) {\n const { get } = useApiHelper({\n apiUrl: authAPIURL,\n withCredentials: true,\n });\n const [loading, setLoading] = useState(true);\n const [qrCode, setQRCode] = useState();\n const [manualCode, setManualCode] = useState();\n const [error, setError] = useState(false);\n let running = false;\n\n const getQRCode = async () => {\n try {\n const enableResponse = await get(\"/v1/mfa/enable\");\n\n if (enableResponse.status === 200) {\n setQRCode(enableResponse.data.qrCode);\n setManualCode(enableResponse.data.manual);\n }\n } catch {\n setError(true);\n } finally {\n setLoading(false);\n }\n };\n\n useEffect(() => {\n if (!qrCode && !running) {\n running = true;\n getQRCode();\n }\n }, []);\n\n return loading ? (\n \n ) : error ? (\n
\n \n
\n ) : (\n
\n

\n Please scan the below QR code with your preferred authenticator app,\n alternatively manually enter the code shown below the QR code\n

\n \"QR\n
\n

{manualCode}

\n
\n \n
\n );\n}\n\nexport function MFAEnable({ open, onClose }: ModalControlProps) {\n const { user } = useUser();\n const [step, setStep] = useState(0);\n const addNotification = useNotification();\n\n const handleCancel = () => {\n setStep(0);\n onClose(true);\n };\n\n const handleNext = () => {\n if (step === 2) {\n user.refetch();\n addNotification(\n \"success\",\n \"Successfully enabled multi-factor authentication\",\n );\n handleCancel();\n } else {\n setStep((step) => step + 1);\n }\n };\n\n const handleBack = () => setStep((step) => step - 1);\n\n const baseStepProps: StepButtonsProps = {\n handleCancel: handleCancel,\n handleBack: handleBack,\n handleNext: handleNext,\n step: step,\n };\n\n const getStep = () => {\n switch (step) {\n case 2:\n return ;\n case 1:\n return ;\n case 0:\n default:\n return ;\n }\n };\n\n return (\n \n {getStep()}\n \n );\n}\n","import { Dispatch, SetStateAction, useState } from \"react\";\n\nimport { Modal } from \"../../../layouts/Modal\";\nimport useApiHelper from \"../../../hooks/useApiHelper\";\nimport { authAPIURL } from \"../../../config\";\nimport { Alert } from \"../../base/Alert\";\nimport { TextField } from \"../../base/TextField\";\nimport { SectionLoading } from \"../../shared/SectionLoading\";\nimport { Button } from \"../../base/Button\";\nimport { useNotification } from \"../../../hooks/useNotifications\";\nimport useUser from \"../../../data/user/useUser\";\n\ninterface MFASetupProps {\n open: boolean;\n onClose: Dispatch>;\n}\n\nexport function MFADisable({ open, onClose }: MFASetupProps) {\n const { post } = useApiHelper({\n apiUrl: authAPIURL,\n withCredentials: true,\n });\n const { user } = useUser();\n const addNotification = useNotification();\n const [password, setPassword] = useState();\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState(false);\n const [otpIncorrect, setOtpIncorrect] = useState(false);\n\n const verifyPassword = async () => {\n setLoading(true);\n try {\n const verifyResponse = await post(\"/v1/mfa/disable\", {\n password: password,\n });\n\n if (verifyResponse.status === 200) {\n user.refetch();\n addNotification(\n \"success\",\n \"Successfully disabled multi-factor authentication\",\n );\n onClose(true);\n } else {\n throw Error(\"Error disabling MFA\");\n }\n } catch (e: any) {\n if (e.response.status && e.response.status === 400) {\n setOtpIncorrect(true);\n } else {\n setError(true);\n }\n } finally {\n setLoading(false);\n }\n };\n\n return (\n \n {loading ? (\n \n ) : error ? (\n
\n \n
\n ) : (\n
\n

Please enter your password to confirm

\n {otpIncorrect && (\n \n )}\n
\n setPassword(e.currentTarget.value)}\n />\n
\n
\n \n \n
\n
\n )}\n
\n );\n}\n","import { useState } from \"react\";\n\nimport { Button } from \"../base/Button\";\nimport { Modal } from \"../../layouts/Modal\";\nimport { TextField } from \"../base/TextField\";\n\nexport interface ConfirmDeleteProps {\n open: boolean;\n onCancel: () => void;\n onConfirm: (password?: string) => void;\n}\n\nexport function ConfirmPassword({\n open,\n onCancel,\n onConfirm,\n}: ConfirmDeleteProps) {\n const [password, setPassword] = useState();\n\n const handleClose = () => {\n setTimeout(() => setPassword(undefined), 200);\n };\n\n const handleConfirm = (password?: string) => {\n onConfirm(password);\n handleClose();\n };\n\n const handleCancel = () => {\n onCancel();\n handleClose();\n };\n\n return (\n \n
\n setPassword(e.currentTarget.value)}\n type=\"password\"\n value={password}\n />\n
\n
\n \n \n
\n \n );\n}\n","import { useEffect, useState } from \"react\";\nimport { MFARecoveryCodesResponse } from \"../../../types/responses/mfa/MFARecoveryCodesResponse\";\nimport useApiHelper from \"../../../hooks/useApiHelper\";\nimport { authAPIURL } from \"../../../config\";\nimport { SectionLoading } from \"../../shared/SectionLoading\";\nimport { Alert } from \"../../base/Alert\";\nimport { Modal, ModalControlProps } from \"../../../layouts/Modal\";\nimport { Button } from \"../../base/Button\";\nimport { ConfirmPassword } from \"../../shared/ConfirmPassword\";\nimport { useNotification } from \"../../../hooks/useNotifications\";\nimport { MFARegenerateRequest } from \"../../../types/requests/mfa/MFARegenerateRequest\";\nimport { MFARegenerateResponse } from \"./../../../types/responses/mfa/MFARegenerateResponse\";\n\nexport function MFARecoveryCodes({ open, onClose }: ModalControlProps) {\n const { get, post } = useApiHelper({\n apiUrl: authAPIURL,\n withCredentials: true,\n });\n const addNotification = useNotification();\n const [requirePasswordOpen, setRequirePasswordOpen] = useState(false);\n const [loading, setLoading] = useState(true);\n const [recoveryCodes, setRecoveryCodes] = useState();\n const [error, setError] = useState(false);\n\n const handleCopyCodes = async () =>\n await navigator.clipboard.writeText(recoveryCodes!.join(\"\\n\"));\n\n const handleDownloadCodes = () => {\n var element = document.createElement(\"a\");\n element.setAttribute(\n \"href\",\n \"data:text/plain;charset=utf-8,\" +\n encodeURIComponent(recoveryCodes!.join(\"\\n\")),\n );\n element.setAttribute(\"download\", \"planet-devices-recovery-codes.txt\");\n\n element.style.display = \"none\";\n document.body.appendChild(element);\n\n element.click();\n\n document.body.removeChild(element);\n };\n\n const handleRegenerate = async (password?: string) => {\n setRequirePasswordOpen(false);\n setLoading(true);\n\n try {\n const regenerateResponse = await post<\n MFARegenerateRequest,\n MFARegenerateResponse\n >(\"/v1/mfa/recover/regenerate\", { password });\n\n if (regenerateResponse.status === 200) {\n onClose(false);\n addNotification(\n \"success\",\n regenerateResponse.data.message ?? \"MFA Recovery codes regenerated\",\n );\n }\n } catch (e) {\n addNotification(\"error\", \"Password incorrect\");\n } finally {\n onClose(false);\n setLoading(false);\n }\n };\n\n const getRecoveryCodes = async () => {\n try {\n const codesResponse =\n await get(\"/v1/mfa/recover\");\n\n if (codesResponse.status === 200) {\n setRecoveryCodes(codesResponse.data.codes);\n } else {\n throw Error(\"Error getting MFA details\");\n }\n } catch {\n setError(true);\n } finally {\n setLoading(false);\n }\n };\n\n useEffect(() => {\n if (open) {\n getRecoveryCodes();\n }\n }, [open]);\n\n return (\n <>\n setRequirePasswordOpen(false)}\n />\n \n {loading ? (\n \n ) : error ? (\n
\n \n
\n ) : (\n
\n

\n Please take a copy of these codes and keep them safe, they will\n allow you to gain access to your account in the event of an\n authenticator not being available\n

\n
\n {recoveryCodes?.map((code) => (\n
\n {code}\n
\n ))}\n
\n
\n \n
\n
\n \n
\n \n \n
\n
\n
\n )}\n
\n \n );\n}\n","import { useState } from \"react\";\n\nimport { Button } from \"../base/Button\";\nimport useUser from \"../../data/user/useUser\";\nimport { MFAEnable } from \"./Security/MFASetup\";\nimport { MFADisable } from \"./Security/MFADisable\";\nimport { SectionLoading } from \"../shared/SectionLoading\";\nimport { MFARecoveryCodes } from \"./Security/MFARecoveryCodes\";\n\nexport function SecurityTab() {\n const { user } = useUser();\n const [mfaEnableOpen, setMfaEnableOpen] = useState(false);\n const [mfaDisableOpen, setMfaDisableOpen] = useState(false);\n const [mfaCodesOpen, setMfaCodesOpen] = useState(false);\n\n return (\n <>\n <>\n setMfaEnableOpen(false)}\n />\n setMfaDisableOpen(false)}\n />\n setMfaCodesOpen(false)}\n />\n \n
\n
\n

\n Security\n

\n

\n Manage multi-factor authentication.\n

\n {user.isLoading ? (\n \n ) : (\n
\n
\n
\n Multi-factor authentication\n
\n
\n
\n \n {user.data?.mfaEnabled ? \"Enabled\" : \"Disabled\"}\n \n {user.data?.mfaEnabled && (\n setMfaCodesOpen(true)}\n size=\"sm\"\n className=\"font-semibold\"\n >\n Recovery Codes\n \n )}\n
\n setMfaDisableOpen(true)\n : () => setMfaEnableOpen(true)\n }\n size=\"sm\"\n className=\"font-semibold\"\n >\n {user.data?.mfaEnabled ? \"Disable\" : \"Enable\"}\n \n
\n
\n {/*
\n
\n Password\n
\n
\n
\n \n
\n
*/}\n
\n )}\n
\n
\n \n );\n}\n","import { useRef } from \"react\";\n\n// Saves incoming handler to the ref in order to avoid \"useCallback hell\"\nexport function useEventCallback(handler?: (value: T) => void): (value: T) => void {\n const callbackRef = useRef(handler);\n const fn = useRef((value: T) => {\n callbackRef.current && callbackRef.current(value);\n });\n callbackRef.current = handler;\n\n return fn.current;\n}\n","// Clamps a value between an upper and lower bound.\n// We use ternary operators because it makes the minified code\n// 2 times shorter then `Math.min(Math.max(a,b),c)`\nexport const clamp = (number: number, min = 0, max = 1): number => {\n return number > max ? max : number < min ? min : number;\n};\n","import React, { useRef, useMemo, useEffect } from \"react\";\n\nimport { useEventCallback } from \"../../hooks/useEventCallback\";\nimport { clamp } from \"../../utils/clamp\";\n\nexport interface Interaction {\n left: number;\n top: number;\n}\n\n// Check if an event was triggered by touch\nconst isTouch = (event: MouseEvent | TouchEvent): event is TouchEvent => \"touches\" in event;\n\n// Finds a proper touch point by its identifier\nconst getTouchPoint = (touches: TouchList, touchId: null | number): Touch => {\n for (let i = 0; i < touches.length; i++) {\n if (touches[i].identifier === touchId) return touches[i];\n }\n return touches[0];\n};\n\n// Finds the proper window object to fix iframe embedding issues\nconst getParentWindow = (node?: HTMLDivElement | null): Window => {\n return (node && node.ownerDocument.defaultView) || self;\n};\n\n// Returns a relative position of the pointer inside the node's bounding box\nconst getRelativePosition = (\n node: HTMLDivElement,\n event: MouseEvent | TouchEvent,\n touchId: null | number\n): Interaction => {\n const rect = node.getBoundingClientRect();\n\n // Get user's pointer position from `touches` array if it's a `TouchEvent`\n const pointer = isTouch(event) ? getTouchPoint(event.touches, touchId) : (event as MouseEvent);\n\n return {\n left: clamp((pointer.pageX - (rect.left + getParentWindow(node).pageXOffset)) / rect.width),\n top: clamp((pointer.pageY - (rect.top + getParentWindow(node).pageYOffset)) / rect.height),\n };\n};\n\n// Browsers introduced an intervention, making touch events passive by default.\n// This workaround removes `preventDefault` call from the touch handlers.\n// https://github.com/facebook/react/issues/19651\nconst preventDefaultMove = (event: MouseEvent | TouchEvent): void => {\n !isTouch(event) && event.preventDefault();\n};\n\n// Prevent mobile browsers from handling mouse events (conflicting with touch ones).\n// If we detected a touch interaction before, we prefer reacting to touch events only.\nconst isInvalid = (event: MouseEvent | TouchEvent, hasTouch: boolean): boolean => {\n return hasTouch && !isTouch(event);\n};\n\ninterface Props {\n onMove: (interaction: Interaction) => void;\n onKey: (offset: Interaction) => void;\n children: React.ReactNode;\n}\n\nconst InteractiveBase = ({ onMove, onKey, ...rest }: Props) => {\n const container = useRef(null);\n const onMoveCallback = useEventCallback(onMove);\n const onKeyCallback = useEventCallback(onKey);\n const touchId = useRef(null);\n const hasTouch = useRef(false);\n\n const [handleMoveStart, handleKeyDown, toggleDocumentEvents] = useMemo(() => {\n const handleMoveStart = ({ nativeEvent }: React.MouseEvent | React.TouchEvent) => {\n const el = container.current;\n if (!el) return;\n\n // Prevent text selection\n preventDefaultMove(nativeEvent);\n\n if (isInvalid(nativeEvent, hasTouch.current) || !el) return;\n\n if (isTouch(nativeEvent)) {\n hasTouch.current = true;\n const changedTouches = nativeEvent.changedTouches || [];\n if (changedTouches.length) touchId.current = changedTouches[0].identifier;\n }\n\n el.focus();\n onMoveCallback(getRelativePosition(el, nativeEvent, touchId.current));\n toggleDocumentEvents(true);\n };\n\n const handleMove = (event: MouseEvent | TouchEvent) => {\n // Prevent text selection\n preventDefaultMove(event);\n\n // If user moves the pointer outside of the window or iframe bounds and release it there,\n // `mouseup`/`touchend` won't be fired. In order to stop the picker from following the cursor\n // after the user has moved the mouse/finger back to the document, we check `event.buttons`\n // and `event.touches`. It allows us to detect that the user is just moving his pointer\n // without pressing it down\n const isDown = isTouch(event) ? event.touches.length > 0 : event.buttons > 0;\n\n if (isDown && container.current) {\n onMoveCallback(getRelativePosition(container.current, event, touchId.current));\n } else {\n toggleDocumentEvents(false);\n }\n };\n\n const handleMoveEnd = () => toggleDocumentEvents(false);\n\n const handleKeyDown = (event: React.KeyboardEvent) => {\n const keyCode = event.which || event.keyCode;\n\n // Ignore all keys except arrow ones\n if (keyCode < 37 || keyCode > 40) return;\n // Do not scroll page by arrow keys when document is focused on the element\n event.preventDefault();\n // Send relative offset to the parent component.\n // We use codes (37←, 38↑, 39→, 40↓) instead of keys ('ArrowRight', 'ArrowDown', etc)\n // to reduce the size of the library\n onKeyCallback({\n left: keyCode === 39 ? 0.05 : keyCode === 37 ? -0.05 : 0,\n top: keyCode === 40 ? 0.05 : keyCode === 38 ? -0.05 : 0,\n });\n };\n\n function toggleDocumentEvents(state?: boolean) {\n const touch = hasTouch.current;\n const el = container.current;\n const parentWindow = getParentWindow(el);\n\n // Add or remove additional pointer event listeners\n const toggleEvent = state ? parentWindow.addEventListener : parentWindow.removeEventListener;\n toggleEvent(touch ? \"touchmove\" : \"mousemove\", handleMove);\n toggleEvent(touch ? \"touchend\" : \"mouseup\", handleMoveEnd);\n }\n\n return [handleMoveStart, handleKeyDown, toggleDocumentEvents];\n }, [onKeyCallback, onMoveCallback]);\n\n // Remove window event listeners before unmounting\n useEffect(() => toggleDocumentEvents, [toggleDocumentEvents]);\n\n return (\n \n );\n};\n\nexport const Interactive = React.memo(InteractiveBase);\n","export const formatClassName = (names: unknown[]): string => names.filter(Boolean).join(\" \");\n","import React from \"react\";\nimport { formatClassName } from \"../../utils/format\";\n\ninterface Props {\n className?: string;\n top?: number;\n left: number;\n color: string;\n}\n\nexport const Pointer = ({ className, color, left, top = 0.5 }: Props): JSX.Element => {\n const nodeClassName = formatClassName([\"react-colorful__pointer\", className]);\n\n const style = {\n top: `${top * 100}%`,\n left: `${left * 100}%`,\n };\n\n return (\n
\n
\n
\n );\n};\n","export const round = (number: number, digits = 0, base = Math.pow(10, digits)): number => {\n return Math.round(base * number) / base;\n};\n","import { round } from \"./round\";\nimport { RgbaColor, RgbColor, HslaColor, HslColor, HsvaColor, HsvColor } from \"../types\";\n\n/**\n * Valid CSS units.\n * https://developer.mozilla.org/en-US/docs/Web/CSS/angle\n */\nconst angleUnits: Record = {\n grad: 360 / 400,\n turn: 360,\n rad: 360 / (Math.PI * 2),\n};\n\nexport const hexToHsva = (hex: string): HsvaColor => rgbaToHsva(hexToRgba(hex));\n\nexport const hexToRgba = (hex: string): RgbaColor => {\n if (hex[0] === \"#\") hex = hex.substring(1);\n\n if (hex.length < 6) {\n return {\n r: parseInt(hex[0] + hex[0], 16),\n g: parseInt(hex[1] + hex[1], 16),\n b: parseInt(hex[2] + hex[2], 16),\n a: hex.length === 4 ? round(parseInt(hex[3] + hex[3], 16) / 255, 2) : 1,\n };\n }\n\n return {\n r: parseInt(hex.substring(0, 2), 16),\n g: parseInt(hex.substring(2, 4), 16),\n b: parseInt(hex.substring(4, 6), 16),\n a: hex.length === 8 ? round(parseInt(hex.substring(6, 8), 16) / 255, 2) : 1,\n };\n};\n\nexport const parseHue = (value: string, unit = \"deg\"): number => {\n return Number(value) * (angleUnits[unit] || 1);\n};\n\nexport const hslaStringToHsva = (hslString: string): HsvaColor => {\n const matcher = /hsla?\\(?\\s*(-?\\d*\\.?\\d+)(deg|rad|grad|turn)?[,\\s]+(-?\\d*\\.?\\d+)%?[,\\s]+(-?\\d*\\.?\\d+)%?,?\\s*[/\\s]*(-?\\d*\\.?\\d+)?(%)?\\s*\\)?/i;\n const match = matcher.exec(hslString);\n\n if (!match) return { h: 0, s: 0, v: 0, a: 1 };\n\n return hslaToHsva({\n h: parseHue(match[1], match[2]),\n s: Number(match[3]),\n l: Number(match[4]),\n a: match[5] === undefined ? 1 : Number(match[5]) / (match[6] ? 100 : 1),\n });\n};\n\nexport const hslStringToHsva = hslaStringToHsva;\n\nexport const hslaToHsva = ({ h, s, l, a }: HslaColor): HsvaColor => {\n s *= (l < 50 ? l : 100 - l) / 100;\n\n return {\n h: h,\n s: s > 0 ? ((2 * s) / (l + s)) * 100 : 0,\n v: l + s,\n a,\n };\n};\n\nexport const hsvaToHex = (hsva: HsvaColor): string => rgbaToHex(hsvaToRgba(hsva));\n\nexport const hsvaToHsla = ({ h, s, v, a }: HsvaColor): HslaColor => {\n const hh = ((200 - s) * v) / 100;\n\n return {\n h: round(h),\n s: round(hh > 0 && hh < 200 ? ((s * v) / 100 / (hh <= 100 ? hh : 200 - hh)) * 100 : 0),\n l: round(hh / 2),\n a: round(a, 2),\n };\n};\n\nexport const hsvaToHslString = (hsva: HsvaColor): string => {\n const { h, s, l } = hsvaToHsla(hsva);\n return `hsl(${h}, ${s}%, ${l}%)`;\n};\n\nexport const hsvaToHsvString = (hsva: HsvaColor): string => {\n const { h, s, v } = roundHsva(hsva);\n return `hsv(${h}, ${s}%, ${v}%)`;\n};\n\nexport const hsvaToHsvaString = (hsva: HsvaColor): string => {\n const { h, s, v, a } = roundHsva(hsva);\n return `hsva(${h}, ${s}%, ${v}%, ${a})`;\n};\n\nexport const hsvaToHslaString = (hsva: HsvaColor): string => {\n const { h, s, l, a } = hsvaToHsla(hsva);\n return `hsla(${h}, ${s}%, ${l}%, ${a})`;\n};\n\nexport const hsvaToRgba = ({ h, s, v, a }: HsvaColor): RgbaColor => {\n h = (h / 360) * 6;\n s = s / 100;\n v = v / 100;\n\n const hh = Math.floor(h),\n b = v * (1 - s),\n c = v * (1 - (h - hh) * s),\n d = v * (1 - (1 - h + hh) * s),\n module = hh % 6;\n\n return {\n r: round([v, c, b, b, d, v][module] * 255),\n g: round([d, v, v, c, b, b][module] * 255),\n b: round([b, b, d, v, v, c][module] * 255),\n a: round(a, 2),\n };\n};\n\nexport const hsvaToRgbString = (hsva: HsvaColor): string => {\n const { r, g, b } = hsvaToRgba(hsva);\n return `rgb(${r}, ${g}, ${b})`;\n};\n\nexport const hsvaToRgbaString = (hsva: HsvaColor): string => {\n const { r, g, b, a } = hsvaToRgba(hsva);\n return `rgba(${r}, ${g}, ${b}, ${a})`;\n};\n\nexport const hsvaStringToHsva = (hsvString: string): HsvaColor => {\n const matcher = /hsva?\\(?\\s*(-?\\d*\\.?\\d+)(deg|rad|grad|turn)?[,\\s]+(-?\\d*\\.?\\d+)%?[,\\s]+(-?\\d*\\.?\\d+)%?,?\\s*[/\\s]*(-?\\d*\\.?\\d+)?(%)?\\s*\\)?/i;\n const match = matcher.exec(hsvString);\n\n if (!match) return { h: 0, s: 0, v: 0, a: 1 };\n\n return roundHsva({\n h: parseHue(match[1], match[2]),\n s: Number(match[3]),\n v: Number(match[4]),\n a: match[5] === undefined ? 1 : Number(match[5]) / (match[6] ? 100 : 1),\n });\n};\n\nexport const hsvStringToHsva = hsvaStringToHsva;\n\nexport const rgbaStringToHsva = (rgbaString: string): HsvaColor => {\n const matcher = /rgba?\\(?\\s*(-?\\d*\\.?\\d+)(%)?[,\\s]+(-?\\d*\\.?\\d+)(%)?[,\\s]+(-?\\d*\\.?\\d+)(%)?,?\\s*[/\\s]*(-?\\d*\\.?\\d+)?(%)?\\s*\\)?/i;\n const match = matcher.exec(rgbaString);\n\n if (!match) return { h: 0, s: 0, v: 0, a: 1 };\n\n return rgbaToHsva({\n r: Number(match[1]) / (match[2] ? 100 / 255 : 1),\n g: Number(match[3]) / (match[4] ? 100 / 255 : 1),\n b: Number(match[5]) / (match[6] ? 100 / 255 : 1),\n a: match[7] === undefined ? 1 : Number(match[7]) / (match[8] ? 100 : 1),\n });\n};\n\nexport const rgbStringToHsva = rgbaStringToHsva;\n\nconst format = (number: number) => {\n const hex = number.toString(16);\n return hex.length < 2 ? \"0\" + hex : hex;\n};\n\nexport const rgbaToHex = ({ r, g, b, a }: RgbaColor): string => {\n const alphaHex = a < 1 ? format(round(a * 255)) : \"\";\n return \"#\" + format(r) + format(g) + format(b) + alphaHex;\n};\n\nexport const rgbaToHsva = ({ r, g, b, a }: RgbaColor): HsvaColor => {\n const max = Math.max(r, g, b);\n const delta = max - Math.min(r, g, b);\n\n // prettier-ignore\n const hh = delta\n ? max === r\n ? (g - b) / delta\n : max === g\n ? 2 + (b - r) / delta\n : 4 + (r - g) / delta\n : 0;\n\n return {\n h: round(60 * (hh < 0 ? hh + 6 : hh)),\n s: round(max ? (delta / max) * 100 : 0),\n v: round((max / 255) * 100),\n a,\n };\n};\n\nexport const roundHsva = (hsva: HsvaColor): HsvaColor => ({\n h: round(hsva.h),\n s: round(hsva.s),\n v: round(hsva.v),\n a: round(hsva.a, 2),\n});\n\nexport const rgbaToRgb = ({ r, g, b }: RgbaColor): RgbColor => ({ r, g, b });\n\nexport const hslaToHsl = ({ h, s, l }: HslaColor): HslColor => ({ h, s, l });\n\nexport const hsvaToHsv = (hsva: HsvaColor): HsvColor => {\n const { h, s, v } = roundHsva(hsva);\n return { h, s, v };\n};\n","import React from \"react\";\n\nimport { Interactive, Interaction } from \"./Interactive\";\nimport { Pointer } from \"./Pointer\";\n\nimport { hsvaToHslString } from \"../../utils/convert\";\nimport { formatClassName } from \"../../utils/format\";\nimport { clamp } from \"../../utils/clamp\";\nimport { round } from \"../../utils/round\";\n\ninterface Props {\n className?: string;\n hue: number;\n onChange: (newHue: { h: number }) => void;\n}\n\nconst HueBase = ({ className, hue, onChange }: Props) => {\n const handleMove = (interaction: Interaction) => {\n onChange({ h: 360 * interaction.left });\n };\n\n const handleKey = (offset: Interaction) => {\n // Hue measured in degrees of the color circle ranging from 0 to 360\n onChange({\n h: clamp(hue + offset.left * 360, 0, 360),\n });\n };\n\n const nodeClassName = formatClassName([\"react-colorful__hue\", className]);\n\n return (\n
\n \n \n \n
\n );\n};\n\nexport const Hue = React.memo(HueBase);\n","import React from \"react\";\nimport { Interactive, Interaction } from \"./Interactive\";\nimport { Pointer } from \"./Pointer\";\nimport { HsvaColor } from \"../../types\";\nimport { hsvaToHslString } from \"../../utils/convert\";\nimport { clamp } from \"../../utils/clamp\";\nimport { round } from \"../../utils/round\";\n\ninterface Props {\n hsva: HsvaColor;\n onChange: (newColor: { s: number; v: number }) => void;\n}\n\nconst SaturationBase = ({ hsva, onChange }: Props) => {\n const handleMove = (interaction: Interaction) => {\n onChange({\n s: interaction.left * 100,\n v: 100 - interaction.top * 100,\n });\n };\n\n const handleKey = (offset: Interaction) => {\n // Saturation and brightness always fit into [0, 100] range\n onChange({\n s: clamp(hsva.s + offset.left * 100, 0, 100),\n v: clamp(hsva.v - offset.top * 100, 0, 100),\n });\n };\n\n const containerStyle = {\n backgroundColor: hsvaToHslString({ h: hsva.h, s: 100, v: 100, a: 1 }),\n };\n\n return (\n
\n \n \n \n
\n );\n};\n\nexport const Saturation = React.memo(SaturationBase);\n","import { hexToRgba } from \"./convert\";\nimport { ObjectColor } from \"../types\";\n\nexport const equalColorObjects = (first: ObjectColor, second: ObjectColor): boolean => {\n if (first === second) return true;\n\n for (const prop in first) {\n // The following allows for a type-safe calling of this function (first & second have to be HSL, HSV, or RGB)\n // with type-unsafe iterating over object keys. TS does not allow this without an index (`[key: string]: number`)\n // on an object to define how iteration is normally done. To ensure extra keys are not allowed on our types,\n // we must cast our object to unknown (as RGB demands `r` be a key, while `Record` does not care if\n // there is or not), and then as a type TS can iterate over.\n if (\n ((first as unknown) as Record)[prop] !==\n ((second as unknown) as Record)[prop]\n )\n return false;\n }\n\n return true;\n};\n\nexport const equalColorString = (first: string, second: string): boolean => {\n return first.replace(/\\s/g, \"\") === second.replace(/\\s/g, \"\");\n};\n\nexport const equalHex = (first: string, second: string): boolean => {\n if (first.toLowerCase() === second.toLowerCase()) return true;\n\n // To compare colors like `#FFF` and `ffffff` we convert them into RGB objects\n return equalColorObjects(hexToRgba(first), hexToRgba(second));\n};\n","import { useState, useEffect, useCallback, useRef } from \"react\";\nimport { ColorModel, AnyColor, HsvaColor } from \"../types\";\nimport { equalColorObjects } from \"../utils/compare\";\nimport { useEventCallback } from \"./useEventCallback\";\n\nexport function useColorManipulation(\n colorModel: ColorModel,\n color: T,\n onChange?: (color: T) => void\n): [HsvaColor, (color: Partial) => void] {\n // Save onChange callback in the ref for avoiding \"useCallback hell\"\n const onChangeCallback = useEventCallback(onChange);\n\n // No matter which color model is used (HEX, RGB(A) or HSL(A)),\n // all internal calculations are based on HSVA model\n const [hsva, updateHsva] = useState(() => colorModel.toHsva(color));\n\n // By using this ref we're able to prevent extra updates\n // and the effects recursion during the color conversion\n const cache = useRef({ color, hsva });\n\n // Update local HSVA-value if `color` property value is changed,\n // but only if that's not the same color that we just sent to the parent\n useEffect(() => {\n if (!colorModel.equal(color, cache.current.color)) {\n const newHsva = colorModel.toHsva(color);\n cache.current = { hsva: newHsva, color };\n updateHsva(newHsva);\n }\n }, [color, colorModel]);\n\n // Trigger `onChange` callback only if an updated color is different from cached one;\n // save the new color to the ref to prevent unnecessary updates\n useEffect(() => {\n let newColor;\n if (\n !equalColorObjects(hsva, cache.current.hsva) &&\n !colorModel.equal((newColor = colorModel.fromHsva(hsva)), cache.current.color)\n ) {\n cache.current = { hsva, color: newColor };\n onChangeCallback(newColor);\n }\n }, [hsva, colorModel, onChangeCallback]);\n\n // Merge the current HSVA color object with updated params.\n // For example, when a child component sends `h` or `s` only\n const handleChange = useCallback((params: Partial) => {\n updateHsva((current) => Object.assign({}, current, params));\n }, []);\n\n return [hsva, handleChange];\n}\n","declare const __webpack_nonce__: string | undefined;\nlet nonce: string | undefined;\n\n/**\n * Returns a nonce hash included by Webpack or the one defined manually by developer.\n * https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce\n * https://webpack.js.org/guides/csp/\n */\nexport const getNonce = (): string | undefined => {\n if (nonce) return nonce;\n if (typeof __webpack_nonce__ !== \"undefined\") return __webpack_nonce__;\n return undefined;\n};\n\n/**\n * Signs the style tag with a base64-encoded string (nonce) to conforms to Content Security Policies.\n * This function has to be invoked before any picker is rendered if you aren't using Webpack for CSP.\n */\nexport const setNonce = (hash: string): void => {\n nonce = hash;\n};\n","import { useLayoutEffect, useEffect } from \"react\";\n\n// React currently throws a warning when using useLayoutEffect on the server.\n// To get around it, we can conditionally useEffect on the server (no-op) and\n// useLayoutEffect in the browser.\nexport const useIsomorphicLayoutEffect =\n typeof window !== \"undefined\" ? useLayoutEffect : useEffect;\n","import { RefObject } from \"react\";\n\nimport { useIsomorphicLayoutEffect } from \"./useIsomorphicLayoutEffect\";\nimport { getNonce } from \"../utils/nonce\";\n\n// Bundler is configured to load this as a processed minified CSS-string\nimport styles from \"../css/styles.css\";\n\nconst styleElementMap: Map = new Map();\n\n/**\n * Injects CSS code into the document's \n */\nexport const useStyleSheet = (nodeRef: RefObject): void => {\n useIsomorphicLayoutEffect(() => {\n const parentDocument = nodeRef.current ? nodeRef.current.ownerDocument : document;\n\n if (typeof parentDocument !== \"undefined\" && !styleElementMap.has(parentDocument)) {\n const styleElement = parentDocument.createElement(\"style\");\n styleElement.innerHTML = styles;\n styleElementMap.set(parentDocument, styleElement);\n\n // Conform to CSP rules by setting `nonce` attribute to the inline styles\n const nonce = getNonce();\n if (nonce) styleElement.setAttribute(\"nonce\", nonce);\n\n parentDocument.head.appendChild(styleElement);\n }\n }, []);\n};\n","import React, { useRef } from \"react\";\n\nimport { Hue } from \"./Hue\";\nimport { Saturation } from \"./Saturation\";\n\nimport { ColorModel, ColorPickerBaseProps, AnyColor } from \"../../types\";\nimport { useColorManipulation } from \"../../hooks/useColorManipulation\";\nimport { useStyleSheet } from \"../../hooks/useStyleSheet\";\nimport { formatClassName } from \"../../utils/format\";\n\ninterface Props extends Partial> {\n colorModel: ColorModel;\n}\n\nexport const ColorPicker = ({\n className,\n colorModel,\n color = colorModel.defaultColor,\n onChange,\n ...rest\n}: Props): JSX.Element => {\n const nodeRef = useRef(null);\n useStyleSheet(nodeRef);\n\n const [hsva, updateHsva] = useColorManipulation(colorModel, color, onChange);\n\n const nodeClassName = formatClassName([\"react-colorful\", className]);\n\n return (\n
\n \n \n
\n );\n};\n","import React from \"react\";\n\nimport { ColorPicker } from \"./common/ColorPicker\";\nimport { ColorModel, ColorPickerBaseProps, RgbColor } from \"../types\";\nimport { equalColorObjects } from \"../utils/compare\";\nimport { rgbaToHsva, hsvaToRgba, rgbaToRgb } from \"../utils/convert\";\n\nconst colorModel: ColorModel = {\n defaultColor: { r: 0, g: 0, b: 0 },\n toHsva: ({ r, g, b }) => rgbaToHsva({ r, g, b, a: 1 }),\n fromHsva: (hsva) => rgbaToRgb(hsvaToRgba(hsva)),\n equal: equalColorObjects,\n};\n\nexport const RgbColorPicker = (props: Partial>): JSX.Element => (\n \n);\n","export default function RGBtoHEX(\n r: number | string,\n g: number | string,\n b: number | string,\n): string {\n const componentToHex = (c: number) => {\n const hex = c.toString(16);\n return hex.length === 1 ? \"0\" + hex : hex;\n };\n\n const hexR = componentToHex(parseInt(r as string));\n const hexG = componentToHex(parseInt(g as string));\n const hexB = componentToHex(parseInt(b as string));\n\n return \"#\" + hexR + hexG + hexB;\n}\n","export default function HEXtoRGB(hex: string) {\n const strippedHex = hex.replace(\"#\", \"\");\n const bigint = parseInt(strippedHex, 16);\n const r = (bigint >> 16) & 255;\n const g = (bigint >> 8) & 255;\n const b = bigint & 255;\n\n return { r, g, b };\n}\n","import { useMutation } from \"react-query\";\n\nimport useApiHelper from \"../../hooks/useApiHelper\";\nimport { IBranding } from \"../../types/Branding/IBranding\";\nimport { useDefaultMutateResponseHandlers } from \"../../hooks/useDefaultMutateResponeHandlers\";\n\nexport function useBrandingMutations() {\n const { put } = useApiHelper();\n const {\n handleSuccess: handleBrandingSuccess,\n handleError: handleBrandingError,\n } = useDefaultMutateResponseHandlers(\"Branding\");\n const { handleSuccess: handleLogoSuccess, handleError: handleLogoError } =\n useDefaultMutateResponseHandlers(\"Logo\");\n\n const updateBranding = useMutation({\n mutationFn: (branding: Omit) =>\n put(\"/v1/brand\", branding),\n onError: (error) => handleBrandingError(error, \"update\"),\n onSuccess: (data) => handleBrandingSuccess(data, \"update\"),\n });\n\n const updateLogo = useMutation({\n mutationFn: (logo: FormData) =>\n put(\"/v1/brand/logo\", logo, {\n headers: { \"Content-Type\": \"multipart/form-data\" },\n }),\n onError: (error) => handleLogoError(error, \"update\"),\n onSuccess: (data) => handleLogoSuccess(data, \"update\"),\n });\n\n return {\n updateBranding,\n updateLogo,\n };\n}\n","import g, { PureComponent as E, createRef as M } from \"react\";\nconst _ = {\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n unit: \"px\"\n};\nfunction R(e, n, i) {\n return Math.min(Math.max(e, n), i);\n}\nfunction Y(e, n) {\n return e.width === n.width && e.height === n.height && e.x === n.x && e.y === n.y && e.unit === n.unit;\n}\nfunction k(e, n, i, r) {\n const t = C(e, i, r);\n return e.width && (t.height = t.width / n), e.height && (t.width = t.height * n), t.y + t.height > r && (t.height = r - t.y, t.width = t.height * n), t.x + t.width > i && (t.width = i - t.x, t.height = t.width / n), e.unit === \"%\" ? y(t, i, r) : t;\n}\nfunction H(e, n, i) {\n const r = C(e, n, i);\n return r.x = (n - r.width) / 2, r.y = (i - r.height) / 2, e.unit === \"%\" ? y(r, n, i) : r;\n}\nfunction y(e, n, i) {\n return e.unit === \"%\" ? { ..._, ...e, unit: \"%\" } : {\n unit: \"%\",\n x: e.x ? e.x / n * 100 : 0,\n y: e.y ? e.y / i * 100 : 0,\n width: e.width ? e.width / n * 100 : 0,\n height: e.height ? e.height / i * 100 : 0\n };\n}\nfunction C(e, n, i) {\n return e.unit ? e.unit === \"px\" ? { ..._, ...e, unit: \"px\" } : {\n unit: \"px\",\n x: e.x ? e.x * n / 100 : 0,\n y: e.y ? e.y * i / 100 : 0,\n width: e.width ? e.width * n / 100 : 0,\n height: e.height ? e.height * i / 100 : 0\n } : { ..._, ...e, unit: \"px\" };\n}\nfunction P(e, n, i, r, t, s = 0, w = 0, a = r, l = t) {\n const o = { ...e };\n let d = Math.min(s, r), c = Math.min(w, t), h = Math.min(a, r), p = Math.min(l, t);\n n && (n > 1 ? (d = w ? w * n : d, c = d / n, h = a * n) : (c = s ? s / n : c, d = c * n, p = l / n)), o.y < 0 && (o.height = Math.max(o.height + o.y, c), o.y = 0), o.x < 0 && (o.width = Math.max(o.width + o.x, d), o.x = 0);\n const m = r - (o.x + o.width);\n m < 0 && (o.x = Math.min(o.x, r - d), o.width += m);\n const b = t - (o.y + o.height);\n if (b < 0 && (o.y = Math.min(o.y, t - c), o.height += b), o.width < d && ((i === \"sw\" || i == \"nw\") && (o.x -= d - o.width), o.width = d), o.height < c && ((i === \"nw\" || i == \"ne\") && (o.y -= c - o.height), o.height = c), o.width > h && ((i === \"sw\" || i == \"nw\") && (o.x -= h - o.width), o.width = h), o.height > p && ((i === \"nw\" || i == \"ne\") && (o.y -= p - o.height), o.height = p), n) {\n const D = o.width / o.height;\n if (D < n) {\n const x = Math.max(o.width / n, c);\n (i === \"nw\" || i == \"ne\") && (o.y -= x - o.height), o.height = x;\n } else if (D > n) {\n const x = Math.max(o.height * n, d);\n (i === \"sw\" || i == \"nw\") && (o.x -= x - o.width), o.width = x;\n }\n }\n return o;\n}\nfunction S(e, n, i, r) {\n const t = { ...e };\n return n === \"ArrowLeft\" ? r === \"nw\" ? (t.x -= i, t.y -= i, t.width += i, t.height += i) : r === \"w\" ? (t.x -= i, t.width += i) : r === \"sw\" ? (t.x -= i, t.width += i, t.height += i) : r === \"ne\" ? (t.y += i, t.width -= i, t.height -= i) : r === \"e\" ? t.width -= i : r === \"se\" && (t.width -= i, t.height -= i) : n === \"ArrowRight\" && (r === \"nw\" ? (t.x += i, t.y += i, t.width -= i, t.height -= i) : r === \"w\" ? (t.x += i, t.width -= i) : r === \"sw\" ? (t.x += i, t.width -= i, t.height -= i) : r === \"ne\" ? (t.y -= i, t.width += i, t.height += i) : r === \"e\" ? t.width += i : r === \"se\" && (t.width += i, t.height += i)), n === \"ArrowUp\" ? r === \"nw\" ? (t.x -= i, t.y -= i, t.width += i, t.height += i) : r === \"n\" ? (t.y -= i, t.height += i) : r === \"ne\" ? (t.y -= i, t.width += i, t.height += i) : r === \"sw\" ? (t.x += i, t.width -= i, t.height -= i) : r === \"s\" ? t.height -= i : r === \"se\" && (t.width -= i, t.height -= i) : n === \"ArrowDown\" && (r === \"nw\" ? (t.x += i, t.y += i, t.width -= i, t.height -= i) : r === \"n\" ? (t.y += i, t.height -= i) : r === \"ne\" ? (t.y += i, t.width -= i, t.height -= i) : r === \"sw\" ? (t.x -= i, t.width += i, t.height += i) : r === \"s\" ? t.height += i : r === \"se\" && (t.width += i, t.height += i)), t;\n}\nfunction X(e) {\n var n, i, r = \"\";\n if (typeof e == \"string\" || typeof e == \"number\")\n r += e;\n else if (typeof e == \"object\")\n if (Array.isArray(e))\n for (n = 0; n < e.length; n++)\n e[n] && (i = X(e[n])) && (r && (r += \" \"), r += i);\n else\n for (n in e)\n e[n] && (r && (r += \" \"), r += n);\n return r;\n}\nfunction K() {\n for (var e, n, i = 0, r = \"\"; i < arguments.length; )\n (e = arguments[i++]) && (n = X(e)) && (r && (r += \" \"), r += n);\n return r;\n}\nconst f = { capture: !0, passive: !1 }, u = class extends E {\n constructor() {\n super(...arguments), this.docMoveBound = !1, this.mouseDownOnCrop = !1, this.dragStarted = !1, this.evData = {\n startClientX: 0,\n startClientY: 0,\n startCropX: 0,\n startCropY: 0,\n clientX: 0,\n clientY: 0,\n isResize: !0\n }, this.componentRef = M(), this.mediaRef = M(), this.initChangeCalled = !1, this.state = {\n cropIsActive: !1,\n newCropIsBeingDrawn: !1\n }, this.onCropPointerDown = (e) => {\n const { crop: n, disabled: i } = this.props, r = this.getBox();\n if (!n)\n return;\n const t = C(n, r.width, r.height);\n if (i)\n return;\n e.cancelable && e.preventDefault(), this.bindDocMove(), this.componentRef.current.focus({ preventScroll: !0 });\n const s = e.target.dataset.ord, w = !!s;\n let a = e.clientX, l = e.clientY, o = t.x, d = t.y;\n if (s) {\n const c = e.clientX - r.x, h = e.clientY - r.y;\n let p = 0, m = 0;\n s === \"ne\" || s == \"e\" ? (p = c - (t.x + t.width), m = h - t.y, o = t.x, d = t.y + t.height) : s === \"se\" || s === \"s\" ? (p = c - (t.x + t.width), m = h - (t.y + t.height), o = t.x, d = t.y) : s === \"sw\" || s == \"w\" ? (p = c - t.x, m = h - (t.y + t.height), o = t.x + t.width, d = t.y) : (s === \"nw\" || s == \"n\") && (p = c - t.x, m = h - t.y, o = t.x + t.width, d = t.y + t.height), a = o + r.x + p, l = d + r.y + m;\n }\n this.evData = {\n startClientX: a,\n startClientY: l,\n startCropX: o,\n startCropY: d,\n clientX: e.clientX,\n clientY: e.clientY,\n isResize: w,\n ord: s\n }, this.mouseDownOnCrop = !0, this.setState({ cropIsActive: !0 });\n }, this.onComponentPointerDown = (e) => {\n const { crop: n, disabled: i, locked: r, keepSelection: t, onChange: s } = this.props, w = this.getBox();\n if (i || r || t && n)\n return;\n e.cancelable && e.preventDefault(), this.bindDocMove(), this.componentRef.current.focus({ preventScroll: !0 });\n const a = e.clientX - w.x, l = e.clientY - w.y, o = {\n unit: \"px\",\n x: a,\n y: l,\n width: 0,\n height: 0\n };\n this.evData = {\n startClientX: e.clientX,\n startClientY: e.clientY,\n startCropX: a,\n startCropY: l,\n clientX: e.clientX,\n clientY: e.clientY,\n isResize: !0\n }, this.mouseDownOnCrop = !0, s(C(o, w.width, w.height), y(o, w.width, w.height)), this.setState({ cropIsActive: !0, newCropIsBeingDrawn: !0 });\n }, this.onDocPointerMove = (e) => {\n const { crop: n, disabled: i, onChange: r, onDragStart: t } = this.props, s = this.getBox();\n if (i || !n || !this.mouseDownOnCrop)\n return;\n e.cancelable && e.preventDefault(), this.dragStarted || (this.dragStarted = !0, t && t(e));\n const { evData: w } = this;\n w.clientX = e.clientX, w.clientY = e.clientY;\n let a;\n w.isResize ? a = this.resizeCrop() : a = this.dragCrop(), Y(n, a) || r(\n C(a, s.width, s.height),\n y(a, s.width, s.height)\n );\n }, this.onComponentKeyDown = (e) => {\n const { crop: n, disabled: i, onChange: r, onComplete: t } = this.props, s = this.getBox();\n if (i)\n return;\n const w = e.key;\n let a = !1;\n if (!n)\n return;\n const l = this.makePixelCrop(), d = (navigator.platform.match(\"Mac\") ? e.metaKey : e.ctrlKey) ? u.nudgeStepLarge : e.shiftKey ? u.nudgeStepMedium : u.nudgeStep;\n if (w === \"ArrowLeft\" ? (l.x -= d, a = !0) : w === \"ArrowRight\" ? (l.x += d, a = !0) : w === \"ArrowUp\" ? (l.y -= d, a = !0) : w === \"ArrowDown\" && (l.y += d, a = !0), a) {\n e.cancelable && e.preventDefault(), l.x = R(l.x, 0, s.width - l.width), l.y = R(l.y, 0, s.height - l.height);\n const c = C(l, s.width, s.height), h = y(l, s.width, s.height);\n r(c, h), t && t(c, h);\n }\n }, this.onHandlerKeyDown = (e, n) => {\n const {\n aspect: i = 0,\n crop: r,\n disabled: t,\n minWidth: s = 0,\n minHeight: w = 0,\n maxWidth: a,\n maxHeight: l,\n onChange: o,\n onComplete: d\n } = this.props, c = this.getBox();\n if (t || !r)\n return;\n if (e.key === \"ArrowUp\" || e.key === \"ArrowDown\" || e.key === \"ArrowLeft\" || e.key === \"ArrowRight\")\n e.stopPropagation(), e.preventDefault();\n else\n return;\n const p = (navigator.platform.match(\"Mac\") ? e.metaKey : e.ctrlKey) ? u.nudgeStepLarge : e.shiftKey ? u.nudgeStepMedium : u.nudgeStep, m = C(r, c.width, c.height), b = S(m, e.key, p, n), D = P(\n b,\n i,\n n,\n c.width,\n c.height,\n s,\n w,\n a,\n l\n );\n if (!Y(r, D)) {\n const x = y(D, c.width, c.height);\n o(D, x), d && d(D, x);\n }\n }, this.onDocPointerDone = (e) => {\n const { crop: n, disabled: i, onComplete: r, onDragEnd: t } = this.props, s = this.getBox();\n this.unbindDocMove(), !(i || !n) && this.mouseDownOnCrop && (this.mouseDownOnCrop = !1, this.dragStarted = !1, t && t(e), r && r(C(n, s.width, s.height), y(n, s.width, s.height)), this.setState({ cropIsActive: !1, newCropIsBeingDrawn: !1 }));\n }, this.onDragFocus = (e) => {\n var n;\n (n = this.componentRef.current) == null || n.scrollTo(0, 0);\n };\n }\n get document() {\n return document;\n }\n // We unfortunately get the bounding box every time as x+y changes\n // due to scrolling.\n getBox() {\n const e = this.mediaRef.current;\n if (!e)\n return { x: 0, y: 0, width: 0, height: 0 };\n const { x: n, y: i, width: r, height: t } = e.getBoundingClientRect();\n return { x: n, y: i, width: r, height: t };\n }\n componentDidUpdate(e) {\n const { crop: n, onComplete: i } = this.props;\n if (i && !e.crop && n) {\n const { width: r, height: t } = this.getBox();\n r && t && i(C(n, r, t), y(n, r, t));\n }\n }\n componentWillUnmount() {\n this.resizeObserver && this.resizeObserver.disconnect();\n }\n bindDocMove() {\n this.docMoveBound || (this.document.addEventListener(\"pointermove\", this.onDocPointerMove, f), this.document.addEventListener(\"pointerup\", this.onDocPointerDone, f), this.document.addEventListener(\"pointercancel\", this.onDocPointerDone, f), this.docMoveBound = !0);\n }\n unbindDocMove() {\n this.docMoveBound && (this.document.removeEventListener(\"pointermove\", this.onDocPointerMove, f), this.document.removeEventListener(\"pointerup\", this.onDocPointerDone, f), this.document.removeEventListener(\"pointercancel\", this.onDocPointerDone, f), this.docMoveBound = !1);\n }\n getCropStyle() {\n const { crop: e } = this.props;\n if (e)\n return {\n top: `${e.y}${e.unit}`,\n left: `${e.x}${e.unit}`,\n width: `${e.width}${e.unit}`,\n height: `${e.height}${e.unit}`\n };\n }\n dragCrop() {\n const { evData: e } = this, n = this.getBox(), i = this.makePixelCrop(), r = e.clientX - e.startClientX, t = e.clientY - e.startClientY;\n return i.x = R(e.startCropX + r, 0, n.width - i.width), i.y = R(e.startCropY + t, 0, n.height - i.height), i;\n }\n getPointRegion(e) {\n const { evData: n } = this, i = n.clientX - e.x, t = n.clientY - e.y < n.startCropY;\n return i < n.startCropX ? t ? \"nw\" : \"sw\" : t ? \"ne\" : \"se\";\n }\n resizeCrop() {\n const { evData: e } = this, n = this.getBox(), { aspect: i = 0, minWidth: r = 0, minHeight: t = 0, maxWidth: s, maxHeight: w } = this.props, a = this.getPointRegion(n), l = this.makePixelCrop(), o = e.ord ? e.ord : a, d = e.clientX - e.startClientX, c = e.clientY - e.startClientY, h = {\n unit: \"px\",\n x: 0,\n y: 0,\n width: 0,\n height: 0\n };\n a === \"ne\" ? (h.x = e.startCropX, h.width = d, i ? (h.height = h.width / i, h.y = e.startCropY - h.height) : (h.height = Math.abs(c), h.y = e.startCropY - h.height)) : a === \"se\" ? (h.x = e.startCropX, h.y = e.startCropY, h.width = d, i ? h.height = h.width / i : h.height = c) : a === \"sw\" ? (h.x = e.startCropX + d, h.y = e.startCropY, h.width = Math.abs(d), i ? h.height = h.width / i : h.height = c) : a === \"nw\" && (h.x = e.startCropX + d, h.width = Math.abs(d), i ? (h.height = h.width / i, h.y = e.startCropY - h.height) : (h.height = Math.abs(c), h.y = e.startCropY + c));\n const p = P(\n h,\n i,\n a,\n n.width,\n n.height,\n r,\n t,\n s,\n w\n );\n return i || u.xyOrds.indexOf(o) > -1 ? (l.x = p.x, l.y = p.y, l.width = p.width, l.height = p.height) : u.xOrds.indexOf(o) > -1 ? (l.x = p.x, l.width = p.width) : u.yOrds.indexOf(o) > -1 && (l.y = p.y, l.height = p.height), l;\n }\n createCropSelection() {\n const {\n ariaLabels: e = u.defaultProps.ariaLabels,\n disabled: n,\n locked: i,\n renderSelectionAddon: r,\n ruleOfThirds: t,\n crop: s\n } = this.props, w = this.getCropStyle();\n if (s)\n return /* @__PURE__ */ g.createElement(\n \"div\",\n {\n style: w,\n className: \"ReactCrop__crop-selection\",\n onPointerDown: this.onCropPointerDown,\n \"aria-label\": e.cropArea,\n tabIndex: 0,\n onKeyDown: this.onComponentKeyDown,\n role: \"group\"\n },\n !n && !i && /* @__PURE__ */ g.createElement(\"div\", { className: \"ReactCrop__drag-elements\", onFocus: this.onDragFocus }, /* @__PURE__ */ g.createElement(\"div\", { className: \"ReactCrop__drag-bar ord-n\", \"data-ord\": \"n\" }), /* @__PURE__ */ g.createElement(\"div\", { className: \"ReactCrop__drag-bar ord-e\", \"data-ord\": \"e\" }), /* @__PURE__ */ g.createElement(\"div\", { className: \"ReactCrop__drag-bar ord-s\", \"data-ord\": \"s\" }), /* @__PURE__ */ g.createElement(\"div\", { className: \"ReactCrop__drag-bar ord-w\", \"data-ord\": \"w\" }), /* @__PURE__ */ g.createElement(\n \"div\",\n {\n className: \"ReactCrop__drag-handle ord-nw\",\n \"data-ord\": \"nw\",\n tabIndex: 0,\n \"aria-label\": e.nwDragHandle,\n onKeyDown: (a) => this.onHandlerKeyDown(a, \"nw\"),\n role: \"button\"\n }\n ), /* @__PURE__ */ g.createElement(\n \"div\",\n {\n className: \"ReactCrop__drag-handle ord-n\",\n \"data-ord\": \"n\",\n tabIndex: 0,\n \"aria-label\": e.nDragHandle,\n onKeyDown: (a) => this.onHandlerKeyDown(a, \"n\"),\n role: \"button\"\n }\n ), /* @__PURE__ */ g.createElement(\n \"div\",\n {\n className: \"ReactCrop__drag-handle ord-ne\",\n \"data-ord\": \"ne\",\n tabIndex: 0,\n \"aria-label\": e.neDragHandle,\n onKeyDown: (a) => this.onHandlerKeyDown(a, \"ne\"),\n role: \"button\"\n }\n ), /* @__PURE__ */ g.createElement(\n \"div\",\n {\n className: \"ReactCrop__drag-handle ord-e\",\n \"data-ord\": \"e\",\n tabIndex: 0,\n \"aria-label\": e.eDragHandle,\n onKeyDown: (a) => this.onHandlerKeyDown(a, \"e\"),\n role: \"button\"\n }\n ), /* @__PURE__ */ g.createElement(\n \"div\",\n {\n className: \"ReactCrop__drag-handle ord-se\",\n \"data-ord\": \"se\",\n tabIndex: 0,\n \"aria-label\": e.seDragHandle,\n onKeyDown: (a) => this.onHandlerKeyDown(a, \"se\"),\n role: \"button\"\n }\n ), /* @__PURE__ */ g.createElement(\n \"div\",\n {\n className: \"ReactCrop__drag-handle ord-s\",\n \"data-ord\": \"s\",\n tabIndex: 0,\n \"aria-label\": e.sDragHandle,\n onKeyDown: (a) => this.onHandlerKeyDown(a, \"s\"),\n role: \"button\"\n }\n ), /* @__PURE__ */ g.createElement(\n \"div\",\n {\n className: \"ReactCrop__drag-handle ord-sw\",\n \"data-ord\": \"sw\",\n tabIndex: 0,\n \"aria-label\": e.swDragHandle,\n onKeyDown: (a) => this.onHandlerKeyDown(a, \"sw\"),\n role: \"button\"\n }\n ), /* @__PURE__ */ g.createElement(\n \"div\",\n {\n className: \"ReactCrop__drag-handle ord-w\",\n \"data-ord\": \"w\",\n tabIndex: 0,\n \"aria-label\": e.wDragHandle,\n onKeyDown: (a) => this.onHandlerKeyDown(a, \"w\"),\n role: \"button\"\n }\n )),\n r && /* @__PURE__ */ g.createElement(\"div\", { className: \"ReactCrop__selection-addon\", onMouseDown: (a) => a.stopPropagation() }, r(this.state)),\n t && /* @__PURE__ */ g.createElement(g.Fragment, null, /* @__PURE__ */ g.createElement(\"div\", { className: \"ReactCrop__rule-of-thirds-hz\" }), /* @__PURE__ */ g.createElement(\"div\", { className: \"ReactCrop__rule-of-thirds-vt\" }))\n );\n }\n makePixelCrop() {\n const e = { ..._, ...this.props.crop || {} }, n = this.getBox();\n return C(e, n.width, n.height);\n }\n render() {\n const { aspect: e, children: n, circularCrop: i, className: r, crop: t, disabled: s, locked: w, style: a, ruleOfThirds: l } = this.props, { cropIsActive: o, newCropIsBeingDrawn: d } = this.state, c = t ? this.createCropSelection() : null, h = K(\"ReactCrop\", r, {\n \"ReactCrop--active\": o,\n \"ReactCrop--disabled\": s,\n \"ReactCrop--locked\": w,\n \"ReactCrop--new-crop\": d,\n \"ReactCrop--fixed-aspect\": t && e,\n \"ReactCrop--circular-crop\": t && i,\n \"ReactCrop--rule-of-thirds\": t && l,\n \"ReactCrop--invisible-crop\": !this.dragStarted && t && !t.width && !t.height,\n \"ReactCrop--no-animate\": i\n });\n return /* @__PURE__ */ g.createElement(\"div\", { ref: this.componentRef, className: h, style: a }, /* @__PURE__ */ g.createElement(\"div\", { ref: this.mediaRef, className: \"ReactCrop__child-wrapper\", onPointerDown: this.onComponentPointerDown }, n), c);\n }\n};\nlet v = u;\nv.xOrds = [\"e\", \"w\"];\nv.yOrds = [\"n\", \"s\"];\nv.xyOrds = [\"nw\", \"ne\", \"se\", \"sw\"];\nv.nudgeStep = 1;\nv.nudgeStepMedium = 10;\nv.nudgeStepLarge = 100;\nv.defaultProps = {\n ariaLabels: {\n cropArea: \"Use the arrow keys to move the crop selection area\",\n nwDragHandle: \"Use the arrow keys to move the north west drag handle to change the crop selection area\",\n nDragHandle: \"Use the up and down arrow keys to move the north drag handle to change the crop selection area\",\n neDragHandle: \"Use the arrow keys to move the north east drag handle to change the crop selection area\",\n eDragHandle: \"Use the up and down arrow keys to move the east drag handle to change the crop selection area\",\n seDragHandle: \"Use the arrow keys to move the south east drag handle to change the crop selection area\",\n sDragHandle: \"Use the up and down arrow keys to move the south drag handle to change the crop selection area\",\n swDragHandle: \"Use the arrow keys to move the south west drag handle to change the crop selection area\",\n wDragHandle: \"Use the up and down arrow keys to move the west drag handle to change the crop selection area\"\n }\n};\nexport {\n v as Component,\n v as ReactCrop,\n Y as areCropsEqual,\n H as centerCrop,\n R as clamp,\n P as containCrop,\n y as convertToPercentCrop,\n C as convertToPixelCrop,\n v as default,\n _ as defaultCrop,\n k as makeAspectCrop,\n S as nudgeCrop\n};\n","import { PixelCrop } from \"react-image-crop\";\n\nconst TO_RADIANS = Math.PI / 180;\n\nexport async function canvasPreview(\n image: HTMLImageElement,\n canvas: HTMLCanvasElement,\n crop: PixelCrop,\n scale = 1,\n rotate = 0,\n) {\n const ctx = canvas.getContext(\"2d\");\n\n if (!ctx) {\n throw new Error(\"No 2d context\");\n }\n\n const scaleX = image.naturalWidth / image.width;\n const scaleY = image.naturalHeight / image.height;\n // devicePixelRatio slightly increases sharpness on retina devices\n // at the expense of slightly slower render times and needing to\n // size the image back down if you want to download/upload and be\n // true to the images natural size.\n const pixelRatio = window.devicePixelRatio;\n\n canvas.width = Math.floor(crop.width * scaleX * pixelRatio);\n canvas.height = Math.floor(crop.height * scaleY * pixelRatio);\n\n ctx.scale(pixelRatio, pixelRatio);\n ctx.imageSmoothingQuality = \"high\";\n\n const cropX = crop.x * scaleX;\n const cropY = crop.y * scaleY;\n\n const rotateRads = rotate * TO_RADIANS;\n const centerX = image.naturalWidth / 2;\n const centerY = image.naturalHeight / 2;\n\n ctx.save();\n\n // 5) Move the crop origin to the canvas origin (0,0)\n ctx.translate(-cropX, -cropY);\n // 4) Move the origin to the center of the original position\n ctx.translate(centerX, centerY);\n // 3) Rotate around the origin\n ctx.rotate(rotateRads);\n // 2) Scale the image\n ctx.scale(scale, scale);\n // 1) Move the center of the image to the origin (0,0)\n ctx.translate(-centerX, -centerY);\n ctx.drawImage(\n image,\n 0,\n 0,\n image.naturalWidth,\n image.naturalHeight,\n 0,\n 0,\n image.naturalWidth,\n image.naturalHeight,\n );\n\n ctx.restore();\n}\n","import { ChangeEvent, Dispatch, SetStateAction, useRef, useState } from \"react\";\n\nimport ReactCrop, { Crop, PixelCrop } from \"react-image-crop\";\n\nimport { Button } from \"../../base/Button\";\nimport { Modal } from \"../../../layouts/Modal\";\nimport { canvasPreview } from \"./canvasPreview\";\nimport { useDebounceEffect } from \"./useDebounceEffect\";\nimport { useTheme } from \"../../../contexts/ThemeContext\";\nimport { SectionLoading } from \"../../shared/SectionLoading\";\nimport { useBrandingMutations } from \"../../../data/branding/useBrandingMutations\";\n\nimport \"react-image-crop/dist/ReactCrop.css\";\n\ninterface LogoCropProps {\n open: boolean;\n onClose: Dispatch>;\n}\n\nfunction readFile(file: File) {\n return new Promise((resolve) => {\n const reader = new FileReader();\n reader.addEventListener(\"load\", () => resolve(reader.result), false);\n reader.readAsDataURL(file);\n });\n}\n\nexport function LogoCrop({ open, onClose }: LogoCropProps) {\n const {\n theme: { logo },\n setTheme,\n } = useTheme();\n const { updateLogo } = useBrandingMutations();\n const previewCanvasRef = useRef(null);\n const imgRef = useRef(null);\n const [imageSrc, setImageSrc] = useState();\n const [imageFileName, setImageFileName] = useState();\n const [crop, setCrop] = useState();\n const [completedCrop, setCompletedCrop] = useState();\n const [uploading, setUploading] = useState(false);\n\n const handleClose = () => {\n setTimeout(() => {\n setImageSrc(undefined);\n setCrop(undefined);\n setCompletedCrop(undefined);\n }, 200);\n onClose(false);\n };\n\n const onFileChange = async (e: ChangeEvent) => {\n if (e.currentTarget.files && e.currentTarget.files.length > 0) {\n const fileName = e.currentTarget.files[0].name;\n const imageDataUrl = await readFile(e.currentTarget.files[0]);\n\n setImageFileName(fileName);\n setImageSrc(imageDataUrl!);\n }\n };\n\n const onCropClick = () => {\n setUploading(true);\n\n if (!previewCanvasRef.current) {\n setUploading(false);\n throw new Error(\"Crop canvas does not exist\");\n }\n\n previewCanvasRef.current.toBlob((blob) => {\n if (!blob) {\n setUploading(false);\n throw new Error(\"Failed to create blob\");\n }\n\n const formData = new FormData();\n\n formData.append(\"logo\", blob, \"image.png\");\n\n updateLogo.mutate(formData, {\n onSuccess: () => {\n setTheme({ type: \"logo\", payload: logo + `?rid=${Date.now()}` });\n setUploading(false);\n handleClose();\n },\n onError: () => setUploading(false),\n });\n });\n };\n\n useDebounceEffect(\n async () => {\n if (\n completedCrop?.width &&\n completedCrop?.height &&\n imgRef.current &&\n previewCanvasRef.current\n ) {\n // We use canvasPreview as it's much faster than imgPreview.\n canvasPreview(imgRef.current, previewCanvasRef.current, completedCrop);\n }\n },\n 100,\n [completedCrop],\n );\n\n return (\n \n {uploading ? (\n \n ) : (\n <>\n
\n \n

{imageFileName}

\n
\n {imageSrc && (\n
\n setCompletedCrop(c)}\n onChange={(c) => setCrop(c)}\n style={{\n maxHeight: \"28rem\",\n }}\n >\n \"\"\n \n
\n )}\n {!!completedCrop && (\n \n )}\n
\n {completedCrop && }\n \n
\n \n )}\n
\n );\n}\n","import { useEffect, DependencyList } from \"react\";\n\nexport function useDebounceEffect(\n fn: () => void,\n waitTime: number,\n deps?: DependencyList,\n) {\n useEffect(() => {\n const t = setTimeout(() => {\n fn.apply(undefined, []);\n }, waitTime);\n\n return () => {\n clearTimeout(t);\n };\n }, deps);\n}\n","import { useEffect, useState } from \"react\";\n\nimport clsx from \"clsx\";\nimport { RgbColorPicker } from \"react-colorful\";\n\nimport { Button } from \"../base/Button\";\nimport RGBtoHEX from \"../../utils/RGBtoHEX\";\nimport HEXtoRGB from \"../../utils/HEXtoRGB\";\nimport { TextField } from \"../base/TextField\";\nimport { LoadingWheel } from \"../base/LoadingWheel\";\nimport useBranding from \"../../data/branding/useBranding\";\nimport { ColorValue, useTheme } from \"../../contexts/ThemeContext\";\nimport { useBrandingMutations } from \"../../data/branding/useBrandingMutations\";\nimport { LogoCrop } from \"./Branding/LogoCrop\";\n\nexport function BrandingTab() {\n const { theme, setTheme } = useTheme();\n const { branding } = useBranding();\n const { updateBranding } = useBrandingMutations();\n const [currentTab, setCurrentTab] = useState(0);\n const [logoCropOpen, setLogoCropOpen] = useState(false);\n const [brandName, setBrandName] = useState(\"\");\n const [domain, setDomain] = useState(\"\");\n const [lightPrimary, setLightPrimary] = useState(\n undefined,\n );\n const [lightSecondary, setLightSecondary] = useState(\n undefined,\n );\n const [darkPrimary, setDarkPrimary] = useState(\n undefined,\n );\n const [darkSecondary, setDarkSecondary] = useState(\n undefined,\n );\n const [loading, setLoading] = useState(true);\n\n const previewTheme = () => {\n setTheme({\n type: \"colors\",\n payload: {\n light: { primary: lightPrimary!, secondary: lightSecondary! },\n dark: { primary: darkPrimary!, secondary: darkSecondary! },\n },\n });\n };\n\n const handleUpdate = () => {\n updateBranding.mutate({\n name: brandName,\n domain: domain,\n lightPrimaryColour: [lightPrimary!.r, lightPrimary!.g, lightPrimary!.b],\n lightSecondaryColour: [\n lightSecondary!.r,\n lightSecondary!.g,\n lightSecondary!.b,\n ],\n darkPrimaryColour: [darkPrimary!.r, darkPrimary!.g, darkPrimary!.b],\n darkSecondaryColour: [\n darkSecondary!.r,\n darkSecondary!.g,\n darkSecondary!.b,\n ],\n });\n previewTheme();\n };\n\n const logoHatchingStyles = {\n backgroundColor: \"#e5e5f7\",\n opacity: 0.8,\n backgroundImage:\n \"repeating-linear-gradient(45deg, #ccc 25%, transparent 25%, transparent 75%, #ccc 75%, #ccc), repeating-linear-gradient(45deg, #ccc 25%, #fff 25%, #fff 75%, #ccc 75%, #ccc)\",\n backgroundPosition: \"0 0, 10px 10px\",\n backgroundSize: \"20px 20px\",\n };\n\n useEffect(() => {\n if (!branding.isLoading && branding.data) {\n const d = branding.data[0];\n setLightPrimary({\n r: d.lightPrimaryColour[0],\n g: d.lightPrimaryColour[1],\n b: d.lightPrimaryColour[2],\n });\n setLightSecondary({\n r: d.lightSecondaryColour[0],\n g: d.lightSecondaryColour[1],\n b: d.lightSecondaryColour[2],\n });\n setDarkPrimary({\n r: d.darkPrimaryColour[0],\n g: d.darkPrimaryColour[1],\n b: d.darkPrimaryColour[2],\n });\n setDarkSecondary({\n r: d.darkSecondaryColour[0],\n g: d.darkSecondaryColour[1],\n b: d.darkSecondaryColour[2],\n });\n\n setBrandName(d.name);\n setDomain(d.domain);\n setLoading(false);\n }\n }, [branding.isLoading, branding.data]);\n\n if (loading) {\n return ;\n } else {\n const colours =\n currentTab === 0\n ? {\n primary: lightPrimary!,\n setPrimary: setLightPrimary,\n secondary: lightSecondary!,\n setSecondary: setLightSecondary,\n }\n : {\n primary: darkPrimary!,\n setPrimary: setDarkPrimary,\n secondary: darkSecondary!,\n setSecondary: setDarkSecondary,\n };\n\n return (\n <>\n setLogoCropOpen(false)} />\n
\n
\n

\n Branding\n

\n

\n Upload your company logo, and add your brand colours.\n

\n\n
\n
\n Brand Name\n
\n
\n setBrandName(e.currentTarget.value)}\n />\n
\n
\n
\n\n {/*
\n
\n Domain\n
\n
\n setDomain(e.currentTarget.value)}\n />\n
\n
\n
*/}\n\n
\n
\n Logo\n
\n
\n \n
\n
\n setLogoCropOpen(true)}\n size=\"sm\"\n className=\"font-semibold\"\n >\n Update\n \n
\n
\n\n
\n \n
\n
\n
\n
\n
\n Primary\n
\n
\n \n
\n
\n \n colours.setPrimary(HEXtoRGB(e.currentTarget.value))\n }\n type=\"text\"\n value={RGBtoHEX(\n colours.primary.r,\n colours.primary.g,\n colours.primary.b,\n )}\n />\n
\n
\n
\n
\n
\n Secondary\n
\n
\n \n
\n
\n \n colours.setSecondary(HEXtoRGB(e.currentTarget.value))\n }\n type=\"text\"\n value={RGBtoHEX(\n colours.secondary.r,\n colours.secondary.g,\n colours.secondary.b,\n )}\n />\n
\n
\n
\n
\n
\n
\n \n \n
\n
\n
\n \n );\n }\n}\n","import { useQuery } from \"react-query\";\n\nimport useApiHelper from \"../../hooks/useApiHelper\";\n\nimport { IDefaultResponseWithData } from \"../../types/system/DefaultResponse\";\nimport { IInstallerBrandingGetResponse } from \"../../types/responses/installer/branding/InstallerBrandingGet\";\n\nexport default function useBranding() {\n const { get } = useApiHelper();\n\n const branding = useQuery({\n queryKey: [\"branding\"],\n queryFn: () =>\n get>(\n \"/v1/brand\",\n ).then((res) => res.data.data),\n });\n\n return {\n branding,\n };\n}\n","import * as React from \"react\";\nfunction CheckIcon({\n title,\n titleId,\n ...props\n}, svgRef) {\n return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n xmlns: \"http://www.w3.org/2000/svg\",\n fill: \"none\",\n viewBox: \"0 0 24 24\",\n strokeWidth: 1.5,\n stroke: \"currentColor\",\n \"aria-hidden\": \"true\",\n ref: svgRef,\n \"aria-labelledby\": titleId\n }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n id: titleId\n }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\",\n d: \"M4.5 12.75l6 6 9-13.5\"\n }));\n}\nconst ForwardRef = React.forwardRef(CheckIcon);\nexport default ForwardRef;","import { useMutation, useQueryClient } from \"react-query\";\n\nimport useApiHelper from \"../../hooks/useApiHelper\";\nimport { useDefaultMutateResponseHandlers } from \"../../hooks/useDefaultMutateResponeHandlers\";\n\nimport { IHardwareType } from \"../../types/Hardware/Hardware\";\n\nexport default function useHardwareTypeMutations() {\n const queryClient = useQueryClient();\n const { post, put, del } = useApiHelper();\n const { handleSuccess, handleError } =\n useDefaultMutateResponseHandlers(\"Hardware Type\");\n\n const createHardwareType = useMutation({\n mutationFn: (hardwareType) =>\n post(\"/v1/superadmin/hardware/types\", hardwareType),\n onError: (error) => handleError(error, \"create\"),\n onSuccess: (data) => handleSuccess(data, \"create\"),\n onSettled: () => {\n queryClient.invalidateQueries([\"hardware\", \"types\"]);\n queryClient.invalidateQueries([\"superadmin\", \"hardware\", \"types\"]);\n },\n });\n\n const updateHardwareType = useMutation({\n mutationFn: (hardwareType: IHardwareType) =>\n put(\n `/v1/superadmin/hardware/types/${hardwareType.id}`,\n hardwareType,\n ),\n onError: (error) => handleError(error, \"update\"),\n onSuccess: (data) => handleSuccess(data, \"update\"),\n onSettled: () => {\n queryClient.invalidateQueries([\"hardware\", \"types\"]);\n queryClient.invalidateQueries([\"superadmin\", \"hardware\", \"types\"]);\n },\n });\n\n const delHardwareType = useMutation({\n mutationFn: (hardwareType: IHardwareType) =>\n del(`/v1/superadmin/hardware/types/${hardwareType.id}`),\n onError: (error) => handleError(error, \"delete\"),\n onSuccess: (data) => handleSuccess(data, \"delete\"),\n onSettled: () => {\n queryClient.invalidateQueries([\"hardware\", \"types\"]);\n queryClient.invalidateQueries([\"superadmin\", \"hardware\", \"types\"]);\n },\n });\n\n return {\n createHardwareType,\n updateHardwareType,\n delHardwareType,\n };\n}\n","import { Dispatch, SetStateAction, useEffect, useState } from \"react\";\nimport { useForm } from \"react-hook-form\";\n\nimport { Modal } from \"../../layouts/Modal\";\n\nimport { TextField } from \"../base/TextField\";\nimport { Button } from \"../base/Button\";\nimport { SectionLoading } from \"../shared/SectionLoading\";\nimport useHardwareTypes from \"../../data/hardware/useHardwareTypes\";\n\nimport { IHardwareType } from \"../../types/Hardware/Hardware\";\nimport { Toggle } from \"../base/Toggle\";\nimport useHardwareTypeMutations from \"../../data/hardware/useHardwareTypeMutations\";\n\nexport interface CreateEditHardwareTypeProps {\n open: boolean;\n onClose: Dispatch>;\n hardwareType?: IHardwareType;\n}\n\nexport function CreateEditHardwareType({\n open,\n onClose,\n hardwareType,\n}: CreateEditHardwareTypeProps) {\n const { register, reset, handleSubmit } = useForm();\n const { hardwareTypes } = useHardwareTypes();\n const { createHardwareType, updateHardwareType } = useHardwareTypeMutations();\n const [checked, setChecked] = useState(true);\n\n const handleClose = () => {\n onClose(false);\n setTimeout(() => reset({}), 200);\n };\n\n const handleCreate = (data: any) => {\n createHardwareType.mutate({ ...data, disabled: checked });\n handleClose();\n };\n\n const handleUpdate = (data: any) => {\n updateHardwareType.mutate({\n ...hardwareType,\n ...data,\n disabled: checked,\n });\n handleClose();\n };\n\n useEffect(() => {\n if (hardwareType) {\n setChecked(hardwareType.disabled);\n reset({\n name: hardwareType.name,\n });\n } else {\n setChecked(true);\n reset({});\n }\n }, [reset, hardwareType]);\n\n return (\n \n {hardwareTypes.isLoading ? (\n \n ) : (\n \n \n\n
\n
\n \n \n
\n \n
\n \n )}\n \n );\n}\n","import { useState } from \"react\";\n\nimport { createColumnHelper } from \"@tanstack/react-table\";\nimport {\n ArrowUturnDownIcon,\n CheckIcon,\n PencilIcon,\n TrashIcon,\n XMarkIcon,\n} from \"@heroicons/react/24/outline\";\n\nimport { Card } from \"../../../components/base/Card\";\nimport { Table } from \"../../../components/base/Table\";\nimport { Button } from \"../../../components/base/Button\";\nimport { IHardwareType } from \"../../../types/Hardware/Hardware\";\nimport { ConfirmDelete } from \"../../../components/shared/ConfirmDelete\";\nimport useHardwareTypeMutations from \"../../../data/hardware/useHardwareTypeMutations\";\nimport { CreateEditHardwareType } from \"../../../components/Hardware/CreateEditHardwareType\";\nimport { useClipboardCopy } from \"../../../hooks/useClipboardCopy\";\n\nconst colHelper = createColumnHelper();\n\nexport function HardwareTypesPage() {\n const { CopyToClipboardButton } = useClipboardCopy();\n const { delHardwareType, updateHardwareType } = useHardwareTypeMutations();\n const [editOpen, setEditOpen] = useState(false);\n const [deleteOpen, setDeleteOpen] = useState(false);\n const [editHardwareType, setEditHardwareType] = useState<\n IHardwareType | undefined\n >(undefined);\n const [deleteHardwareType, setDeleteHardwareType] = useState<\n IHardwareType | undefined\n >(undefined);\n\n const handleDeleteHardwareType = (hardwareType: IHardwareType) => {\n setDeleteHardwareType(hardwareType);\n setDeleteOpen(true);\n };\n\n const handleConfirmDeleteHardwareType = () => {\n delHardwareType.mutate(deleteHardwareType!);\n setDeleteOpen(false);\n };\n\n const handleRestoreHardwareType = (hardwareType: IHardwareType) => {\n updateHardwareType.mutate({ ...hardwareType, restore: true });\n };\n\n const handleEditHardwareType = (hardwareType: IHardwareType) => {\n setEditHardwareType(hardwareType);\n setEditOpen(true);\n };\n\n const handleCreateEditClose = () => {\n editHardwareType && setTimeout(() => setEditHardwareType(undefined), 200);\n setEditOpen(false);\n };\n\n const cols = [\n colHelper.display({\n header: \"Status\",\n cell: (info) =>\n info.row.original.disabled ? (\n \n ) : (\n \n ),\n }),\n colHelper.accessor(\"name\", { header: \"Type\" }),\n colHelper.display({\n header: \"Actions\",\n cell: (info) => (\n
\n {info.cell.row.original.deletedOn ? (\n handleRestoreHardwareType(info.row.original)}\n />\n ) : (\n <>\n \n handleEditHardwareType(info.row.original)}\n />\n handleDeleteHardwareType(info.row.original)}\n />\n \n )}\n
\n ),\n }),\n ];\n\n return (\n <>\n \n setDeleteOpen(false)}\n onConfirm={() => handleConfirmDeleteHardwareType()}\n />\n \n
\n \n
\n
\n \n url=\"/superadmin/hardware/types\"\n queryKey={[\"superadmin\", \"hardware\", \"types\"]}\n columns={cols}\n enableShowDeleted\n />\n
\n
\n \n );\n}\n","import { useMutation, useQueryClient } from \"react-query\";\n\nimport useApiHelper from \"../../hooks/useApiHelper\";\nimport { useDefaultMutateResponseHandlers } from \"../../hooks/useDefaultMutateResponeHandlers\";\n\nimport { IJobCategory } from \"../../types/JobCategory/JobCategory\";\n\nexport default function useJobCategoriesMutations() {\n const queryClient = useQueryClient();\n const { post, put, del } = useApiHelper();\n const { handleSuccess, handleError } =\n useDefaultMutateResponseHandlers(\"Hardware Type\");\n\n const createJobCategory = useMutation({\n mutationFn: (jobCategory) =>\n post(\"/v1/superadmin/job/categories\", jobCategory),\n onError: (error) => handleError(error, \"create\"),\n onSuccess: (data) => handleSuccess(data, \"create\"),\n onSettled: () => {\n queryClient.invalidateQueries([\"job\", \"categories\"]);\n queryClient.invalidateQueries([\"superadmin\", \"job\", \"categories\"]);\n },\n });\n\n const updateJobCategory = useMutation({\n mutationFn: (jobCategory: IJobCategory) =>\n put(\n `/v1/superadmin/job/categories/${jobCategory.id}`,\n jobCategory,\n ),\n onError: (error) => handleError(error, \"update\"),\n onSuccess: (data) => handleSuccess(data, \"update\"),\n onSettled: () => {\n queryClient.invalidateQueries([\"job\", \"categories\"]);\n queryClient.invalidateQueries([\"superadmin\", \"job\", \"categories\"]);\n },\n });\n\n const delJobCategory = useMutation({\n mutationFn: (jobCategory: IJobCategory) =>\n del(`/v1/superadmin/job/categories/${jobCategory.id}`),\n onError: (error) => handleError(error, \"delete\"),\n onSuccess: (data) => handleSuccess(data, \"delete\"),\n onSettled: () => {\n queryClient.invalidateQueries([\"job\", \"categories\"]);\n queryClient.invalidateQueries([\"superadmin\", \"job\", \"categories\"]);\n },\n });\n\n return {\n createJobCategory,\n updateJobCategory,\n delJobCategory,\n };\n}\n","import { Dispatch, SetStateAction, useEffect, useState } from \"react\";\nimport { useForm } from \"react-hook-form\";\n\nimport { Modal } from \"../../layouts/Modal\";\n\nimport { TextField } from \"../base/TextField\";\nimport { Button } from \"../base/Button\";\nimport { SectionLoading } from \"../shared/SectionLoading\";\nimport useHardwareTypes from \"../../data/hardware/useHardwareTypes\";\n\nimport { Toggle } from \"../base/Toggle\";\nimport { IJobCategory } from \"../../types/JobCategory/JobCategory\";\nimport useJobCategoriesMutations from \"../../data/job/useJobCategoriesMutations\";\nimport useJobCategories from \"../../data/job/useJobCategories\";\nimport { RgbColorPicker, RgbaColorPicker } from \"react-colorful\";\nimport { CategoryPill } from \"./CategoryPill\";\n\nexport interface CreateEditJobCategoryProps {\n open: boolean;\n onClose: Dispatch>;\n jobCategory?: IJobCategory;\n}\n\nexport function CreateEditJobCategory({\n open,\n onClose,\n jobCategory,\n}: CreateEditJobCategoryProps) {\n const { register, reset, handleSubmit, watch } = useForm();\n const { jobCategories } = useJobCategories();\n const { createJobCategory, updateJobCategory } = useJobCategoriesMutations();\n const [color, setColor] = useState({ r: 0, g: 0, b: 0 });\n\n const handleClose = () => {\n onClose(false);\n setTimeout(() => reset({}), 200);\n };\n\n const handleCreate = (data: any) => {\n createJobCategory.mutate({ ...data, rgb: [color.r, color.g, color.b] });\n handleClose();\n };\n\n const handleUpdate = (data: any) => {\n updateJobCategory.mutate({\n ...jobCategory,\n ...data,\n rgb: [color.r, color.g, color.b],\n });\n handleClose();\n };\n\n useEffect(() => {\n if (jobCategory) {\n reset({\n name: jobCategory.name,\n colour: jobCategory.colour,\n });\n setColor({\n r: jobCategory?.rgb[0],\n g: jobCategory?.rgb[1],\n b: jobCategory?.rgb[2],\n });\n } else {\n reset({});\n }\n }, [reset, jobCategory]);\n\n const name = watch(\"name\");\n\n return (\n \n {jobCategories.isLoading ? (\n \n ) : (\n \n
\n \n
\n \n {name ? (\n
\n \n
\n ) : (\n
\n Start typing a name to see a preview\n
\n )}\n
\n
\n
\n \n
\n \n
\n
\n
\n \n \n
\n \n )}\n \n );\n}\n","import { useState } from \"react\";\n\nimport { createColumnHelper } from \"@tanstack/react-table\";\nimport {\n ArrowUturnDownIcon,\n PencilIcon,\n TrashIcon,\n} from \"@heroicons/react/24/outline\";\n\nimport { Card } from \"../../../components/base/Card\";\nimport { Table } from \"../../../components/base/Table\";\nimport { Button } from \"../../../components/base/Button\";\nimport { CategoryPill } from \"../../../components/Job/CategoryPill\";\nimport { IJobCategory } from \"../../../types/JobCategory/JobCategory\";\nimport { ConfirmDelete } from \"../../../components/shared/ConfirmDelete\";\nimport useJobCategoriesMutations from \"../../../data/job/useJobCategoriesMutations\";\nimport { CreateEditJobCategory } from \"../../../components/Job/CreateEditJobCategory\";\nimport { useClipboardCopy } from \"../../../hooks/useClipboardCopy\";\n\nconst colHelper = createColumnHelper();\n\nexport function JobCategoriesPage() {\n const { CopyToClipboardButton } = useClipboardCopy();\n const { delJobCategory, updateJobCategory } = useJobCategoriesMutations();\n const [editOpen, setEditOpen] = useState(false);\n const [deleteOpen, setDeleteOpen] = useState(false);\n const [editJobCategory, setEditJobCategory] = useState<\n IJobCategory | undefined\n >(undefined);\n const [deleteJobCategory, setDeleteJobCategory] = useState<\n IJobCategory | undefined\n >(undefined);\n\n const handleDeleteJobCategory = (jobCategory: IJobCategory) => {\n setDeleteJobCategory(jobCategory);\n setDeleteOpen(true);\n };\n\n const handleConfirmDeleteJobCategory = () => {\n delJobCategory.mutate(deleteJobCategory!);\n setDeleteOpen(false);\n };\n\n const handleRestoreJobCategory = (jobCategory: IJobCategory) => {\n updateJobCategory.mutate({ ...jobCategory, restore: true });\n };\n\n const handleEditJobCategory = (jobCategory: IJobCategory) => {\n setEditJobCategory(jobCategory);\n setEditOpen(true);\n };\n\n const handleCreateEditClose = () => {\n editJobCategory && setTimeout(() => setEditJobCategory(undefined), 200);\n setEditOpen(false);\n };\n\n const cols = [\n colHelper.accessor(\"name\", {\n header: \"Category\",\n cell: (info) => ,\n }),\n colHelper.display({\n header: \"Actions\",\n cell: (info) => (\n
\n {info.cell.row.original.deletedOn ? (\n handleRestoreJobCategory(info.row.original)}\n />\n ) : (\n <>\n \n handleEditJobCategory(info.row.original)}\n />\n handleDeleteJobCategory(info.row.original)}\n />\n \n )}\n
\n ),\n }),\n ];\n\n return (\n <>\n \n setDeleteOpen(false)}\n onConfirm={() => handleConfirmDeleteJobCategory()}\n />\n \n
\n \n
\n
\n \n url=\"/superadmin/job/categories\"\n queryKey={[\"superadmin\", \"job\", \"categories\"]}\n columns={cols}\n enableShowDeleted\n />\n
\n
\n \n );\n}\n","export default function getAddress(obj: any) {\n let address = \"\";\n\n if (obj.line1) {\n address += `${obj.line1}, `;\n }\n\n if (obj.line2) {\n address += `${obj.line2}, `;\n }\n\n if (obj.city) {\n address += `${obj.city}, `;\n }\n\n if (obj.county) {\n address += `${obj.county}, `;\n }\n\n if (obj.country) {\n address += `${obj.country}, `;\n }\n\n if (obj.postcode) {\n address += `${obj.postcode}`;\n }\n\n return address;\n}\n","import { useState } from \"react\";\n\nimport { AxiosError } from \"axios\";\n\nimport { Alert } from \"../../base/Alert\";\nimport { Button } from \"../../base/Button\";\nimport { Toggle } from \"../../base/Toggle\";\nimport { Modal } from \"../../../layouts/Modal\";\nimport { SectionLoading } from \"../../shared/SectionLoading\";\nimport { IDefaultResponse } from \"../../../types/system/DefaultResponse\";\nimport useOrganisationInstallerMutations from \"../../../data/organisationInstaller/useOrganisationInstallerMutations\";\n\nexport interface ConfirmDeleteProps {\n installerName: string;\n open: boolean;\n onCancel: () => void;\n onConfirm: () => void;\n}\n\nexport function UnlinkInstaller({\n installerName,\n open,\n onCancel,\n onConfirm,\n}: ConfirmDeleteProps) {\n const { deleteInstaller } = useOrganisationInstallerMutations();\n const [submitting, setSubmitting] = useState(false);\n const [error, setError] = useState(undefined);\n\n const handleCancel = () => {\n onCancel();\n setTimeout(() => {\n setSubmitting(false);\n setError(undefined);\n }, 200);\n };\n\n const handleConfirm = () => {\n setSubmitting(true);\n\n deleteInstaller.mutate(undefined, {\n onSuccess: () => onConfirm(),\n onError: (err) =>\n setError((err as AxiosError).response?.data?.message),\n onSettled: () => setSubmitting(false),\n });\n };\n\n return (\n \n {submitting ? (\n \n ) : error !== undefined ? (\n
\n \n
\n ) : (\n <>\n
\n

\n When unlinking an installer you relinquish all visibility and\n control of your devices. The devices will also be removed from the\n installers subscription if they are currently assigned a tier. It\n is then your responsibility to manage subscriptions.\n

\n
\n \n )}\n
\n \n \n
\n \n );\n}\n","import { useMutation, useQueryClient } from \"react-query\";\n\nimport useApiHelper from \"../../hooks/useApiHelper\";\n\nimport { useDefaultMutateResponseHandlers } from \"../../hooks/useDefaultMutateResponeHandlers\";\n\nexport default function useOrganisationInstallerMutations() {\n const queryClient = useQueryClient();\n const { del } = useApiHelper();\n const { handleSuccess, handleError } =\n useDefaultMutateResponseHandlers(\"Installer\");\n\n const deleteInstaller = useMutation({\n mutationFn: () => del(`/v1/organisation/installer`),\n onError: (error) => handleError(error, \"unlinke\"),\n onSuccess: (data) => handleSuccess(data, \"unlinke\"),\n onSettled: () =>\n queryClient.invalidateQueries([\"organisation\", \"installer\"]),\n });\n\n return {\n deleteInstaller,\n };\n}\n","import { useState } from \"react\";\n\nimport { Button } from \"../base/Button\";\nimport getAddress from \"../../utils/getAddress\";\nimport { SectionLoading } from \"../shared/SectionLoading\";\nimport { UnlinkInstaller } from \"./Installer/UnlinkInstaller\";\nimport useOrganisationInstaller from \"../../data/organisationInstaller/useOrganisationInstaller\";\nimport { Alert } from \"../base/Alert\";\nimport { useNavigate } from \"react-router\";\nimport { useUserContext } from \"../../contexts/UserContext\";\n\nexport function InstallerTab() {\n const navigate = useNavigate();\n const { reload } = useUserContext();\n const { installer } = useOrganisationInstaller();\n const [unlinkOpen, setUnlinkOpen] = useState(false);\n\n const handleUnlinkSuccess = () => {\n setUnlinkOpen(false);\n navigate(\"..\");\n reload();\n };\n\n return (\n <>\n setUnlinkOpen(false)}\n onConfirm={handleUnlinkSuccess}\n />\n
\n
\n

\n Installer Access\n

\n

\n View installer's who have access to your devices.\n

\n {installer.isLoading ? (\n \n ) : installer.isError ? (\n
\n \n
\n ) : (\n
\n
\n
\n Installer Name\n
\n
\n
\n

{installer.data?.[0].organisationName}

\n
\n
\n
\n
\n
\n Installer Contact\n
\n
\n
\n

\n {installer.data?.[0].contact.forename}{\" \"}\n {installer.data?.[0].contact.surname}\n

\n

{installer.data?.[0].contact.email}

\n

{installer.data?.[0].contact.telephone}

\n
\n
\n
\n
\n
\n Installer Address\n
\n
\n
\n {getAddress(installer.data?.[0].address)\n .split(\",\")\n .map((ln) => (\n

{ln}

\n ))}\n
\n
\n
\n
\n
\n Remove Access\n
\n
\n
\n \n
\n
\n
\n
\n )}\n
\n
\n \n );\n}\n","import { useQuery } from \"react-query\";\n\nimport useApiHelper from \"../../hooks/useApiHelper\";\n\nimport { IDefaultResponseWithData } from \"../../types/system/DefaultResponse\";\nimport { IInstaller } from \"../../types/installer/Installer\";\n\nexport default function useOrganisationInstaller() {\n const { get } = useApiHelper();\n\n const installer = useQuery({\n queryKey: [\"organisation\", \"installer\"],\n queryFn: () =>\n get>(\n \"/v1/organisation/installer\",\n ).then((res) => res.data.data),\n });\n\n return {\n installer,\n };\n}\n","import { useMutation, useQueryClient } from \"react-query\";\n\nimport useApiHelper from \"../../hooks/useApiHelper\";\nimport { configurationQueryKeys } from \"../QueryKeys\";\nimport { IDefaultResponseWithData } from \"../../types/system/DefaultResponse\";\nimport { useDefaultMutateResponseHandlers } from \"../../hooks/useDefaultMutateResponeHandlers\";\nimport {\n ITemplateConfiguration,\n TemplateCreateUpdateRequest,\n} from \"../../types/Template/Template\";\n\nexport default function useInstallerTemplateConfigurationsMutations() {\n const { handleError, handleSuccess } =\n useDefaultMutateResponseHandlers(\"Template\");\n const queryClient = useQueryClient();\n const { put, post, del } = useApiHelper();\n\n const createTemplate = useMutation({\n mutationFn: (config: TemplateCreateUpdateRequest) =>\n post<\n TemplateCreateUpdateRequest,\n IDefaultResponseWithData\n >(\"/v1/installer/configurations\", config).then((res) => res.data.data),\n onError: (error) => handleError(error, \"create\"),\n onSuccess: (data) => handleSuccess(data, \"create\"),\n onSettled: () => {\n queryClient.invalidateQueries(configurationQueryKeys.all());\n },\n });\n\n const updateTemplate = useMutation({\n mutationFn: (config: TemplateCreateUpdateRequest) =>\n put<\n TemplateCreateUpdateRequest,\n IDefaultResponseWithData\n >(`/v1/installer/configurations/${config.id}`, config).then(\n (res) => res.data.data\n ),\n onError: (error) => handleError(error, \"update\"),\n onSuccess: (data) => handleSuccess(data, \"update\"),\n onSettled: () => {\n queryClient.invalidateQueries(configurationQueryKeys.all());\n },\n });\n\n const delTemplate = useMutation({\n mutationFn: (config: ITemplateConfiguration) =>\n del(`/v1/installer/configurations/${config.id}`),\n onError: (error) => handleError(error, \"delete\"),\n onSuccess: (data) => handleSuccess(data, \"delete\"),\n onSettled: () => {\n queryClient.invalidateQueries(configurationQueryKeys.all());\n },\n });\n\n return {\n createTemplate,\n updateTemplate,\n delTemplate,\n };\n}\n","import { useState } from \"react\";\n\nimport { Button } from \"../../base/Button\";\nimport { Form } from \"../../base/Form/Form\";\nimport { LoadingWheel } from \"../../base/LoadingWheel\";\nimport { FormErrors } from \"../../base/Form/FormErrors\";\nimport { FormSelect } from \"../../base/Form/FormSelect\";\nimport { FormTextField } from \"../../base/Form/FormTextField\";\nimport { useUserContext } from \"../../../contexts/UserContext\";\nimport { FormModelSelect } from \"../../Hardware/FormModelSelect\";\nimport useHardwareTypes from \"../../../data/hardware/useHardwareTypes\";\nimport { FormManufacturerSelect } from \"../../Hardware/FormManufacturerSelect\";\nimport { ConfigurationType } from \"../../../types/Configuration/Configuration\";\nimport useInstallerTemplateConfigurationsMutations from \"../../../data/configuration/useInstallerTemplateConfigurationsMutations\";\nimport { ITemplateConfiguration } from \"../../../types/Template/Template\";\n\ninterface TemplateConfigFormFields {\n hardwareTypeId: string;\n hardwareManufacturerId: string;\n hardwareModelId: string;\n name: string;\n}\n\ninterface CreateTemplateHardwareInformationProps {\n onTemplateCreate: (template: ITemplateConfiguration) => void;\n}\n\nexport function CreateTemplateHardwareInformation({\n onTemplateCreate,\n}: CreateTemplateHardwareInformationProps) {\n const { organisationId } = useUserContext();\n const { hardwareTypes } = useHardwareTypes();\n const { createTemplate } = useInstallerTemplateConfigurationsMutations();\n const [submitting, setSubmitting] = useState(false);\n\n const handleSubmit = (data: TemplateConfigFormFields) => {\n setSubmitting(true);\n\n createTemplate.mutate(\n {\n type: ConfigurationType.template,\n ownerId: organisationId!,\n template: {\n ...data,\n managedBy: organisationId!,\n default: true,\n tiles: [],\n },\n },\n {\n onSuccess: (template) => {\n onTemplateCreate(template[0]);\n setSubmitting(false);\n },\n }\n //TODO: ERROR HANDLING\n );\n };\n\n return (\n <>\n {submitting ? (\n
\n \n
\n ) : (\n
\n

Create Template

\n onSubmit={handleSubmit}>\n {({ register, watch }) => (\n
\n
\n \n
\n \n \n {hardwareTypes.data?.map((type) => (\n \n ))}\n \n
\n \n
\n
\n \n
\n \n
\n \n
\n
\n )}\n \n
\n )}\n \n );\n}\n","import { useMutation, useQueryClient } from \"react-query\";\n\nimport useApiHelper from \"../../hooks/useApiHelper\";\nimport { configurationQueryKeys } from \"../QueryKeys\";\nimport { IDefaultResponseWithData } from \"../../types/system/DefaultResponse\";\nimport { useDefaultMutateResponseHandlers } from \"../../hooks/useDefaultMutateResponeHandlers\";\nimport {\n ITemplateConfiguration,\n TemplateCreateUpdateRequest,\n} from \"../../types/Template/Template\";\n\nexport default function useCustomerTemplateConfigurationsMutations() {\n const { handleError, handleSuccess } =\n useDefaultMutateResponseHandlers(\"Template\");\n const queryClient = useQueryClient();\n const { put, post, del } = useApiHelper();\n\n const createTemplate = useMutation({\n mutationFn: (config: TemplateCreateUpdateRequest) =>\n post<\n TemplateCreateUpdateRequest,\n IDefaultResponseWithData\n >(\"/v1/organisation/configurations\", config).then((res) => res.data.data),\n onError: (error) => handleError(error, \"create\"),\n onSuccess: (data) => handleSuccess(data, \"create\"),\n onSettled: () => {\n queryClient.invalidateQueries(configurationQueryKeys.all());\n },\n });\n\n const updateTemplate = useMutation({\n mutationFn: (config: TemplateCreateUpdateRequest) =>\n put<\n TemplateCreateUpdateRequest,\n IDefaultResponseWithData\n >(`/v1/organisation/configurations/${config.id}`, config).then(\n (res) => res.data.data\n ),\n onError: (error) => handleError(error, \"update\"),\n onSuccess: (data) => handleSuccess(data, \"update\"),\n onSettled: () => {\n queryClient.invalidateQueries(configurationQueryKeys.all());\n },\n });\n\n const delTemplate = useMutation({\n mutationFn: (config: ITemplateConfiguration) =>\n del(`/v1/organisation/configurations/${config.id}`),\n onError: (error) => handleError(error, \"delete\"),\n onSuccess: (data) => handleSuccess(data, \"delete\"),\n onSettled: () => {\n queryClient.invalidateQueries(configurationQueryKeys.all());\n },\n });\n\n return {\n createTemplate,\n updateTemplate,\n delTemplate,\n };\n}\n","import { useEffect, useState } from \"react\";\n\nimport { Select } from \"../../base/Select\";\nimport { LoadingWheel } from \"../../base/LoadingWheel\";\nimport { useHardwareLookups } from \"../../../hooks/useHardwareLookups\";\nimport { ITemplateConfiguration } from \"../../../types/Template/Template\";\n\ninterface TemplateSelectProps {\n templates: ITemplateConfiguration[];\n onChange: (template: ITemplateConfiguration) => void;\n}\n\nexport function TemplateSelect({ templates, onChange }: TemplateSelectProps) {\n const {\n manufacturerLookup,\n modelLookup,\n isLoading: isLookupsLoading,\n } = useHardwareLookups();\n const [selectedTemplateId, setSelectedTemplateId] = useState(\n templates.length > 0 ? templates[0].id : \"no-templates\"\n );\n\n const handleTemplateSelect = (e: React.FormEvent) => {\n setSelectedTemplateId(e.currentTarget.value);\n onChange(templates.find((t) => t.id === e.currentTarget.value)!);\n };\n\n useEffect(() => {\n if (templates.length > 0) {\n onChange(templates[0]);\n }\n }, [onChange, templates]);\n\n return isLookupsLoading ? (\n
\n \n
\n ) : (\n
\n \n {templates.length === 0 ? (\n \n ) : (\n templates.map((template) => (\n \n ))\n )}\n \n
\n );\n}\n","import { useState } from \"react\";\n\nimport { Button } from \"../../base/Button\";\nimport { ITemplateConfiguration } from \"../../../types/Template/Template\";\nimport { useUserContext } from \"../../../contexts/UserContext\";\nimport useInstallerTemplateConfigurations from \"../../../data/configuration/useInstallerTemplateConfiguration\";\nimport useCustomerTemplateConfigurationsMutations from \"../../../data/configuration/useCustomerTemplateConfigurationsMutations\";\nimport { ConfigurationType } from \"../../../types/Configuration/Configuration\";\nimport { LoadingWheel } from \"../../base/LoadingWheel\";\nimport { Alert } from \"../../base/Alert\";\nimport { TemplateSelect } from \"./TemplateSelect\";\nimport { Toggle } from \"../../base/Toggle\";\n\nexport interface ImportTemplateProps {\n setEditTemplate: (template: ITemplateConfiguration) => void;\n}\n\nexport function ImportTemplate({\n setEditTemplate,\n}: ImportTemplateProps) {\n const { organisationId } = useUserContext();\n const { templateConfigurations } = useInstallerTemplateConfigurations();\n const { createTemplate } = useCustomerTemplateConfigurationsMutations();\n const [selectedTemplate, setSelectedTemplate] =\n useState();\n const [shouldOpenEdit, setShouldOpenEdit] = useState(true);\n const [submitting, setSubmitting] = useState(false);\n const [error, setError] = useState();\n\n const handleImportTemplate = () => {\n if (!selectedTemplate) {\n setError(\"Please select a template to import\");\n return;\n }\n\n setSubmitting(true);\n\n createTemplate.mutate(\n {\n ...selectedTemplate!,\n id: undefined,\n type: ConfigurationType.template,\n ownerId: organisationId!,\n },\n {\n onSuccess: (data) => {\n if (shouldOpenEdit) {\n setEditTemplate(data[0]);\n }\n },\n onSettled: () => {\n setSubmitting(false);\n },\n }\n );\n };\n\n return templateConfigurations.isLoading ? (\n
\n \n
\n ) : (\n <>\n {submitting ? (\n
\n \n
\n ) : (\n
\n {error && }\n \n setShouldOpenEdit((cv) => !cv)}\n />\n \n
\n )}\n \n );\n}\n","import { useUserContext } from \"../../../contexts/UserContext\";\nimport { Modal, ModalControlProps } from \"../../../layouts/Modal\";\nimport { Button } from \"../../base/Button\";\nimport { Seperator } from \"../../base/Seperator\";\nimport { CreateTemplateHardwareInformation } from \"./CreateTemplateHardwareInformation\";\nimport { ITemplateConfiguration } from \"../../../types/Template/Template\";\nimport { useState } from \"react\";\nimport { ImportTemplate } from \"./ImportTemplate\";\n\ninterface AddTemplateModalProps extends ModalControlProps {\n setEditTemplate: (template: ITemplateConfiguration) => void;\n}\n\nexport function AddTemplateModal({\n setEditTemplate,\n open,\n onClose,\n}: AddTemplateModalProps) {\n const { installerId, installerName } = useUserContext();\n const [showImport, setShowImport] = useState(false);\n\n const handleImportSuccess = (template: ITemplateConfiguration) => {\n setEditTemplate(template);\n setShowImport(false);\n };\n\n return (\n \n {showImport ? (\n \n ) : (\n
\n

\n To get started creating a template we need to know the type, make\n and model of appliance you are intending to create the template for\n

\n {installerId && (\n

\n As you are logged in as an installer you can copy templates you\n have already setup to the customers account, this then defaults\n the view for the customer to this template and also allows you to\n modify the template per customer\n

\n )}\n {installerId && (\n <>\n
\n

Import Template

\n \n
\n \n \n )}\n \n
\n )}\n
\n );\n}\n","import { useMemo } from \"react\";\n\nimport { PencilIcon, TrashIcon } from \"@heroicons/react/24/outline\";\n\nimport { ITemplateConfiguration } from \"../../../types/Template/Template\";\nimport { useHardwareLookups } from \"../../../hooks/useHardwareLookups\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\n\ninterface UserRowProps {\n template: ITemplateConfiguration;\n onEdit: (template: ITemplateConfiguration) => void;\n onDelete: (template: ITemplateConfiguration) => void;\n}\n\nexport function TemplateListRow({ template, onEdit, onDelete }: UserRowProps) {\n const { typeLookup, manufacturerLookup, modelLookup } = useHardwareLookups();\n\n const makeModelString = useMemo(\n () => `${typeLookup(template.template.hardwareTypeId)?.name} | ${manufacturerLookup(template.template.hardwareManufacturerId)?.name}\n | ${modelLookup(template.template.hardwareModelId)?.name}`,\n [\n typeLookup,\n manufacturerLookup,\n modelLookup,\n template.template.hardwareTypeId,\n template.template.hardwareManufacturerId,\n template.template.hardwareModelId,\n ]\n );\n\n return (\n \n
\n \n
\n
\n

\n {makeModelString}\n

\n

\n {template.template.name}\n

\n
\n
\n onEdit(template)}\n />\n
\n
\n onDelete(template)}\n />\n
\n
\n );\n}\n","import { useMemo } from \"react\";\n\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { IconName, IconPrefix } from \"@fortawesome/fontawesome-svg-core\";\n\nimport { Toggle } from \"../../base/Toggle\";\nimport { useTemplateEditContext } from \"../../../contexts/TemplateEditContext\";\n\nexport function DataPointConfiguration() {\n const {\n state: template,\n dispatch,\n selectedDataPoint,\n } = useTemplateEditContext();\n\n const dataPoint = useMemo(\n () =>\n [...template.avaliableDataPoints, ...template.visibleDataPoints].find(\n (t) => t.dataPointId === selectedDataPoint?.dataPointId\n ),\n [\n template.avaliableDataPoints,\n template.visibleDataPoints,\n selectedDataPoint,\n ]\n );\n\n const isVisibleDataPoint = useMemo(\n () =>\n template.visibleDataPoints.some(\n (t) => t.dataPointId === selectedDataPoint?.dataPointId\n ),\n [template.visibleDataPoints, selectedDataPoint]\n );\n\n const displayIcon = useMemo(\n () =>\n selectedDataPoint?.dataPoint.icon\n ? (selectedDataPoint?.dataPoint.icon.split(\",\") as [\n IconPrefix,\n IconName,\n ])\n : ([\"fas\", \"question\"] as [IconPrefix, IconName]),\n [selectedDataPoint]\n );\n\n return (\n
\n {dataPoint ? (\n
\n
\n \n
\n

{dataPoint.dataPoint.name}

\n {dataPoint.dataPoint.registerName ? (\n

\n {dataPoint.dataPoint.registerName}\n

\n ) : (\n <>\n )}\n
\n
\n
\n
\n \n dispatch({\n type: \"hide\",\n dataPointId: dataPoint.dataPointId,\n value: !dataPoint.hide,\n })\n }\n checked={!dataPoint.hide}\n disabled={\n isVisibleDataPoint ||\n dataPoint.dataPoint.customerEnable === true\n }\n />\n
\n
\n \n dispatch({\n type: \"control\",\n dataPointId: dataPoint.dataPointId,\n value: !dataPoint.control,\n })\n }\n disabled={!dataPoint.dataPoint.hasActions}\n checked={\n !dataPoint.dataPoint.hasActions ? false : dataPoint.control\n }\n />\n
\n
\n
\n ) : (\n
\n

No data point selected

\n
\n )}\n
\n );\n}\n","import { useEffect, useState } from \"react\";\n\nimport { UseMutationResult } from \"react-query\";\n\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { IconName, IconPrefix } from \"@fortawesome/fontawesome-svg-core\";\n\nimport { Button } from \"../../base/Button\";\nimport { LoadingWheel } from \"../../base/LoadingWheel\";\nimport { TemplateViewConfigDatapointSelect } from \"../../shared/TemplateViewConfigDataPointSelect\";\nimport { Modal, ModalControlProps } from \"../../../layouts/Modal\";\nimport { DataPointConfiguration } from \"./DataPointConfiguration\";\nimport { ISingleTile, TileVisability } from \"../../../types/Tile/Tile\";\nimport { useTemplateEditContext } from \"../../../contexts/TemplateEditContext\";\nimport {\n ITemplateConfiguration,\n TemplateCreateUpdateRequest,\n} from \"../../../types/Template/Template\";\nimport { TextField } from \"../../base/TextField\";\nimport useDataPointsByHardwareModel from \"../../../data/datapoint/useDataPointsByHardwareModel\";\n\ninterface CreateEditTemplateModalProps extends ModalControlProps {\n template: ITemplateConfiguration;\n updateMutationFn: UseMutationResult<\n ITemplateConfiguration[],\n unknown,\n TemplateCreateUpdateRequest,\n unknown\n >;\n}\n\nconst keyInformation = [\n {\n icon: [\"fas\", \"thumbtack\"],\n description:\n \"Core datapoint - core datapoints can be removed from the template but cannot be outright disabled\",\n },\n {\n icon: [\"fas\", \"toggle-on\"],\n description:\n \"Control enabled - users will be able to use the control aspect of this datapoint\",\n },\n {\n icon: [\"fas\", \"toggle-off\"],\n description:\n \"Control disabled - users will not be able to use the control aspect of this datapoint\",\n },\n];\n\nexport function CreateEditTemplateModal({\n template,\n open,\n onClose,\n updateMutationFn,\n}: CreateEditTemplateModalProps) {\n const { state: templateState, dispatch } = useTemplateEditContext();\n const { dataPoints } = useDataPointsByHardwareModel(\n template ? template.template.hardwareModelId : \"\"\n );\n const [templateName, setTemplateName] = useState(\n template ? template.template.name : \"\"\n );\n const [submitting, setSubmitting] = useState(false);\n\n const handleClose = () => {\n dispatch({ type: \"reset\" });\n onClose(true);\n };\n\n const handleSubmit = () => {\n setSubmitting(true);\n\n let tiles: ISingleTile[] = [];\n\n templateState.avaliableDataPoints.forEach((dp) => {\n tiles.push({\n dataPointId: dp.dataPointId,\n visability: dp.hide ? TileVisability.exclude : TileVisability.hide,\n control: dp.control,\n });\n });\n\n templateState.visibleDataPoints.forEach((dp) => {\n tiles.push({\n dataPointId: dp.dataPointId,\n visability: TileVisability.show,\n control: dp.control,\n });\n });\n\n updateMutationFn.mutate(\n {\n ...template,\n template: {\n ...template.template,\n name: templateName,\n tiles: tiles,\n },\n },\n {\n onSuccess: () => {\n handleClose();\n },\n onSettled: () => {\n setSubmitting(false);\n },\n }\n );\n };\n\n useEffect(() => {\n if (\n !dataPoints.isLoading &&\n dataPoints.data &&\n template.template.tiles.length > 0 &&\n templateState.avaliableDataPoints.length === 0\n ) {\n dispatch({\n type: \"loadFromTemplate\",\n dataPoints: dataPoints.data!,\n template: template,\n });\n\n setTemplateName(template ? template.template.name : \"\");\n } else if (\n !dataPoints.isLoading &&\n dataPoints.data &&\n templateState.avaliableDataPoints.length === 0\n ) {\n dispatch({\n type: \"loadFromDataPoints\",\n dataPoints: dataPoints.data!,\n });\n\n setTemplateName(template ? template.template.name : \"\");\n }\n }, [\n dataPoints.isLoading,\n dataPoints.data,\n templateState.avaliableDataPoints.length,\n template,\n dispatch,\n ]);\n\n return (\n 0 ? \"Edit\" : \"Create\"} Template`}\n open={open}\n onClose={onClose}\n >\n {dataPoints.isLoading || submitting ? (\n
\n \n
\n ) : (\n <>\n
\n setTemplateName(e.currentTarget.value)}\n />\n
\n \n \n \n )}\n
\n \n \n {keyInformation.map((key, i) => (\n \n \n \n \n ))}\n \n
\n
\n \n
\n
{key.description}
\n
\n
\n \n \n
\n \n );\n}\n","import { useState } from \"react\";\n\nimport { Button } from \"../../base/Button\";\nimport { AddTemplateModal } from \"./AddTemplate\";\nimport { TemplateListRow } from \"./TemplateListRow\";\nimport { LoadingWheel } from \"../../base/LoadingWheel\";\nimport { SectionLoading } from \"../../shared/SectionLoading\";\nimport { CreateEditTemplateModal } from \"./CreateEditTemplateModal\";\nimport { useHardwareLookups } from \"../../../hooks/useHardwareLookups\";\nimport { ITemplateConfiguration } from \"../../../types/Template/Template\";\nimport { TemplateEditContextProvider } from \"../../../contexts/TemplateEditContext\";\nimport useCustomerTemplateConfigurations from \"../../../data/configuration/useCustomerTemplateConfiguration\";\nimport useCustomerTemplateConfigurationsMutations from \"../../../data/configuration/useCustomerTemplateConfigurationsMutations\";\nimport { ConfirmDelete } from \"../../shared/ConfirmDelete\";\n\nexport function CustomerTemplates() {\n const { isLoading: isLookupsLoading } = useHardwareLookups();\n const { templateConfigurations } = useCustomerTemplateConfigurations();\n const { updateTemplate, delTemplate } =\n useCustomerTemplateConfigurationsMutations();\n const [addOpen, setAddOpen] = useState(false);\n const [editOpen, setEditOpen] = useState(false);\n const [editTemplate, setEditTemplate] = useState();\n const [deleteOpen, setDeleteOpen] = useState(false);\n const [deleteTemplate, setDeleteTemplate] =\n useState();\n\n const handleEditOpen = (template: ITemplateConfiguration) => {\n addOpen && setAddOpen(false);\n setEditTemplate(template);\n setEditOpen(true);\n };\n\n const handleEditClose = () => {\n setEditOpen(false);\n setEditTemplate(undefined);\n };\n\n const handleDeleteTemplate = (template: ITemplateConfiguration) => {\n setDeleteTemplate(template);\n setDeleteOpen(true);\n };\n\n const handleConfirmDeleteTemplate = () => {\n delTemplate.mutate(deleteTemplate!, {\n onSettled: () => {\n setDeleteTemplate(undefined);\n setDeleteOpen(false);\n },\n });\n };\n\n return templateConfigurations.isLoading || isLookupsLoading ? (\n
\n \n
\n ) : (\n <>\n \n \n \n setAddOpen(false)}\n setEditTemplate={handleEditOpen}\n />\n setDeleteOpen(false)}\n onConfirm={handleConfirmDeleteTemplate}\n />\n
\n

Customer templates

\n
\n

\n Since the available data points vary by appliance model, templates are\n created for each specific model. Once a template is created, you can\n apply it by navigating to the Live View page on your account or any of\n your customers' accounts.\n

\n
\n\n
\n \n
\n\n
\n {templateConfigurations.isLoading ? (\n \n ) : (\n
    \n {templateConfigurations.data?.length ? (\n templateConfigurations.data?.map((template) => (\n \n ))\n ) : (\n
    \n

    No templates

    \n
    \n )}\n
\n )}\n
\n \n );\n}\n","import { useState } from \"react\";\n\nimport { ITemplateConfiguration } from \"../../../types/Template/Template\";\nimport { TemplateEditContextProvider } from \"../../../contexts/TemplateEditContext\";\nimport useInstallerTemplateConfigurations from \"../../../data/configuration/useInstallerTemplateConfiguration\";\nimport { LoadingWheel } from \"../../base/LoadingWheel\";\nimport useInstallerTemplateConfigurationsMutations from \"../../../data/configuration/useInstallerTemplateConfigurationsMutations\";\nimport { Button } from \"../../base/Button\";\nimport { SectionLoading } from \"../../shared/SectionLoading\";\nimport { useHardwareLookups } from \"../../../hooks/useHardwareLookups\";\nimport { TemplateListRow } from \"./TemplateListRow\";\nimport { AddTemplateModal } from \"./AddTemplate\";\nimport { CreateEditTemplateModal } from \"./CreateEditTemplateModal\";\nimport { ConfirmDelete } from \"../../shared/ConfirmDelete\";\n\nexport function InstallerTemplates() {\n const { isLoading: isLookupsLoading } = useHardwareLookups();\n const { templateConfigurations } = useInstallerTemplateConfigurations();\n const { updateTemplate, delTemplate } =\n useInstallerTemplateConfigurationsMutations();\n const [addOpen, setAddOpen] = useState(false);\n const [editOpen, setEditOpen] = useState(false);\n const [editTemplate, setEditTemplate] = useState();\n const [deleteOpen, setDeleteOpen] = useState(false);\n const [deleteTemplate, setDeleteTemplate] =\n useState();\n\n const handleEditOpen = (template: ITemplateConfiguration) => {\n addOpen && setAddOpen(false);\n setEditTemplate(template);\n setEditOpen(true);\n };\n\n const handleEditClose = () => {\n setEditOpen(false);\n setEditTemplate(undefined);\n };\n\n const handleDeleteTemplate = (template: ITemplateConfiguration) => {\n setDeleteTemplate(template);\n setDeleteOpen(true);\n };\n\n const handleConfirmDeleteTemplate = () => {\n delTemplate.mutate(deleteTemplate!, {\n onSettled: () => {\n setDeleteTemplate(undefined);\n setDeleteOpen(false);\n },\n });\n };\n\n return templateConfigurations.isLoading || isLookupsLoading ? (\n
\n \n
\n ) : (\n <>\n {editTemplate && (\n \n \n \n )}\n setAddOpen(false)}\n setEditTemplate={handleEditOpen}\n />\n setDeleteOpen(false)}\n onConfirm={handleConfirmDeleteTemplate}\n />\n
\n

\n Templates allow you to customize the Live Readings view by specifying\n which tiles users can see and in what order. You can also hide certain\n tiles entirely, preventing users from accessing them, and disable\n control options for specific tiles.\n

\n
\n

\n Since the available data points vary by appliance model, templates are\n created for each specific model. Once a template is created, you can\n apply it by navigating to the Live View page on your account or any of\n your customers' accounts.\n

\n
\n\n
\n \n
\n\n
\n {templateConfigurations.isLoading ? (\n \n ) : (\n
    \n {templateConfigurations.data?.length ? (\n templateConfigurations.data?.map((template) => (\n \n ))\n ) : (\n
    \n

    \n No templates\n

    \n
    \n )}\n
\n )}\n
\n \n );\n}\n","import { useUserContext } from \"../../contexts/UserContext\";\nimport { CustomerTemplates } from \"./Templates/CustomerTemplates\";\nimport { InstallerTemplates } from \"./Templates/InstallerTemplates\";\n\nexport function TemplatesTab() {\n const { installerId } = useUserContext();\n\n return (\n <>\n
\n
\n

\n Templates\n

\n

\n View, create and edit your templates.\n

\n
\n {installerId ? : }\n
\n
\n
\n \n );\n}\n","import * as React from \"react\";\nfunction FunnelIcon({\n title,\n titleId,\n ...props\n}, svgRef) {\n return /*#__PURE__*/React.createElement(\"svg\", Object.assign({\n xmlns: \"http://www.w3.org/2000/svg\",\n fill: \"none\",\n viewBox: \"0 0 24 24\",\n strokeWidth: 1.5,\n stroke: \"currentColor\",\n \"aria-hidden\": \"true\",\n ref: svgRef,\n \"aria-labelledby\": titleId\n }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n id: titleId\n }, title) : null, /*#__PURE__*/React.createElement(\"path\", {\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\",\n d: \"M12 3c2.755 0 5.455.232 8.083.678.533.09.917.556.917 1.096v1.044a2.25 2.25 0 01-.659 1.591l-5.432 5.432a2.25 2.25 0 00-.659 1.591v2.927a2.25 2.25 0 01-1.244 2.013L9.75 21v-6.568a2.25 2.25 0 00-.659-1.591L3.659 7.409A2.25 2.25 0 013 5.818V4.774c0-.54.384-1.006.917-1.096A48.32 48.32 0 0112 3z\"\n }));\n}\nconst ForwardRef = React.forwardRef(FunnelIcon);\nexport default ForwardRef;","import { useMutation, useQueryClient } from \"react-query\";\n\nimport useApiHelper from \"../../hooks/useApiHelper\";\n\nimport { IHardwareModel } from \"../../types/Hardware/Hardware\";\nimport { useDefaultMutateResponseHandlers } from \"../../hooks/useDefaultMutateResponeHandlers\";\n\nexport default function useHardwareModelsMutations() {\n const queryClient = useQueryClient();\n const { post, put, del } = useApiHelper();\n const { handleSuccess, handleError } =\n useDefaultMutateResponseHandlers(\"Hardware Model\");\n\n const createHardwareModel = useMutation({\n mutationFn: (hardwareModel) =>\n post(\"/v1/superadmin/hardware/models\", hardwareModel),\n onError: (error) => handleError(error, \"create\"),\n onSuccess: (data) => handleSuccess(data, \"create\"),\n onSettled: () => {\n queryClient.invalidateQueries([\"hardware\", \"models\"]);\n queryClient.invalidateQueries([\"superadmin\", \"hardware\", \"models\"]);\n },\n });\n\n const updateHardwareModel = useMutation({\n mutationFn: (hardwareModel: IHardwareModel) =>\n put(\n `/v1/superadmin/hardware/models/${hardwareModel.id}`,\n hardwareModel,\n ),\n onError: (error) => handleError(error, \"update\"),\n onSuccess: (data) => handleSuccess(data, \"update\"),\n onSettled: () => {\n queryClient.invalidateQueries([\"hardware\", \"models\"]);\n queryClient.invalidateQueries([\"superadmin\", \"hardware\", \"models\"]);\n },\n });\n\n const delHardwareModel = useMutation({\n mutationFn: (hardwareModel: IHardwareModel) =>\n del(`/v1/superadmin/hardware/models/${hardwareModel.id}`),\n onError: (error) => handleError(error, \"delete\"),\n onSuccess: (data) => handleSuccess(data, \"delete\"),\n onSettled: () => {\n queryClient.invalidateQueries([\"hardware\", \"models\"]);\n queryClient.invalidateQueries([\"superadmin\", \"hardware\", \"models\"]);\n },\n });\n\n return {\n createHardwareModel,\n updateHardwareModel,\n delHardwareModel,\n };\n}\n","import {\n createContext,\n Dispatch,\n ReactElement,\n useContext,\n useReducer,\n} from \"react\";\n\nimport { IHardwareModel } from \"../types/Hardware/Hardware\";\nimport { Outlet } from \"react-router\";\n\ninterface GlobalHardwareModelFilterContextValue {\n hardware: IHardwareModel | undefined;\n dispatch: Dispatch;\n}\n\nconst GlobalHardwareModelFilterContext =\n createContext({\n hardware: undefined,\n dispatch: () => {},\n });\n\ninterface GlobalHardwareModelFilterContextProviderProps {\n children: ReactElement | ReactElement[];\n}\n\nfunction globalHardwareModelFilterReducer(\n state: IHardwareModel | undefined,\n action: GlobalHardwareModelFilterContextActions,\n): IHardwareModel | undefined {\n switch (action.type) {\n case \"set\":\n return action.payload;\n case \"reset\":\n return undefined;\n default:\n console.error(\"Unhandled action passed to globalHardwareFilterReducer\");\n return state;\n }\n}\n\ntype GlobalHardwareModelFilterContextActions =\n | {\n type: \"set\";\n payload: IHardwareModel | undefined;\n }\n | {\n type: \"reset\";\n };\n\nexport function GlobalHardwareModelFilterProvider() {\n const [hardware, dispatch] = useReducer(\n globalHardwareModelFilterReducer,\n undefined,\n );\n\n return (\n \n \n \n );\n}\n\nexport function useGlobalHardwareModelFilter() {\n const globalHardwareModelCtx = useContext(GlobalHardwareModelFilterContext);\n\n if (!globalHardwareModelCtx) {\n throw Error(\n \"useGlobalHardwareFilter() must be used within a GlobalHardwareFilterProvider\",\n );\n }\n\n return {\n globalHardwareModelFilter: globalHardwareModelCtx.hardware,\n setGlobalHardwareModelFilter: globalHardwareModelCtx.dispatch,\n };\n}\n","import React from \"react\";\n\nimport { LoadingWheel } from \"../base/LoadingWheel\";\nimport { Select } from \"../base/Select\";\n\nimport useHardwareModels from \"../../data/hardware/useHardwareModel\";\n\nexport interface ModelSelectProps {\n manufacturer: string;\n label?: string;\n}\n\nexport const ModelSelect = React.forwardRef(\n ({ manufacturer, label, ...rest }, ref) => {\n const { hardwareModels } = useHardwareModels(manufacturer);\n\n if (hardwareModels.isLoading) {\n return (\n
\n \n
\n );\n } else {\n return (\n \n \n {hardwareModels.data?.map((type) => (\n \n ))}\n \n );\n }\n },\n);\n","import React from \"react\";\n\nimport { LoadingWheel } from \"../base/LoadingWheel\";\nimport { Select } from \"../base/Select\";\n\nimport useHardwareManufacturers from \"../../data/hardware/useHardwareManufacturers\";\n\nexport interface ManufacturerSelectProps {\n type: string;\n}\n\nexport const ManufacturerSelect = React.forwardRef<\n any,\n ManufacturerSelectProps\n>(({ type, ...rest }, ref) => {\n const { hardwareManufacturers } = useHardwareManufacturers(type);\n\n if (hardwareManufacturers.isLoading) {\n return (\n
\n \n
\n );\n } else {\n return (\n \n );\n }\n});\n","import { Dispatch, SetStateAction, useEffect, useState } from \"react\";\n\nimport { useForm } from \"react-hook-form\";\n\nimport { Button } from \"../base/Button\";\nimport { Select } from \"../base/Select\";\nimport { Toggle } from \"../base/Toggle\";\nimport { Modal } from \"../../layouts/Modal\";\nimport { ModelSelect } from \"./ModelSelect\";\nimport { TextField } from \"../base/TextField\";\nimport { SectionLoading } from \"../shared/SectionLoading\";\nimport { ManufacturerSelect } from \"./ManufacturerSelect\";\nimport useHardwareTypes from \"../../data/hardware/useHardwareTypes\";\nimport useHardwareModels from \"../../data/hardware/useHardwareModel\";\nimport useHardwareModelsMutations from \"../../data/hardware/useHardwareModelMutations\";\nimport {\n BaudRateOptions,\n DataBitsOptions,\n HardwareModelClassification,\n HardwareModelEndianness,\n IHardwareModel,\n ParityOptions,\n StopBitsOptions,\n} from \"../../types/Hardware/Hardware\";\nimport { ClipboardDocumentIcon } from \"@heroicons/react/24/outline\";\n\nexport interface CreateEditHardwareModelProps {\n open: boolean;\n onClose: Dispatch>;\n hardwareModel?: IHardwareModel;\n}\n\nexport function CreateEditHardwareModel({\n open,\n onClose,\n hardwareModel,\n}: CreateEditHardwareModelProps) {\n const { register, reset, handleSubmit, watch, resetField } = useForm();\n const { hardwareTypes } = useHardwareTypes();\n const { hardwareModels } = useHardwareModels();\n const { createHardwareModel, updateHardwareModel } =\n useHardwareModelsMutations();\n const [checked, setChecked] = useState(true);\n const [partial, setPartial] = useState(false);\n const [actionProfiles, setActionProfiles] = useState(true);\n const [actionTransformations, setActionTransformations] = useState(true);\n const [dataProfiles, setDataProfiles] = useState(true);\n const [dataOptions, setDataOptions] = useState(true);\n const [dataTransformations, setDataTransformations] = useState(true);\n\n const hardwareModelClassifications = [\n ...Object.values(HardwareModelClassification).filter((ct) =>\n isNaN(Number(ct)),\n ),\n ];\n\n const hardwareModelEndiannesses = [\n ...Object.values(HardwareModelEndianness)\n .filter((e) => isNaN(Number(e)))\n .map((endianess, i) => ({ label: endianess, value: i })),\n ];\n\n const handleClose = () => {\n onClose(false);\n setTimeout(() => reset({}), 200);\n };\n\n const handleCreate = (data: any) => {\n createHardwareModel.mutate({\n ...data,\n serialSettings: {\n ...data.serialSettings,\n parity: parseInt(data.serialSettings.parity),\n },\n classification: parseInt(data.classification),\n disabled: checked,\n partial: partial,\n hardwareModelId:\n data.hardwareModelId !== \"\" ? data.hardwareModelId : null,\n duplicateActionProfiles: actionProfiles,\n duplicateActionTransformations: actionTransformations,\n duplicateDataProfiles: dataProfiles,\n duplicateDataOptions: dataOptions,\n duplicateDataTransformations: dataTransformations,\n });\n handleClose();\n };\n\n const handleUpdate = (data: any) => {\n updateHardwareModel.mutate({\n ...hardwareModel,\n ...data,\n serialSettings: {\n ...data.serialSettings,\n parity: parseInt(data.serialSettings.parity),\n },\n classification: parseInt(data.classification),\n endianness: parseInt(data.endianness),\n disabled: checked,\n partial: partial,\n hardwareModelId: null,\n });\n handleClose();\n };\n\n const handleCopyID = async () =>\n await navigator.clipboard.writeText(hardwareModel?.id ?? \"\");\n\n useEffect(() => {\n if (hardwareModel) {\n setChecked(hardwareModel.disabled);\n setPartial(hardwareModel.partial);\n reset({\n name: hardwareModel.name,\n hardwareTypeId: hardwareModel.hardwareTypeId,\n hardwareManufacturerId: hardwareModel.hardwareManufacturerId,\n classification: hardwareModel.classification,\n serialSettings: {\n baudRate: hardwareModel.serialSettings.baudRate,\n dataBits: hardwareModel.serialSettings.dataBits,\n parity: hardwareModel.serialSettings.parity,\n stopBits: hardwareModel.serialSettings.stopBits,\n },\n address: hardwareModel.address,\n endianness: hardwareModel.endianness,\n });\n } else {\n setChecked(true);\n setPartial(false);\n reset({ address: 1 });\n }\n }, [reset, hardwareModel]);\n\n return (\n \n {hardwareModels.isLoading && hardwareTypes.isLoading ? (\n \n ) : (\n \n {hardwareModel && (\n
\n
\n \n
\n \n
\n )}\n \n {watch(\"hardwareTypeId\") && (\n \n )}\n {watch(\"hardwareManufacturerId\") && (\n <>\n \n \n\n \n \n {BaudRateOptions.map((x, i) => (\n \n ))}\n \n\n \n \n {DataBitsOptions.map((x, i) => (\n \n ))}\n \n\n \n {ParityOptions.map(\n (x: { key: string; value: number }, i: number) => (\n \n ),\n )}\n \n\n \n \n {StopBitsOptions.map((x, i) => (\n \n ))}\n \n\n \n {hardwareModelEndiannesses.map((x, i) => (\n \n ))}\n \n\n \n\n {hardwareModel === undefined && (\n \n )}\n \n )}\n {watch(\"hardwareModelId\") && (\n
\n \n \n \n \n \n
\n )}\n
\n
\n \n \n
\n
\n \n \n
\n
\n \n )}\n \n );\n}\n","import { XMarkIcon } from \"@heroicons/react/24/outline\";\nimport { useGlobalHardwareModelFilter } from \"./../../contexts/GlobalHardwareFilterContext\";\n\nexport function GlobalHardwareModelFilterBanner() {\n const { globalHardwareModelFilter, setGlobalHardwareModelFilter } =\n useGlobalHardwareModelFilter();\n\n if (globalHardwareModelFilter) {\n return (\n
\n \n Filtering for {globalHardwareModelFilter?.hardwareManufacturer.name}{\" \"}\n {globalHardwareModelFilter?.name}\n \n setGlobalHardwareModelFilter({ type: \"reset\" })}\n />\n
\n );\n } else {\n return <>;\n }\n}\n","import useSuperAdminHardwareManufacturers from \"../data/hardware/useSuperAdminHardwareManufacturers\";\nimport useSuperAdminHardwareModels from \"../data/hardware/useSuperAdminHardwareModels\";\nimport useSuperAdminHardwareTypes from \"../data/hardware/useSuperAdminHardwareTypes\";\n\nconst useSuperAdminHardwareTypeLookup = () => {\n const { hardwareTypes } = useSuperAdminHardwareTypes();\n\n const lookup = (typeId: string) =>\n hardwareTypes.data?.find((m) => m.id === typeId);\n\n return {\n isLoading: hardwareTypes.isLoading,\n lookup,\n };\n};\n\nconst useSuperAdminHardwareManufacturerLookup = () => {\n const { hardwareManufacturers } = useSuperAdminHardwareManufacturers();\n\n const lookup = (manufacturerId: string) =>\n hardwareManufacturers.data?.find((m) => m.id === manufacturerId);\n\n return {\n isLoading: hardwareManufacturers.isLoading,\n lookup,\n };\n};\n\nconst useSuperAdminHardwareModelLookup = () => {\n const { hardwareModels } = useSuperAdminHardwareModels();\n\n const lookup = (modelId: string) =>\n hardwareModels.data?.find((m) => m.id === modelId);\n\n return {\n isLoading: hardwareModels.isLoading,\n lookup,\n };\n};\n\nexport const useSuperAdminHardwareLookups = () => {\n const { isLoading: typesLoading, lookup: typeLookup } =\n useSuperAdminHardwareTypeLookup();\n\n const { isLoading: manufacturersLoading, lookup: manufacturerLookup } =\n useSuperAdminHardwareManufacturerLookup();\n\n const { isLoading: modelsLoading, lookup: modelLookup } =\n useSuperAdminHardwareModelLookup();\n\n const isLoading = manufacturersLoading || typesLoading || modelsLoading;\n\n return {\n isLoading,\n typeLookup,\n manufacturerLookup,\n modelLookup,\n };\n};\n","import { useQuery } from \"react-query\";\n\nimport useApiHelper from \"../../hooks/useApiHelper\";\nimport { IHardwareSelection } from \"../../types/Hardware/Hardware\";\nimport { IDefaultResponseWithData } from \"../../types/system/DefaultResponse\";\n\nexport default function useSuperAdminHardwareTypes() {\n const { get } = useApiHelper();\n\n const hardwareTypes = useQuery({\n queryKey: [\"superadmin\", \"hardware\", \"types\"],\n queryFn: () =>\n get>(\n `/v1/superadmin/hardware/types`,\n ).then((res) => res.data.data),\n });\n\n return {\n hardwareTypes,\n };\n}\n","import { useQuery } from \"react-query\";\n\nimport useApiHelper from \"../../hooks/useApiHelper\";\nimport { IHardwareSelection } from \"../../types/Hardware/Hardware\";\nimport { IDefaultResponseWithData } from \"../../types/system/DefaultResponse\";\n\nexport default function useSuperAdminHardwareManufacturers() {\n const { get } = useApiHelper();\n\n const hardwareManufacturers = useQuery({\n queryKey: [\"superadmin\", \"hardware\", \"manufacturers\"],\n queryFn: () =>\n get>(\n `/v1/superadmin/hardware/manufacturers`,\n ).then((res) => res.data.data),\n });\n\n return {\n hardwareManufacturers,\n };\n}\n","import { useQuery } from \"react-query\";\n\nimport useApiHelper from \"../../hooks/useApiHelper\";\nimport { IHardwareSelection } from \"../../types/Hardware/Hardware\";\nimport { IDefaultResponseWithData } from \"../../types/system/DefaultResponse\";\n\nexport default function useSuperAdminHardwareModels() {\n const { get } = useApiHelper();\n\n const hardwareModels = useQuery({\n queryKey: [\"superadmin\", \"hardware\", \"models\"],\n queryFn: () =>\n get>(\n `/v1/superadmin/hardware/models`,\n ).then((res) => res.data.data),\n });\n\n return {\n hardwareModels,\n };\n}\n","import { useState } from \"react\";\n\nimport { createColumnHelper } from \"@tanstack/react-table\";\nimport {\n ArrowUturnDownIcon,\n CheckIcon,\n FunnelIcon,\n PencilIcon,\n TrashIcon,\n XMarkIcon,\n} from \"@heroicons/react/24/outline\";\n\nimport { Card } from \"../../../components/base/Card\";\nimport { Pill } from \"../../../components/base/Pill\";\nimport { Table } from \"../../../components/base/Table\";\nimport { Button } from \"../../../components/base/Button\";\nimport { useNotification } from \"../../../hooks/useNotifications\";\nimport { ConfirmDelete } from \"../../../components/shared/ConfirmDelete\";\nimport useHardwareModelsMutations from \"../../../data/hardware/useHardwareModelMutations\";\nimport { useGlobalHardwareModelFilter } from \"../../../contexts/GlobalHardwareFilterContext\";\nimport { CreateEditHardwareModel } from \"../../../components/Hardware/CreateEditHardwareModel\";\nimport {\n HardwareModelClassification,\n HardwareModelClassificationColours,\n IHardwareManufacturer,\n IHardwareModel,\n} from \"../../../types/Hardware/Hardware\";\nimport { GlobalHardwareModelFilterBanner } from \"../../../components/shared/GlobalHardwareModelFilterBanner\";\nimport { LoadingWheel } from \"../../../components/base/LoadingWheel\";\nimport { useSuperAdminHardwareLookups } from \"../../../hooks/useSuperAdminHardwareLookups\";\nimport { useClipboardCopy } from \"../../../hooks/useClipboardCopy\";\n\nconst colHelper = createColumnHelper();\n\nexport function HardwareModelsPage() {\n const { CopyToClipboardButton } = useClipboardCopy();\n const addNotification = useNotification();\n const { delHardwareModel, updateHardwareModel } =\n useHardwareModelsMutations();\n const { setGlobalHardwareModelFilter } = useGlobalHardwareModelFilter();\n const [editOpen, setEditOpen] = useState(false);\n const [deleteOpen, setDeleteOpen] = useState(false);\n const [editHardwareModel, setEditHardwareModel] = useState<\n IHardwareModel | undefined\n >(undefined);\n const [deleteHardwareModel, setDeleteHardwareModel] = useState<\n IHardwareModel | undefined\n >(undefined);\n const { isLoading: isTypeLoading, typeLookup } =\n useSuperAdminHardwareLookups();\n const { isLoading: isHardwareLoading, manufacturerLookup } =\n useSuperAdminHardwareLookups();\n\n const handleDeleteHardwareModel = (hardwareModel: IHardwareModel) => {\n setDeleteHardwareModel(hardwareModel);\n setDeleteOpen(true);\n };\n\n const handleConfirmDeleteHardwareModel = () => {\n delHardwareModel.mutate(deleteHardwareModel!);\n setDeleteOpen(false);\n };\n\n const handleRestoreHardwareModel = (hardwareModel: IHardwareModel) => {\n updateHardwareModel.mutate({ ...hardwareModel, restore: true });\n };\n\n const handleEditHardwareModel = (hardwareModel: IHardwareModel) => {\n setEditHardwareModel(hardwareModel);\n setEditOpen(true);\n };\n\n const handleCreateEditClose = () => {\n editHardwareModel && setTimeout(() => setEditHardwareModel(undefined), 200);\n setEditOpen(false);\n };\n\n const handleSetModelFilter = (hardwareModel: IHardwareModel) => {\n hardwareModel.hardwareManufacturer = manufacturerLookup(\n hardwareModel.hardwareManufacturerId\n ) as IHardwareManufacturer;\n setGlobalHardwareModelFilter({ type: \"set\", payload: hardwareModel });\n addNotification(\n \"success\",\n `Global Filter set to ${hardwareModel.hardwareManufacturer.name} ${hardwareModel.name}`\n );\n };\n\n const cols = [\n colHelper.display({\n header: \"Status\",\n cell: (info) =>\n info.row.original.disabled ? (\n \n ) : (\n \n ),\n }),\n colHelper.accessor((row) => typeLookup(row.hardwareTypeId)?.name, {\n header: \"Type\",\n }),\n colHelper.accessor(\n (row) => manufacturerLookup(row.hardwareManufacturerId)?.name,\n { header: \"Manufacturer\" }\n ),\n colHelper.accessor(\"name\", { header: \"Model\" }),\n colHelper.display({\n header: \"Classification\",\n cell: (info) => (\n <>\n {info.row.original.classification !== 0 ? (\n \n ) : (\n \"\"\n )}\n {info.row.original.partial ? (\n \n ) : (\n \"\"\n )}\n \n ),\n }),\n colHelper.display({\n header: \"Actions\",\n cell: (info) => (\n
\n {info.cell.row.original.deletedOn ? (\n handleRestoreHardwareModel(info.row.original)}\n />\n ) : (\n <>\n \n handleEditHardwareModel(info.row.original)}\n />\n handleDeleteHardwareModel(info.row.original)}\n />\n handleSetModelFilter(info.row.original)}\n title={`Set global hardware filter to ${info.row.original.name}`}\n />\n \n )}\n
\n ),\n }),\n ];\n\n return (\n <>\n \n setDeleteOpen(false)}\n onConfirm={() => handleConfirmDeleteHardwareModel()}\n />\n \n
\n \n
\n
\n \n
\n
\n {isTypeLoading || isHardwareLoading ? (\n \n ) : (\n \n url=\"/superadmin/hardware/models\"\n queryKey={[\"superadmin\", \"hardware\", \"models\"]}\n columns={cols}\n enableShowDeleted\n />\n )}\n
\n
\n \n );\n}\n","import { useMutation, useQueryClient } from \"react-query\";\n\nimport useApiHelper from \"../../../hooks/useApiHelper\";\n\nimport { useDefaultMutateResponseHandlers } from \"../../../hooks/useDefaultMutateResponeHandlers\";\nimport { IDataPoint } from \"../../../types/DataPoint/DataPoint\";\n\nexport default function useSuperAdminDataPointMutations() {\n const queryClient = useQueryClient();\n const { post, put, del } = useApiHelper();\n const { handleSuccess, handleError } =\n useDefaultMutateResponseHandlers(\"Data Point\");\n\n const createDataPoint = useMutation({\n mutationFn: (dataPoint) => post(\"/v1/superadmin/datapoint\", dataPoint),\n onError: (error) => handleError(error, \"create\"),\n onSuccess: (data) => handleSuccess(data, \"create\"),\n onSettled: () => { \n queryClient.invalidateQueries([\"superadmin\", \"datapoint\"])\n queryClient.resetQueries([\"reading\", \"datapoints\"])\n }\n });\n\n const updateDataPoint = useMutation({\n mutationFn: (dataPoint: IDataPoint) =>\n put(`/v1/superadmin/datapoint/${dataPoint.id}`, dataPoint),\n onError: (error) => handleError(error, \"update\"),\n onSuccess: (data) => handleSuccess(data, \"update\"),\n onSettled:() => { \n queryClient.invalidateQueries([\"superadmin\", \"datapoint\"])\n queryClient.resetQueries([\"reading\", \"datapoints\"])\n }\n });\n\n const delDataPoint = useMutation({\n mutationFn: (dataPoint: IDataPoint) =>\n del(`/v1/superadmin/datapoint/${dataPoint.id}`),\n onError: (error) => handleError(error, \"delete\"),\n onSuccess: (data) => handleSuccess(data, \"delete\"),\n onSettled: () => { \n queryClient.invalidateQueries([\"superadmin\", \"datapoint\"])\n queryClient.resetQueries([\"reading\", \"datapoints\"])\n }\n });\n\n return {\n createDataPoint,\n updateDataPoint,\n delDataPoint,\n };\n}\n","import { Dispatch, SetStateAction, useEffect, useState } from \"react\";\n\nimport { useForm } from \"react-hook-form\";\n\nimport { Select } from \"../base/Select\";\nimport { Button } from \"../base/Button\";\nimport { Toggle } from \"../base/Toggle\";\nimport { Modal } from \"../../layouts/Modal\";\nimport { TextField } from \"../base/TextField\";\nimport { SectionLoading } from \"../shared/SectionLoading\";\nimport { IDataPoint } from \"../../types/DataPoint/DataPoint\";\nimport useHardwareTypes from \"../../data/hardware/useHardwareTypes\";\nimport useSuperAdminDataPointMutations from \"../../data/datapoint/superadmin/useSuperAdminDataPointMutation\";\n\nexport interface CreateEditDataPointProps {\n open: boolean;\n onClose: Dispatch>;\n dataPoint?: IDataPoint;\n}\n\nexport function CreateEditDataPoint({\n open,\n onClose,\n dataPoint,\n}: CreateEditDataPointProps) {\n const { register, reset, handleSubmit } = useForm({\n defaultValues: {\n icon: \"fas,\",\n },\n });\n const { hardwareTypes } = useHardwareTypes();\n const { createDataPoint, updateDataPoint } =\n useSuperAdminDataPointMutations();\n const [customerEnable, setCustomerEnable] = useState(true);\n const [installerEnable, setInstallerEnable] = useState(true);\n const [graphEnable, setGraphEnable] = useState(false);\n const [archiveEnable, setArchiveEnable] = useState(false);\n\n const handleClose = () => {\n onClose(false);\n setTimeout(() => reset({}), 200);\n };\n\n const handleCreate = (data: any) => {\n createDataPoint.mutate({\n ...data,\n customerEnable,\n installerEnable,\n graphEnable,\n archiveEnable,\n });\n handleClose();\n };\n\n const handleUpdate = (data: any) => {\n updateDataPoint.mutate({\n ...dataPoint,\n ...data,\n customerEnable,\n installerEnable,\n graphEnable,\n archiveEnable,\n });\n handleClose();\n };\n\n useEffect(() => {\n if (dataPoint) {\n reset({\n name: dataPoint.name,\n unit: dataPoint.unit,\n icon: dataPoint.icon,\n hardwareTypeId: dataPoint.hardwareTypeId,\n });\n setCustomerEnable(dataPoint.customerEnable);\n setInstallerEnable(dataPoint.installerEnable);\n setGraphEnable(dataPoint.graphEnable);\n setArchiveEnable(dataPoint.archiveEnable);\n }\n }, [reset, dataPoint, hardwareTypes.data, hardwareTypes.isLoading]);\n\n return (\n \n {hardwareTypes.isLoading ? (\n \n ) : (\n \n \n \n \n
\n \n \n \n \n
\n \n
\n \n \n
\n \n )}\n \n );\n}\n","import { useState } from \"react\";\n\nimport { createColumnHelper } from \"@tanstack/react-table\";\nimport {\n ArrowUturnDownIcon,\n PencilIcon,\n TrashIcon,\n} from \"@heroicons/react/24/outline\";\n\nimport { Card } from \"../../../components/base/Card\";\nimport { Table } from \"../../../components/base/Table\";\nimport { Button } from \"../../../components/base/Button\";\nimport { IDataPoint } from \"../../../types/DataPoint/DataPoint\";\nimport { ConfirmDelete } from \"../../../components/shared/ConfirmDelete\";\nimport { CreateEditDataPoint } from \"../../../components/DataPoint/CreateEditDataPoint\";\nimport useSuperAdminDataPointMutations from \"../../../data/datapoint/superadmin/useSuperAdminDataPointMutation\";\nimport { useSuperAdminHardwareLookups } from \"../../../hooks/useSuperAdminHardwareLookups\";\nimport { useClipboardCopy } from \"../../../hooks/useClipboardCopy\";\n\nconst colHelper = createColumnHelper();\n\nexport function DataPointsPage() {\n const { CopyToClipboardButton } = useClipboardCopy();\n const { delDataPoint, updateDataPoint } = useSuperAdminDataPointMutations();\n const [editOpen, setEditOpen] = useState(false);\n const [deleteOpen, setDeleteOpen] = useState(false);\n const [editDataPoint, setEditDataPoint] = useState(\n undefined\n );\n const [deleteDataPoint, setDeleteDataPoint] = useState<\n IDataPoint | undefined\n >(undefined);\n const { isLoading, typeLookup } = useSuperAdminHardwareLookups();\n\n const handleDeleteDataPoint = (dataPoint: IDataPoint) => {\n setDeleteDataPoint(dataPoint);\n setDeleteOpen(true);\n };\n\n const handleConfirmDeleteDataPoint = () => {\n delDataPoint.mutate(deleteDataPoint!);\n setDeleteOpen(false);\n };\n\n const handleRestoreDataPoint = (dataPoint: IDataPoint) => {\n updateDataPoint.mutate({ ...dataPoint, restore: true });\n };\n\n const handleEditDataPoint = (dataPoint: IDataPoint) => {\n setEditDataPoint(dataPoint);\n setEditOpen(true);\n };\n\n const handleCreateEditClose = () => {\n editDataPoint && setTimeout(() => setEditDataPoint(undefined), 200);\n setEditOpen(false);\n };\n\n const cols = [\n colHelper.accessor((row) => typeLookup(row.hardwareTypeId)?.name, {\n header: \"Type\",\n }),\n colHelper.accessor(\"name\", { header: \"Name\" }),\n colHelper.accessor(\"unit\", { header: \"Unit\" }),\n colHelper.display({\n header: \"Actions\",\n cell: (info) => (\n
\n {info.cell.row.original.deletedOn ? (\n handleRestoreDataPoint(info.row.original)}\n />\n ) : (\n <>\n \n handleEditDataPoint(info.row.original)}\n />\n handleDeleteDataPoint(info.row.original)}\n />\n \n )}\n
\n ),\n }),\n ];\n\n return (\n <>\n \n setDeleteOpen(false)}\n onConfirm={() => handleConfirmDeleteDataPoint()}\n />\n \n
\n \n
\n
\n \n url=\"/superadmin/datapoint\"\n queryKey={[\"superadmin\", \"datapoint\"]}\n columns={cols}\n enableShowDeleted\n filterFields={[{ field: \"name\", fieldLabel: \"Name\" }]}\n />\n
\n
\n \n );\n}\n","import { useEffect, useState } from \"react\";\n\nimport { useForm } from \"react-hook-form\";\nimport { useLocation, useNavigate } from \"react-router\";\n\nimport useApiHelper from \"../../hooks/useApiHelper\";\nimport { Button } from \"../../components/base/Button\";\nimport { applicationId, authAPIURL } from \"../../config\";\nimport { TextField } from \"../../components/base/TextField\";\nimport { useUserContext } from \"../../contexts/UserContext\";\nimport { Alert, AlertProps } from \"../../components/base/Alert\";\nimport { SectionLoading } from \"../../components/shared/SectionLoading\";\nimport { SSOPasswordResetFormFields } from \"../../types/requests/sso/SSOPasswordResetRequest\";\n\nexport function ForgottenPassword() {\n const location = useLocation();\n const navigate = useNavigate();\n const { post } = useApiHelper({\n apiUrl: authAPIURL,\n withCredentials: false,\n addToken: false,\n });\n const { loading, isLoggedIn } = useUserContext();\n const { register, handleSubmit } = useForm({\n values: {\n email: location.state && location.state.email ? location.state.email : \"\",\n },\n });\n const [submitting, setSubmitting] = useState(false);\n const [error, setError] = useState();\n const [success, setSuccess] = useState(false);\n\n const handleResetRequest = async (\n resetDetails: SSOPasswordResetFormFields,\n ) => {\n setSubmitting(true);\n\n try {\n let resetResponse = await post(\"/v1/sso/password/request\", {\n ...resetDetails,\n applicationId: applicationId,\n });\n\n if (resetResponse.status === 200) {\n setSuccess(true);\n } else {\n throw Error(\"An unknown error has occurred\");\n }\n } catch (err: any) {\n if (err.response?.data?.message) {\n setError({ severity: \"error\", message: err.response.data.message });\n } else {\n setError({\n severity: \"error\",\n message: \"An unknown error has occurred\",\n });\n }\n } finally {\n setSubmitting(false);\n }\n };\n\n useEffect(() => {\n if (!loading && isLoggedIn) {\n navigate(\"/\");\n }\n }, [loading, isLoggedIn, navigate]);\n\n return (\n
\n {submitting ? (\n \n ) : (\n <>\n
\n Password Reset\n
\n {error && }\n {success && (\n \n )}\n {!success ? (\n
\n
\n \n
\n
\n \n
\n
\n ) : (\n \n )}\n \n )}\n
\n );\n}\n","import * as Sentry from \"@sentry/react\";\nimport { Outlet } from \"react-router\";\n\nimport { CDNURL } from \"../config\";\nimport { ErrorFallback } from \"../ErrorFallback\";\n\nexport function UnauthenticatedLayout() {\n return (\n }>\n
\n
\n
\n \n
\n
\n \n
\n
\n );\n}\n","import React, { useEffect, useState } from \"react\";\n\nimport { LoadingWheel } from \"../base/LoadingWheel\";\nimport { Select } from \"../base/Select\";\n\nimport useSuperAdminActions from \"../../data/action/useSuperAdminActions\";\nimport useSuperAdminActionProfiles from \"../../data/action/useSuperAdminActionProfiles\";\nimport { IAction } from \"../../types/Action/Action\";\n\nexport interface ActionSelectProps {\n type: string;\n model: string;\n filter?: boolean;\n selected: string | undefined;\n}\n\nexport const ActionSelect = React.forwardRef(\n ({ type, model, filter, selected, ...rest }, ref) => {\n const { actions: allActions } = useSuperAdminActions();\n const { actionProfiles } = useSuperAdminActionProfiles(model);\n const [actions, setActions] = useState(undefined);\n const [loading, setLoading] = useState(true);\n\n useEffect(() => {\n if (\n !allActions.isLoading &&\n !actionProfiles.isLoading &&\n allActions.data &&\n actionProfiles.data\n ) {\n let currentAction;\n let filteredActions;\n\n if (filter) {\n filteredActions = allActions.data.filter(\n (action) =>\n !actionProfiles.data?.some(\n (actionProfile) => actionProfile.actionId === action.id,\n ),\n );\n\n if (selected) {\n currentAction = allActions.data.find(\n (action) => action.id === selected,\n );\n currentAction && filteredActions.push(currentAction);\n }\n } else {\n filteredActions = allActions.data;\n }\n\n setActions(filteredActions);\n setLoading(false);\n }\n }, [\n type,\n model,\n filter,\n selected,\n allActions.isLoading,\n allActions.data,\n actionProfiles.isLoading,\n actionProfiles.data,\n ]);\n\n if (allActions.isLoading || actionProfiles.isLoading || loading) {\n return (\n
\n \n
\n );\n } else {\n return (\n \n );\n }\n },\n);\n","import { useQuery } from \"react-query\";\n\nimport useApiHelper from \"../../hooks/useApiHelper\";\n\nimport { IDefaultResponseWithData } from \"../../types/system/DefaultResponse\";\n\nimport { IActionProfile } from \"../../types/Action/ActionProfile\";\nimport { actionProfileQueryKeys } from \"../QueryKeys\";\n\nexport default function useSuperAdminActionProfiles(hardwareModelId: string) {\n const { get } = useApiHelper();\n\n const actionProfiles = useQuery({\n queryKey: actionProfileQueryKeys.superAdminByModel(hardwareModelId),\n queryFn: () =>\n get>(\n `/v1/superadmin/action/profile/${hardwareModelId}`,\n ).then((res) => res.data.data),\n });\n\n return {\n actionProfiles,\n };\n}\n","import { useMutation, useQueryClient } from \"react-query\";\n\nimport useApiHelper from \"../../hooks/useApiHelper\";\nimport { actionProfileQueryKeys } from \"../QueryKeys\";\nimport { IActionProfile } from \"../../types/Action/ActionProfile\";\nimport { useDefaultMutateResponseHandlers } from \"../../hooks/useDefaultMutateResponeHandlers\";\n\nexport default function useSuperAdminActionProfileMutations() {\n const queryClient = useQueryClient();\n const { post, put, del } = useApiHelper();\n const { handleSuccess, handleError } =\n useDefaultMutateResponseHandlers(\"Action Profile\");\n\n const createActionProfile = useMutation({\n mutationKey: actionProfileQueryKeys.create(),\n mutationFn: (actionProfile) =>\n post(\"/v1/superadmin/action/profile\", actionProfile),\n onError: (error) => handleError(error, \"create\"),\n onSuccess: (data) => handleSuccess(data, \"create\"),\n onSettled: () =>\n queryClient.invalidateQueries(actionProfileQueryKeys.superAdminAll()),\n });\n\n const updateActionProfile = useMutation({\n mutationKey: actionProfileQueryKeys.update(),\n mutationFn: (actionProfile: IActionProfile) =>\n put(\n `/v1/superadmin/action/profile/${actionProfile.id}`,\n actionProfile,\n ),\n onError: (error) => handleError(error, \"update\"),\n onSuccess: (data) => handleSuccess(data, \"update\"),\n onSettled: () =>\n queryClient.invalidateQueries(actionProfileQueryKeys.superAdminAll()),\n });\n\n const delActionProfile = useMutation({\n mutationKey: actionProfileQueryKeys.delete(),\n mutationFn: (actionProfile: IActionProfile) =>\n del(`/v1/superadmin/action/profile/${actionProfile.id}`),\n onError: (error) => handleError(error, \"delete\"),\n onSuccess: (data) => handleSuccess(data, \"delete\"),\n onSettled: () =>\n queryClient.invalidateQueries(actionProfileQueryKeys.superAdminAll()),\n });\n\n return {\n createActionProfile,\n updateActionProfile,\n delActionProfile,\n };\n}\n","import { useQuery } from \"react-query\";\n\nimport useApiHelper from \"../../../hooks/useApiHelper\";\n\nimport { IDataPoint } from \"../../../types/DataPoint/DataPoint\";\nimport { IDefaultResponseWithData } from \"../../../types/system/DefaultResponse\";\n\nexport default function useSuperAdminDataPoints(hardwareType?: string) {\n const { get } = useApiHelper();\n\n const dataPoints = useQuery({\n queryKey: [\"superadmin\", \"datapoints\", hardwareType],\n queryFn: () =>\n get>(\n `/v1/superadmin/datapoint/${hardwareType}`,\n ).then((res) => res.data.data),\n });\n\n return {\n dataPoints,\n };\n}\n","import { useQuery } from \"react-query\";\n\nimport useApiHelper from \"../../../hooks/useApiHelper\";\n\nimport { IDefaultResponseWithData } from \"../../../types/system/DefaultResponse\";\nimport { IDataPointProfile } from \"../../../types/DataPoint/DataPointProfile\";\n\nexport default function useSuperAdminDataPointProfiles(hardwareModel?: string) {\n const { get } = useApiHelper();\n\n const dataPointProfiles = useQuery({\n queryKey: [\"superadmin\", \"datapoint\", \"profiles\", hardwareModel],\n queryFn: () =>\n get>(\n `/v1/superadmin/datapoint/profile${\n hardwareModel ? `/${hardwareModel}` : \"\"\n }`,\n ).then((res) => res.data.data),\n });\n\n return {\n dataPointProfiles,\n };\n}\n","import React, { useEffect, useState } from \"react\";\n\nimport { Select } from \"../base/Select\";\nimport { LoadingWheel } from \"../base/LoadingWheel\";\n\nimport useSuperAdminDataPoints from \"../../data/datapoint/superadmin/useSuperAdminDataPoints\";\nimport useSuperAdminDataPointProfiles from \"../../data/datapoint/superadmin/useSuperAdminDataPointProfiles\";\n\nimport { IDataPoint } from \"../../types/DataPoint/DataPoint\";\n\nexport interface DataPointSelectProps {\n type: string;\n model: string;\n selected?: string;\n filterForActionProfiles?: boolean;\n filterForDataPointTransformations?: boolean;\n filterUnused?: boolean;\n filterUsed?: boolean;\n label?: string;\n}\n\nexport const DataPointSelect = React.forwardRef(\n (\n {\n type,\n model,\n selected,\n filterForActionProfiles,\n filterForDataPointTransformations,\n filterUnused,\n filterUsed,\n label = \"Data Point\",\n ...rest\n },\n ref\n ) => {\n const { dataPoints: allDataPoints } = useSuperAdminDataPoints(type);\n const { dataPointProfiles } = useSuperAdminDataPointProfiles(model);\n const [dataPoints, setDataPoints] = useState(\n undefined\n );\n const [loading, setLoading] = useState(true);\n\n useEffect(() => {\n if (\n !allDataPoints.isLoading &&\n !dataPointProfiles.isLoading &&\n allDataPoints.data &&\n dataPointProfiles.data\n ) {\n let currentDataPoint;\n let filteredDataPoints;\n\n if (filterForActionProfiles || filterForDataPointTransformations) {\n // Filter where datapoint profile exists & datapoint profile isn't readonly\n filteredDataPoints = allDataPoints.data.filter((dataPoint) =>\n dataPointProfiles.data?.some(\n (decodeProfile) => decodeProfile.dataPointId === dataPoint.id\n )\n );\n\n if (filterForActionProfiles) {\n filteredDataPoints = allDataPoints.data.filter((dataPoint) =>\n dataPointProfiles.data?.some(\n (decodeProfile) => !decodeProfile.readOnly\n )\n );\n }\n } else if (filterUnused) {\n filteredDataPoints = allDataPoints.data.filter(\n (dataPoint) =>\n !dataPointProfiles.data?.some(\n (decodeProfile) => decodeProfile.dataPointId === dataPoint.id\n )\n );\n } else if (filterUsed) {\n filteredDataPoints = allDataPoints.data.filter((dataPoint) =>\n dataPointProfiles.data?.some(\n (decodeProfile) => decodeProfile.dataPointId === dataPoint.id\n )\n );\n } else {\n filteredDataPoints = allDataPoints.data;\n }\n\n if (selected) {\n currentDataPoint = allDataPoints.data.find(\n (dataPoint) => dataPoint.id === selected\n );\n\n currentDataPoint && filteredDataPoints.push(currentDataPoint);\n }\n\n filteredDataPoints.sort((a, b) => a.name.localeCompare(b.name));\n\n setDataPoints(filteredDataPoints);\n setLoading(false);\n }\n }, [\n type,\n model,\n selected,\n filterUnused,\n filterUsed,\n allDataPoints.isLoading,\n allDataPoints.data,\n dataPointProfiles.isLoading,\n dataPointProfiles.data,\n filterForActionProfiles,\n ]);\n\n if (allDataPoints.isLoading || dataPointProfiles.isLoading || loading) {\n return (\n
\n \n
\n );\n } else {\n return (\n \n );\n }\n }\n);\n","import { Dispatch, SetStateAction, useEffect } from \"react\";\n\nimport { useForm } from \"react-hook-form\";\n\nimport { Select } from \"../base/Select\";\nimport { Button } from \"../base/Button\";\nimport { Modal } from \"../../layouts/Modal\";\nimport { TextArea } from \"../base/TextArea\";\nimport { ActionSelect } from \"./ActionSelect\";\nimport { TextField } from \"../base/TextField\";\nimport { ModelSelect } from \"../Hardware/ModelSelect\";\nimport { SectionLoading } from \"../shared/SectionLoading\";\nimport { IActionProfile, InputType } from \"../../types/Action/ActionProfile\";\nimport useHardwareTypes from \"../../data/hardware/useHardwareTypes\";\nimport { ManufacturerSelect } from \"../Hardware/ManufacturerSelect\";\nimport useSuperAdminActionProfileMutations from \"../../data/action/useSuperAdminActionProfileMutation\";\nimport { useGlobalHardwareModelFilter } from \"../../contexts/GlobalHardwareFilterContext\";\nimport { GlobalHardwareModelFilterBanner } from \"../shared/GlobalHardwareModelFilterBanner\";\nimport { DataPointSelect } from \"../DataPoint/DataPointSelect\";\n\nexport interface CreateEditActionProfileProps {\n open: boolean;\n onClose: Dispatch>;\n actionProfile?: IActionProfile;\n}\n\nexport function CreateEditActionProfile({\n open,\n onClose,\n actionProfile,\n}: CreateEditActionProfileProps) {\n const { register, reset, handleSubmit, watch, resetField } =\n useForm();\n const { hardwareTypes } = useHardwareTypes();\n const { createActionProfile, updateActionProfile } =\n useSuperAdminActionProfileMutations();\n const { globalHardwareModelFilter } = useGlobalHardwareModelFilter();\n\n const handleClose = () => {\n onClose(false);\n setTimeout(() => reset({}), 200);\n };\n\n const handleCreate = (data: any) => {\n createActionProfile.mutate({\n ...data,\n dataPointId: data.dataPointId === \"\" ? null : data.dataPointId,\n bit: data.bit !== \"\" ? data.bit : null,\n inputType: parseInt(data.inputType),\n });\n handleClose();\n };\n\n const handleUpdate = (data: any) => {\n updateActionProfile.mutate({\n ...actionProfile,\n ...data,\n dataPointId: data.dataPointId === \"\" ? null : data.dataPointId,\n bit: data.bit !== \"\" ? data.bit : null,\n inputType: parseInt(data.inputType),\n });\n handleClose();\n };\n\n const inputTypes = [\n ...Object.values(InputType).filter((ct) => isNaN(Number(ct))),\n ];\n\n useEffect(() => {\n if (actionProfile) {\n reset({\n hardwareTypeId: actionProfile.hardwareTypeId,\n hardwareManufacturerId: actionProfile.hardwareManufacturerId,\n hardwareModelId: actionProfile.hardwareModelId,\n actionId: actionProfile.actionId,\n dataPointId: actionProfile.dataPointId,\n hardwareModel: actionProfile.hardwareModel,\n command: actionProfile.command,\n responseLength: actionProfile.responseLength,\n responseTimeout: actionProfile.responseTimeout,\n inputType: actionProfile.inputType,\n step: actionProfile.step,\n });\n } else if (globalHardwareModelFilter) {\n reset({\n hardwareModelId: globalHardwareModelFilter.id,\n hardwareManufacturerId:\n globalHardwareModelFilter.hardwareManufacturerId,\n hardwareTypeId: globalHardwareModelFilter.hardwareTypeId,\n command: \"AT+WSAO={{a}},{{v}}\",\n responseTimeout: 0,\n responseLength: 0,\n });\n } else {\n reset({\n command: \"AT+WSAO={{a}},{{v}}\",\n responseTimeout: 0,\n responseLength: 0,\n });\n }\n }, [\n reset,\n open,\n actionProfile,\n hardwareTypes.data,\n hardwareTypes.isLoading,\n globalHardwareModelFilter,\n ]);\n\n return (\n \n \n {hardwareTypes.isLoading ? (\n \n ) : (\n \n \n \n {hardwareTypes.data?.map((type) => (\n \n ))}\n \n {\n resetField(\"hardwareModelId\");\n resetField(\"actionId\");\n },\n })}\n type={watch(\"hardwareTypeId\")}\n />\n {\n resetField(\"actionId\");\n },\n })}\n manufacturer={watch(\"hardwareManufacturerId\")}\n />\n \n \n
\n